Skip to main content

omnibias.core.locus

0.5.0rc1Release candidatePython >=3.10Apache-2.0

Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.

import omnibias.core.locus
Module contract & mathematical conventions

Equality-locus geometry (theory 01-09).

Forcing collapsed units to agree, f_i(x) = f_j(x), cuts out a codimension-m constraint manifold whose Jacobian and Hessian the derivative tower supplies in closed form. Newton projection needs no autodiff; existence on a box is the Krawczyk test already in omnibias.core.verified.kantorovich.

The units are founding bias collapse (delta -> 0). There is no temperature collapse here. An equality locus is a **constraint manifold**, not a PDE solution -- that step is spec 02-12.

Pure Python: no tensor imports.

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

AffineSet​

omnibias.core.AffineSetSource ↗
class AffineSet

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.

Hyperplane normal . x + offset = 0 on an order-matched branch.

Parameters

NameType & defaultContract
normaldataclass fieldtuple[float, ...]RequiredSee the operation contract and implementation below.
offsetdataclass fieldfloatRequiredSee the operation contract and implementation below.
branchdataclass fieldintRequiredSee the operation contract and implementation below.

Fields & methods

normalfield
normal: tuple[float, ...]

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

View source ↗
offsetfield
offset: float

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

View source ↗
branchfield
branch: int

+1 identity z_i = z_j; -1 mirror z_i = -z_j

View source ↗
Read the implementation
class AffineSet:
    """Hyperplane ``normal . x + offset = 0`` on an order-matched branch."""

    normal: tuple[float, ...]
    offset: float
    branch: int  # +1 identity z_i = z_j; -1 mirror z_i = -z_j
Other public import paths
  • omnibias.core.AffineSet
  • omnibias.fields.AffineSet
  • omnibias.core.locus.AffineSet
  • omnibias.fields.locus.AffineSet
CLASS

EqualitySystem​

omnibias.core.EqualitySystemSource ↗
class EqualitySystem

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.

m + 1 units yield the residual map F : R^D -> R^m.

Parameters

NameType & defaultContract
termsdataclass fieldtuple[UnitTerm, ...]RequiredSee the operation contract and implementation below.
basedataclass fieldstrDefault: 'tanh'See the operation contract and implementation below.
Executed regression · mismatched is not affine

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_mismatched_is_not_affine() -> None:
    assert affine_locus(_case_b()) is None
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_mismatched_is_not_affine" -q
Regression example · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest packages/omnibias-core/tests/test_locus.py -k test_g3_quadratic_rate_case_b -q

Fields & methods

termsfield
terms: tuple[UnitTerm, ...]

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

View source ↗
basefield
base: str = 'tanh'

Declared str field on EqualitySystem. Default expression: 'tanh'.

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 len(self.terms) < 2, raises ValueError('EqualitySystem needs at least two units').
  • When any((len(t.normal) != dim for t in self.terms)), raises ValueError('all unit normals must share a dimension').
  • When name not in _SUPPORTED_BASES, raises ValueError(f'unsupported locus base {self.base!r}; expected one of {sorted(_SUPPORTED_BASES)}').
Executed regression · mismatched is not affine

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_mismatched_is_not_affine() -> None:
    assert affine_locus(_case_b()) is None
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_mismatched_is_not_affine" -q
Method implementation
    def __post_init__(self) -> None:
        if len(self.terms) < 2:
            raise ValueError("EqualitySystem needs at least two units")
        dim = len(self.terms[0].normal)
        if any(len(t.normal) != dim for t in self.terms):
            raise ValueError("all unit normals must share a dimension")
        name = str(self.base).lower().strip()
        if name not in _SUPPORTED_BASES:
            raise ValueError(
                f"unsupported locus base {self.base!r}; "
                f"expected one of {sorted(_SUPPORTED_BASES)}"
            )
        object.__setattr__(self, "base", name)
View source ↗
dimproperty
dim(self) -> int

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

Returns: int

Executed regression · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g3_quadratic_rate_case_b" -q
Method implementation
    def dim(self) -> int:
        return len(self.terms[0].normal)
View source ↗
n_termsproperty
n_terms(self) -> int

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

Returns: int

Executed regression · g1 forward residual

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_forward_residual() -> None:
    torch.set_default_dtype(torch.float64)
    sys = _matched()
    layer = EqualityLocusLayer(sys, dtype=torch.float64)
    x0 = torch.tensor([0.4, -0.1], dtype=torch.float64)
    out = layer(x0)
    assert bool(out.converged.detach())
    nrm = abs(residual(sys, tuple(float(v) for v in out.point.detach().tolist()))[0])
    assert nrm <= 1e-12
    assert out.branch.numel() >= 1
    assert float(out.condition.detach()) >= 1.0
python -m pytest "packages/omnibias-fields/tests/test_locus_layer.py::test_g1_forward_residual" -q
Method implementation
    def n_terms(self) -> int:
        return len(self.terms)
View source ↗
codimensionproperty
codimension(self) -> int

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

Returns: int

Executed regression · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g3_quadratic_rate_case_b" -q
Method implementation
    def codimension(self) -> int:
        return len(self.terms) - 1
View source ↗
Read the implementation
class EqualitySystem:
    """``m + 1`` units yield the residual map ``F : R^D -> R^m``."""

    terms: tuple[UnitTerm, ...]
    base: str = "tanh"

    def __post_init__(self) -> None:
        if len(self.terms) < 2:
            raise ValueError("EqualitySystem needs at least two units")
        dim = len(self.terms[0].normal)
        if any(len(t.normal) != dim for t in self.terms):
            raise ValueError("all unit normals must share a dimension")
        name = str(self.base).lower().strip()
        if name not in _SUPPORTED_BASES:
            raise ValueError(
                f"unsupported locus base {self.base!r}; "
                f"expected one of {sorted(_SUPPORTED_BASES)}"
            )
        object.__setattr__(self, "base", name)

    @property
    def dim(self) -> int:
        return len(self.terms[0].normal)

    @property
    def n_terms(self) -> int:
        return len(self.terms)

    @property
    def codimension(self) -> int:
        return len(self.terms) - 1
Other public import paths
  • omnibias.core.EqualitySystem
  • omnibias.fields.EqualitySystem
  • omnibias.core.locus.EqualitySystem
  • omnibias.fields.locus.EqualitySystem
CLASS

NewtonResult​

omnibias.core.NewtonResultSource ↗
class NewtonResult

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.

Gauss-Newton projection onto the locus.

Parameters

NameType & defaultContract
pointdataclass fieldtuple[float, ...]RequiredSee the operation contract and implementation below.
residual_normdataclass fieldfloatRequiredSee the operation contract and implementation below.
iterationsdataclass fieldintRequiredSee the operation contract and implementation below.
convergeddataclass fieldboolRequiredSee the operation contract and implementation below.
conditiondataclass fieldfloatRequiredSee the operation contract and implementation below.
branchdataclass fieldtuple[int, ...]RequiredSee the operation contract and implementation below.
transversaldataclass fieldboolRequiredSee the operation contract and implementation below.

Fields & methods

pointfield
point: tuple[float, ...]

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

View source ↗
residual_normfield
residual_norm: float

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

View source ↗
iterationsfield
iterations: int

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

View source ↗
convergedfield
converged: bool

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

View source ↗
conditionfield
condition: float

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

View source ↗
branchfield
branch: tuple[int, ...]

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

View source ↗
transversalfield
transversal: bool

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

View source ↗
Read the implementation
class NewtonResult:
    """Gauss-Newton projection onto the locus."""

    point: tuple[float, ...]
    residual_norm: float
    iterations: int
    converged: bool
    condition: float
    branch: tuple[int, ...]
    transversal: bool
Other public import paths
  • omnibias.core.NewtonResult
  • omnibias.fields.NewtonResult
  • omnibias.core.locus.NewtonResult
  • omnibias.fields.locus.NewtonResult
CLASS

UnitTerm​

omnibias.core.UnitTermSource ↗
class UnitTerm

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.

One collapsed unit f(x) = c * sigma^(n)(w . x + b).

Parameters

NameType & defaultContract
orderdataclass fieldintRequiredSee the operation contract and implementation below.
weightdataclass fieldfloatRequiredSee the operation contract and implementation below.
normaldataclass fieldtuple[float, ...]RequiredSee the operation contract and implementation below.
biasdataclass fieldfloatDefault: 0.0See the operation contract and implementation below.
Executed regression · mismatched is not affine

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_mismatched_is_not_affine() -> None:
    assert affine_locus(_case_b()) is None
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_mismatched_is_not_affine" -q
Regression example · g3 degeneracy refusal

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_refusal() -> None:
    torch.set_default_dtype(torch.float64)
    sys = EqualitySystem(
        (
            UnitTerm(1, 1.0, (1.0, 0.0), 0.0),
            UnitTerm(1, 1.0, (1.0, 0.0), 0.0),
        )
    )
    layer = EqualityLocusLayer(sys, require_transversal=True, dtype=torch.float64)
    out = layer(torch.tensor([0.2, 0.3], dtype=torch.float64))
    assert bool(out.converged.detach()) is False
    assert float(out.condition.detach()) > 1e6
python -m pytest packages/omnibias-fields/tests/test_locus_layer.py -k test_g3_degeneracy_refusal -q

Fields & methods

orderfield
order: int

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

View source ↗
weightfield
weight: float

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

View source ↗
normalfield
normal: tuple[float, ...]

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

View source ↗
biasfield
bias: float = 0.0

Declared float field on UnitTerm. Default expression: 0.0.

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 self.order < 0, raises ValueError(f'order must be >= 0, got {self.order}').
  • When not self.normal, raises ValueError('normal must be non-empty').
  • When not all((math.isfinite(v) for v in self.normal)), raises ValueError('normal must be finite').
  • When not math.isfinite(self.weight) or not math.isfinite(self.bias), raises ValueError('weight and bias must be finite').
Executed regression · mismatched is not affine

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_mismatched_is_not_affine() -> None:
    assert affine_locus(_case_b()) is None
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_mismatched_is_not_affine" -q
Method implementation
    def __post_init__(self) -> None:
        if self.order < 0:
            raise ValueError(f"order must be >= 0, got {self.order}")
        if not self.normal:
            raise ValueError("normal must be non-empty")
        if not all(math.isfinite(v) for v in self.normal):
            raise ValueError("normal must be finite")
        if not math.isfinite(self.weight) or not math.isfinite(self.bias):
            raise ValueError("weight and bias must be finite")
View source ↗
Read the implementation
class UnitTerm:
    """One collapsed unit ``f(x) = c * sigma^(n)(w . x + b)``."""

    order: int
    weight: float
    normal: tuple[float, ...]
    bias: float = 0.0

    def __post_init__(self) -> None:
        if self.order < 0:
            raise ValueError(f"order must be >= 0, got {self.order}")
        if not self.normal:
            raise ValueError("normal must be non-empty")
        if not all(math.isfinite(v) for v in self.normal):
            raise ValueError("normal must be finite")
        if not math.isfinite(self.weight) or not math.isfinite(self.bias):
            raise ValueError("weight and bias must be finite")
Other public import paths
  • omnibias.core.UnitTerm
  • omnibias.fields.UnitTerm
  • omnibias.core.locus.UnitTerm
  • omnibias.fields.locus.UnitTerm
FUNCTION

affine_locus​

omnibias.core.affine_locusSource ↗
affine_locus(sys: EqualitySystem) -> tuple[AffineSet, ...] | None

Exact hyperplanes when every consecutive pair is order-matched with equal c.

Returns None when any pair is order-mismatched (the curved case).

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
Returnstuple[AffineSet, ...] | None
Executed regression · mismatched is not affine

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_mismatched_is_not_affine() -> None:
    assert affine_locus(_case_b()) is None
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_mismatched_is_not_affine" -q
Regression example · g1 affine lemma diagonals

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_affine_lemma_diagonals() -> None:
    sys = _case_a()
    planes = affine_locus(sys)
    assert planes is not None
    assert len(planes) == 2
    # y = x and y = -x
    for x in (-0.7, -0.2, 0.0, 0.4, 1.1):
        for pt in ((x, x), (x, -x)):
            f = residual(sys, pt)
            assert abs(f[0]) <= 1e-14
    signs_id = branch_signature(sys, (0.3, 0.3))
    signs_m = branch_signature(sys, (0.3, -0.3))
    assert signs_id[0] == 1
    assert signs_m[0] == -1
python -m pytest packages/omnibias-core/tests/test_locus.py -k test_g1_affine_lemma_diagonals -q
Read the implementation
def affine_locus(sys: EqualitySystem) -> tuple[AffineSet, ...] | None:
    """Exact hyperplanes when every consecutive pair is order-matched with equal ``c``.

    Returns ``None`` when any pair is order-mismatched (the curved case).
    """
    planes: list[AffineSet] = []
    for a, b in zip(sys.terms, sys.terms[1:], strict=False):
        if a.order != b.order or a.weight != b.weight:
            return None
        ident = AffineSet(
            tuple(wi - wj for wi, wj in zip(a.normal, b.normal, strict=True)),
            a.bias - b.bias,
            1,
        )
        planes.append(ident)
        if a.order % 2 == 1:
            # even sigma^(n): also the mirror z_i = -z_j
            planes.append(
                AffineSet(
                    tuple(wi + wj for wi, wj in zip(a.normal, b.normal, strict=True)),
                    a.bias + b.bias,
                    -1,
                )
            )
    return tuple(planes)
Other public import paths
  • omnibias.core.affine_locus
  • omnibias.fields.affine_locus
  • omnibias.core.locus.affine_locus
  • omnibias.fields.locus.affine_locus
FUNCTION

branch_signature​

omnibias.core.locus.branch_signatureSource ↗
branch_signature(sys: EqualitySystem, x: Sequence[float]) -> tuple[int, ...]

Which even/odd branch each consecutive pair sits on.

For odd order (even sigma^(n)) +1 is the identity z_i = z_j and -1 is the mirror z_i = -z_j.

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
xpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
Returnstuple[int, ...]
Executed regression · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g3_quadratic_rate_case_b" -q
Regression example · g1 affine lemma diagonals

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_affine_lemma_diagonals() -> None:
    sys = _case_a()
    planes = affine_locus(sys)
    assert planes is not None
    assert len(planes) == 2
    # y = x and y = -x
    for x in (-0.7, -0.2, 0.0, 0.4, 1.1):
        for pt in ((x, x), (x, -x)):
            f = residual(sys, pt)
            assert abs(f[0]) <= 1e-14
    signs_id = branch_signature(sys, (0.3, 0.3))
    signs_m = branch_signature(sys, (0.3, -0.3))
    assert signs_id[0] == 1
    assert signs_m[0] == -1
python -m pytest packages/omnibias-core/tests/test_locus.py -k test_g1_affine_lemma_diagonals -q
Read the implementation
def branch_signature(sys: EqualitySystem, x: Sequence[float]) -> tuple[int, ...]:
    """Which even/odd branch each consecutive pair sits on.

    For odd order (even ``sigma^(n)``) ``+1`` is the identity ``z_i = z_j``
    and ``-1`` is the mirror ``z_i = -z_j``.
    """
    signs: list[int] = []
    for a, b in zip(sys.terms, sys.terms[1:], strict=False):
        z1, z2 = _z(a, x), _z(b, x)
        if a.order == b.order and a.order % 2 == 1:
            signs.append(1 if abs(z1 - z2) <= abs(z1 + z2) else -1)
        else:
            signs.append(1 if z1 >= z2 else -1)
    return tuple(signs)
Other public import paths
  • omnibias.core.locus.branch_signature
  • omnibias.fields.locus.branch_signature
FUNCTION

certify_locus_point​

omnibias.core.certify_locus_pointSource ↗
certify_locus_point(sys: EqualitySystem, box: Sequence[tuple[float, float]], *, free_axes: Sequence[int] | None=None) -> KrawczykCertificate | None

Krawczyk unique-zero test on box.

krawczyk_certificate is square. When codimension < dim the test runs on free_axes (default: the last m coordinates) with the others pinned at the box centre. Never forges a certificate: None means the test did not fire.

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
boxpositional-or-keywordSequence[tuple[float, float]]RequiredSee the operation contract and implementation below.
free_axeskeyword-onlySequence[int] | NoneDefault: NoneSee the operation contract and implementation below.
ReturnsKrawczykCertificate | None
Explicit validation & failure cases
  • When len(box) != sys.dim, raises ValueError(f'box has dim {len(box)}, system has dim {sys.dim}').
  • When len(axes) != m, raises ValueError(f'Krawczyk needs {m} free axes, got {len(axes)}').
  • When r <= 0.0, raises ValueError('box radius must be positive').

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

Executed regression · g4 certificate soundness

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_certificate_soundness() -> None:
    sys = EqualitySystem(
        (
            UnitTerm(1, 1.0, (0.0,), 0.0),
            UnitTerm(2, -2.0, (1.0,), 0.0),
        )
    )
    y = math.atanh(0.26959443640544456)
    cert = certify_locus_point(sys, ((y - 0.02, y + 0.02),))
    assert cert is not None
    lo, hi = cert.enclosure[0]
    landed = newton_project(sys, (y - 0.01,), max_iter=10, tol=1e-14)
    assert lo <= landed.point[0] <= hi
    empty = certify_locus_point(sys, ((2.0, 2.2),))
    assert empty is None
    scan = [residual(sys, (x,))[0] for x in [2.0 + i * 0.01 for i in range(21)]]
    assert all(abs(v) > 1e-3 for v in scan)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g4_certificate_soundness" -q
Read the implementation
def certify_locus_point(
    sys: EqualitySystem,
    box: Sequence[tuple[float, float]],
    *,
    free_axes: Sequence[int] | None = None,
) -> KrawczykCertificate | None:
    """Krawczyk unique-zero test on ``box``.

    ``krawczyk_certificate`` is square. When ``codimension < dim`` the test
    runs on ``free_axes`` (default: the last ``m`` coordinates) with the
    others pinned at the box centre. Never forges a certificate: ``None``
    means the test did not fire.
    """
    if len(box) != sys.dim:
        raise ValueError(f"box has dim {len(box)}, system has dim {sys.dim}")
    m = sys.codimension
    if free_axes is None:
        axes = tuple(range(sys.dim - m, sys.dim)) if m <= sys.dim else tuple(range(sys.dim))
    else:
        axes = tuple(int(i) for i in free_axes)
    if len(axes) != m:
        raise ValueError(f"Krawczyk needs {m} free axes, got {len(axes)}")
    pinned = [0.5 * (lo + hi) for lo, hi in box]
    x_bar = [pinned[i] for i in axes]
    radii = [0.5 * (box[i][1] - box[i][0]) for i in axes]
    r = max(radii)
    if r <= 0.0:
        raise ValueError("box radius must be positive")

    def _embed(ys: Sequence[Interval]) -> list[Interval]:
        xs: list[Interval] = [Interval.point(v) for v in pinned]
        for k, ax in enumerate(axes):
            xs[ax] = ys[k] if isinstance(ys[k], Interval) else Interval.from_value(ys[k])
        return xs

    def func(ys: Sequence[Interval]) -> list[Interval]:
        return residual_iv(sys, _embed(ys))

    def jac(ys: Sequence[Interval]) -> list[list[Interval]]:
        full = jacobian_iv(sys, _embed(ys))
        return [[row[ax] for ax in axes] for row in full]

    center_f = [Interval.point(v) for v in x_bar]
    j_c = [[v.mid for v in row] for row in jac(center_f)]
    try:
        a_inv = _float_inverse(j_c)
    except ZeroDivisionError:
        return None
    return krawczyk_certificate(func, jac, x_bar, a_inv, r)
Other public import paths
  • omnibias.core.certify_locus_point
  • omnibias.fields.certify_locus_point
  • omnibias.core.locus.certify_locus_point
  • omnibias.fields.locus.certify_locus_point
FUNCTION

dF_d_weights​

omnibias.core.locus.dF_d_weightsSource ↗
dF_d_weights(sys: EqualitySystem, x: Sequence[float]) -> tuple[tuple[float, ...], ...]

partial F / partial c, shape m x (m+1), closed form for the IFT.

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
xpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
Returnstuple[tuple[float, ...], ...]
Executed regression · g5 ift matches unrolled

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_ift_matches_unrolled() -> None:
    sys = _case_b()
    x0 = torch.tensor([0.0, 0.20], dtype=torch.float64)
    w = torch.tensor([1.0, -2.0], dtype=torch.float64, requires_grad=True)
    x_ift = newton_project(sys, x0, weights=w, max_iter=8, tol=1e-14)
    loss = x_ift[1]
    loss.backward()
    g_ift = w.grad.detach().clone()

    w2 = torch.tensor([1.0, -2.0], dtype=torch.float64, requires_grad=True)
    x_un = newton_project_unrolled(sys, x0, weights=w2, max_iter=8, tol=1e-14)
    x_un[1].backward()
    g_un = w2.grad.detach().clone()
    rel = torch.norm(g_ift - g_un) / torch.norm(g_un).clamp_min(1e-30)
    assert float(rel.detach()) <= 1e-8
python -m pytest "packages/omnibias-fields/tests/test_locus.py::test_g5_ift_matches_unrolled" -q
Read the implementation
def dF_d_weights(sys: EqualitySystem, x: Sequence[float]) -> tuple[tuple[float, ...], ...]:
    """``partial F / partial c``, shape ``m x (m+1)``, closed form for the IFT."""
    sigmas = [sigma_n(sys.base, _z(t, x), t.order) for t in sys.terms]
    m = sys.codimension
    n_c = sys.n_terms
    rows: list[list[float]] = []
    for k in range(m):
        row = [0.0] * n_c
        row[k] = sigmas[k]
        row[k + 1] = -sigmas[k + 1]
        rows.append(row)
    return tuple(tuple(r) for r in rows)
Other public import paths
  • omnibias.core.locus.dF_d_weights
  • omnibias.fields.locus.dF_d_weights
FUNCTION

hessian_blocks​

omnibias.core.locus.hessian_blocksSource ↗
hessian_blocks(sys: EqualitySystem, x: Sequence[float]) -> tuple[tuple[tuple[float, ...], ...], ...]

Hess F_k = Hess f_k - Hess f_{k+1}, one D x D block per equation.

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
xpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
Returnstuple[tuple[tuple[float, ...], ...], ...]
Explicit validation & failure cases
  • When len(x) != sys.dim, raises ValueError(f'x has dim {len(x)}, system has dim {sys.dim}').

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

Executed regression · g2 jacobian hessian vs fd

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_jacobian_hessian_vs_fd() -> None:
    rng = random.Random(0)
    worst = 0.0

    def f_at(sys: EqualitySystem, pt: tuple[float, float]) -> float:
        return residual(sys, pt)[0]

    def fd4(sys: EqualitySystem, x: tuple[float, float], axis: int, h: float = 1e-4) -> float:
        def shift(s: float) -> float:
            pt = (x[0] + s, x[1]) if axis == 0 else (x[0], x[1] + s)
            return f_at(sys, pt)

        return (-shift(2 * h) + 8 * shift(h) - 8 * shift(-h) + shift(-2 * h)) / (12 * h)

    for _ in range(40):
        n1, n2 = rng.randint(0, 6), rng.randint(0, 6)
        sys = EqualitySystem(
            (
                UnitTerm(n1, rng.uniform(-2, 2), (rng.uniform(-1, 1), rng.uniform(-1, 1))),
                UnitTerm(n2, rng.uniform(-2, 2), (rng.uniform(-1, 1), rng.uniform(-1, 1))),
            )
        )
        x = (rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3))
        df = jacobian(sys, x)
        fd0, fd1 = fd4(sys, x, 0), fd4(sys, x, 1)
        scale = max(abs(df[0][0]), abs(df[0][1]), abs(fd0), abs(fd1), 1e-12)
        rel = max(abs(df[0][0] - fd0), abs(df[0][1] - fd1)) / scale
        worst = max(worst, rel)
        hess = hessian_blocks(sys, x)[0]
        hh = 1e-4
        h00 = (
            f_at(sys, (x[0] + hh, x[1]))
            - 2 * f_at(sys, x)
            + f_at(sys, (x[0] - hh, x[1]))
        ) / (hh * hh)
        scale_h = max(abs(hess[0][0]), abs(h00), 1e-8)
        assert abs(hess[0][0] - h00) / scale_h <= 1e-4
    assert worst <= 1e-10
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g2_jacobian_hessian_vs_fd" -q
Read the implementation
def hessian_blocks(
    sys: EqualitySystem, x: Sequence[float]
) -> tuple[tuple[tuple[float, ...], ...], ...]:
    """``Hess F_k = Hess f_k - Hess f_{k+1}``, one ``D x D`` block per equation."""
    if len(x) != sys.dim:
        raise ValueError(f"x has dim {len(x)}, system has dim {sys.dim}")
    blocks = [_hess_term(t, x, sys.base) for t in sys.terms]
    out: list[tuple[tuple[float, ...], ...]] = []
    for i in range(sys.codimension):
        h0, h1 = blocks[i], blocks[i + 1]
        out.append(
            tuple(
                tuple(h0[r][c] - h1[r][c] for c in range(sys.dim)) for r in range(sys.dim)
            )
        )
    return tuple(out)
Other public import paths
  • omnibias.core.locus.hessian_blocks
  • omnibias.fields.locus.hessian_blocks
FUNCTION

is_transversal​

omnibias.core.locus.is_transversalSource ↗
is_transversal(sys: EqualitySystem, x: Sequence[float], *, tol: float=1e-10) -> bool

Full row-rank of DF (regular-value test).

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
xpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
tolkeyword-onlyfloatDefault: 1e-10See the operation contract and implementation below.
Returnsbool
Executed regression · case b worked point

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_case_b_worked_point() -> None:
    sys = _case_b()
    # t - t^3 = 1/4, the unique root in (0, 1).
    t = 0.26959443640544456
    y = math.atanh(t)
    f = residual(sys, (0.0, y))
    assert abs(f[0]) <= 1e-14
    df = jacobian(sys, (0.0, y))
    assert abs(df[0][0]) <= 1e-12
    assert df[0][1] != 0.0
    assert is_transversal(sys, (0.0, y))
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_case_b_worked_point" -q
Read the implementation
def is_transversal(sys: EqualitySystem, x: Sequence[float], *, tol: float = 1e-10) -> bool:
    """Full row-rank of ``DF`` (regular-value test)."""
    return smallest_singular(jacobian(sys, x)) > tol
Other public import paths
  • omnibias.core.locus.is_transversal
  • omnibias.fields.locus.is_transversal
FUNCTION

jacobian​

omnibias.core.locus.jacobianSource ↗
jacobian(sys: EqualitySystem, x: Sequence[float]) -> tuple[tuple[float, ...], ...]

Closed-form DF, an m x D matrix. No autodiff.

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
xpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
Returnstuple[tuple[float, ...], ...]
Explicit validation & failure cases
  • When len(x) != sys.dim, raises ValueError(f'x has dim {len(x)}, system has dim {sys.dim}').

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

Executed regression · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g3_quadratic_rate_case_b" -q
Regression example · case b worked point

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_case_b_worked_point() -> None:
    sys = _case_b()
    # t - t^3 = 1/4, the unique root in (0, 1).
    t = 0.26959443640544456
    y = math.atanh(t)
    f = residual(sys, (0.0, y))
    assert abs(f[0]) <= 1e-14
    df = jacobian(sys, (0.0, y))
    assert abs(df[0][0]) <= 1e-12
    assert df[0][1] != 0.0
    assert is_transversal(sys, (0.0, y))
python -m pytest packages/omnibias-core/tests/test_locus.py -k test_case_b_worked_point -q
Read the implementation
def jacobian(sys: EqualitySystem, x: Sequence[float]) -> tuple[tuple[float, ...], ...]:
    """Closed-form ``DF``, an ``m x D`` matrix. No autodiff."""
    if len(x) != sys.dim:
        raise ValueError(f"x has dim {len(x)}, system has dim {sys.dim}")
    grads = [_grad_term(t, x, sys.base) for t in sys.terms]
    return tuple(
        tuple(grads[i][d] - grads[i + 1][d] for d in range(sys.dim))
        for i in range(sys.codimension)
    )
Other public import paths
  • omnibias.core.locus.jacobian
  • omnibias.fields.locus.jacobian
FUNCTION

jacobian_iv​

omnibias.core.locus.jacobian_ivSource ↗
jacobian_iv(sys: EqualitySystem, xs: Sequence[Interval]) -> list[list[Interval]]

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

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
xspositional-or-keywordSequence[Interval]RequiredSee the operation contract and implementation below.
Returnslist[list[Interval]]
Executed regression · g4 certificate soundness

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_certificate_soundness() -> None:
    sys = EqualitySystem(
        (
            UnitTerm(1, 1.0, (0.0,), 0.0),
            UnitTerm(2, -2.0, (1.0,), 0.0),
        )
    )
    y = math.atanh(0.26959443640544456)
    cert = certify_locus_point(sys, ((y - 0.02, y + 0.02),))
    assert cert is not None
    lo, hi = cert.enclosure[0]
    landed = newton_project(sys, (y - 0.01,), max_iter=10, tol=1e-14)
    assert lo <= landed.point[0] <= hi
    empty = certify_locus_point(sys, ((2.0, 2.2),))
    assert empty is None
    scan = [residual(sys, (x,))[0] for x in [2.0 + i * 0.01 for i in range(21)]]
    assert all(abs(v) > 1e-3 for v in scan)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g4_certificate_soundness" -q
Read the implementation
def jacobian_iv(sys: EqualitySystem, xs: Sequence[Interval]) -> list[list[Interval]]:
    grads: list[list[Interval]] = []
    for t in sys.terms:
        scale = Interval.point(t.weight) * _sigma_n_iv(sys.base, _z_iv(t, xs), t.order + 1)
        grads.append([scale * Interval.point(w) for w in t.normal])
    return [
        [grads[i][d] - grads[i + 1][d] for d in range(sys.dim)]
        for i in range(sys.codimension)
    ]
FUNCTION

locus_tangent​

omnibias.core.locus.locus_tangentSource ↗
locus_tangent(sys: EqualitySystem, x: Sequence[float]) -> tuple[tuple[float, ...], ...]

An orthonormal basis of ker DF (empty when m = D and transversal).

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
xpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
Returnstuple[tuple[float, ...], ...]
Read the implementation
def locus_tangent(sys: EqualitySystem, x: Sequence[float]) -> tuple[tuple[float, ...], ...]:
    """An orthonormal basis of ``ker DF`` (empty when ``m = D`` and transversal)."""
    df = jacobian(sys, x)
    m, d = len(df), sys.dim
    if m >= d:
        return ()
    # Null-space via one Householder-free SVD-free pass: project standard basis.
    pinv = pseudoinverse(df)
    # P = I - DF^+ DF; columns span the tangent (rank D-m).
    proj_cols: list[list[float]] = []
    for ell in range(d):
        df_col = [df[j][ell] for j in range(m)]
        applied = [_dot(pinv[k], df_col) for k in range(d)]
        col = [float(i == ell) - applied[i] for i in range(d)]
        proj_cols.append(col)
    # Gram-Schmidt, drop tiny columns.
    basis: list[tuple[float, ...]] = []
    for col in proj_cols:
        vec = list(col)
        for b in basis:
            s = _dot(vec, b)
            vec = [vec[i] - s * b[i] for i in range(d)]
        nrm = math.sqrt(_dot(vec, vec))
        if nrm <= 1e-12:
            continue
        basis.append(tuple(v / nrm for v in vec))
        if len(basis) >= d - m:
            break
    return tuple(basis)
Other public import paths
  • omnibias.core.locus.locus_tangent
  • omnibias.fields.locus.locus_tangent
FUNCTION

newton_project​

omnibias.core.locus.newton_projectSource ↗
newton_project(sys: EqualitySystem, x0: Sequence[float], *, max_iter: int=20, tol: float=1e-12) -> NewtonResult

Gauss-Newton projection x <- x - DF^+ F. Minimum-norm correction.

Differentiating this iterate is **not** the IFT path; tensor twins in omnibias.fields.locus attach the implicit-function theorem on the landing point so memory does not scale with max_iter.

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
x0positional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
max_iterkeyword-onlyintDefault: 20See the operation contract and implementation below.
tolkeyword-onlyfloatDefault: 1e-12See the operation contract and implementation below.
ReturnsNewtonResult
Executed regression · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g3_quadratic_rate_case_b" -q
Regression example · g4 certificate 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_g4_certificate_soundness() -> None:
    sys = EqualitySystem(
        (
            UnitTerm(1, 1.0, (0.0,), 0.0),
            UnitTerm(2, -2.0, (1.0,), 0.0),
        )
    )
    y = math.atanh(0.26959443640544456)
    cert = certify_locus_point(sys, ((y - 0.02, y + 0.02),))
    assert cert is not None
    lo, hi = cert.enclosure[0]
    landed = newton_project(sys, (y - 0.01,), max_iter=10, tol=1e-14)
    assert lo <= landed.point[0] <= hi
    empty = certify_locus_point(sys, ((2.0, 2.2),))
    assert empty is None
    scan = [residual(sys, (x,))[0] for x in [2.0 + i * 0.01 for i in range(21)]]
    assert all(abs(v) > 1e-3 for v in scan)
python -m pytest packages/omnibias-core/tests/test_locus.py -k test_g4_certificate_soundness -q
Read the implementation
def newton_project(
    sys: EqualitySystem,
    x0: Sequence[float],
    *,
    max_iter: int = 20,
    tol: float = 1e-12,
) -> NewtonResult:
    """Gauss-Newton projection ``x <- x - DF^+ F``. Minimum-norm correction.

    Differentiating this iterate is **not** the IFT path; tensor twins in
    ``omnibias.fields.locus`` attach the implicit-function theorem on the
    landing point so memory does not scale with ``max_iter``.
    """
    x = tuple(float(v) for v in x0)
    last_f = residual(sys, x)
    it = 0
    cond = 0.0
    transversal = False
    for it in range(1, max_iter + 1):  # noqa: B007 -- `it` is returned as n_iter
        f = residual(sys, x)
        last_f = f
        nrm = _residual_norm(f)
        df = jacobian(sys, x)
        try:
            pinv = pseudoinverse(df)
        except ZeroDivisionError:
            transversal = False
            cond = 0.0
            break
        cond = smallest_singular(df)
        transversal = cond > 1e-10
        step = tuple(_dot(pinv[k], f) for k in range(sys.dim))
        x = tuple(x[k] - step[k] for k in range(sys.dim))
        if nrm <= tol:
            f = residual(sys, x)
            last_f = f
            break
    nrm = _residual_norm(last_f)
    return NewtonResult(
        point=x,
        residual_norm=nrm,
        iterations=it,
        converged=nrm <= tol,
        condition=cond,
        branch=branch_signature(sys, x),
        transversal=transversal,
    )
Other public import paths
  • omnibias.core.locus.newton_project
  • omnibias.fields.locus.newton_project
FUNCTION

pseudoinverse​

omnibias.core.locus.pseudoinverseSource ↗
pseudoinverse(df: Sequence[Sequence[float]]) -> tuple[tuple[float, ...], ...]

Moore-Penrose right inverse DF^+ = DF^T (DF DF^T)^{-1}, shape D x m.

Parameters

NameType & defaultContract
dfpositional-or-keywordSequence[Sequence[float]]RequiredSee the operation contract and implementation below.
Returnstuple[tuple[float, ...], ...]
Executed regression · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g3_quadratic_rate_case_b" -q
Read the implementation
def pseudoinverse(df: Sequence[Sequence[float]]) -> tuple[tuple[float, ...], ...]:
    """Moore-Penrose right inverse ``DF^+ = DF^T (DF DF^T)^{-1}``, shape ``D x m``."""
    m = len(df)
    d = len(df[0])
    gram = [[_dot(df[i], df[j]) for j in range(m)] for i in range(m)]
    ginv = _invert(gram)
    out: list[list[float]] = []
    for k in range(d):
        col_df = [df[i][k] for i in range(m)]
        out.append([_dot(col_df, [ginv[i][j] for i in range(m)]) for j in range(m)])
    return tuple(tuple(row) for row in out)
FUNCTION

residual​

omnibias.core.locus.residualSource ↗
residual(sys: EqualitySystem, x: Sequence[float]) -> tuple[float, ...]

F_k = f_k - f_{k+1}.

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
xpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
Returnstuple[float, ...]
Explicit validation & failure cases
  • When len(x) != sys.dim, raises ValueError(f'x has dim {len(x)}, system has dim {sys.dim}').

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

Executed regression · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g3_quadratic_rate_case_b" -q
Regression example · case b worked point

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_case_b_worked_point() -> None:
    sys = _case_b()
    # t - t^3 = 1/4, the unique root in (0, 1).
    t = 0.26959443640544456
    y = math.atanh(t)
    f = residual(sys, (0.0, y))
    assert abs(f[0]) <= 1e-14
    df = jacobian(sys, (0.0, y))
    assert abs(df[0][0]) <= 1e-12
    assert df[0][1] != 0.0
    assert is_transversal(sys, (0.0, y))
python -m pytest packages/omnibias-core/tests/test_locus.py -k test_case_b_worked_point -q
Read the implementation
def residual(sys: EqualitySystem, x: Sequence[float]) -> tuple[float, ...]:
    """``F_k = f_k - f_{k+1}``."""
    if len(x) != sys.dim:
        raise ValueError(f"x has dim {len(x)}, system has dim {sys.dim}")
    vals = [_eval_term(t, x, sys.base) for t in sys.terms]
    return tuple(vals[i] - vals[i + 1] for i in range(sys.codimension))
Other public import paths
  • omnibias.core.locus.residual
  • omnibias.fields.locus.residual
FUNCTION

residual_iv​

omnibias.core.locus.residual_ivSource ↗
residual_iv(sys: EqualitySystem, xs: Sequence[Interval]) -> list[Interval]

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

Parameters

NameType & defaultContract
syspositional-or-keywordEqualitySystemRequiredSee the operation contract and implementation below.
xspositional-or-keywordSequence[Interval]RequiredSee the operation contract and implementation below.
Returnslist[Interval]
Executed regression · g4 certificate soundness

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_certificate_soundness() -> None:
    sys = EqualitySystem(
        (
            UnitTerm(1, 1.0, (0.0,), 0.0),
            UnitTerm(2, -2.0, (1.0,), 0.0),
        )
    )
    y = math.atanh(0.26959443640544456)
    cert = certify_locus_point(sys, ((y - 0.02, y + 0.02),))
    assert cert is not None
    lo, hi = cert.enclosure[0]
    landed = newton_project(sys, (y - 0.01,), max_iter=10, tol=1e-14)
    assert lo <= landed.point[0] <= hi
    empty = certify_locus_point(sys, ((2.0, 2.2),))
    assert empty is None
    scan = [residual(sys, (x,))[0] for x in [2.0 + i * 0.01 for i in range(21)]]
    assert all(abs(v) > 1e-3 for v in scan)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g4_certificate_soundness" -q
Read the implementation
def residual_iv(sys: EqualitySystem, xs: Sequence[Interval]) -> list[Interval]:
    vals = [
        Interval.point(t.weight) * _sigma_n_iv(sys.base, _z_iv(t, xs), t.order)
        for t in sys.terms
    ]
    return [vals[i] - vals[i + 1] for i in range(sys.codimension)]
FUNCTION

sigma_n​

omnibias.core.locus.sigma_nSource ↗
sigma_n(base: str, z: float, n: int) -> float

Closed-form sigma^(n)(z) for the locus bases.

Parameters

NameType & defaultContract
basepositional-or-keywordstrRequiredSee the operation contract and implementation below.
zpositional-or-keywordfloatRequiredSee the operation contract and implementation below.
npositional-or-keywordintRequiredSee the operation contract and implementation below.
Returnsfloat
Explicit validation & failure cases
  • When n < 0, raises ValueError(f'order n must be >= 0, got {n}').

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

Executed regression · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g3_quadratic_rate_case_b" -q
Regression example · g3 newton thousand

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_newton_thousand() -> None:
    rng = random.Random(1)
    n_ok = 0
    n = 0
    while n < 1000:
        x_true = (rng.uniform(-0.4, 0.4), rng.uniform(-0.4, 0.4))
        n1, n2 = rng.randint(0, 3), rng.randint(0, 3)
        w1 = (rng.uniform(-1.0, 1.0), rng.uniform(-1.0, 1.0))
        w2 = (rng.uniform(-1.0, 1.0), rng.uniform(-1.0, 1.0))
        s2 = sigma_n("tanh", w2[0] * x_true[0] + w2[1] * x_true[1], n2)
        s1 = sigma_n("tanh", w1[0] * x_true[0] + w1[1] * x_true[1], n1)
        if abs(s2) < 1e-6:
            continue
        c2 = s1 / s2
        sys = EqualitySystem(
            (UnitTerm(n1, 1.0, w1), UnitTerm(n2, c2, w2)),
        )
        x0 = (x_true[0] + 0.03 * rng.uniform(-1, 1), x_true[1] + 0.03 * rng.uniform(-1, 1))
        result = newton_project(sys, x0, max_iter=5, tol=1e-12)
        n += 1
        if result.converged and result.residual_norm <= 1e-12:
            n_ok += 1
    assert n_ok >= 950
python -m pytest packages/omnibias-core/tests/test_locus.py -k test_g3_newton_thousand -q
Read the implementation
def sigma_n(base: str, z: float, n: int) -> float:
    """Closed-form ``sigma^(n)(z)`` for the locus bases."""
    if n < 0:
        raise ValueError(f"order n must be >= 0, got {n}")
    name = str(base).lower().strip()
    if name == "tanh":
        return _horner(tanh_polynomial_coeffs(n), math.tanh(z))
    if name == "sigmoid":
        return _horner(sigmoid_polynomial_coeffs(n), _sigmoid(z))
    if name == "gaussian":
        g = math.exp(-0.5 * z * z)
        he = _horner(hermite_coeffs(n), z)
        sign = 1.0 if n % 2 == 0 else -1.0
        return sign * he * g
    raise ValueError(
        f"unsupported locus base {base!r}; expected one of {sorted(_SUPPORTED_BASES)}"
    )
FUNCTION

smallest_singular​

omnibias.core.locus.smallest_singularSource ↗
smallest_singular(df: Sequence[Sequence[float]]) -> float

Smallest singular value of an m x D matrix via the Gram eigenvalues.

Parameters

NameType & defaultContract
dfpositional-or-keywordSequence[Sequence[float]]RequiredSee the operation contract and implementation below.
Returnsfloat
Executed regression · g3 quadratic rate case b

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_quadratic_rate_case_b() -> None:
    sys = _case_b()
    result = newton_project(sys, (0.0, 0.20), max_iter=5, tol=1e-14)
    assert result.converged
    assert result.iterations <= 5
    assert result.residual_norm <= 1e-14
    t = math.tanh(result.point[1])
    assert t - t**3 == pytest.approx(0.25, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_locus.py::test_g3_quadratic_rate_case_b" -q
Read the implementation
def smallest_singular(df: Sequence[Sequence[float]]) -> float:
    """Smallest singular value of an ``m x D`` matrix via the Gram eigenvalues."""
    m = len(df)
    if m == 0:
        return 0.0
    gram = [[sum(df[i][k] * df[j][k] for k in range(len(df[0]))) for j in range(m)] for i in range(m)]
    return math.sqrt(max(_smallest_eig_sym(gram), 0.0))