Skip to main content

omnibias.graph.arrangement

0.1.0a2AlphaPython >=3.10AGPL / commercial

Spectral graph operators and differentiable relaxations for ordering, assignment, and graph-structured learning.

import omnibias.graph.arrangement
Module contract & mathematical conventions

Arrangement graph / Face-Net (theory 02-02, gated).

Sampling is a subgraph. beta -> inf is temperature collapse, not founding delta -> 0. Sound gap.

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
FaceNetomnibias.graph.arrangement.FaceNet
CLASS

ArrangementGraph​

omnibias.graph.arrangement.ArrangementGraphSource ↗
class ArrangementGraph

Dataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
cellsdataclass fieldtuple[tuple[int, ...], ...]RequiredSee the operation contract and implementation below.
edgesdataclass fieldtuple[tuple[int, int, int], ...]RequiredSee the operation contract and implementation below.
representativesdataclass fieldFloatArrayRequiredSee the operation contract and implementation below.
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

Fields & methods

cellsfield
cells: tuple[tuple[int, ...], ...]

Declared tuple[tuple[int, ...], ...] field on ArrangementGraph. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
edgesfield
edges: tuple[tuple[int, int, int], ...]

(u, v, crossed hyperplane)

View source ↗
representativesfield
representatives: FloatArray

Declared FloatArray field on ArrangementGraph. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
__post_init__method
__post_init__(self) -> None

See the class contract above and the exact method implementation below.

Returns: None

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
Method implementation
    def __post_init__(self) -> None:
        object.__setattr__(
            self, "representatives", np.asarray(self.representatives, dtype=np.float64)
        )
View source ↗
Read the implementation
class ArrangementGraph:
    cells: tuple[tuple[int, ...], ...]
    edges: tuple[tuple[int, int, int], ...]  # (u, v, crossed hyperplane)
    representatives: FloatArray

    def __post_init__(self) -> None:
        object.__setattr__(
            self, "representatives", np.asarray(self.representatives, dtype=np.float64)
        )
FUNCTION

build_arrangement_graph​

omnibias.graph.arrangement.build_arrangement_graphSource ↗
build_arrangement_graph(arr: Arrangement, samples: FloatArray) -> ArrangementGraph

Discovery by sampling. Returns what was found; never claims completeness.

Parameters

NameType & defaultContract
arrpositional-or-keywordArrangementRequiredSee the operation contract and implementation below.
samplespositional-or-keywordFloatArrayRequiredSee the operation contract and implementation below.
ReturnsArrangementGraph
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 build_arrangement_graph(
    arr: Arrangement, samples: FloatArray
) -> ArrangementGraph:
    """Discovery by sampling. Returns what was found; never claims completeness."""
    pts = np.asarray(samples, dtype=np.float64)
    if pts.ndim == 1:
        pts = pts.reshape(1, -1)
    cells = realized_cells(arr, pts)
    signs = sign_vector(arr, pts)
    reps: list[list[float]] = []
    for cell in cells:
        mask = np.all(signs == np.asarray(cell, dtype=np.float64), axis=1)
        chosen = pts[mask]
        reps.append(chosen.mean(axis=0).tolist() if len(chosen) else [0.0] * arr.dim)
    raw_edges = tope_graph(cells)
    edges: list[tuple[int, int, int]] = []
    for u, v in raw_edges:
        diffs = [i for i, (a, b) in enumerate(zip(cells[u], cells[v], strict=True)) if a != b]
        crossed = diffs[0] if diffs else 0
        edges.append((u, v, crossed))
    return ArrangementGraph(cells, tuple(edges), np.asarray(reps, dtype=np.float64))
FUNCTION

certify_facenet_gap​

omnibias.graph.arrangement.certify_facenet_gapSource ↗
certify_facenet_gap(logits: Sequence[float], *, beta: float, n_terms: int | None=None) -> dict[str, float | bool]

Reuse logsumexp_gap_bound. Does not fork the constant.

Parameters

NameType & defaultContract
logitspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
betakeyword-onlyfloatRequiredSee the operation contract and implementation below.
n_termskeyword-onlyint | NoneDefault: NoneSee the operation contract and implementation below.
Returnsdict[str, float | bool]
Executed regression · g2 gap sound

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_g2_gap_sound() -> None:
    logits = (0.2, -0.5, 1.1, 0.0)
    cert = certify_facenet_gap(logits, beta=5.0)
    assert cert["sound"] is True
    assert cert["p_vs_np"] is False
    assert cert["theorem_prover_verified"] is False
    assert cert["temperature_collapse"] is True
python -m pytest "packages/omnibias-graph/tests/test_arrangement.py::test_g2_gap_sound" -q
Read the implementation
def certify_facenet_gap(
    logits: Sequence[float], *, beta: float, n_terms: int | None = None
) -> dict[str, float | bool]:
    """Reuse ``logsumexp_gap_bound``. Does not fork the constant."""
    scores = [float(v) for v in logits]
    n = int(n_terms) if n_terms is not None else len(scores)
    gap = logsumexp_gap_bound(n, float(beta))
    hard = max(scores)
    # lse_beta
    m = hard
    lse = m + math.log(sum(math.exp(beta * (s - m)) for s in scores)) / float(beta)
    return {
        "soft": lse,
        "hard": hard,
        "gap": gap,
        "sound": (hard <= lse + 1e-12) and (lse <= hard + gap + 1e-12),
        "temperature_collapse": True,
        "p_vs_np": False,
        "theorem_prover_verified": False,
    }
FUNCTION

node_features​

omnibias.graph.arrangement.node_featuresSource ↗
node_features(arr: Arrangement, graph: ArrangementGraph, *, beta: float) -> FloatArray

Soft mass and margin at each representative. Temperature collapse in beta.

Parameters

NameType & defaultContract
arrpositional-or-keywordArrangementRequiredSee the operation contract and implementation below.
graphpositional-or-keywordArrangementGraphRequiredSee the operation contract and implementation below.
betakeyword-onlyfloatRequiredSee 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 node_features(arr: Arrangement, graph: ArrangementGraph, *, beta: float) -> FloatArray:
    """Soft mass and margin at each representative. Temperature collapse in ``beta``."""
    from omnibias.partition.arrangement import margin, soft_membership

    rows = []
    for cell, rep in zip(graph.cells, graph.representatives, strict=True):
        mass = float(soft_membership(arr, rep, cell, beta=beta).reshape(-1)[0])
        mrg = float(np.asarray(margin(arr, rep)).reshape(-1)[0])
        rows.append([mass, mrg, *rep.tolist()])
    return np.asarray(rows, dtype=np.float64)