Skip to main content

omnibias.partition.arrangement

0.1.0a2AlphaPython >=3.10AGPL / commercial

Trainable soft partitions of unity, regional experts, temperature hardening, and scoped membership bounds.

import omnibias.partition.arrangement
Module contract & mathematical conventions

Arrangement geometry (theory 01-03, gated).

Sampling is a subgraph / lower bound, never a complete face lattice. beta -> inf is temperature collapse, not founding delta -> 0.

Shared formulas do not imply universal floating-point identity. Verify dtype, shape, derivative-order support, and the stated numerical assumptions for the path you use.

Imports & aliases​

These names share a definition with another public module. Follow a name for its full contract, parameters, and examples.

Import from this moduleCanonical reference
Arrangementomnibias.partition.Arrangement
CellGapCertificateomnibias.partition.CellGapCertificate
certify_cell_gapomnibias.partition.certify_cell_gap
max_cellsomnibias.partition.max_cells
soft_membershipomnibias.partition.soft_membership
FUNCTION

affine_values​

omnibias.partition.arrangement.affine_valuesSource ↗
affine_values(arr: Arrangement, x: FloatArray) -> FloatArray

W x - t, shape (..., n).

Parameters

NameType & defaultContract
arrpositional-or-keywordArrangementRequiredSee the operation contract and implementation below.
xpositional-or-keywordFloatArrayRequiredSee the operation contract and implementation below.
ReturnsFloatArray
Executed regression · g6 torch runs

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g6_torch_runs() -> None:
    pytest.importorskip("torch")
    import torch
    from omnibias.graph.arrangement.torch import FaceNet

    torch.set_default_dtype(torch.float64)
    arr = _square()
    samples = np.array([[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [-2.0, 0.0], [0.0, -2.0]])
    graph = build_arrangement_graph(arr, samples)
    net = FaceNet(2, hidden=4, rounds=2, dtype=torch.float64)
    out = net(graph, arr)
    assert out.shape[0] == len(graph.cells)
    assert torch.isfinite(out).all()
python -m pytest "packages/omnibias-graph/tests/test_arrangement.py::test_g6_torch_runs" -q
Read the implementation
def affine_values(arr: Arrangement, x: FloatArray) -> FloatArray:
    """``W x - t``, shape ``(..., n)``."""
    xv = np.asarray(x, dtype=np.float64)
    if xv.ndim == 1:
        xv = xv.reshape(1, -1)
    return xv @ arr.normals.T - arr.offsets[None, :]
FUNCTION

brute_force_cells​

omnibias.partition.arrangement.brute_force_cellsSource ↗
brute_force_cells(arr: Arrangement, box: float=3.0, n_grid: int=21) -> tuple[tuple[int, ...], ...]

Grid sampler used as a reference on tiny arrangements (not a completeness claim).

Parameters

NameType & defaultContract
arrpositional-or-keywordArrangementRequiredSee the operation contract and implementation below.
boxpositional-or-keywordfloatDefault: 3.0See the operation contract and implementation below.
n_gridpositional-or-keywordintDefault: 21See the operation contract and implementation below.
Returnstuple[tuple[int, ...], ...]
Explicit validation & failure cases
  • When arr.dim > 3, raises ValueError('brute_force_cells is a small-D reference').

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · g1 graph matches brute

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g1_graph_matches_brute() -> None:
    arr = _square()
    xs = np.linspace(-2.0, 2.0, 9)
    ys = np.linspace(-2.0, 2.0, 9)
    xx, yy = np.meshgrid(xs, ys, indexing="xy")
    samples = np.stack([xx.reshape(-1), yy.reshape(-1)], axis=1)
    graph = build_arrangement_graph(arr, samples)
    brute = brute_force_cells(arr)
    assert set(graph.cells) == set(brute)
    brute_edges = set(tope_graph(brute))
    found = {(min(u, v), max(u, v)) for u, v, _k in graph.edges}
    # Reindex brute edges by cell identity.
    index = {cell: i for i, cell in enumerate(graph.cells)}
    expect = set()
    listed = list(brute)
    for i, j in tope_graph(listed):
        a, b = index[listed[i]], index[listed[j]]
        expect.add((min(a, b), max(a, b)))
    assert found == expect
    _ = brute_edges
    assert graph.representatives.shape[0] == len(graph.cells)
python -m pytest "packages/omnibias-graph/tests/test_arrangement.py::test_g1_graph_matches_brute" -q
Read the implementation
def brute_force_cells(
    arr: Arrangement, box: float = 3.0, n_grid: int = 21
) -> tuple[tuple[int, ...], ...]:
    """Grid sampler used as a reference on tiny arrangements (not a completeness claim)."""
    if arr.dim > 3:
        raise ValueError("brute_force_cells is a small-D reference")
    axes = [np.linspace(-box, box, n_grid) for _ in range(arr.dim)]
    mesh = np.meshgrid(*axes, indexing="ij")
    pts = np.stack([m.reshape(-1) for m in mesh], axis=1)
    return realized_cells(arr, pts)
FUNCTION

enumerate_cells_vertices​

omnibias.partition.arrangement.enumerate_cells_verticesSource ↗
enumerate_cells_vertices(arr: Arrangement, *, eps: float=1e-06) -> tuple[tuple[int, ...], ...]

Cells found by orthant-perturbing every simple vertex.

At a vertex x = A^{-1} t of D independent planes, the 2^D adjacent cells are the points x + A^{-1} (eps * s). A sum-of-normals poke is the wrong cone. Several eps values are unioned so a nearby extra plane cannot hide a thin cell.

Still a discovered set: parallel or concurrent degeneracies yield fewer cells than max_cells.

Parameters

NameType & defaultContract
arrpositional-or-keywordArrangementRequiredSee the operation contract and implementation below.
epskeyword-onlyfloatDefault: 1e-06See the operation contract and implementation below.
Returnstuple[tuple[int, ...], ...]
Executed regression · g1 general position cell count

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g1_general_position_cell_count() -> None:
    rng = np.random.default_rng(0)
    for n, d in ((5, 2), (8, 2), (6, 3), (10, 3), (8, 4)):
        arr = general_position_normals(n, d, rng)
        cells = enumerate_cells_vertices(arr)
        assert len(cells) == max_cells(n, d), (n, d, len(cells), max_cells(n, d))
python -m pytest "packages/omnibias-partition/tests/test_arrangement.py::test_g1_general_position_cell_count" -q
Regression example · g2 gap soundness

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g2_gap_soundness() -> None:
    rng = np.random.default_rng(1)
    arr = general_position_normals(5, 2, rng)
    cells = enumerate_cells_vertices(arr)
    signs = cells[0]
    grid = np.stack(
        np.meshgrid(np.linspace(-1.5, 1.5, 25), np.linspace(-1.5, 1.5, 25), indexing="ij"),
        axis=-1,
    ).reshape(-1, 2)
    extra = rng.normal(size=(80, 2))
    x = np.concatenate([grid, extra], axis=0)
    for beta in (1.0, 4.0, 16.0):
        cert = certify_cell_gap(arr, x, signs, beta=beta)
        assert cert.is_sound
        assert cert.bound >= cert.measured - 1e-12
python -m pytest packages/omnibias-partition/tests/test_arrangement.py -k test_g2_gap_soundness -q
Read the implementation
def enumerate_cells_vertices(
    arr: Arrangement, *, eps: float = 1e-6
) -> tuple[tuple[int, ...], ...]:
    """Cells found by orthant-perturbing every simple vertex.

    At a vertex ``x = A^{-1} t`` of ``D`` independent planes, the ``2^D``
    adjacent cells are the points ``x + A^{-1} (eps * s)``. A sum-of-normals
    poke is the wrong cone. Several ``eps`` values are unioned so a nearby
    extra plane cannot hide a thin cell.

    Still a discovered set: parallel or concurrent degeneracies yield fewer
    cells than ``max_cells``.
    """
    n, d = arr.n, arr.dim
    if d < 1:
        return ()
    cells: set[tuple[int, ...]] = set()
    scales = (eps * 0.01, eps, eps * 100.0, eps * 1e4)
    for idx in combinations(range(n), d):
        a = arr.normals[list(idx)]
        b = arr.offsets[list(idx)]
        try:
            inv = np.linalg.inv(a)
        except np.linalg.LinAlgError:
            continue
        x = inv @ b
        for bits in range(1 << d):
            local = np.array(
                [1.0 if (bits >> k) & 1 else -1.0 for k in range(d)],
                dtype=np.float64,
            )
            for scale in scales:
                y = x + scale * (inv @ local)
                s = np.sign(y @ arr.normals.T - arr.offsets)
                if np.any(s == 0.0):
                    continue
                cells.add(tuple(int(v) for v in s))
    return tuple(sorted(cells))
FUNCTION

general_position_normals​

omnibias.partition.arrangement.general_position_normalsSource ↗
general_position_normals(n: int, dim: int, rng: np.random.Generator) -> Arrangement

Random normals, offsets; almost surely simple for the G1 sampler.

Parameters

NameType & defaultContract
npositional-or-keywordintRequiredSee the operation contract and implementation below.
dimpositional-or-keywordintRequiredSee the operation contract and implementation below.
rngpositional-or-keywordnp.random.GeneratorRequiredSee the operation contract and implementation below.
ReturnsArrangement
Explicit validation & failure cases
  • When n > _MAX_N or dim > _MAX_D, raises ValueError(f'G1 tooling caps n<= {_MAX_N}, D<= {_MAX_D}').

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · g1 general position cell count

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g1_general_position_cell_count() -> None:
    rng = np.random.default_rng(0)
    for n, d in ((5, 2), (8, 2), (6, 3), (10, 3), (8, 4)):
        arr = general_position_normals(n, d, rng)
        cells = enumerate_cells_vertices(arr)
        assert len(cells) == max_cells(n, d), (n, d, len(cells), max_cells(n, d))
python -m pytest "packages/omnibias-partition/tests/test_arrangement.py::test_g1_general_position_cell_count" -q
Regression example · g2 gap soundness

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g2_gap_soundness() -> None:
    rng = np.random.default_rng(1)
    arr = general_position_normals(5, 2, rng)
    cells = enumerate_cells_vertices(arr)
    signs = cells[0]
    grid = np.stack(
        np.meshgrid(np.linspace(-1.5, 1.5, 25), np.linspace(-1.5, 1.5, 25), indexing="ij"),
        axis=-1,
    ).reshape(-1, 2)
    extra = rng.normal(size=(80, 2))
    x = np.concatenate([grid, extra], axis=0)
    for beta in (1.0, 4.0, 16.0):
        cert = certify_cell_gap(arr, x, signs, beta=beta)
        assert cert.is_sound
        assert cert.bound >= cert.measured - 1e-12
python -m pytest packages/omnibias-partition/tests/test_arrangement.py -k test_g2_gap_soundness -q
Read the implementation
def general_position_normals(n: int, dim: int, rng: np.random.Generator) -> Arrangement:
    """Random normals, offsets; almost surely simple for the G1 sampler."""
    if n > _MAX_N or dim > _MAX_D:
        raise ValueError(f"G1 tooling caps n<= {_MAX_N}, D<= {_MAX_D}")
    W = rng.normal(size=(n, dim))
    W /= np.linalg.norm(W, axis=1, keepdims=True).clip(1e-12)
    t = rng.normal(size=n) * 0.3
    return Arrangement(W, t)
FUNCTION

margin​

omnibias.partition.arrangement.marginSource ↗
margin(arr: Arrangement, x: FloatArray) -> FloatArray

Per-sample minimum absolute affine value.

Parameters

NameType & defaultContract
arrpositional-or-keywordArrangementRequiredSee the operation contract and implementation below.
xpositional-or-keywordFloatArrayRequiredSee the operation contract and implementation below.
ReturnsFloatArray
Executed regression · g6 torch runs

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g6_torch_runs() -> None:
    pytest.importorskip("torch")
    import torch
    from omnibias.graph.arrangement.torch import FaceNet

    torch.set_default_dtype(torch.float64)
    arr = _square()
    samples = np.array([[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [-2.0, 0.0], [0.0, -2.0]])
    graph = build_arrangement_graph(arr, samples)
    net = FaceNet(2, hidden=4, rounds=2, dtype=torch.float64)
    out = net(graph, arr)
    assert out.shape[0] == len(graph.cells)
    assert torch.isfinite(out).all()
python -m pytest "packages/omnibias-graph/tests/test_arrangement.py::test_g6_torch_runs" -q
Read the implementation
def margin(arr: Arrangement, x: FloatArray) -> FloatArray:
    """Per-sample minimum absolute affine value."""
    return np.min(np.abs(affine_values(arr, x)), axis=-1)
FUNCTION

realized_cells​

omnibias.partition.arrangement.realized_cellsSource ↗
realized_cells(arr: Arrangement, samples: FloatArray, *, tol: float=1e-12) -> tuple[tuple[int, ...], ...]

Sign vectors observed at samples. A lower bound, never completeness.

Parameters

NameType & defaultContract
arrpositional-or-keywordArrangementRequiredSee the operation contract and implementation below.
samplespositional-or-keywordFloatArrayRequiredSee the operation contract and implementation below.
tolkeyword-onlyfloatDefault: 1e-12See the operation contract and implementation below.
Returnstuple[tuple[int, ...], ...]
Executed regression · g6 torch runs

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g6_torch_runs() -> None:
    pytest.importorskip("torch")
    import torch
    from omnibias.graph.arrangement.torch import FaceNet

    torch.set_default_dtype(torch.float64)
    arr = _square()
    samples = np.array([[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [-2.0, 0.0], [0.0, -2.0]])
    graph = build_arrangement_graph(arr, samples)
    net = FaceNet(2, hidden=4, rounds=2, dtype=torch.float64)
    out = net(graph, arr)
    assert out.shape[0] == len(graph.cells)
    assert torch.isfinite(out).all()
python -m pytest "packages/omnibias-graph/tests/test_arrangement.py::test_g6_torch_runs" -q
Regression example · g1 degenerate strictly smaller

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g1_degenerate_strictly_smaller() -> None:
    # Two parallel lines in R^2: fewer cells than the simple maximum.
    arr = Arrangement(
        np.array([[1.0, 0.0], [1.0, 0.0], [0.0, 1.0]], dtype=np.float64),
        np.array([-1.0, 1.0, 0.0], dtype=np.float64),
    )
    cells = enumerate_cells_vertices(arr)
    brute = realized_cells(
        arr,
        np.stack(
            np.meshgrid(np.linspace(-2, 2, 41), np.linspace(-2, 2, 41), indexing="ij"),
            axis=-1,
        ).reshape(-1, 2),
    )
    assert len(cells) == len(brute)
    assert len(cells) < max_cells(3, 2)
python -m pytest packages/omnibias-partition/tests/test_arrangement.py -k test_g1_degenerate_strictly_smaller -q
Read the implementation
def realized_cells(
    arr: Arrangement, samples: FloatArray, *, tol: float = 1e-12
) -> tuple[tuple[int, ...], ...]:
    """Sign vectors observed at ``samples``. A lower bound, never completeness."""
    s = sign_vector(arr, samples, tol=tol)
    if s.ndim == 1:
        s = s.reshape(1, -1)
    cells: set[tuple[int, ...]] = set()
    for row in s:
        if np.any(row == 0.0):
            continue
        cells.add(tuple(int(v) for v in row))
    return tuple(sorted(cells))
FUNCTION

sign_vector​

omnibias.partition.arrangement.sign_vectorSource ↗
sign_vector(arr: Arrangement, x: FloatArray, *, tol: float=0.0) -> FloatArray

Signs in {-1, 0, +1}, shape (..., n).

Parameters

NameType & defaultContract
arrpositional-or-keywordArrangementRequiredSee the operation contract and implementation below.
xpositional-or-keywordFloatArrayRequiredSee the operation contract and implementation below.
tolkeyword-onlyfloatDefault: 0.0See the operation contract and implementation below.
ReturnsFloatArray
Executed regression · g6 torch runs

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g6_torch_runs() -> None:
    pytest.importorskip("torch")
    import torch
    from omnibias.graph.arrangement.torch import FaceNet

    torch.set_default_dtype(torch.float64)
    arr = _square()
    samples = np.array([[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [-2.0, 0.0], [0.0, -2.0]])
    graph = build_arrangement_graph(arr, samples)
    net = FaceNet(2, hidden=4, rounds=2, dtype=torch.float64)
    out = net(graph, arr)
    assert out.shape[0] == len(graph.cells)
    assert torch.isfinite(out).all()
python -m pytest "packages/omnibias-graph/tests/test_arrangement.py::test_g6_torch_runs" -q
Read the implementation
def sign_vector(arr: Arrangement, x: FloatArray, *, tol: float = 0.0) -> FloatArray:
    """Signs in ``{-1, 0, +1}``, shape ``(..., n)``."""
    z = affine_values(arr, x)
    s = np.sign(z)
    if tol > 0.0:
        s[np.abs(z) <= tol] = 0.0
    return s.astype(np.float64)
FUNCTION

tope_graph​

omnibias.partition.arrangement.tope_graphSource ↗
tope_graph(cells: Sequence[Sequence[int]]) -> tuple[tuple[int, int], ...]

Adjacency over the discovered cells only (Hamming distance 2 on ±1 vectors).

Parameters

NameType & defaultContract
cellspositional-or-keywordSequence[Sequence[int]]RequiredSee the operation contract and implementation below.
Returnstuple[tuple[int, int], ...]
Executed regression · g6 torch runs

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g6_torch_runs() -> None:
    pytest.importorskip("torch")
    import torch
    from omnibias.graph.arrangement.torch import FaceNet

    torch.set_default_dtype(torch.float64)
    arr = _square()
    samples = np.array([[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [-2.0, 0.0], [0.0, -2.0]])
    graph = build_arrangement_graph(arr, samples)
    net = FaceNet(2, hidden=4, rounds=2, dtype=torch.float64)
    out = net(graph, arr)
    assert out.shape[0] == len(graph.cells)
    assert torch.isfinite(out).all()
python -m pytest "packages/omnibias-graph/tests/test_arrangement.py::test_g6_torch_runs" -q
Regression example · g1 graph matches brute

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g1_graph_matches_brute() -> None:
    arr = _square()
    xs = np.linspace(-2.0, 2.0, 9)
    ys = np.linspace(-2.0, 2.0, 9)
    xx, yy = np.meshgrid(xs, ys, indexing="xy")
    samples = np.stack([xx.reshape(-1), yy.reshape(-1)], axis=1)
    graph = build_arrangement_graph(arr, samples)
    brute = brute_force_cells(arr)
    assert set(graph.cells) == set(brute)
    brute_edges = set(tope_graph(brute))
    found = {(min(u, v), max(u, v)) for u, v, _k in graph.edges}
    # Reindex brute edges by cell identity.
    index = {cell: i for i, cell in enumerate(graph.cells)}
    expect = set()
    listed = list(brute)
    for i, j in tope_graph(listed):
        a, b = index[listed[i]], index[listed[j]]
        expect.add((min(a, b), max(a, b)))
    assert found == expect
    _ = brute_edges
    assert graph.representatives.shape[0] == len(graph.cells)
python -m pytest packages/omnibias-graph/tests/test_arrangement.py -k test_g1_graph_matches_brute -q
Read the implementation
def tope_graph(cells: Sequence[Sequence[int]]) -> tuple[tuple[int, int], ...]:
    """Adjacency over the discovered cells only (Hamming distance 2 on ±1 vectors)."""
    listed = [tuple(int(v) for v in c) for c in cells]
    edges: list[tuple[int, int]] = []
    for i, a in enumerate(listed):
        for j, b in enumerate(listed):
            if j <= i:
                continue
            diffs = sum(1 for u, v in zip(a, b, strict=True) if u != v)
            if diffs == 1:
                edges.append((i, j))
    return tuple(edges)
FUNCTION

tree_arrangement​

omnibias.partition.arrangement.tree_arrangementSource ↗
tree_arrangement(W: FloatArray, t: FloatArray) -> Arrangement

The depth global splits of an oblivious tree, as an arrangement.

Parameters

NameType & defaultContract
Wpositional-or-keywordFloatArrayRequiredSee the operation contract and implementation below.
tpositional-or-keywordFloatArrayRequiredSee the operation contract and implementation below.
ReturnsArrangement
Executed regression · g3 tree agrees with partition weights

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g3_tree_agrees_with_partition_weights() -> None:
    cfg = PartitionConfig(n_features=3, depth=3)
    params = init_params(cfg, rng=0)
    arr = tree_arrangement(params.W, params.t)
    x = np.array([[0.2, -0.1, 0.4], [1.0, 0.0, -0.5], [-0.3, 0.7, 0.1]], dtype=np.float64)
    beta = 3.5
    pw = partition_weights(params, x, beta)
    codes = region_code_matrix(3)
    eps = np.finfo(np.float64).eps
    for leaf in range(8):
        signs = tuple(1 if codes[leaf, j] > 0.5 else -1 for j in range(3))
        sm = soft_membership(arr, x, signs, beta=beta)
        for a, b in zip(sm, pw[:, leaf], strict=True):
            scale = max(abs(float(a)), abs(float(b)), 1.0)
            ulp = abs(float(a) - float(b)) / (eps * scale)
            assert ulp <= 4.0
python -m pytest "packages/omnibias-partition/tests/test_arrangement.py::test_g3_tree_agrees_with_partition_weights" -q
Read the implementation
def tree_arrangement(W: FloatArray, t: FloatArray) -> Arrangement:
    """The ``depth`` global splits of an oblivious tree, as an arrangement."""
    return Arrangement(np.asarray(W, dtype=np.float64), np.asarray(t, dtype=np.float64))