Skip to main content

omnibias.convex.arrangement

0.1.0a2AlphaPython >=3.10AGPL / commercial

Differentiable LP and QP solver paths, barrier methods, KKT sensitivities, and scoped optimality evidence.

import omnibias.convex.arrangement
Module contract & mathematical conventions

Learned-facet arrangement LP (theory 03-02).

Wraps the existing interior-point solver and the Neumaier-Shcherbina bound. Soft membership is temperature collapse (beta -> inf, feasibility), not the founding bias collapse (delta -> 0). Do not conflate the two. Not a new LP algorithm.

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.

CLASS

DiffMode​

omnibias.convex.arrangement.DiffModeSource ↗
class DiffMode(str, Enum)

Which differentiable route produced the gradient.

Regression example · g3 degeneracy soft gradient

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_degeneracy_soft_gradient() -> None:
    poly, c, opt = named_pentagon()
    x_star, value, verts = vertex_optimum(poly, c)
    assert math.isclose(value, opt, abs_tol=1e-10)
    assert is_degenerate_optimum(verts, c, value)
    out = solve_arrangement_lp(poly, c, mode=DiffMode.SOFT, beta=6.0)
    assert out.degenerate is True and out.feasible is True
    y = known_dual_pentagon()
    kkt = kkt_matrix(poly, np.array([1.5, 1.5]), y)
    assert kkt_gradient_usable(kkt) is False
    jac = soft_vertex_dx_dc(verts, c, beta=6.0)
    assert np.all(np.isfinite(jac))
    assert float(np.linalg.norm(jac)) > 1e-6
    xs, _w, _vs = soft_vertex_solution(verts, c, beta=6.0)
    np.testing.assert_allclose(xs, np.array([1.5, 1.5]), atol=0.05)
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g3_degeneracy_soft_gradient -q
Read the implementation
class DiffMode(str, Enum):
    """Which differentiable route produced the gradient."""

    KKT = "kkt"
    SOFT = "soft"
Other public import paths
  • omnibias.convex.arrangement.DiffMode
  • omnibias.convex.arrangement.jax.DiffMode
  • omnibias.convex.arrangement.torch.DiffMode
CLASS

LPOutput​

omnibias.convex.arrangement.LPOutputSource ↗
class LPOutput

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.

Primal point, sound lower bound, and the flags the gradient needs.

Parameters

NameType & defaultContract
xdataclass fieldFloatArrayRequiredSee the operation contract and implementation below.
valuedataclass fieldfloatRequiredSee the operation contract and implementation below.
lower_bounddataclass fieldfloatRequiredSee the operation contract and implementation below.
active_setdataclass fieldtuple[int, ...]RequiredSee the operation contract and implementation below.
degeneratedataclass fieldboolRequiredSee the operation contract and implementation below.
modedataclass fieldDiffModeRequiredSee the operation contract and implementation below.
feasibledataclass fieldboolRequiredSee the operation contract and implementation below.
n_verticesdataclass fieldintDefault: 0See the operation contract and implementation below.

Fields & methods

xfield
x: FloatArray

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

View source ↗
valuefield
value: float

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

View source ↗
lower_boundfield
lower_bound: float

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

View source ↗
active_setfield
active_set: tuple[int, ...]

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

View source ↗
degeneratefield
degenerate: bool

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

View source ↗
modefield
mode: DiffMode

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

View source ↗
feasiblefield
feasible: bool

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

View source ↗
n_verticesfield
n_vertices: int = 0

Declared int field on LPOutput. Default expression: 0.

View source ↗
Read the implementation
class LPOutput:
    """Primal point, sound lower bound, and the flags the gradient needs."""

    x: FloatArray
    value: float
    lower_bound: float
    active_set: tuple[int, ...]
    degenerate: bool
    mode: DiffMode
    feasible: bool
    n_vertices: int = 0
Other public import paths
  • omnibias.convex.arrangement.LPOutput
  • omnibias.convex.arrangement.jax.LPOutput
  • omnibias.convex.arrangement.torch.LPOutput
CLASS

LearnedPolytope​

omnibias.convex.arrangement.LearnedPolytopeSource ↗
class LearnedPolytope

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.

Inequality polytope A x <= b. Facets are arrangement hyperplanes.

Parameters

NameType & defaultContract
normalsdataclass fieldFloatArrayRequiredSee the operation contract and implementation below.
offsetsdataclass fieldFloatArrayRequiredSee the operation contract and implementation below.
Executed regression · infer box pentagon

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_infer_box_pentagon() -> None:
    poly, _c, _opt = named_pentagon()
    lo, hi = infer_box(poly)
    np.testing.assert_allclose(lo, [0.0, 0.0])
    np.testing.assert_allclose(hi, [2.0, 2.0])
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_infer_box_pentagon" -q
Regression example · vertex enum cutoff

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_vertex_enum_cutoff() -> None:
    poly = LearnedPolytope(np.eye(5, dtype=np.float64), np.ones(5))
    with pytest.raises(ValueError, match="small-instance"):
        enumerate_vertices(poly)
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_vertex_enum_cutoff -q

Fields & methods

normalsfield
normals: FloatArray

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

Regression example · g1 solver agrees with vertex enum

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_solver_agrees_with_vertex_enum() -> None:
    jax = pytest.importorskip("jax")
    jax.config.update("jax_enable_x64", True)
    from omnibias.convex.jax import solve_lp

    rng = np.random.default_rng(0)
    for _ in range(8):
        poly, c = random_feasible_lp(2, 3, rng)
        _x, v_enum, verts = vertex_optimum(poly, c)
        assert verts.shape[0] >= 1
        sol = solve_lp(c, poly.normals, poly.offsets)
        x_rec = recover_vertex(poly, np.asarray(sol.x))
        v_rec = float(c @ x_rec)
        assert abs(v_rec - v_enum) <= 1e-10
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g1_solver_agrees_with_vertex_enum -q
View source ↗
offsetsfield
offsets: FloatArray

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

Regression example · g1 solver agrees with vertex enum

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_solver_agrees_with_vertex_enum() -> None:
    jax = pytest.importorskip("jax")
    jax.config.update("jax_enable_x64", True)
    from omnibias.convex.jax import solve_lp

    rng = np.random.default_rng(0)
    for _ in range(8):
        poly, c = random_feasible_lp(2, 3, rng)
        _x, v_enum, verts = vertex_optimum(poly, c)
        assert verts.shape[0] >= 1
        sol = solve_lp(c, poly.normals, poly.offsets)
        x_rec = recover_vertex(poly, np.asarray(sol.x))
        v_rec = float(c @ x_rec)
        assert abs(v_rec - v_enum) <= 1e-10
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g1_solver_agrees_with_vertex_enum -q
View source ↗
__post_init__method
__post_init__(self) -> None

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

Returns: None

Validation & failure cases
  • When a.ndim != 2, raises ValueError('normals must have shape (n, D)').
  • When b.shape[0] != a.shape[0], raises ValueError('offsets must have length n').
Executed regression · infer box pentagon

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_infer_box_pentagon() -> None:
    poly, _c, _opt = named_pentagon()
    lo, hi = infer_box(poly)
    np.testing.assert_allclose(lo, [0.0, 0.0])
    np.testing.assert_allclose(hi, [2.0, 2.0])
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_infer_box_pentagon" -q
Method implementation
    def __post_init__(self) -> None:
        a = np.asarray(self.normals, dtype=np.float64)
        b = np.asarray(self.offsets, dtype=np.float64).reshape(-1)
        if a.ndim != 2:
            raise ValueError("normals must have shape (n, D)")
        if b.shape[0] != a.shape[0]:
            raise ValueError("offsets must have length n")
        object.__setattr__(self, "normals", a)
        object.__setattr__(self, "offsets", b)
View source ↗
nproperty
n(self) -> int

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

Returns: int

Executed regression · infer box pentagon

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_infer_box_pentagon() -> None:
    poly, _c, _opt = named_pentagon()
    lo, hi = infer_box(poly)
    np.testing.assert_allclose(lo, [0.0, 0.0])
    np.testing.assert_allclose(hi, [2.0, 2.0])
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_infer_box_pentagon" -q
Method implementation
    def n(self) -> int:
        return int(self.normals.shape[0])
View source ↗
dimproperty
dim(self) -> int

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

Returns: int

Executed regression · infer box pentagon

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_infer_box_pentagon() -> None:
    poly, _c, _opt = named_pentagon()
    lo, hi = infer_box(poly)
    np.testing.assert_allclose(lo, [0.0, 0.0])
    np.testing.assert_allclose(hi, [2.0, 2.0])
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_infer_box_pentagon" -q
Method implementation
    def dim(self) -> int:
        return int(self.normals.shape[1])
View source ↗
as_arrangementmethod
as_arrangement(self) -> object

The same hyperplanes as an ~omnibias.partition.arrangement.Arrangement.

Returns: object

Method implementation
    def as_arrangement(self) -> object:
        """The same hyperplanes as an :class:`~omnibias.partition.arrangement.Arrangement`."""
        from omnibias.partition.arrangement import Arrangement

        return Arrangement(self.normals, self.offsets)
View source ↗
residualmethod
residual(self, x: object) -> FloatArray

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

Parameters

NameType & defaultContract
xpositional-or-keywordobjectRequiredSee the operation contract and implementation below.

Returns: FloatArray

Executed regression · worked example soft membership

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_worked_example_soft_membership() -> None:
    poly, _c, _opt = named_pentagon()
    w = float(soft_membership(poly, np.array([1.5, 1.5]), beta=5.0))
    assert math.isclose(w, 0.4265470, rel_tol=0.0, abs_tol=2e-6)
    assert math.isclose(soft_cell_gap_bound(n_facets=5, beta=5.0), math.log(5.0) / 5.0)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_worked_example_soft_membership" -q
Method implementation
    def residual(self, x: object) -> FloatArray:
        xv = np.asarray(x, dtype=np.float64)
        if xv.ndim == 1:
            return self.normals @ xv - self.offsets
        return xv @ self.normals.T - self.offsets[None, :]
View source ↗
Read the implementation
class LearnedPolytope:
    """Inequality polytope ``A x <= b``. Facets are arrangement hyperplanes."""

    normals: FloatArray
    offsets: FloatArray

    def __post_init__(self) -> None:
        a = np.asarray(self.normals, dtype=np.float64)
        b = np.asarray(self.offsets, dtype=np.float64).reshape(-1)
        if a.ndim != 2:
            raise ValueError("normals must have shape (n, D)")
        if b.shape[0] != a.shape[0]:
            raise ValueError("offsets must have length n")
        object.__setattr__(self, "normals", a)
        object.__setattr__(self, "offsets", b)

    @property
    def n(self) -> int:
        return int(self.normals.shape[0])

    @property
    def dim(self) -> int:
        return int(self.normals.shape[1])

    def as_arrangement(self) -> object:
        """The same hyperplanes as an :class:`~omnibias.partition.arrangement.Arrangement`."""
        from omnibias.partition.arrangement import Arrangement

        return Arrangement(self.normals, self.offsets)

    def residual(self, x: object) -> FloatArray:
        xv = np.asarray(x, dtype=np.float64)
        if xv.ndim == 1:
            return self.normals @ xv - self.offsets
        return xv @ self.normals.T - self.offsets[None, :]
Other public import paths
  • omnibias.convex.arrangement.LearnedPolytope
  • omnibias.convex.arrangement.jax.LearnedPolytope
  • omnibias.convex.arrangement.torch.LearnedPolytope
CONSTANT

VERTEX_ENUM_MAX_D​

omnibias.convex.arrangement.VERTEX_ENUM_MAX_DSource ↗
VERTEX_ENUM_MAX_D = 4

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
VERTEX_ENUM_MAX_D = 4
CONSTANT

VERTEX_ENUM_MAX_N​

omnibias.convex.arrangement.VERTEX_ENUM_MAX_NSource ↗
VERTEX_ENUM_MAX_N = 16

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
VERTEX_ENUM_MAX_N = 16
FUNCTION

dual_objective​

omnibias.convex.arrangement.dual_objectiveSource ↗
dual_objective(poly: LearnedPolytope, y: object) -> float

-b · y for min c·x / A x <= b. Matches primal at a tight pair.

Parameters

NameType & defaultContract
polypositional-or-keywordLearnedPolytopeRequiredSee the operation contract and implementation below.
ypositional-or-keywordobjectRequiredSee the operation contract and implementation below.
Returnsfloat
Executed regression · g5 duality sign convention

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_g5_duality_sign_convention() -> None:
    poly, c, opt = named_pentagon()
    y = known_dual_pentagon()
    assert duality_holds(poly, c, y)
    assert math.isclose(dual_objective(poly, y), opt, abs_tol=1e-12)
    assert math.isclose(float(c @ np.array([1.5, 1.5])), opt, abs_tol=1e-12)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_g5_duality_sign_convention" -q
Read the implementation
def dual_objective(poly: LearnedPolytope, y: object) -> float:
    """``-b · y`` for ``min c·x`` / ``A x <= b``. Matches primal at a tight pair."""
    return float(-poly.offsets @ np.asarray(y, dtype=np.float64).reshape(-1))
FUNCTION

duality_holds​

omnibias.convex.arrangement.duality_holdsSource ↗
duality_holds(poly: LearnedPolytope, c: object, y: object, *, atol: float=1e-09) -> bool

Stationarity A^T y + c = 0 and y >= 0 (the G5 convention).

Parameters

NameType & defaultContract
polypositional-or-keywordLearnedPolytopeRequiredSee the operation contract and implementation below.
cpositional-or-keywordobjectRequiredSee the operation contract and implementation below.
ypositional-or-keywordobjectRequiredSee the operation contract and implementation below.
atolkeyword-onlyfloatDefault: 1e-09See the operation contract and implementation below.
Returnsbool
Executed regression · g5 duality sign convention

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_g5_duality_sign_convention() -> None:
    poly, c, opt = named_pentagon()
    y = known_dual_pentagon()
    assert duality_holds(poly, c, y)
    assert math.isclose(dual_objective(poly, y), opt, abs_tol=1e-12)
    assert math.isclose(float(c @ np.array([1.5, 1.5])), opt, abs_tol=1e-12)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_g5_duality_sign_convention" -q
Read the implementation
def duality_holds(poly: LearnedPolytope, c: object, y: object, *, atol: float = 1e-9) -> bool:
    """Stationarity ``A^T y + c = 0`` and ``y >= 0`` (the G5 convention)."""
    yv = np.asarray(y, dtype=np.float64).reshape(-1)
    cv = np.asarray(c, dtype=np.float64).reshape(-1)
    if np.any(yv < -atol):
        return False
    return bool(np.allclose(poly.normals.T @ yv + cv, 0.0, atol=atol))
FUNCTION

enumerate_vertices​

omnibias.convex.arrangement.enumerate_verticesSource ↗
enumerate_vertices(poly: LearnedPolytope, *, atol: float=_VERT_ATOL) -> FloatArray

Vertices of A x <= b. Exponential; raises above the published cutoff.

Parameters

NameType & defaultContract
polypositional-or-keywordLearnedPolytopeRequiredSee the operation contract and implementation below.
atolkeyword-onlyfloatDefault: _VERT_ATOLSee the operation contract and implementation below.
ReturnsFloatArray
Explicit validation & failure cases
  • When d > VERTEX_ENUM_MAX_D or n > VERTEX_ENUM_MAX_N, raises ValueError(f'vertex enumeration is a small-instance tool only (D<={VERTEX_ENUM_MAX_D}, n<={VERTEX_ENUM_MAX_N}); got D={d}, n={n}').

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

Executed regression · vertex enum cutoff

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_vertex_enum_cutoff() -> None:
    poly = LearnedPolytope(np.eye(5, dtype=np.float64), np.ones(5))
    with pytest.raises(ValueError, match="small-instance"):
        enumerate_vertices(poly)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_vertex_enum_cutoff" -q
Regression example · g1 solver agrees with vertex enum

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_solver_agrees_with_vertex_enum() -> None:
    jax = pytest.importorskip("jax")
    jax.config.update("jax_enable_x64", True)
    from omnibias.convex.jax import solve_lp

    rng = np.random.default_rng(0)
    for _ in range(8):
        poly, c = random_feasible_lp(2, 3, rng)
        _x, v_enum, verts = vertex_optimum(poly, c)
        assert verts.shape[0] >= 1
        sol = solve_lp(c, poly.normals, poly.offsets)
        x_rec = recover_vertex(poly, np.asarray(sol.x))
        v_rec = float(c @ x_rec)
        assert abs(v_rec - v_enum) <= 1e-10
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g1_solver_agrees_with_vertex_enum -q
Read the implementation
def enumerate_vertices(poly: LearnedPolytope, *, atol: float = _VERT_ATOL) -> FloatArray:
    """Vertices of ``A x <= b``. Exponential; raises above the published cutoff."""
    d = poly.dim
    n = poly.n
    if d > VERTEX_ENUM_MAX_D or n > VERTEX_ENUM_MAX_N:
        raise ValueError(
            f"vertex enumeration is a small-instance tool only "
            f"(D<={VERTEX_ENUM_MAX_D}, n<={VERTEX_ENUM_MAX_N}); got D={d}, n={n}"
        )
    if d < 1 or n < d:
        return np.zeros((0, d), dtype=np.float64)
    verts: list[FloatArray] = []
    seen: list[FloatArray] = []
    a = poly.normals
    b = poly.offsets
    for idx in combinations(range(n), d):
        ai = a[list(idx)]
        if abs(float(np.linalg.det(ai))) < 1e-12:
            continue
        x = np.linalg.solve(ai, b[list(idx)])
        if not np.all(a @ x <= b + atol):
            continue
        if any(np.allclose(x, s, atol=1e-8) for s in seen):
            continue
        seen.append(x)
        verts.append(x)
    if not verts:
        return np.zeros((0, d), dtype=np.float64)
    return np.stack(verts, axis=0)
FUNCTION

honesty_payload​

omnibias.convex.arrangement.honesty_payloadSource ↗
honesty_payload() -> dict[str, bool]

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

Returnsdict[str, bool]
Executed regression · linear three verdicts

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_linear_three_verdicts() -> None:
    register_inequality_backend(LinearInequalityBackend())
    proved = InequalitySystem(
        sort="linear",
        existential=True,
        data={"A": [["1"], ["-1"]], "b": ["1", "0"]},
    )
    disproved = InequalitySystem(
        sort="linear",
        existential=True,
        data={"A": [["1"], ["-1"]], "b": ["-1", "-1"]},
    )
    high_a = []
    high_b = []
    for i in range(5):
        pos = ["0"] * 5
        neg = ["0"] * 5
        pos[i] = "1"
        neg[i] = "-1"
        high_a.extend([pos, neg])
        high_b.extend(["-1", "-1"])
    blocked = InequalitySystem(
        sort="linear",
        existential=True,
        data={"A": high_a, "b": high_b},
    )
    assert run_inequality_pipeline(proved)[0] == "PROVED"
    assert run_inequality_pipeline(disproved)[0] == "DISPROVED"
    assert run_inequality_pipeline(blocked)[0] == "BLOCKED"
python -m pytest "packages/omnibias-convex/tests/test_inequality_adapter.py::test_linear_three_verdicts" -q
Read the implementation
def honesty_payload() -> dict[str, bool]:
    return {
        "new_lp_algorithm": False,
        "uncorrected_float_dual": False,
        "vertex_enum_is_exponential": True,
        "selection_is_temperature_collapse": True,
        "founding_bias_collapse_in_selection": False,
    }
FUNCTION

knapsack_simplex​

omnibias.convex.arrangement.knapsack_simplexSource ↗
knapsack_simplex() -> LearnedPolytope

x1 + x2 <= 1, x >= 0 -- the G4 decision polytope.

ReturnsLearnedPolytope
Executed regression · g4 e2e beats two stage

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_g4_e2e_beats_two_stage() -> None:
    poly = knapsack_simplex()
    verts = enumerate_vertices(poly)
    skills: list[float] = []
    for seed in range(5):
        rng = np.random.default_rng(20 + seed)
        zs = rng.choice(np.array([-1.0, 1.0]), size=10)
        true_c = np.stack([-10.0 * zs, 10.0 * zs], axis=1)
        x_star = np.stack([vertex_optimum(poly, c)[0] for c in true_c])
        c_mean = two_stage_constant_predict(true_c)
        x_2s = vertex_optimum(poly, c_mean)[0]
        regret_2s = float(np.mean([predict_then_optimize_regret(c, x_2s, xs) for c, xs in zip(true_c, x_star, strict=True)]))
        w = 0.1
        for _ in range(60):
            grad = 0.0
            for z, c in zip(zs, true_c, strict=True):
                chat = np.array([-w * z, w * z], dtype=np.float64)
                jac = soft_vertex_dx_dc(verts, chat, beta=8.0)
                dchat = np.array([-z, z], dtype=np.float64)
                grad += float(c @ (jac @ dchat))
            w -= 0.15 * grad / float(len(zs))
        x_e2e = []
        for z in zs:
            chat = np.array([-w * z, w * z], dtype=np.float64)
            x_e2e.append(soft_vertex_solution(verts, chat, beta=8.0)[0])
        regret_e2e = float(
            np.mean([predict_then_optimize_regret(c, xh, xs) for c, xh, xs in zip(true_c, x_e2e, x_star, strict=True)])
        )
        skills.append(1.0 - regret_e2e / max(regret_2s, 1e-12))
    assert float(np.mean(skills)) > 0.0
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_g4_e2e_beats_two_stage" -q
Read the implementation
def knapsack_simplex() -> LearnedPolytope:
    """``x1 + x2 <= 1``, ``x >= 0`` -- the G4 decision polytope."""
    a = np.array([[1.0, 1.0], [-1.0, 0.0], [0.0, -1.0]], dtype=np.float64)
    b = np.array([1.0, 0.0, 0.0], dtype=np.float64)
    return LearnedPolytope(a, b)
FUNCTION

known_dual_pentagon​

omnibias.convex.arrangement.known_dual_pentagonSource ↗
known_dual_pentagon() -> FloatArray

y = (0,0,1,0,0): A^T y = -c and -b·y = -3.

ReturnsFloatArray
Executed regression · g5 duality sign convention

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_g5_duality_sign_convention() -> None:
    poly, c, opt = named_pentagon()
    y = known_dual_pentagon()
    assert duality_holds(poly, c, y)
    assert math.isclose(dual_objective(poly, y), opt, abs_tol=1e-12)
    assert math.isclose(float(c @ np.array([1.5, 1.5])), opt, abs_tol=1e-12)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_g5_duality_sign_convention" -q
Regression example · g3 degeneracy soft gradient

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_degeneracy_soft_gradient() -> None:
    poly, c, opt = named_pentagon()
    x_star, value, verts = vertex_optimum(poly, c)
    assert math.isclose(value, opt, abs_tol=1e-10)
    assert is_degenerate_optimum(verts, c, value)
    out = solve_arrangement_lp(poly, c, mode=DiffMode.SOFT, beta=6.0)
    assert out.degenerate is True and out.feasible is True
    y = known_dual_pentagon()
    kkt = kkt_matrix(poly, np.array([1.5, 1.5]), y)
    assert kkt_gradient_usable(kkt) is False
    jac = soft_vertex_dx_dc(verts, c, beta=6.0)
    assert np.all(np.isfinite(jac))
    assert float(np.linalg.norm(jac)) > 1e-6
    xs, _w, _vs = soft_vertex_solution(verts, c, beta=6.0)
    np.testing.assert_allclose(xs, np.array([1.5, 1.5]), atol=0.05)
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g3_degeneracy_soft_gradient -q
Read the implementation
def known_dual_pentagon() -> FloatArray:
    """``y = (0,0,1,0,0)``: ``A^T y = -c`` and ``-b·y = -3``."""
    return np.array([0.0, 0.0, 1.0, 0.0, 0.0], dtype=np.float64)
FUNCTION

named_pentagon​

omnibias.convex.arrangement.named_pentagonSource ↗
named_pentagon() -> tuple[LearnedPolytope, FloatArray, float]

Spec §5: min -x-y over the pentagon, optimum value -3.

Returnstuple[LearnedPolytope, FloatArray, float]
Executed regression · infer box pentagon

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_infer_box_pentagon() -> None:
    poly, _c, _opt = named_pentagon()
    lo, hi = infer_box(poly)
    np.testing.assert_allclose(lo, [0.0, 0.0])
    np.testing.assert_allclose(hi, [2.0, 2.0])
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_infer_box_pentagon" -q
Regression example · g5 duality sign convention

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_g5_duality_sign_convention() -> None:
    poly, c, opt = named_pentagon()
    y = known_dual_pentagon()
    assert duality_holds(poly, c, y)
    assert math.isclose(dual_objective(poly, y), opt, abs_tol=1e-12)
    assert math.isclose(float(c @ np.array([1.5, 1.5])), opt, abs_tol=1e-12)
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g5_duality_sign_convention -q
Read the implementation
def named_pentagon() -> tuple[LearnedPolytope, FloatArray, float]:
    """Spec §5: ``min -x-y`` over the pentagon, optimum value ``-3``."""
    a = np.array(
        [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [-1.0, 0.0], [0.0, -1.0]],
        dtype=np.float64,
    )
    b = np.array([2.0, 2.0, 3.0, 0.0, 0.0], dtype=np.float64)
    c = np.array([-1.0, -1.0], dtype=np.float64)
    return LearnedPolytope(a, b), c, -3.0
Other public import paths
  • omnibias.convex.arrangement.named_pentagon
  • omnibias.convex.arrangement.jax.named_pentagon
  • omnibias.convex.arrangement.torch.named_pentagon
FUNCTION

random_feasible_lp​

omnibias.convex.arrangement.random_feasible_lpSource ↗
random_feasible_lp(dim: int, n_extra: int, rng: Generator, *, unique_c: bool=True) -> tuple[LearnedPolytope, FloatArray]

Bounded feasible LP: random halfspaces plus a box. 0 is strictly feasible.

Parameters

NameType & defaultContract
dimpositional-or-keywordintRequiredSee the operation contract and implementation below.
n_extrapositional-or-keywordintRequiredSee the operation contract and implementation below.
rngpositional-or-keywordGeneratorRequiredSee the operation contract and implementation below.
unique_ckeyword-onlyboolDefault: TrueSee the operation contract and implementation below.
Returnstuple[LearnedPolytope, FloatArray]
Executed regression · g1 solver agrees with vertex enum

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_solver_agrees_with_vertex_enum() -> None:
    jax = pytest.importorskip("jax")
    jax.config.update("jax_enable_x64", True)
    from omnibias.convex.jax import solve_lp

    rng = np.random.default_rng(0)
    for _ in range(8):
        poly, c = random_feasible_lp(2, 3, rng)
        _x, v_enum, verts = vertex_optimum(poly, c)
        assert verts.shape[0] >= 1
        sol = solve_lp(c, poly.normals, poly.offsets)
        x_rec = recover_vertex(poly, np.asarray(sol.x))
        v_rec = float(c @ x_rec)
        assert abs(v_rec - v_enum) <= 1e-10
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_g1_solver_agrees_with_vertex_enum" -q
Regression example · g2 sound bound never exceeds opt

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_sound_bound_never_exceeds_opt() -> None:
    rng = np.random.default_rng(1)
    instances: list[tuple[LearnedPolytope, np.ndarray]] = [named_pentagon()[:2]]
    for _ in range(6):
        instances.append(random_feasible_lp(2, 4, rng))
    # Ill-conditioned: two nearly parallel facets.
    a = np.array(
        [[1.0, 0.0], [1.0, 1e-8], [0.0, 1.0], [-1.0, 0.0], [0.0, -1.0]],
        dtype=np.float64,
    )
    b = np.array([1.0, 1.0, 1.0, 0.0, 0.0], dtype=np.float64)
    instances.append((LearnedPolytope(a, b), np.array([-1.0, -0.2])))
    for poly, c in instances:
        _x, opt, verts = vertex_optimum(poly, c)
        if verts.shape[0] == 0:
            continue
        out = solve_arrangement_lp(poly, c)
        assert out.lower_bound <= opt + 1e-9
        y = np.zeros(poly.n)
        lo = sound_lower_bound(poly, c, y)
        assert lo <= opt + 1e-9
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g2_sound_bound_never_exceeds_opt -q
Read the implementation
def random_feasible_lp(
    dim: int,
    n_extra: int,
    rng: Generator,
    *,
    unique_c: bool = True,
) -> tuple[LearnedPolytope, FloatArray]:
    """Bounded feasible LP: random halfspaces plus a box. ``0`` is strictly feasible."""
    extra = max(int(n_extra), 0)
    g = rng.normal(size=(extra, dim))
    norms = np.linalg.norm(g, axis=1, keepdims=True)
    g = g / np.maximum(norms, 1e-12)
    b_extra = rng.uniform(0.8, 2.5, size=extra)
    box_a = np.vstack([np.eye(dim), -np.eye(dim)])
    box_b = np.concatenate([np.full(dim, 2.0), np.zeros(dim)])
    if extra:
        a = np.vstack([g, box_a])
        b = np.concatenate([b_extra, box_b])
    else:
        a = box_a
        b = box_b
    c = rng.normal(size=dim)
    if unique_c:
        c = c + 0.15 * np.arange(1, dim + 1, dtype=np.float64)
    return LearnedPolytope(a.astype(np.float64), b.astype(np.float64)), c.astype(np.float64)
FUNCTION

recover_vertex​

omnibias.convex.arrangement.recover_vertexSource ↗
recover_vertex(poly: LearnedPolytope, x: object) -> FloatArray

Active-set crossover: solve the D tightest residuals for a vertex.

Parameters

NameType & defaultContract
polypositional-or-keywordLearnedPolytopeRequiredSee the operation contract and implementation below.
xpositional-or-keywordobjectRequiredSee the operation contract and implementation below.
ReturnsFloatArray
Executed regression · g1 solver agrees with vertex enum

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_solver_agrees_with_vertex_enum() -> None:
    jax = pytest.importorskip("jax")
    jax.config.update("jax_enable_x64", True)
    from omnibias.convex.jax import solve_lp

    rng = np.random.default_rng(0)
    for _ in range(8):
        poly, c = random_feasible_lp(2, 3, rng)
        _x, v_enum, verts = vertex_optimum(poly, c)
        assert verts.shape[0] >= 1
        sol = solve_lp(c, poly.normals, poly.offsets)
        x_rec = recover_vertex(poly, np.asarray(sol.x))
        v_rec = float(c @ x_rec)
        assert abs(v_rec - v_enum) <= 1e-10
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_g1_solver_agrees_with_vertex_enum" -q
Read the implementation
def recover_vertex(poly: LearnedPolytope, x: object) -> FloatArray:
    """Active-set crossover: solve the ``D`` tightest residuals for a vertex."""
    d = poly.dim
    res = np.abs(poly.residual(x))
    order = np.argsort(res)
    for extra in range(0, min(4, poly.n - d + 1)):
        idx = order[: d + extra]
        for combo in combinations(idx.tolist(), d):
            ai = poly.normals[list(combo)]
            if abs(float(np.linalg.det(ai))) < 1e-10:
                continue
            xv = np.linalg.solve(ai, poly.offsets[list(combo)])
            if np.all(poly.normals @ xv <= poly.offsets + 1e-6):
                return xv.astype(np.float64, copy=False)
    return np.asarray(x, dtype=np.float64).reshape(-1)
FUNCTION

soft_cell_gap_bound​

omnibias.convex.arrangement.soft_cell_gap_boundSource ↗
soft_cell_gap_bound(*, n_facets: int, beta: float) -> float

log(n)/beta, the same Gibbs scale certify_partition_gap reports.

Parameters

NameType & defaultContract
n_facetskeyword-onlyintRequiredSee the operation contract and implementation below.
betakeyword-onlyfloatRequiredSee the operation contract and implementation below.
Returnsfloat
Explicit validation & failure cases
  • When int(n_facets) < 1, raises ValueError('n_facets must be >= 1').
  • When float(beta) <= 0.0, raises ValueError('beta must be > 0').

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

Executed regression · worked example soft membership

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_worked_example_soft_membership() -> None:
    poly, _c, _opt = named_pentagon()
    w = float(soft_membership(poly, np.array([1.5, 1.5]), beta=5.0))
    assert math.isclose(w, 0.4265470, rel_tol=0.0, abs_tol=2e-6)
    assert math.isclose(soft_cell_gap_bound(n_facets=5, beta=5.0), math.log(5.0) / 5.0)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_worked_example_soft_membership" -q
Read the implementation
def soft_cell_gap_bound(*, n_facets: int, beta: float) -> float:
    """``log(n)/beta``, the same Gibbs scale ``certify_partition_gap`` reports."""
    if int(n_facets) < 1:
        raise ValueError("n_facets must be >= 1")
    if float(beta) <= 0.0:
        raise ValueError("beta must be > 0")
    return math.log(int(n_facets)) / float(beta)
Other public import paths
  • omnibias.convex.arrangement.soft_cell_gap_bound
  • omnibias.convex.arrangement.jax.soft_cell_gap_bound
  • omnibias.convex.arrangement.torch.soft_cell_gap_bound
FUNCTION

soft_membership​

omnibias.convex.arrangement.soft_membershipSource ↗
soft_membership(poly: LearnedPolytope, x: object, *, beta: float) -> FloatArray

Soft feasible-cell weight prod_i sigma(beta (b_i - a_i · x)).

Parameters

NameType & defaultContract
polypositional-or-keywordLearnedPolytopeRequiredSee the operation contract and implementation below.
xpositional-or-keywordobjectRequiredSee the operation contract and implementation below.
betakeyword-onlyfloatRequiredSee the operation contract and implementation below.
ReturnsFloatArray
Explicit validation & failure cases
  • When float(beta) <= 0.0, raises ValueError('beta must be > 0 (temperature collapse axis)').

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

Executed regression · worked example soft membership

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_worked_example_soft_membership() -> None:
    poly, _c, _opt = named_pentagon()
    w = float(soft_membership(poly, np.array([1.5, 1.5]), beta=5.0))
    assert math.isclose(w, 0.4265470, rel_tol=0.0, abs_tol=2e-6)
    assert math.isclose(soft_cell_gap_bound(n_facets=5, beta=5.0), math.log(5.0) / 5.0)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_worked_example_soft_membership" -q
Regression example · g6 soft membership parity

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_soft_membership_parity() -> None:
    poly, _c, _opt = named_pentagon()
    x = np.array([1.5, 1.5], dtype=np.float64)
    ref = float(soft_membership(poly, x, beta=5.0))
    torch = pytest.importorskip("torch")
    tw = __import__("omnibias.convex.arrangement.torch", fromlist=["soft_membership"]).soft_membership
    got_t = float(tw(torch.as_tensor(poly.normals), torch.as_tensor(poly.offsets), torch.as_tensor(x), beta=5.0))
    assert math.isclose(got_t, ref, rel_tol=0.0, abs_tol=1e-15)
    jax = pytest.importorskip("jax")
    jax.config.update("jax_enable_x64", True)
    jw = __import__("omnibias.convex.arrangement.jax", fromlist=["soft_membership"]).soft_membership
    got_j = float(np.asarray(jw(poly.normals, poly.offsets, x, beta=5.0)))
    assert math.isclose(got_j, ref, rel_tol=0.0, abs_tol=2e-15)
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g6_soft_membership_parity -q
Read the implementation
def soft_membership(poly: LearnedPolytope, x: object, *, beta: float) -> FloatArray:
    """Soft feasible-cell weight ``prod_i sigma(beta (b_i - a_i · x))``."""
    if float(beta) <= 0.0:
        raise ValueError("beta must be > 0 (temperature collapse axis)")
    slack = -poly.residual(x)
    w = _sigmoid(float(beta) * slack)
    if w.ndim == 1:
        return np.asarray(np.prod(w), dtype=np.float64)
    return np.prod(w, axis=-1).astype(np.float64, copy=False)
FUNCTION

soft_vertex_dx_dc​

omnibias.convex.arrangement.soft_vertex_dx_dcSource ↗
soft_vertex_dx_dc(verts: FloatArray, c: object, *, beta: float) -> FloatArray

Jacobian dx/dc of the softmax vertex mixture. Finite when KKT is not.

Parameters

NameType & defaultContract
vertspositional-or-keywordFloatArrayRequiredSee the operation contract and implementation below.
cpositional-or-keywordobjectRequiredSee the operation contract and implementation below.
betakeyword-onlyfloatRequiredSee the operation contract and implementation below.
ReturnsFloatArray
Executed regression · g3 degeneracy soft gradient

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_degeneracy_soft_gradient() -> None:
    poly, c, opt = named_pentagon()
    x_star, value, verts = vertex_optimum(poly, c)
    assert math.isclose(value, opt, abs_tol=1e-10)
    assert is_degenerate_optimum(verts, c, value)
    out = solve_arrangement_lp(poly, c, mode=DiffMode.SOFT, beta=6.0)
    assert out.degenerate is True and out.feasible is True
    y = known_dual_pentagon()
    kkt = kkt_matrix(poly, np.array([1.5, 1.5]), y)
    assert kkt_gradient_usable(kkt) is False
    jac = soft_vertex_dx_dc(verts, c, beta=6.0)
    assert np.all(np.isfinite(jac))
    assert float(np.linalg.norm(jac)) > 1e-6
    xs, _w, _vs = soft_vertex_solution(verts, c, beta=6.0)
    np.testing.assert_allclose(xs, np.array([1.5, 1.5]), atol=0.05)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_g3_degeneracy_soft_gradient" -q
Regression example · g4 e2e beats two stage

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_g4_e2e_beats_two_stage() -> None:
    poly = knapsack_simplex()
    verts = enumerate_vertices(poly)
    skills: list[float] = []
    for seed in range(5):
        rng = np.random.default_rng(20 + seed)
        zs = rng.choice(np.array([-1.0, 1.0]), size=10)
        true_c = np.stack([-10.0 * zs, 10.0 * zs], axis=1)
        x_star = np.stack([vertex_optimum(poly, c)[0] for c in true_c])
        c_mean = two_stage_constant_predict(true_c)
        x_2s = vertex_optimum(poly, c_mean)[0]
        regret_2s = float(np.mean([predict_then_optimize_regret(c, x_2s, xs) for c, xs in zip(true_c, x_star, strict=True)]))
        w = 0.1
        for _ in range(60):
            grad = 0.0
            for z, c in zip(zs, true_c, strict=True):
                chat = np.array([-w * z, w * z], dtype=np.float64)
                jac = soft_vertex_dx_dc(verts, chat, beta=8.0)
                dchat = np.array([-z, z], dtype=np.float64)
                grad += float(c @ (jac @ dchat))
            w -= 0.15 * grad / float(len(zs))
        x_e2e = []
        for z in zs:
            chat = np.array([-w * z, w * z], dtype=np.float64)
            x_e2e.append(soft_vertex_solution(verts, chat, beta=8.0)[0])
        regret_e2e = float(
            np.mean([predict_then_optimize_regret(c, xh, xs) for c, xh, xs in zip(true_c, x_e2e, x_star, strict=True)])
        )
        skills.append(1.0 - regret_e2e / max(regret_2s, 1e-12))
    assert float(np.mean(skills)) > 0.0
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g4_e2e_beats_two_stage -q
Read the implementation
def soft_vertex_dx_dc(verts: FloatArray, c: object, *, beta: float) -> FloatArray:
    """Jacobian ``dx/dc`` of the softmax vertex mixture. Finite when KKT is not."""
    cv = np.asarray(c, dtype=np.float64).reshape(-1)
    vals = verts @ cv
    w = softmax_neg(vals, beta=beta)
    x = w @ verts
    # d w_i / d c = -beta w_i (v_i - x)
    # dx/dc = sum_i v_i (dw_i/dc)^T = -beta sum_i w_i (v_i - x) v_i^T
    centered = verts - x[None, :]
    jac = -float(beta) * ((w[:, None] * centered).T @ verts)
    return jac.astype(np.float64, copy=False)
FUNCTION

solve_arrangement_lp​

omnibias.convex.arrangement.solve_arrangement_lpSource ↗
solve_arrangement_lp(poly: LearnedPolytope, c: object, *, mode: DiffMode=DiffMode.KKT, beta: float=8.0, dual: object | None=None) -> LPOutput

Exact vertex solve (small instances) plus a sound NS lower bound.

Parameters

NameType & defaultContract
polypositional-or-keywordLearnedPolytopeRequiredSee the operation contract and implementation below.
cpositional-or-keywordobjectRequiredSee the operation contract and implementation below.
modekeyword-onlyDiffModeDefault: DiffMode.KKTSee the operation contract and implementation below.
betakeyword-onlyfloatDefault: 8.0See the operation contract and implementation below.
dualkeyword-onlyobject | NoneDefault: NoneSee the operation contract and implementation below.
ReturnsLPOutput
Executed regression · infeasible is reported

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_infeasible_is_reported() -> None:
    poly = LearnedPolytope(
        np.array([[1.0], [-1.0]], dtype=np.float64),
        np.array([-1.0, 0.0], dtype=np.float64),
    )
    out = solve_arrangement_lp(poly, np.array([1.0]))
    assert out.feasible is False
    assert math.isinf(out.value)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_infeasible_is_reported" -q
Regression example · g3 degeneracy soft gradient

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_degeneracy_soft_gradient() -> None:
    poly, c, opt = named_pentagon()
    x_star, value, verts = vertex_optimum(poly, c)
    assert math.isclose(value, opt, abs_tol=1e-10)
    assert is_degenerate_optimum(verts, c, value)
    out = solve_arrangement_lp(poly, c, mode=DiffMode.SOFT, beta=6.0)
    assert out.degenerate is True and out.feasible is True
    y = known_dual_pentagon()
    kkt = kkt_matrix(poly, np.array([1.5, 1.5]), y)
    assert kkt_gradient_usable(kkt) is False
    jac = soft_vertex_dx_dc(verts, c, beta=6.0)
    assert np.all(np.isfinite(jac))
    assert float(np.linalg.norm(jac)) > 1e-6
    xs, _w, _vs = soft_vertex_solution(verts, c, beta=6.0)
    np.testing.assert_allclose(xs, np.array([1.5, 1.5]), atol=0.05)
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g3_degeneracy_soft_gradient -q
Read the implementation
def solve_arrangement_lp(
    poly: LearnedPolytope,
    c: object,
    *,
    mode: DiffMode = DiffMode.KKT,
    beta: float = 8.0,
    dual: object | None = None,
) -> LPOutput:
    """Exact vertex solve (small instances) plus a sound NS lower bound."""
    cv = np.asarray(c, dtype=np.float64).reshape(-1)
    x_star, value, verts = vertex_optimum(poly, cv)
    feasible = verts.shape[0] > 0 and math.isfinite(value)
    if not feasible:
        lo, hi = infer_box(poly)
        if np.any(lo > hi):
            return LPOutput(
                x=np.full(poly.dim, np.nan),
                value=float("inf"),
                lower_bound=float("-inf"),
                active_set=(),
                degenerate=False,
                mode=mode,
                feasible=False,
                n_vertices=0,
            )
        return LPOutput(
            x=np.full(poly.dim, np.nan),
            value=float("inf"),
            lower_bound=sound_lower_bound(poly, cv, np.zeros(poly.n), x_lower=lo, x_upper=hi),
            active_set=(),
            degenerate=False,
            mode=mode,
            feasible=False,
            n_vertices=0,
        )
    degenerate = is_degenerate_optimum(verts, cv, value)
    if mode is DiffMode.SOFT:
        x_out, _w, value_soft = soft_vertex_solution(verts, cv, beta=beta)
        value_rep = value_soft
        x_rep = x_out
    else:
        x_rep = x_star
        value_rep = value
    y = np.asarray(dual, dtype=np.float64).reshape(-1) if dual is not None else _vertex_dual(poly, x_star, cv)
    lower = sound_lower_bound(poly, cv, y)
    return LPOutput(
        x=x_rep,
        value=float(value_rep),
        lower_bound=lower,
        active_set=active_set(poly, x_star),
        degenerate=degenerate,
        mode=mode,
        feasible=True,
        n_vertices=int(verts.shape[0]),
    )
Other public import paths
  • omnibias.convex.arrangement.solve_arrangement_lp
  • omnibias.convex.arrangement.jax.solve_arrangement_lp
  • omnibias.convex.arrangement.torch.solve_arrangement_lp
FUNCTION

sound_lower_bound​

omnibias.convex.arrangement.sound_lower_boundSource ↗
sound_lower_bound(poly: LearnedPolytope, c: object, dual: object, *, x_lower: object | None=None, x_upper: object | None=None) -> float

Neumaier-Shcherbina lo only. No uncorrected float dual is offered.

Parameters

NameType & defaultContract
polypositional-or-keywordLearnedPolytopeRequiredSee the operation contract and implementation below.
cpositional-or-keywordobjectRequiredSee the operation contract and implementation below.
dualpositional-or-keywordobjectRequiredSee the operation contract and implementation below.
x_lowerkeyword-onlyobject | NoneDefault: NoneSee the operation contract and implementation below.
x_upperkeyword-onlyobject | NoneDefault: NoneSee the operation contract and implementation below.
Returnsfloat
Executed regression · g3 degeneracy soft gradient

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_degeneracy_soft_gradient() -> None:
    poly, c, opt = named_pentagon()
    x_star, value, verts = vertex_optimum(poly, c)
    assert math.isclose(value, opt, abs_tol=1e-10)
    assert is_degenerate_optimum(verts, c, value)
    out = solve_arrangement_lp(poly, c, mode=DiffMode.SOFT, beta=6.0)
    assert out.degenerate is True and out.feasible is True
    y = known_dual_pentagon()
    kkt = kkt_matrix(poly, np.array([1.5, 1.5]), y)
    assert kkt_gradient_usable(kkt) is False
    jac = soft_vertex_dx_dc(verts, c, beta=6.0)
    assert np.all(np.isfinite(jac))
    assert float(np.linalg.norm(jac)) > 1e-6
    xs, _w, _vs = soft_vertex_solution(verts, c, beta=6.0)
    np.testing.assert_allclose(xs, np.array([1.5, 1.5]), atol=0.05)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_g3_degeneracy_soft_gradient" -q
Regression example · infer box pentagon

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_infer_box_pentagon() -> None:
    poly, _c, _opt = named_pentagon()
    lo, hi = infer_box(poly)
    np.testing.assert_allclose(lo, [0.0, 0.0])
    np.testing.assert_allclose(hi, [2.0, 2.0])
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_infer_box_pentagon -q
Read the implementation
def sound_lower_bound(
    poly: LearnedPolytope,
    c: object,
    dual: object,
    *,
    x_lower: object | None = None,
    x_upper: object | None = None,
) -> float:
    """Neumaier-Shcherbina ``lo`` only. No uncorrected float dual is offered."""
    if x_lower is None or x_upper is None:
        x_lower, x_upper = infer_box(poly)
    iv = lp_dual_lower_bound(
        np.asarray(c, dtype=float),
        poly.normals,
        poly.offsets,
        dual,
        x_lower=x_lower,
        x_upper=x_upper,
    )
    return float(iv.lo)
Other public import paths
  • omnibias.convex.arrangement.sound_lower_bound
  • omnibias.convex.arrangement.jax.sound_lower_bound
  • omnibias.convex.arrangement.torch.sound_lower_bound
FUNCTION

vertex_optimum​

omnibias.convex.arrangement.vertex_optimumSource ↗
vertex_optimum(poly: LearnedPolytope, c: object) -> tuple[FloatArray, float, FloatArray]

Exact min of c·x over enumerated vertices. Empty => infeasible/unbounded.

Parameters

NameType & defaultContract
polypositional-or-keywordLearnedPolytopeRequiredSee the operation contract and implementation below.
cpositional-or-keywordobjectRequiredSee the operation contract and implementation below.
Returnstuple[FloatArray, float, FloatArray]
Executed regression · infeasible is reported

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_infeasible_is_reported() -> None:
    poly = LearnedPolytope(
        np.array([[1.0], [-1.0]], dtype=np.float64),
        np.array([-1.0, 0.0], dtype=np.float64),
    )
    out = solve_arrangement_lp(poly, np.array([1.0]))
    assert out.feasible is False
    assert math.isinf(out.value)
python -m pytest "packages/omnibias-convex/tests/test_arrangement_lp.py::test_infeasible_is_reported" -q
Regression example · g1 solver agrees with vertex enum

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_solver_agrees_with_vertex_enum() -> None:
    jax = pytest.importorskip("jax")
    jax.config.update("jax_enable_x64", True)
    from omnibias.convex.jax import solve_lp

    rng = np.random.default_rng(0)
    for _ in range(8):
        poly, c = random_feasible_lp(2, 3, rng)
        _x, v_enum, verts = vertex_optimum(poly, c)
        assert verts.shape[0] >= 1
        sol = solve_lp(c, poly.normals, poly.offsets)
        x_rec = recover_vertex(poly, np.asarray(sol.x))
        v_rec = float(c @ x_rec)
        assert abs(v_rec - v_enum) <= 1e-10
python -m pytest packages/omnibias-convex/tests/test_arrangement_lp.py -k test_g1_solver_agrees_with_vertex_enum -q
Read the implementation
def vertex_optimum(poly: LearnedPolytope, c: object) -> tuple[FloatArray, float, FloatArray]:
    """Exact min of ``c·x`` over enumerated vertices. Empty => infeasible/unbounded."""
    verts = enumerate_vertices(poly)
    cv = np.asarray(c, dtype=np.float64).reshape(-1)
    if verts.shape[0] == 0:
        return np.zeros(poly.dim, dtype=np.float64), float("inf"), verts
    vals = verts @ cv
    k = int(np.argmin(vals))
    return verts[k].copy(), float(vals[k]), verts