omnibias.difference
Finite-difference stencils, confluence limits, polynomial sequences, and scoped derivative-extraction certificates.
import omnibias.differenceThis package studies finite shifts and their derivative limit. The bias gap approaching zero is distinct from inverse temperature approaching infinity. A finite-difference estimate at a nonzero gap is not the same computation as evaluating an analytic derivative formula directly.
Stencil offsets, signs, normalization, and derivative order determine the quantity being extracted. Small gaps can amplify cancellation in floating-point subtraction; high orders can amplify coefficient growth. Read the remainder bound and domain assumptions before attaching a certificate to an approximation.
The algebraic utilities also cover polynomial sequences and asymptotic coefficients. Exact arithmetic claims refer to the represented algebraic object and scalar domain; tensor evaluation introduces backend floating-point behavior. Compare against the corresponding analytic identity with a stated tolerance.
Module contract & mathematical conventions
omnibias-difference -- the founding delta -> 0 register for discrete calculus.
This package is the **founding bias collapse** the library is named for: K
biases on a difference stencil (spread delta), with signs
s_k = (-1)^(K-k) C(K-1, k-1) / delta^(K-1), so
f_K(z) = \sum_k s_k\,\sigma(z + b_k) \;\longrightarrow\; \sigma^{(K-1)}(z + b_{\text{mean}}) \qquad \text{as } \delta \to 0.
The many biases coalesce and the finite difference *becomes* the derivative
sigma^(K-1). The closed-form tower evaluates that limit **exactly**, with no
1/delta^(K-1) catastrophic cancellation.
This is a delta -> 0 limit yielding a smooth **derivative** -- it is **not**
**temperature collapse** -- the beta -> inf *feasibility penalty* of
omnibias-convex / -control / -routing (a 0/1 step). Same word, opposite limit: **do not
conflate** the two (see the omnibias-core-concepts skill and
docs/derivatives.md).
Honesty labels used throughout: **closed-form** (the sigma / sech / tanh towers
and the exact integer/rational special-number coefficients) and **numerical**
(the finite-difference estimate and any floating-point asymptotic). There is no
autodiff-exact path in this package.
The pure-Python core (omnibias.difference._core) imports only
omnibias.core.*. The optional omnibias.difference.torch /
omnibias.difference.jax twins add a bit-identical finite-difference
stencil operator and require the respective backend.
important:
**Bit-parity with the PyTorch twin requires 64-bit JAX** -- jax.config.update("jax_enable_x64", True) before the first JAX array is created (or JAX_ENABLE_X64=1). JAX otherwise truncates to float32 while PyTorch uses float64, so the twins stay internally consistent but agree only to float32 tolerance. Where a value feeds a threshold, a rounding step or an argmax, that is enough to change the decision rather than just the last digits. See omnibias.jax.precision.
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.
bell_number_asymptotic
omnibias.difference.bell_number_asymptoticSource ↗bell_number_asymptotic(n: int) -> floatDobinski saddle-point asymptotic of the Bell number Bell(n).
Bell(n) ~ e^{n/r - 1} n! / (r^n sqrt(2 pi n (r+1))) with r = W(n). Use
log_bell_number_asymptotic when n is large enough to overflow.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExecuted regression · bell asymptotic matches reference and exact
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_bell_asymptotic_matches_reference_and_exact(seed: int) -> None:
rng = random.Random(400 + seed)
n = rng.randint(15, 25)
approx = bell_number_asymptotic(n)
with mpmath.workdps(60):
r = mpmath.lambertw(n)
ref = (
mpmath.e ** (mpmath.mpf(n) / r - 1)
* mpmath.factorial(n)
/ (r**n * mpmath.sqrt(2 * mpmath.pi * n * (r + 1)))
)
# our pure-Python saddle-point (with our Lambert W) matches the mpmath eval
assert abs(approx / float(ref) - 1.0) < 1e-6
# and it approximates the exact Bell number (saddle point: ~1-2% by n ~ 20)
assert abs(float(bell_number(n)) / approx - 1.0) < 5e-2
# the log form agrees with the direct form
assert abs(math.log(approx) - log_bell_number_asymptotic(n)) < 1e-9python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_bell_asymptotic_matches_reference_and_exact[0]" -qRegression example · euler asymptotic matches reference and exact
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_euler_asymptotic_matches_reference_and_exact(seed: int) -> None:
rng = random.Random(300 + seed)
m = rng.randint(5, 18)
n = 2 * m
approx = euler_asymptotic(n)
with mpmath.workdps(60):
ref = (-1) ** m * mpmath.mpf(2) ** (2 * m + 2) * mpmath.factorial(n) / mpmath.pi ** (2 * m + 1)
exact = mpmath.taylor(lambda z: mpmath.sech(z), 0, n)[n] * mpmath.factorial(n)
assert abs(approx / float(ref) - 1.0) < 1e-9
assert abs(float(exact) / approx - 1.0) < 2e-2python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_euler_asymptotic_matches_reference_and_exact -qRead the implementation
def bell_number_asymptotic(n: int) -> float:
r"""Dobinski saddle-point asymptotic of the Bell number ``Bell(n)``.
``Bell(n) ~ e^{n/r - 1} n! / (r^n sqrt(2 pi n (r+1)))`` with ``r = W(n)``. Use
:func:`log_bell_number_asymptotic` when ``n`` is large enough to overflow.
"""
return exp(log_bell_number_asymptotic(n))bernoulli_asymptotic
omnibias.difference.bernoulli_asymptoticSource ↗bernoulli_asymptotic(n: int) -> floatSigned leading asymptotic of B_n (even n = 2m >= 2 only).
B_{2m} ~ (-1)^{m+1} 2 (2m)! / (2 pi)^{2m}.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
n < 2 or n % 2 == 1, raisesValueError(f'Bernoulli asymptotic is defined for even n >= 2, got {n}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · bernoulli and euler asymptotics tighten with n
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_bernoulli_and_euler_asymptotics_tighten_with_n() -> None:
def bern_rel(n: int) -> float:
with mpmath.workdps(60):
return abs(float(mpmath.bernoulli(n)) / bernoulli_asymptotic(n) - 1.0)
assert bern_rel(20) < bern_rel(8)python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_bernoulli_and_euler_asymptotics_tighten_with_n" -qRegression example · asymptotic domain guards
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_asymptotic_domain_guards() -> None:
with pytest.raises(ValueError):
bernoulli_asymptotic(7) # odd
with pytest.raises(ValueError):
euler_asymptotic(0) # too small
with pytest.raises(ValueError):
stirling_second_asymptotic(5, 0) # k >= 1python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_asymptotic_domain_guards -qRead the implementation
def bernoulli_asymptotic(n: int) -> float:
r"""Signed leading asymptotic of ``B_n`` (even ``n = 2m >= 2`` only).
``B_{2m} ~ (-1)^{m+1} 2 (2m)! / (2 pi)^{2m}``.
"""
if n < 2 or n % 2 == 1:
raise ValueError(f"Bernoulli asymptotic is defined for even n >= 2, got {n}")
m = n // 2
log_mag = log(2.0) + lgamma(n + 1) - n * log(2.0 * pi)
return (-1.0) ** (m + 1) * exp(log_mag)euler_asymptotic
omnibias.difference.euler_asymptoticSource ↗euler_asymptotic(n: int) -> floatSigned leading asymptotic of the Euler (secant) number E_n (even n = 2m >= 2).
E_{2m} ~ (-1)^m 2^{2m+2} (2m)! / pi^{2m+1}.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
n < 2 or n % 2 == 1, raisesValueError(f'Euler asymptotic is defined for even n >= 2, got {n}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · asymptotic domain guards
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_asymptotic_domain_guards() -> None:
with pytest.raises(ValueError):
bernoulli_asymptotic(7) # odd
with pytest.raises(ValueError):
euler_asymptotic(0) # too small
with pytest.raises(ValueError):
stirling_second_asymptotic(5, 0) # k >= 1python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_asymptotic_domain_guards" -qRegression example · euler asymptotic matches reference and exact
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_euler_asymptotic_matches_reference_and_exact(seed: int) -> None:
rng = random.Random(300 + seed)
m = rng.randint(5, 18)
n = 2 * m
approx = euler_asymptotic(n)
with mpmath.workdps(60):
ref = (-1) ** m * mpmath.mpf(2) ** (2 * m + 2) * mpmath.factorial(n) / mpmath.pi ** (2 * m + 1)
exact = mpmath.taylor(lambda z: mpmath.sech(z), 0, n)[n] * mpmath.factorial(n)
assert abs(approx / float(ref) - 1.0) < 1e-9
assert abs(float(exact) / approx - 1.0) < 2e-2python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_euler_asymptotic_matches_reference_and_exact -qRead the implementation
def euler_asymptotic(n: int) -> float:
r"""Signed leading asymptotic of the Euler (secant) number ``E_n`` (even ``n = 2m >= 2``).
``E_{2m} ~ (-1)^m 2^{2m+2} (2m)! / pi^{2m+1}``.
"""
if n < 2 or n % 2 == 1:
raise ValueError(f"Euler asymptotic is defined for even n >= 2, got {n}")
m = n // 2
log_mag = (2 * m + 2) * log(2.0) + lgamma(n + 1) - (2 * m + 1) * log(pi)
return (-1.0) ** m * exp(log_mag)log_bell_number_asymptotic
omnibias.difference.log_bell_number_asymptoticSource ↗log_bell_number_asymptotic(n: int) -> floatNatural log of the Bell-number saddle-point asymptotic (safe for large n).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
n < 1, raisesValueError(f'n must be >= 1, got {n}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · refined bell beats raw baseline
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_refined_bell_beats_raw_baseline(n: int) -> None:
log_exact = log(bell_number(n))
err_raw = abs(expm1(log_bell_number_asymptotic(n) - log_exact))
err_ref = abs(expm1(log_bell_number_asymptotic_refined(n) - log_exact))
assert err_ref < err_raw / 20.0 # measured ~80-120x; assert a conservative 20xpython -m pytest "packages/omnibias-difference/tests/test_generating.py::test_refined_bell_beats_raw_baseline[10]" -qRegression example · bell asymptotic matches reference and exact
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_bell_asymptotic_matches_reference_and_exact(seed: int) -> None:
rng = random.Random(400 + seed)
n = rng.randint(15, 25)
approx = bell_number_asymptotic(n)
with mpmath.workdps(60):
r = mpmath.lambertw(n)
ref = (
mpmath.e ** (mpmath.mpf(n) / r - 1)
* mpmath.factorial(n)
/ (r**n * mpmath.sqrt(2 * mpmath.pi * n * (r + 1)))
)
# our pure-Python saddle-point (with our Lambert W) matches the mpmath eval
assert abs(approx / float(ref) - 1.0) < 1e-6
# and it approximates the exact Bell number (saddle point: ~1-2% by n ~ 20)
assert abs(float(bell_number(n)) / approx - 1.0) < 5e-2
# the log form agrees with the direct form
assert abs(math.log(approx) - log_bell_number_asymptotic(n)) < 1e-9python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_bell_asymptotic_matches_reference_and_exact -qRead the implementation
def log_bell_number_asymptotic(n: int) -> float:
r"""Natural log of the Bell-number saddle-point asymptotic (safe for large ``n``)."""
if n < 1:
raise ValueError(f"n must be >= 1, got {n}")
r = _lambert_w(float(n))
return (n / r - 1.0) + lgamma(n + 1) - n * log(r) - 0.5 * log(2.0 * pi * n * (r + 1.0))stirling_second_asymptotic
omnibias.difference.stirling_second_asymptoticSource ↗stirling_second_asymptotic(n: int, k: int) -> floatFixed-k leading asymptotic S(n, k) ~ k^n / k! as n -> inf.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
k < 1, raisesValueError(f'k must be >= 1, got {k}'). - When
n < 0, raisesValueError(f'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 · asymptotic domain guards
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_asymptotic_domain_guards() -> None:
with pytest.raises(ValueError):
bernoulli_asymptotic(7) # odd
with pytest.raises(ValueError):
euler_asymptotic(0) # too small
with pytest.raises(ValueError):
stirling_second_asymptotic(5, 0) # k >= 1python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_asymptotic_domain_guards" -qRegression example · stirling second fixed k asymptotic converges
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_stirling_second_fixed_k_asymptotic_converges() -> None:
# S(n, k) ~ k^n / k! as n -> inf, for fixed k.
def ratio(n: int, k: int) -> float:
return stirling_second(n, k) / stirling_second_asymptotic(n, k)
assert ratio(25, 4) > ratio(15, 4) > ratio(8, 4)
assert 0.99 < ratio(25, 4) <= 1.0python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_stirling_second_fixed_k_asymptotic_converges -qRead the implementation
def stirling_second_asymptotic(n: int, k: int) -> float:
r"""Fixed-``k`` leading asymptotic ``S(n, k) ~ k^n / k!`` as ``n -> inf``."""
if k < 1:
raise ValueError(f"k must be >= 1, got {k}")
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
return exp(n * log(k) - lgamma(k + 1))bernoulli_number
omnibias.difference.bernoulli_numberSource ↗bernoulli_number(n: int) -> FractionThe n-th Bernoulli number B_n (exact Fraction; B_1 = -1/2).
A thin re-export of omnibias.core.verified.coeffs.bernoulli_number_exact
-- the shared source of truth also consumed by the certified Euler-Maclaurin
engine -- so the Bernoulli numbers are defined once (off the tanh tower) and
never forked per package.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
FractionExecuted regression · bernoulli enclosure contains exact
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_bernoulli_enclosure_contains_exact(n: int) -> None:
assert _encloses(bernoulli_enclosure(n), bernoulli_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_bernoulli_enclosure_contains_exact[10]" -qRegression example · appell of bernoulli numbers are bernoulli polynomials
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_appell_of_bernoulli_numbers_are_bernoulli_polynomials() -> None:
constants = [bernoulli_number(n) for n in range(6)]
seq = appell_sequence(constants)
for n in range(6):
assert tuple(seq[n]) == bernoulli_polynomial(n)python -m pytest packages/omnibias-difference/tests/test_umbral.py -k test_appell_of_bernoulli_numbers_are_bernoulli_polynomials -qRead the implementation
def bernoulli_number(n: int) -> Fraction:
"""The ``n``-th Bernoulli number ``B_n`` (exact ``Fraction``; ``B_1 = -1/2``).
A thin re-export of :func:`omnibias.core.verified.coeffs.bernoulli_number_exact`
-- the shared source of truth also consumed by the certified Euler-Maclaurin
engine -- so the Bernoulli numbers are defined once (off the ``tanh`` tower) and
never forked per package.
"""
return bernoulli_number_exact(n)bernoulli_polynomial
omnibias.difference.bernoulli_polynomialSource ↗bernoulli_polynomial(n: int) -> tuple[Fraction, ...]Coefficients of the Bernoulli polynomial B_n(x) = sum_k C(n,k) B_{n-k} x^k.
Returns (c_0, ..., c_n) with B_n(x) = sum_k c_k x^k. This is an Appell
sequence: B_n'(x) = n B_{n-1}(x) and B_n(0) = B_n.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
n < 0, raisesValueError(f'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 · appell of bernoulli numbers are bernoulli polynomials
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_appell_of_bernoulli_numbers_are_bernoulli_polynomials() -> None:
constants = [bernoulli_number(n) for n in range(6)]
seq = appell_sequence(constants)
for n in range(6):
assert tuple(seq[n]) == bernoulli_polynomial(n)python -m pytest "packages/omnibias-difference/tests/test_umbral.py::test_appell_of_bernoulli_numbers_are_bernoulli_polynomials" -qRegression example · sheffer bernoulli pair is bernoulli polynomial
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_sheffer_bernoulli_pair_is_bernoulli_polynomial(n: int) -> None:
# Bernoulli polynomials are Sheffer for (g, f) = ((e^t-1)/t, t) (an Appell sequence).
seq = sheffer_sequence(_bernoulli_g(N), (0, 1), N)
assert tuple(seq[n]) == bernoulli_polynomial(n)python -m pytest packages/omnibias-difference/tests/test_sheffer.py -k test_sheffer_bernoulli_pair_is_bernoulli_polynomial -qRead the implementation
def bernoulli_polynomial(n: int) -> tuple[Fraction, ...]:
r"""Coefficients of the Bernoulli polynomial ``B_n(x) = sum_k C(n,k) B_{n-k} x^k``.
Returns ``(c_0, ..., c_n)`` with ``B_n(x) = sum_k c_k x^k``. This is an Appell
sequence: ``B_n'(x) = n B_{n-1}(x)`` and ``B_n(0) = B_n``.
"""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
return tuple(Fraction(comb(n, k)) * bernoulli_number(n - k) for k in range(n + 1))power_sum_coeffs
omnibias.difference.power_sum_coeffsSource ↗power_sum_coeffs(p: int) -> tuple[Fraction, ...]Faulhaber coefficients of S_p(N) = sum_{i=0}^{N-1} i^p as a polynomial in N.
Returns (c_0, ..., c_{p+1}) with S_p(N) = sum_j c_j N^j, via
S_p(N) = (B_{p+1}(N) - B_{p+1}) / (p + 1). (Sum runs to N - 1, the
convention matched to B_1 = -1/2.)
Parameters
| Name | Type & default | Contract |
|---|---|---|
ppositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
p < 0, raisesValueError(f'p must be >= 0, got {p}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · faulhaber power sums
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_faulhaber_power_sums() -> None:
assert power_sum_coeffs(1) == (Fraction(0), Fraction(-1, 2), Fraction(1, 2))
assert power_sum_coeffs(2) == (Fraction(0), Fraction(1, 6), Fraction(-1, 2), Fraction(1, 3))
c = power_sum_coeffs(3) # S_3(N) = sum_{i<N} i^3
for big_n in (4, 7, 10):
expected = sum(i**3 for i in range(big_n))
assert sum(c[j] * big_n**j for j in range(len(c))) == expectedpython -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_faulhaber_power_sums" -qRead the implementation
def power_sum_coeffs(p: int) -> tuple[Fraction, ...]:
r"""Faulhaber coefficients of ``S_p(N) = sum_{i=0}^{N-1} i^p`` as a polynomial in ``N``.
Returns ``(c_0, ..., c_{p+1})`` with ``S_p(N) = sum_j c_j N^j``, via
``S_p(N) = (B_{p+1}(N) - B_{p+1}) / (p + 1)``. (Sum runs to ``N - 1``, the
convention matched to ``B_1 = -1/2``.)
"""
if p < 0:
raise ValueError(f"p must be >= 0, got {p}")
out = [Fraction(0)] * (p + 2)
for k in range(1, p + 2):
out[k] = Fraction(comb(p + 1, k)) * bernoulli_number(p + 1 - k) / Fraction(p + 1)
return tuple(out)DerivativeProofVerdict
omnibias.difference.DerivativeProofVerdictSource ↗class DerivativeProofVerdictDataclass 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.
A sealed derivative certificate plus its Lean-kernel adjudication.
Parameters
| Name | Type & default | Contract |
|---|---|---|
certificatedataclass field | CertRequired | See the operation contract and implementation below. |
signdataclass field | strRequired | See the operation contract and implementation below. |
obligationdataclass field | str | NoneRequired | See the operation contract and implementation below. |
leandataclass field | LeanCheckResultRequired | See the operation contract and implementation below. |
Executed regression · straddling enclosure has no obligation
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_straddling_enclosure_has_no_obligation() -> None:
# tanh''(0) = 0, so the enclosure straddles zero: a documented obligation gap.
verdict = check_derivative_certificate(certified_derivative_enclosure("tanh", 0.0, 2))
assert verdict.sign == "indeterminate"
assert not verdict.obligation_generated
assert not verdict.theorem_prover_verified # no finite obligation to checkpython -m pytest "packages/omnibias-difference/tests/test_certify.py::test_straddling_enclosure_has_no_obligation" -qFields & methods
certificatefield
certificate: CertDeclared Cert field on DerivativeProofVerdict. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗signfield
sign: strDeclared str field on DerivativeProofVerdict. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗obligationfield
obligation: str | NoneDeclared str | None field on DerivativeProofVerdict. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗leanfield
lean: LeanCheckResultDeclared LeanCheckResult field on DerivativeProofVerdict. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗theorem_prover_verifiedproperty
theorem_prover_verified(self) -> boolTrue only on a genuine Lean lake build pass (never forged).
Returns: bool
Executed regression · straddling enclosure has no obligation
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_straddling_enclosure_has_no_obligation() -> None:
# tanh''(0) = 0, so the enclosure straddles zero: a documented obligation gap.
verdict = check_derivative_certificate(certified_derivative_enclosure("tanh", 0.0, 2))
assert verdict.sign == "indeterminate"
assert not verdict.obligation_generated
assert not verdict.theorem_prover_verified # no finite obligation to checkpython -m pytest "packages/omnibias-difference/tests/test_certify.py::test_straddling_enclosure_has_no_obligation" -qMethod implementation
def theorem_prover_verified(self) -> bool:
"""``True`` only on a genuine Lean ``lake build`` pass (never forged)."""
return self.lean.verifiedsealed_okproperty
sealed_ok(self) -> boolWhether the certificate's tamper-evident digest matches its body.
Returns: bool
Executed regression · sign definite round trip across many points
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_sign_definite_round_trip_across_many_points() -> None:
zs = [0.3 + 0.1 * i for i in range(8)] # K = 8 sign-definite (tanh' > 0) points
for z in zs:
verdict = check_derivative_certificate(certified_derivative_enclosure("tanh", z, 1))
assert verdict.sign == "positive"
assert verdict.obligation_generated
assert verdict.sealed_ok
assert verdict.theorem_prover_verified == verdict.lean.verifiedpython -m pytest "packages/omnibias-difference/tests/test_certify.py::test_sign_definite_round_trip_across_many_points" -qMethod implementation
def sealed_ok(self) -> bool:
"""Whether the certificate's tamper-evident digest matches its body."""
return verify_certificate_digest(self.certificate)obligation_generatedproperty
obligation_generated(self) -> boolWhether a finite, Lean-checkable obligation was produced (sign-definite).
Returns: bool
Executed regression · straddling enclosure has no obligation
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_straddling_enclosure_has_no_obligation() -> None:
# tanh''(0) = 0, so the enclosure straddles zero: a documented obligation gap.
verdict = check_derivative_certificate(certified_derivative_enclosure("tanh", 0.0, 2))
assert verdict.sign == "indeterminate"
assert not verdict.obligation_generated
assert not verdict.theorem_prover_verified # no finite obligation to checkpython -m pytest "packages/omnibias-difference/tests/test_certify.py::test_straddling_enclosure_has_no_obligation" -qMethod implementation
def obligation_generated(self) -> bool:
"""Whether a finite, Lean-checkable obligation was produced (sign-definite)."""
return self.obligation is not NoneRead the implementation
class DerivativeProofVerdict:
"""A sealed derivative certificate plus its Lean-kernel adjudication."""
certificate: Cert
sign: str
obligation: str | None
lean: LeanCheckResult
@property
def theorem_prover_verified(self) -> bool:
"""``True`` only on a genuine Lean ``lake build`` pass (never forged)."""
return self.lean.verified
@property
def sealed_ok(self) -> bool:
"""Whether the certificate's tamper-evident digest matches its body."""
return verify_certificate_digest(self.certificate)
@property
def obligation_generated(self) -> bool:
"""Whether a finite, Lean-checkable obligation was produced (sign-definite)."""
return self.obligation is not Nonecheck_derivative_certificate
omnibias.difference.check_derivative_certificateSource ↗check_derivative_certificate(enc: DerivativeEnclosure, *, meta: dict[str, Any] | None=None, timeout: float=600.0, start: Path | None=None) -> DerivativeProofVerdictSeal enc into a certificate and run the Lean-kernel bridge on it.
Returns a DerivativeProofVerdict; theorem_prover_verified is set
only on a real kernel pass. When no Lean toolchain is present the bridge
degrades gracefully (lean.available is False), so this is safe to call in
a normal CI run.
Parameters
| Name | Type & default | Contract |
|---|---|---|
encpositional-or-keyword | DerivativeEnclosureRequired | See the operation contract and implementation below. |
metakeyword-only | dict[str, Any] | NoneDefault: None | See the operation contract and implementation below. |
timeoutkeyword-only | floatDefault: 600.0 | See the operation contract and implementation below. |
startkeyword-only | Path | NoneDefault: None | See the operation contract and implementation below. |
DerivativeProofVerdictExecuted regression · straddling enclosure has no obligation
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_straddling_enclosure_has_no_obligation() -> None:
# tanh''(0) = 0, so the enclosure straddles zero: a documented obligation gap.
verdict = check_derivative_certificate(certified_derivative_enclosure("tanh", 0.0, 2))
assert verdict.sign == "indeterminate"
assert not verdict.obligation_generated
assert not verdict.theorem_prover_verified # no finite obligation to checkpython -m pytest "packages/omnibias-difference/tests/test_certify.py::test_straddling_enclosure_has_no_obligation" -qRegression example · sign definite round trip across many points
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_sign_definite_round_trip_across_many_points() -> None:
zs = [0.3 + 0.1 * i for i in range(8)] # K = 8 sign-definite (tanh' > 0) points
for z in zs:
verdict = check_derivative_certificate(certified_derivative_enclosure("tanh", z, 1))
assert verdict.sign == "positive"
assert verdict.obligation_generated
assert verdict.sealed_ok
assert verdict.theorem_prover_verified == verdict.lean.verifiedpython -m pytest packages/omnibias-difference/tests/test_certify.py -k test_sign_definite_round_trip_across_many_points -qRead the implementation
def check_derivative_certificate(
enc: DerivativeEnclosure,
*,
meta: dict[str, Any] | None = None,
timeout: float = 600.0,
start: Path | None = None,
) -> DerivativeProofVerdict:
"""Seal ``enc`` into a certificate and run the Lean-kernel bridge on it.
Returns a :class:`DerivativeProofVerdict`; ``theorem_prover_verified`` is set
only on a real kernel pass. When no Lean toolchain is present the bridge
degrades gracefully (``lean.available is False``), so this is safe to call in
a normal CI run.
"""
cert = derivative_sign_certificate(enc, meta=meta)
obligation = generate_obligation(cert)
lean = check_certificate(cert, timeout=timeout, start=start)
return DerivativeProofVerdict(cert, _sign_word(enc.value), obligation, lean)derivative_sign_certificate
omnibias.difference.derivative_sign_certificateSource ↗derivative_sign_certificate(enc: DerivativeEnclosure, *, meta: dict[str, Any] | None=None) -> CertWrap a DerivativeEnclosure as a sealed v1 interval certificate.
The claim records the enclosure and its sign; the honesty flags hard-wire
unproven_claim=False (the omnibias convention). Provenance (activation, order,
argument box, closed-form label) is carried in meta.
Parameters
| Name | Type & default | Contract |
|---|---|---|
encpositional-or-keyword | DerivativeEnclosureRequired | See the operation contract and implementation below. |
metakeyword-only | dict[str, Any] | NoneDefault: None | See the operation contract and implementation below. |
CertExecuted regression · certificate is well formed and sealed
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_certificate_is_well_formed_and_sealed() -> None:
enc = certified_derivative_enclosure("tanh", 0.6, 1) # tanh' > 0
cert = derivative_sign_certificate(enc)
assert schema_errors_v1(cert) == []
assert verify_certificate_digest(cert)
assert cert["payload"]["type"] == "interval"
assert cert["meta"]["name"] == "tanh"
assert cert["meta"]["sign"] == "positive"python -m pytest "packages/omnibias-difference/tests/test_certify.py::test_certificate_is_well_formed_and_sealed" -qRegression example · tampering breaks the digest
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_tampering_breaks_the_digest() -> None:
enc = certified_derivative_enclosure("tanh", 0.6, 1)
cert = derivative_sign_certificate(enc)
tampered = copy.deepcopy(cert)
tampered["claim"] = "a wider, false claim"
assert not verify_certificate_digest(tampered)
# The bridge refuses a tampered certificate before emitting any Lean.
from omnibias.core.proof.lean_check import check_certificate
result = check_certificate(tampered)
assert not result.verified
assert "digest" in result.detail.lower()python -m pytest packages/omnibias-difference/tests/test_certify.py -k test_tampering_breaks_the_digest -qRead the implementation
def derivative_sign_certificate(enc: DerivativeEnclosure, *, meta: dict[str, Any] | None = None) -> Cert:
"""Wrap a :class:`DerivativeEnclosure` as a sealed v1 interval certificate.
The claim records the enclosure and its sign; the honesty flags hard-wire
``unproven_claim=False`` (the omnibias convention). Provenance (activation, order,
argument box, ``closed-form`` label) is carried in ``meta``.
"""
value = enc.value
sign = _sign_word(value)
claim = (
f"{enc.name}^({enc.order}) over [{enc.argument.lo!r}, {enc.argument.hi!r}] "
f"is enclosed in [{value.lo!r}, {value.hi!r}] (sign: {sign})"
)
payload_meta: dict[str, Any] = {
"name": enc.name,
"order": enc.order,
"argument_lo": enc.argument.lo,
"argument_hi": enc.argument.hi,
"label": enc.label,
"sign": sign,
}
if meta:
payload_meta.update(meta)
return interval_certificate(claim, value, honesty={"unproven_claim": False}, meta=payload_meta)euler_number
omnibias.difference.euler_numberSource ↗euler_number(n: int) -> intThe n-th Euler (secant) number E_n = sech^(n)(0) = Q_n(0) (exact int).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
n < 0, raisesValueError(f'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 · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qRegression example · euler small exact
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_euler_small_exact() -> None:
assert [euler_number(n) for n in range(9)] == [1, 0, -1, 0, 5, 0, -61, 0, 1385]python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_euler_small_exact -qRead the implementation
def euler_number(n: int) -> int:
"""The ``n``-th Euler (secant) number ``E_n = sech^(n)(0) = Q_n(0)`` (exact int)."""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
return sech_poly_coeffs_exact(n)[0]euler_polynomial
omnibias.difference.euler_polynomialSource ↗euler_polynomial(n: int) -> tuple[Fraction, ...]Coefficients of the Euler polynomial E_n(x).
Uses E_n(x) = sum_k C(n,k) (E_k / 2^k) (x - 1/2)^{n-k} (with E_k the
Euler numbers), so E_n(1/2) = E_n / 2^n. Returns (c_0, ..., c_n) with
E_n(x) = sum_j c_j x^j (e.g. E_1(x) = x - 1/2, E_2(x) = x^2 - x).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
n < 0, raisesValueError(f'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 · bernoulli and euler polynomials
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_bernoulli_and_euler_polynomials() -> None:
assert bernoulli_polynomial(0) == (Fraction(1),)
assert bernoulli_polynomial(1) == (Fraction(-1, 2), Fraction(1))
assert bernoulli_polynomial(2) == (Fraction(1, 6), Fraction(-1), Fraction(1))
assert euler_polynomial(1) == (Fraction(-1, 2), Fraction(1))
assert euler_polynomial(2) == (Fraction(0), Fraction(-1), Fraction(1))python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_bernoulli_and_euler_polynomials" -qRead the implementation
def euler_polynomial(n: int) -> tuple[Fraction, ...]:
r"""Coefficients of the Euler polynomial ``E_n(x)``.
Uses ``E_n(x) = sum_k C(n,k) (E_k / 2^k) (x - 1/2)^{n-k}`` (with ``E_k`` the
Euler numbers), so ``E_n(1/2) = E_n / 2^n``. Returns ``(c_0, ..., c_n)`` with
``E_n(x) = sum_j c_j x^j`` (e.g. ``E_1(x) = x - 1/2``, ``E_2(x) = x^2 - x``).
"""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
out = [Fraction(0)] * (n + 1)
for k in range(n + 1):
coeff = Fraction(comb(n, k)) * Fraction(euler_number(k), 2**k)
m = n - k
for j in range(m + 1):
out[j] += coeff * Fraction(comb(m, j)) * Fraction((-1) ** (m - j), 2 ** (m - j))
return tuple(out)eulerian_number
omnibias.difference.eulerian_numberSource ↗eulerian_number(n: int, k: int) -> intEulerian number A(n, k) via the Worpitzky summation (classical, not a tower).
A(n, k) = sum_{j=0}^{k} (-1)^j C(n+1, j) (k+1-j)^n counts permutations of
n with exactly k ascents (0 <= k <= n-1 for n >= 1). This is the
genuine Eulerian triangle; see the module docstring for why it is *not* read
off the logistic-sigmoid tower.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
n < 0, raisesValueError(f'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 · eulerian numbers exact
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_eulerian_numbers_exact() -> None:
assert [eulerian_number(4, k) for k in range(4)] == [1, 11, 11, 1]
assert [eulerian_number(5, k) for k in range(5)] == [1, 26, 66, 26, 1]python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_eulerian_numbers_exact" -qRegression example · eulerian numbers are not claimed off the sigmoid tower
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_eulerian_numbers_are_not_claimed_off_the_sigmoid_tower() -> None:
doc = euler.__doc__ or ""
assert "Worpitzky" in doc
assert "not" in doc.lower()
assert "eulerian" in doc.lower() and "sigmoid" in doc.lower()
fn_doc = D.eulerian_number.__doc__ or ""
assert "Worpitzky" in fn_docpython -m pytest packages/omnibias-difference/tests/test_scope.py -k test_eulerian_numbers_are_not_claimed_off_the_sigmoid_tower -qRead the implementation
def eulerian_number(n: int, k: int) -> int:
r"""Eulerian number ``A(n, k)`` via the Worpitzky summation (classical, not a tower).
``A(n, k) = sum_{j=0}^{k} (-1)^j C(n+1, j) (k+1-j)^n`` counts permutations of
``n`` with exactly ``k`` ascents (``0 <= k <= n-1`` for ``n >= 1``). This is the
genuine Eulerian triangle; see the module docstring for why it is *not* read
off the logistic-sigmoid tower.
"""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
if n == 0:
return 1 if k == 0 else 0
if k < 0 or k > n - 1:
return 0
return sum((-1) ** j * comb(n + 1, j) * (k + 1 - j) ** n for j in range(k + 1))DerivBound
omnibias.difference.DerivBoundSource ↗DerivBound = Callable[[int, Interval], Interval]A derivative-enclosure oracle: deriv_bound(k, box) returns a rigorous
class:Interval enclosure of f^(k) over box. This is the seam that
decouples the certified-remainder engine from the built-in activation
dictionary -- omnibias.core.verified.sigma.sigma_tower_interval is one
provider, but *any* function with a sound derivative-tower / interval-jet
enclosure (a hand-written analytic tower, a composed compose_jet tower, a
differentiated Taylor model, ...) can be certified through the same math.
Read the implementation
DerivBound = Callable[[int, Interval], Interval]DerivativeEnclosure
omnibias.difference.DerivativeEnclosureSource ↗class DerivativeEnclosureDataclass 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.
Closed-form rigorous enclosure of sigma^(0..order)(z).
Parameters
| Name | Type & default | Contract |
|---|---|---|
namedataclass field | strRequired | See the operation contract and implementation below. |
orderdataclass field | intRequired | See the operation contract and implementation below. |
argumentdataclass field | IntervalRequired | See the operation contract and implementation below. |
towerdataclass field | tuple[Interval, ...]Required | See the operation contract and implementation below. |
valuedataclass field | IntervalRequired | See the operation contract and implementation below. |
labeldataclass field | strDefault: 'closed-form' | See the operation contract and implementation below. |
Fields & methods
namefield
name: strDeclared str field on DerivativeEnclosure. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗orderfield
order: intDeclared int field on DerivativeEnclosure. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗argumentfield
argument: IntervalDeclared Interval field on DerivativeEnclosure. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗towerfield
tower: tuple[Interval, ...]Declared tuple[Interval, ...] field on DerivativeEnclosure. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗valuefield
value: IntervalDeclared Interval field on DerivativeEnclosure. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗labelfield
label: str = 'closed-form'Declared str field on DerivativeEnclosure. Default expression: 'closed-form'.
Read the implementation
class DerivativeEnclosure:
"""Closed-form rigorous enclosure of ``sigma^(0..order)(z)``."""
name: str
order: int
argument: Interval
tower: tuple[Interval, ...]
value: Interval
label: str = "closed-form"DifferenceEstimate
omnibias.difference.DifferenceEstimateSource ↗class DifferenceEstimateDataclass 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.
Numerical finite-difference estimate of sigma^(order)(z).
Parameters
| Name | Type & default | Contract |
|---|---|---|
namedataclass field | strRequired | See the operation contract and implementation below. |
orderdataclass field | intRequired | See the operation contract and implementation below. |
zdataclass field | floatRequired | See the operation contract and implementation below. |
deltadataclass field | floatRequired | See the operation contract and implementation below. |
stencildataclass field | strRequired | See the operation contract and implementation below. |
estimatedataclass field | floatRequired | See the operation contract and implementation below. |
labeldataclass field | strDefault: 'numerical' | See the operation contract and implementation below. |
Fields & methods
namefield
name: strDeclared str field on DifferenceEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗orderfield
order: intDeclared int field on DifferenceEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗zfield
z: floatDeclared float field on DifferenceEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗deltafield
delta: floatDeclared float field on DifferenceEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗stencilfield
stencil: strDeclared str field on DifferenceEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗estimatefield
estimate: floatDeclared float field on DifferenceEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗labelfield
label: str = 'numerical'Declared str field on DifferenceEstimate. Default expression: 'numerical'.
Read the implementation
class DifferenceEstimate:
"""Numerical finite-difference estimate of ``sigma^(order)(z)``."""
name: str
order: int
z: float
delta: float
stencil: str
estimate: float
label: str = "numerical"FiniteDifferenceCertificate
omnibias.difference.FiniteDifferenceCertificateSource ↗class FiniteDifferenceCertificateDataclass 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.
A certified sandwich linking the numerical estimate to the closed-form tower.
enclosure rigorously contains the true sigma^(order)(z) (closed-form),
and |estimate - sigma^(order)(z)| <= error_bound is certified by a Taylor
remainder enclosed over the whole stencil box. Hence the true derivative lies
in [estimate - error_bound, estimate + error_bound] *and* the estimate lies
in enclosure widened by error_bound -- a self-checking sandwich.
Parameters
| Name | Type & default | Contract |
|---|---|---|
namedataclass field | strRequired | See the operation contract and implementation below. |
orderdataclass field | intRequired | See the operation contract and implementation below. |
zdataclass field | floatRequired | See the operation contract and implementation below. |
deltadataclass field | floatRequired | See the operation contract and implementation below. |
stencildataclass field | strRequired | See the operation contract and implementation below. |
estimatedataclass field | floatRequired | See the operation contract and implementation below. |
enclosuredataclass field | IntervalRequired | See the operation contract and implementation below. |
error_bounddataclass field | floatRequired | See the operation contract and implementation below. |
accuracy_orderdataclass field | intRequired | See the operation contract and implementation below. |
labeldataclass field | strDefault: 'closed-form + numerical' | See the operation contract and implementation below. |
Executed regression · general engine certifies function outside dictionary
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_general_engine_certifies_function_outside_dictionary() -> None:
"""exp is NOT one of the nine activations; the engine still certifies it."""
exp_bound = lambda k, box: exp_iv(box) # noqa: E731 -- exp^(k) = exp
# delta=1e-2 keeps truncation above the 1/delta^order float-cancellation floor
# (at 1e-3 the order-3 stencil's roundoff would exceed the truncation bound).
for order in (1, 2, 3):
cert = certified_fd_error_general(
math.exp, exp_bound, 0.6, order, 1e-2, "central", name="exp"
)
true = math.exp(0.6) # every derivative of exp equals exp
assert cert.name == "exp"
assert cert.certified
assert cert.true_derivative_interval.contains(true)
assert cert.enclosure.contains(true)python -m pytest "packages/omnibias-difference/tests/test_extraction.py::test_general_engine_certifies_function_outside_dictionary" -qFields & methods
namefield
name: strDeclared str field on FiniteDifferenceCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗orderfield
order: intDeclared int field on FiniteDifferenceCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗zfield
z: floatDeclared float field on FiniteDifferenceCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗deltafield
delta: floatDeclared float field on FiniteDifferenceCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗stencilfield
stencil: strDeclared str field on FiniteDifferenceCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗estimatefield
estimate: floatDeclared float field on FiniteDifferenceCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗enclosurefield
enclosure: IntervalDeclared Interval field on FiniteDifferenceCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗error_boundfield
error_bound: floatDeclared float field on FiniteDifferenceCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗accuracy_orderfield
accuracy_order: intDeclared int field on FiniteDifferenceCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗labelfield
label: str = 'closed-form + numerical'Declared str field on FiniteDifferenceCertificate. Default expression: 'closed-form + numerical'.
certifiedproperty
certified(self) -> boolWhether the numerical estimate is consistent with the certified sandwich.
Returns: bool
Executed regression · general engine certifies function outside dictionary
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_general_engine_certifies_function_outside_dictionary() -> None:
"""exp is NOT one of the nine activations; the engine still certifies it."""
exp_bound = lambda k, box: exp_iv(box) # noqa: E731 -- exp^(k) = exp
# delta=1e-2 keeps truncation above the 1/delta^order float-cancellation floor
# (at 1e-3 the order-3 stencil's roundoff would exceed the truncation bound).
for order in (1, 2, 3):
cert = certified_fd_error_general(
math.exp, exp_bound, 0.6, order, 1e-2, "central", name="exp"
)
true = math.exp(0.6) # every derivative of exp equals exp
assert cert.name == "exp"
assert cert.certified
assert cert.true_derivative_interval.contains(true)
assert cert.enclosure.contains(true)python -m pytest "packages/omnibias-difference/tests/test_extraction.py::test_general_engine_certifies_function_outside_dictionary" -qMethod implementation
def certified(self) -> bool:
"""Whether the numerical estimate is consistent with the certified sandwich."""
return (
self.enclosure.lo - self.error_bound
<= self.estimate
<= self.enclosure.hi + self.error_bound
)true_derivative_intervalproperty
true_derivative_interval(self) -> IntervalThe estimate widened by the certified error: a rigorous bracket of the truth.
Returns: Interval
Executed regression · general engine certifies function outside dictionary
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_general_engine_certifies_function_outside_dictionary() -> None:
"""exp is NOT one of the nine activations; the engine still certifies it."""
exp_bound = lambda k, box: exp_iv(box) # noqa: E731 -- exp^(k) = exp
# delta=1e-2 keeps truncation above the 1/delta^order float-cancellation floor
# (at 1e-3 the order-3 stencil's roundoff would exceed the truncation bound).
for order in (1, 2, 3):
cert = certified_fd_error_general(
math.exp, exp_bound, 0.6, order, 1e-2, "central", name="exp"
)
true = math.exp(0.6) # every derivative of exp equals exp
assert cert.name == "exp"
assert cert.certified
assert cert.true_derivative_interval.contains(true)
assert cert.enclosure.contains(true)python -m pytest "packages/omnibias-difference/tests/test_extraction.py::test_general_engine_certifies_function_outside_dictionary" -qMethod implementation
def true_derivative_interval(self) -> Interval:
"""The estimate widened by the certified error: a rigorous bracket of the truth."""
return Interval(self.estimate - self.error_bound, self.estimate + self.error_bound)Read the implementation
class FiniteDifferenceCertificate:
"""A certified sandwich linking the numerical estimate to the closed-form tower.
``enclosure`` rigorously contains the true ``sigma^(order)(z)`` (closed-form),
and ``|estimate - sigma^(order)(z)| <= error_bound`` is certified by a Taylor
remainder enclosed over the whole stencil box. Hence the true derivative lies
in ``[estimate - error_bound, estimate + error_bound]`` *and* the estimate lies
in ``enclosure`` widened by ``error_bound`` -- a self-checking sandwich.
"""
name: str
order: int
z: float
delta: float
stencil: str
estimate: float
enclosure: Interval
error_bound: float
accuracy_order: int
label: str = "closed-form + numerical"
@property
def certified(self) -> bool:
"""Whether the numerical estimate is consistent with the certified sandwich."""
return (
self.enclosure.lo - self.error_bound
<= self.estimate
<= self.enclosure.hi + self.error_bound
)
@property
def true_derivative_interval(self) -> Interval:
"""The estimate widened by the certified error: a rigorous bracket of the truth."""
return Interval(self.estimate - self.error_bound, self.estimate + self.error_bound)certified_derivative_enclosure
omnibias.difference.certified_derivative_enclosureSource ↗certified_derivative_enclosure(name: str, z: IntervalLike, order: int) -> DerivativeEnclosureClosed-form interval enclosure of the derivative tower sigma^(0..order)(z).
z may be a scalar (an exact point) or an Interval (a box); the
returned value is the guaranteed enclosure of the true order-th
derivative over that box.
Parameters
| Name | Type & default | Contract |
|---|---|---|
namepositional-or-keyword | strRequired | See the operation contract and implementation below. |
zpositional-or-keyword | IntervalLikeRequired | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
DerivativeEnclosureExplicit validation & failure cases
- When
order < 0, raisesValueError(f'order must be >= 0, got {order}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · negative order raises
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_negative_order_raises() -> None:
with pytest.raises(ValueError):
certified_derivative_enclosure("tanh", 0.0, -1)
with pytest.raises(ValueError):
certified_fd_error("tanh", 0.0, -1, 1e-2)python -m pytest "packages/omnibias-difference/tests/test_extraction.py::test_negative_order_raises" -qRegression example · pointwise enclosure is tight and true
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_pointwise_enclosure_is_tight_and_true(name: str) -> None:
order = 4
z0 = 0.4
enc = certified_derivative_enclosure(name, z0, order)
true = _true_derivative(name, z0, order)
assert enc.value.lo <= true <= enc.value.hi
assert enc.value.width <= 1e-7 * (1 + abs(true))python -m pytest packages/omnibias-difference/tests/test_extraction.py -k test_pointwise_enclosure_is_tight_and_true -qRead the implementation
def certified_derivative_enclosure(
name: str, z: IntervalLike, order: int
) -> DerivativeEnclosure:
"""Closed-form interval enclosure of the derivative tower ``sigma^(0..order)(z)``.
``z`` may be a scalar (an exact point) or an :class:`Interval` (a box); the
returned ``value`` is the guaranteed enclosure of the true ``order``-th
derivative over that box.
"""
if order < 0:
raise ValueError(f"order must be >= 0, got {order}")
z_iv = Interval.from_value(z)
tower = sigma_tower_interval(name, z_iv, order)
return DerivativeEnclosure(name, order, z_iv, tower, tower[order])certified_fd_error
omnibias.difference.certified_fd_errorSource ↗certified_fd_error(name: str, z: float, order: int, delta: float, stencil: Stencil='central') -> FiniteDifferenceCertificateCertify |finite_difference - sigma^(order)(z)| <= error_bound.
A thin adapter over certified_fd_error_general that binds the built-in
activation dictionary: the float value comes from _sigma_float and the
derivative-over-box enclosures from
omnibias.core.verified.sigma.sigma_tower_interval. See the general
function for the remainder math.
Parameters
| Name | Type & default | Contract |
|---|---|---|
namepositional-or-keyword | strRequired | See the operation contract and implementation below. |
zpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
deltapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
stencilpositional-or-keyword | StencilDefault: 'central' | See the operation contract and implementation below. |
FiniteDifferenceCertificateExecuted regression · negative order raises
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_negative_order_raises() -> None:
with pytest.raises(ValueError):
certified_derivative_enclosure("tanh", 0.0, -1)
with pytest.raises(ValueError):
certified_fd_error("tanh", 0.0, -1, 1e-2)python -m pytest "packages/omnibias-difference/tests/test_extraction.py::test_negative_order_raises" -qRegression example · honesty labels are correct
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_honesty_labels_are_correct() -> None:
enc = D.certified_derivative_enclosure("tanh", 0.0, 2)
assert enc.label == "closed-form"
est = D.finite_difference_estimate("tanh", 0.0, 2, 1e-2)
assert est.label == "numerical"
cert = D.certified_fd_error("tanh", 0.0, 2, 1e-2)
assert "closed-form" in cert.label and "numerical" in cert.labelpython -m pytest packages/omnibias-difference/tests/test_scope.py -k test_honesty_labels_are_correct -qRead the implementation
def certified_fd_error(
name: str, z: float, order: int, delta: float, stencil: Stencil = "central"
) -> FiniteDifferenceCertificate:
r"""Certify ``|finite_difference - sigma^(order)(z)| <= error_bound``.
A thin adapter over :func:`certified_fd_error_general` that binds the built-in
activation dictionary: the float value comes from :func:`_sigma_float` and the
derivative-over-box enclosures from
:func:`omnibias.core.verified.sigma.sigma_tower_interval`. See the general
function for the remainder math.
"""
return certified_fd_error_general(
lambda x: _sigma_float(name, x),
lambda k, box: sigma_tower_interval(name, box, k)[k],
z,
order,
delta,
stencil,
name=name,
)certified_fd_error_general
omnibias.difference.certified_fd_error_generalSource ↗certified_fd_error_general(f_float: Callable[[float], float], deriv_bound: DerivBound, z: float, order: int, delta: float, stencil: Stencil='central', *, name: str='f') -> FiniteDifferenceCertificateCertify |finite_difference - f^(order)(z)| <= error_bound for **any** f.
The activation-agnostic core of certified_fd_error: it takes a plain
f_float (for the numerical stencil evaluation) and a DerivBound
oracle deriv_bound(k, box) enclosing f^(k) over a box, so it works for
any function with a sound derivative-tower / interval-jet enclosure -- not just
the nine built-in activations.
The stencil kills every Taylor moment below the accuracy order, so the exact
remainder is sum_j s_j b_j^{m+p} f^(m+p)(xi_j) / (m+p)! with each xi_j
in the stencil box. Enclosing f^(m+p) over that box gives the rigorous bound
|\text{error}| \le \frac{1}{(m+p)!}\Big(\sum_j |s_j|\,|b_j|^{m+p}\Big)\, \max_{\text{box}} |f^{(m+p)}|,
which is O(delta^p) (p = 1 forward, p = 2 central).
Parameters
| Name | Type & default | Contract |
|---|---|---|
f_floatpositional-or-keyword | Callable[[float], float]Required | See the operation contract and implementation below. |
deriv_boundpositional-or-keyword | DerivBoundRequired | See the operation contract and implementation below. |
zpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
deltapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
stencilpositional-or-keyword | StencilDefault: 'central' | See the operation contract and implementation below. |
namekeyword-only | strDefault: 'f' | See the operation contract and implementation below. |
FiniteDifferenceCertificateExplicit validation & failure cases
- When
order < 0, raisesValueError(f'order must be >= 0, got {order}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · negative order raises
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_negative_order_raises() -> None:
with pytest.raises(ValueError):
certified_derivative_enclosure("tanh", 0.0, -1)
with pytest.raises(ValueError):
certified_fd_error("tanh", 0.0, -1, 1e-2)python -m pytest "packages/omnibias-difference/tests/test_extraction.py::test_negative_order_raises" -qRegression example · general engine exact polynomial stencil
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_general_engine_exact_polynomial_stencil() -> None:
"""A user tower with a vanishing high derivative gives a ~zero truncation bound."""
def cubic_bound(k: int, box: Interval) -> Interval:
if k == 0:
return box.pow_int(3)
if k == 1:
return Interval.from_rational(3) * box.pow_int(2)
if k == 2:
return Interval.from_rational(6) * box
if k == 3:
return Interval.from_rational(6)
return Interval.point(0.0)
cert = certified_fd_error_general(lambda t: t**3, cubic_bound, 2.0, 2, 0.1, "central")
assert cert.error_bound < 1e-15 # f'''' = 0 -> central 2nd-deriv is exactpython -m pytest packages/omnibias-difference/tests/test_extraction.py -k test_general_engine_exact_polynomial_stencil -qRead the implementation
def certified_fd_error_general(
f_float: Callable[[float], float],
deriv_bound: DerivBound,
z: float,
order: int,
delta: float,
stencil: Stencil = "central",
*,
name: str = "f",
) -> FiniteDifferenceCertificate:
r"""Certify ``|finite_difference - f^(order)(z)| <= error_bound`` for **any** ``f``.
The activation-agnostic core of :func:`certified_fd_error`: it takes a plain
``f_float`` (for the numerical stencil evaluation) and a :data:`DerivBound`
oracle ``deriv_bound(k, box)`` enclosing ``f^(k)`` over a box, so it works for
any function with a sound derivative-tower / interval-jet enclosure -- not just
the nine built-in activations.
The stencil kills every Taylor moment below the accuracy order, so the exact
remainder is ``sum_j s_j b_j^{m+p} f^(m+p)(xi_j) / (m+p)!`` with each ``xi_j``
in the stencil box. Enclosing ``f^(m+p)`` over that box gives the rigorous bound
.. math::
|\text{error}| \le \frac{1}{(m+p)!}\Big(\sum_j |s_j|\,|b_j|^{m+p}\Big)\,
\max_{\text{box}} |f^{(m+p)}|,
which is ``O(delta^p)`` (``p = 1`` forward, ``p = 2`` central).
"""
if order < 0:
raise ValueError(f"order must be >= 0, got {order}")
p = accuracy_order(stencil)
z_iv = Interval.from_value(float(z))
enclosure = deriv_bound(order, z_iv)
# Numerical stencil estimate in plain float (the cancellation-prone register).
float_signs = stencil_signs(order, delta, stencil)
float_offsets = stencil_offsets(order, delta, stencil)
estimate = sum(
s * f_float(float(z) + b)
for s, b in zip(float_signs, float_offsets, strict=True)
)
signs = signs_exact(order, Fraction(delta))
offsets = offsets_exact(order, Fraction(delta), stencil)
mp = order + p
# Rigorous (outward) coefficient sum_j |s_j| |b_j|^{mp} / (mp)!.
coeff = Interval.point(0.0)
for s, b in zip(signs, offsets, strict=True):
coeff = coeff + Interval.from_rational(abs(s)) * (Interval.from_rational(abs(b)) ** mp)
coeff = coeff * Interval.from_rational(Fraction(1, factorial(mp)))
# Box enclosing the whole stencil support [z + min b_j, z + max b_j].
span = Interval(Interval.from_rational(min(offsets)).lo, Interval.from_rational(max(offsets)).hi)
box = z_iv + span
fmp = deriv_bound(mp, box)
error_bound = (coeff * Interval(-fmp.mag, fmp.mag)).mag
return FiniteDifferenceCertificate(
name, order, float(z), float(delta), stencil, estimate, enclosure, error_bound, p
)finite_difference_estimate
omnibias.difference.finite_difference_estimateSource ↗finite_difference_estimate(name: str, z: float, order: int, delta: float, stencil: Stencil='central') -> DifferenceEstimateNumerical multi-bias stencil sum_j s_j sigma(z + b_j) (the FD estimate).
This is the *naive* estimate: the signs scale like 1/delta^order, so for a
very small delta it loses precision to catastrophic cancellation -- exactly
the failure the closed-form tower sidesteps.
Parameters
| Name | Type & default | Contract |
|---|---|---|
namepositional-or-keyword | strRequired | See the operation contract and implementation below. |
zpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
deltapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
stencilpositional-or-keyword | StencilDefault: 'central' | See the operation contract and implementation below. |
DifferenceEstimateExecuted regression · honesty labels are correct
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_honesty_labels_are_correct() -> None:
enc = D.certified_derivative_enclosure("tanh", 0.0, 2)
assert enc.label == "closed-form"
est = D.finite_difference_estimate("tanh", 0.0, 2, 1e-2)
assert est.label == "numerical"
cert = D.certified_fd_error("tanh", 0.0, 2, 1e-2)
assert "closed-form" in cert.label and "numerical" in cert.labelpython -m pytest "packages/omnibias-difference/tests/test_scope.py::test_honesty_labels_are_correct" -qRegression example · fd converges at scheme order
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_fd_converges_at_scheme_order(stencil: str, p: int) -> None:
name, z, order = "tanh", 0.6, 3
true = _true_derivative(name, z, order)
errs = []
for delta in (1e-1, 1e-2, 1e-3):
est = finite_difference_estimate(name, z, order, delta, stencil).estimate
errs.append(abs(est - true))
# each 10x shrink of delta cuts the error by ~10^p (allow slack for constants)
for a, b in zip(errs, errs[1:], strict=False):
assert b < a
assert b <= a / (10 ** (p - 1)) * 1.5python -m pytest packages/omnibias-difference/tests/test_extraction.py -k test_fd_converges_at_scheme_order -qRead the implementation
def finite_difference_estimate(
name: str, z: float, order: int, delta: float, stencil: Stencil = "central"
) -> DifferenceEstimate:
"""Numerical multi-bias stencil ``sum_j s_j sigma(z + b_j)`` (the FD estimate).
This is the *naive* estimate: the signs scale like ``1/delta^order``, so for a
very small ``delta`` it loses precision to catastrophic cancellation -- exactly
the failure the closed-form tower sidesteps.
"""
signs = stencil_signs(order, delta, stencil)
offsets = stencil_offsets(order, delta, stencil)
estimate = sum(
s * _sigma_float(name, float(z) + b) for s, b in zip(signs, offsets, strict=True)
)
return DifferenceEstimate(name, order, float(z), float(delta), stencil, estimate)sigma_deriv_bound
omnibias.difference.sigma_deriv_boundSource ↗sigma_deriv_bound(name: str) -> DerivBoundThe DerivBound oracle for a built-in activation (from sigma_tower_interval).
Parameters
| Name | Type & default | Contract |
|---|---|---|
namepositional-or-keyword | strRequired | See the operation contract and implementation below. |
DerivBoundExecuted regression · general engine matches dictionary wrapper
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_general_engine_matches_dictionary_wrapper(name: str, order: int) -> None:
"""certified_fd_error is exactly certified_fd_error_general bound to the tower."""
import math as _math
fdict = {
"tanh": _math.tanh,
"sigmoid": lambda z: 1.0 / (1.0 + _math.exp(-z)),
"gaussian": lambda z: _math.exp(-0.5 * z * z),
"sech": lambda z: 1.0 / _math.cosh(z),
}
z, delta = 0.42, 1e-2
wrapped = certified_fd_error(name, z, order, delta, "central")
general = certified_fd_error_general(
fdict[name], sigma_deriv_bound(name), z, order, delta, "central", name=name
)
assert general.estimate == wrapped.estimate
assert general.error_bound == wrapped.error_bound
assert general.enclosure == wrapped.enclosurepython -m pytest "packages/omnibias-difference/tests/test_extraction.py::test_general_engine_matches_dictionary_wrapper[1-gaussian]" -qRead the implementation
def sigma_deriv_bound(name: str) -> DerivBound:
"""The :data:`DerivBound` oracle for a built-in activation (from ``sigma_tower_interval``)."""
return lambda k, box: sigma_tower_interval(name, box, k)[k]TransferEstimate
omnibias.difference.TransferEstimateSource ↗class TransferEstimateDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
The transfer theorem's coefficient asymptotic with a **certified** error bar.
For a singular template f(z) = scale * (1 - z/radius)^{-exponent} the true
[z^n] f is the exact rational exact_coefficient (certified); the
classical leading asymptotic scale * radius^{-n} * n^{exponent-1} /
Gamma(exponent) is leading (numerical). abs_error /
rel_error rigorously bound how far the leading term is from the exact
coefficient (abs_error is the outward magnitude of exact - leading).
Parameters
| Name | Type & default | Contract |
|---|---|---|
ndataclass field | intRequired | See the operation contract and implementation below. |
leadingdataclass field | floatRequired | See the operation contract and implementation below. |
exact_coefficientdataclass field | IntervalRequired | See the operation contract and implementation below. |
abs_errordataclass field | floatRequired | See the operation contract and implementation below. |
rel_errordataclass field | floatRequired | See the operation contract and implementation below. |
labeldataclass field | strDefault: 'numerical asymptotic + certified exact-coefficient enclosure' | See the operation contract and implementation below. |
Fields & methods
nfield
n: intDeclared int field on TransferEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗leadingfield
leading: floatDeclared float field on TransferEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗exact_coefficientfield
exact_coefficient: IntervalDeclared Interval field on TransferEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗abs_errorfield
abs_error: floatDeclared float field on TransferEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗rel_errorfield
rel_error: floatDeclared float field on TransferEstimate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗labelfield
label: str = 'numerical asymptotic + certified exact-coefficient enclosure'Declared str field on TransferEstimate. Default expression: 'numerical asymptotic + certified exact-coefficient enclosure'.
Read the implementation
class TransferEstimate:
r"""The transfer theorem's coefficient asymptotic with a **certified** error bar.
For a singular template ``f(z) = scale * (1 - z/radius)^{-exponent}`` the true
``[z^n] f`` is the exact rational :attr:`exact_coefficient` (certified); the
classical leading asymptotic ``scale * radius^{-n} * n^{exponent-1} /
Gamma(exponent)`` is :attr:`leading` (numerical). :attr:`abs_error` /
:attr:`rel_error` rigorously bound how far the leading term is from the exact
coefficient (``abs_error`` is the outward magnitude of ``exact - leading``).
"""
n: int
leading: float
exact_coefficient: Interval
abs_error: float
rel_error: float
label: str = "numerical asymptotic + certified exact-coefficient enclosure"bell_asymptotic_relative_error
omnibias.difference.bell_asymptotic_relative_errorSource ↗bell_asymptotic_relative_error(n: int) -> floatRelative error of the refined Bell saddle point vs the exact B_n (numerical).
Computed in **log space** as |expm1(log_approx - log_exact)| = |approx/exact - 1|,
using math.log on the exact big-integer ~omnibias.difference._core.stirling.bell_number
(Python's log accepts arbitrary-precision ints). This avoids the float overflow
that the value-space form bell_number_asymptotic_refined hits past n ~ 150,
so the probe is valid for arbitrarily large n. It is a *calibration* probe for
recommended_bell_fallback_n, not a hot path.
Empirically the error decays like ~n^{-3/2} in the large-n regime but is
**non-monotone** at small n: it dips to ~4e-5 at n = 5 (a near-cancellation
fluke), rises back to a ~2.8e-4 local max near n = 10, then decreases -- which is
exactly why recommended_bell_fallback_n uses a last-exceedance (not first-crossing)
rule.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExecuted regression · recommended fallback raises when window too small
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_recommended_fallback_raises_when_window_too_small() -> None:
with pytest.raises(ValueError, match="widen n_max"):
recommended_bell_fallback_n(1e-9, n_max=200)python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_recommended_fallback_raises_when_window_too_small" -qRegression example · relative error probe no overflow large n
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_relative_error_probe_no_overflow_large_n() -> None:
# log-space probe is valid past the value-form overflow horizon (n ~ 150).
assert bell_asymptotic_relative_error(400) < 1e-5python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_relative_error_probe_no_overflow_large_n -qRead the implementation
def bell_asymptotic_relative_error(n: int) -> float:
r"""Relative error of the refined Bell saddle point vs the exact ``B_n`` (numerical).
Computed in **log space** as ``|expm1(log_approx - log_exact)| = |approx/exact - 1|``,
using :func:`math.log` on the exact big-integer :func:`~omnibias.difference._core.stirling.bell_number`
(Python's ``log`` accepts arbitrary-precision ints). This avoids the ``float`` overflow
that the value-space form :func:`bell_number_asymptotic_refined` hits past ``n ~ 150``,
so the probe is valid for arbitrarily large ``n``. It is a *calibration* probe for
:func:`recommended_bell_fallback_n`, not a hot path.
Empirically the error decays like ``~n^{-3/2}`` in the large-``n`` regime but is
**non-monotone** at small ``n``: it dips to ``~4e-5`` at ``n = 5`` (a near-cancellation
fluke), rises back to a ``~2.8e-4`` local max near ``n = 10``, then decreases -- which is
exactly why :func:`recommended_bell_fallback_n` uses a last-exceedance (not first-crossing)
rule.
"""
from omnibias.difference._core.stirling import bell_number
log_exact = log(bell_number(n))
log_approx = log_bell_number_asymptotic_refined(n)
return abs(expm1(log_approx - log_exact))bell_dobinski_enclosure
omnibias.difference.bell_dobinski_enclosureSource ↗bell_dobinski_enclosure(n: int, *, rel_tol: float=1e-18, max_terms: int=100000) -> IntervalCertified enclosure of the Bell number B_n via Dobinski's formula (n >= 1).
B_n = e^{-1} sum_{k>=0} k^n / k!. The terms t_k = k^n/k! rise then fall with a
ratio t_{k+1}/t_k = (1 + 1/k)^n / (k+1) that decreases monotonically in k; once
it drops below 1 (past the peak) the omitted tail obeys the geometric bound
sum_{j>k} t_j <= t_k q / (1-q) with q = ratio(k) < 1 (since later ratios are
smaller). Summation continues until that certified tail is below rel_tol times the
partial sum, so the enclosure is float-tight. The exact rational partial sum plus the
rigorous tail, divided by the certified e (E_IV), provably contains B_n -- a
genuine (non-asymptotic) error bar for the Bell numbers, complementing the saddle point.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
rel_tolkeyword-only | floatDefault: 1e-18 | See the operation contract and implementation below. |
max_termskeyword-only | intDefault: 100000 | See the operation contract and implementation below. |
IntervalExplicit validation & failure cases
- When
n < 1, raisesValueError(f'n must be >= 1, got {n}'). - When
rel_tol <= 0.0, raisesValueError(f'rel_tol must be > 0, got {rel_tol}'). - When
k > max_terms, raisesRuntimeError(f'Dobinski tail did not converge within {max_terms} terms').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · bell dobinski contains exact
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_bell_dobinski_contains_exact(n: int) -> None:
assert _encloses(bell_dobinski_enclosure(n), bell_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_bell_dobinski_contains_exact[10]" -qRegression example · bell dobinski contains mpmath
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_bell_dobinski_contains_mpmath(n: int) -> None:
assert bell_dobinski_enclosure(n).contains(float(mpmath.bell(n)))python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_bell_dobinski_contains_mpmath -qRead the implementation
def bell_dobinski_enclosure(
n: int, *, rel_tol: float = 1e-18, max_terms: int = 100_000
) -> Interval:
r"""Certified enclosure of the Bell number ``B_n`` via Dobinski's formula (``n >= 1``).
``B_n = e^{-1} sum_{k>=0} k^n / k!``. The terms ``t_k = k^n/k!`` rise then fall with a
ratio ``t_{k+1}/t_k = (1 + 1/k)^n / (k+1)`` that decreases monotonically in ``k``; once
it drops below ``1`` (past the peak) the omitted tail obeys the geometric bound
``sum_{j>k} t_j <= t_k q / (1-q)`` with ``q = ratio(k) < 1`` (since later ratios are
smaller). Summation continues until that certified tail is below ``rel_tol`` times the
partial sum, so the enclosure is float-tight. The exact rational partial sum plus the
rigorous tail, divided by the certified ``e`` (``E_IV``), provably contains ``B_n`` -- a
genuine (non-asymptotic) error bar for the Bell numbers, complementing the saddle point.
"""
if n < 1:
raise ValueError(f"n must be >= 1, got {n}")
if rel_tol <= 0.0:
raise ValueError(f"rel_tol must be > 0, got {rel_tol}")
tol = Fraction(rel_tol).limit_denominator(10**18)
partial = Fraction(0)
tail_hi = Fraction(0)
k = 1
while True:
t_k = Fraction(k**n, factorial(k))
partial += t_k
ratio = Fraction((k + 1) ** n, k**n * (k + 1)) # t_{k+1}/t_k, decreasing in k
if ratio < 1:
# sum_{j>k} t_j <= t_k q/(1-q); tight once the peak is well behind us.
tail_hi = t_k * ratio / (1 - ratio)
if tail_hi <= partial * tol:
break
k += 1
if k > max_terms: # pragma: no cover - safety valve, never hit for sane n
raise RuntimeError(f"Dobinski tail did not converge within {max_terms} terms")
total = Interval(
Interval.from_rational(partial).lo,
Interval.from_rational(partial + tail_hi).hi,
)
return total * E_IV.reciprocal() # multiply by e^{-1}bell_number_asymptotic_refined
omnibias.difference.bell_number_asymptotic_refinedSource ↗bell_number_asymptotic_refined(n: int) -> floatRefined Moser--Wyman Bell asymptotic; see log_bell_number_asymptotic_refined.
Returns the value as a float, which **overflows** for n beyond ~150
(B_n exceeds the double range). For large n -- or any relative-accuracy
comparison -- use log_bell_number_asymptotic_refined and stay in log space
(see bell_asymptotic_relative_error).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
log_val > 709.78, raisesOverflowError(f'bell_number_asymptotic_refined({n}) overflows float (log value {log_val:.1f} > 709.78); use log_bell_number_asymptotic_refined').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · bell value asymptotic matches log form small n
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_bell_value_asymptotic_matches_log_form_small_n() -> None:
for n in (5, 20, 60):
assert bell_number_asymptotic_refined(n) == pytest.approx(
mpmath.e ** log_bell_number_asymptotic_refined(n), rel=1e-12
)python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_bell_value_asymptotic_matches_log_form_small_n" -qRegression example · log bell asymptotic no overflow large n
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_log_bell_asymptotic_no_overflow_large_n() -> None:
# log form stays finite where the value form overflows float.
assert log_bell_number_asymptotic_refined(1000) > 0.0
with pytest.raises(OverflowError, match="overflows float"):
bell_number_asymptotic_refined(1000)python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_log_bell_asymptotic_no_overflow_large_n -qRead the implementation
def bell_number_asymptotic_refined(n: int) -> float:
r"""Refined Moser--Wyman Bell asymptotic; see :func:`log_bell_number_asymptotic_refined`.
Returns the value as a ``float``, which **overflows** for ``n`` beyond ``~150``
(``B_n`` exceeds the double range). For large ``n`` -- or any relative-accuracy
comparison -- use :func:`log_bell_number_asymptotic_refined` and stay in log space
(see :func:`bell_asymptotic_relative_error`).
"""
log_val = log_bell_number_asymptotic_refined(n)
if log_val > 709.78:
raise OverflowError(
f"bell_number_asymptotic_refined({n}) overflows float "
f"(log value {log_val:.1f} > 709.78); use log_bell_number_asymptotic_refined"
)
return exp(log_val)bernoulli_enclosure
omnibias.difference.bernoulli_enclosureSource ↗bernoulli_enclosure(n: int) -> IntervalCertified signed enclosure of the Bernoulli number B_n (even n >= 2).
B_{2m} = (-1)^{m+1} \, 2 (2m)! \, zeta(2m) / (2 pi)^{2m}, composing the exact
(2m)!, the certified zeta_int_enclosure, and the certified 2 pi from
PI_IV. The enclosure provably contains the exact B_n; its relative width
-> 0 as n grows (zeta(2m) -> 1) -- the error bar the float asymptotic
~omnibias.difference._core.asymptotics.bernoulli_asymptotic lacks.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
IntervalExplicit validation & failure cases
- When
n < 2 or n % 2 == 1, raisesValueError(f'bernoulli_enclosure is defined for even n >= 2, got {n}'). - When
n > _FACTORIAL_FLOAT_LIMIT, raisesValueError(f'bernoulli_enclosure overflows float for n > {_FACTORIAL_FLOAT_LIMIT}; a log-space enclosure is out of scope').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · bernoulli enclosure contains exact
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_bernoulli_enclosure_contains_exact(n: int) -> None:
assert _encloses(bernoulli_enclosure(n), bernoulli_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_bernoulli_enclosure_contains_exact[10]" -qRegression example · bernoulli enclosure contains mpmath
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_bernoulli_enclosure_contains_mpmath(n: int) -> None:
assert bernoulli_enclosure(n).contains(float(mpmath.bernoulli(n)))python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_bernoulli_enclosure_contains_mpmath -qRead the implementation
def bernoulli_enclosure(n: int) -> Interval:
r"""Certified signed enclosure of the Bernoulli number ``B_n`` (even ``n >= 2``).
``B_{2m} = (-1)^{m+1} \, 2 (2m)! \, zeta(2m) / (2 pi)^{2m}``, composing the exact
``(2m)!``, the certified :func:`zeta_int_enclosure`, and the certified ``2 pi`` from
``PI_IV``. The enclosure provably contains the exact ``B_n``; its relative width
``-> 0`` as ``n`` grows (``zeta(2m) -> 1``) -- the error bar the float asymptotic
:func:`~omnibias.difference._core.asymptotics.bernoulli_asymptotic` lacks.
"""
if n < 2 or n % 2 == 1:
raise ValueError(f"bernoulli_enclosure is defined for even n >= 2, got {n}")
if n > _FACTORIAL_FLOAT_LIMIT:
raise ValueError(
f"bernoulli_enclosure overflows float for n > {_FACTORIAL_FLOAT_LIMIT}; "
"a log-space enclosure is out of scope"
)
m = n // 2
# Fold the tiny (2 pi)^{-n} factor in *before* the large (2m)! so no
# intermediate overflows float even when the final B_n is representable.
scale = Interval.from_rational(2) * (Interval.from_rational(2) * PI_IV).pow_int(n).reciprocal()
magnitude = scale * Interval.from_rational(factorial(n)) * zeta_int_enclosure(n)
return magnitude if m % 2 == 1 else -magnitude # sign (-1)^{m+1}catalan_asymptotic
omnibias.difference.catalan_asymptoticSource ↗catalan_asymptotic(n: int) -> floatSingularity-analysis asymptotic C_n ~ 4^n / (sqrt(pi) n^{3/2}) (numerical).
The OGF (1 - sqrt(1 - 4x)) / (2x) has its dominant singularity at x = 1/4;
the square-root branch point gives the n^{-3/2} sub-exponential factor.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
n < 1, raisesValueError(f'n must be >= 1, got {n}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · catalan asymptotic ratio to exact
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_catalan_asymptotic_ratio_to_exact() -> None:
# C_n ~ 4^n / (sqrt(pi) n^{3/2}); ratio -> 1 (from above) and improves with n.
def exact(n: int) -> int:
return comb(2 * n, n) // (n + 1)
r30 = catalan_asymptotic(30) / exact(30)
r200 = catalan_asymptotic(200) / exact(200)
assert 1.0 < r200 < r30 < 1.05python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_catalan_asymptotic_ratio_to_exact" -qRegression example · catalan leading matches classic asymptotic
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_catalan_leading_matches_classic_asymptotic(self) -> None:
# Catalan singular part -2 (1 - 4z)^{1/2}; leading term == catalan_asymptotic.
for n in (10, 20, 40):
est = transfer_theorem(-2, Fraction(1, 4), Fraction(-1, 2), n)
assert est.leading == pytest.approx(catalan_asymptotic(n), rel=1e-9)python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_catalan_leading_matches_classic_asymptotic -qRead the implementation
def catalan_asymptotic(n: int) -> float:
r"""Singularity-analysis asymptotic ``C_n ~ 4^n / (sqrt(pi) n^{3/2})`` (numerical).
The OGF ``(1 - sqrt(1 - 4x)) / (2x)`` has its dominant singularity at ``x = 1/4``;
the square-root branch point gives the ``n^{-3/2}`` sub-exponential factor.
"""
if n < 1:
raise ValueError(f"n must be >= 1, got {n}")
return exp(n * log(4.0) - 0.5 * log(pi) - 1.5 * log(n))cauchy_product
omnibias.difference.cauchy_productSource ↗cauchy_product(a: Sequence[Rational], b: Sequence[Rational]) -> tuple[Fraction, ...]Coefficients of the OGF product (sum a_i x^i)(sum b_j x^j) (exact).
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
bpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
not af or not bf, raisesValueError('cauchy_product needs non-empty coefficient lists').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · cauchy product rejects empty
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_cauchy_product_rejects_empty() -> None:
with pytest.raises(ValueError, match="non-empty"):
cauchy_product([], [1])python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_cauchy_product_rejects_empty" -qRegression example · cauchy product matches manual
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_cauchy_product_matches_manual() -> None:
# (1 + 2x)(1 + 3x + x^2) = 1 + 5x + 7x^2 + 2x^3.
assert cauchy_product([1, 2], [1, 3, 1]) == (1, 5, 7, 2)python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_cauchy_product_matches_manual -qRead the implementation
def cauchy_product(a: Sequence[Rational], b: Sequence[Rational]) -> tuple[Fraction, ...]:
r"""Coefficients of the OGF product ``(sum a_i x^i)(sum b_j x^j)`` (exact)."""
af = [Fraction(x) for x in a]
bf = [Fraction(x) for x in b]
if not af or not bf:
raise ValueError("cauchy_product needs non-empty coefficient lists")
out: list[Fraction] = []
for n in range(len(af) + len(bf) - 1):
lo = max(0, n - len(bf) + 1)
hi = min(n, len(af) - 1)
out.append(sum((af[i] * bf[n - i] for i in range(lo, hi + 1)), Fraction(0)))
return tuple(out)dirichlet_beta_odd_enclosure
omnibias.difference.dirichlet_beta_odd_enclosureSource ↗dirichlet_beta_odd_enclosure(s: int, *, terms: int=64) -> IntervalCertified enclosure of the Dirichlet beta beta(s) = sum_k (-1)^k (2k+1)^{-s}.
For odd s >= 1 (where the closed form beta(2m+1) is a rational multiple of
pi^{2m+1}). The series is alternating with terms decreasing to zero, so the true
value lies between two consecutive partial sums -- the tight one-term bracket used
here.
Parameters
| Name | Type & default | Contract |
|---|---|---|
spositional-or-keyword | intRequired | See the operation contract and implementation below. |
termskeyword-only | intDefault: 64 | See the operation contract and implementation below. |
IntervalExplicit validation & failure cases
- When
s < 1 or s % 2 == 0, raisesValueError(f'dirichlet_beta_odd_enclosure requires odd s >= 1, got {s}'). - When
terms < 1, raisesValueError(f'terms must be >= 1, got {terms}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qRegression example · dirichlet beta enclosure contains mpmath
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_dirichlet_beta_enclosure_contains_mpmath(s: int) -> None:
iv = dirichlet_beta_odd_enclosure(s, terms=200)
assert iv.lo <= float(_mp_beta(s)) <= iv.hipython -m pytest packages/omnibias-difference/tests/test_generating.py -k test_dirichlet_beta_enclosure_contains_mpmath -qRead the implementation
def dirichlet_beta_odd_enclosure(s: int, *, terms: int = 64) -> Interval:
r"""Certified enclosure of the Dirichlet beta ``beta(s) = sum_k (-1)^k (2k+1)^{-s}``.
For odd ``s >= 1`` (where the closed form ``beta(2m+1)`` is a rational multiple of
``pi^{2m+1}``). The series is alternating with terms decreasing to zero, so the true
value lies between two consecutive partial sums -- the tight one-term bracket used
here.
"""
if s < 1 or s % 2 == 0:
raise ValueError(f"dirichlet_beta_odd_enclosure requires odd s >= 1, got {s}")
if terms < 1:
raise ValueError(f"terms must be >= 1, got {terms}")
partial = sum(
(Fraction((-1) ** k, (2 * k + 1) ** s) for k in range(terms)), Fraction(0)
)
nxt = partial + Fraction((-1) ** terms, (2 * terms + 1) ** s)
lo, hi = (partial, nxt) if partial <= nxt else (nxt, partial)
return Interval(Interval.from_rational(lo).lo, Interval.from_rational(hi).hi)dominant_pole_coefficient_asymptotic
omnibias.difference.dominant_pole_coefficient_asymptoticSource ↗dominant_pole_coefficient_asymptotic(numer: Sequence[Rational], denom: Sequence[Rational], n: int) -> floatLeading coefficient asymptotic c * rho^{-n} of a rational OGF (numerical).
For f = numer/denom (ascending order) with a **simple, real, dominant** pole
rho (the smallest-modulus denominator root), singularity analysis gives
[z^n] f ~ c rho^{-n} with residue-derived c = -numer(rho) / (rho
denom'(rho)). Numerical (the pole comes from _polynomial_roots); raises if
the dominant pole is complex (an oscillatory asymptotic needs the conjugate pair).
The exact coefficients themselves are available -- exactly -- from
rational_ogf_coefficients; this is the closed-form *growth law*.
Parameters
| Name | Type & default | Contract |
|---|---|---|
numerpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
denompositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
n < 0, raisesValueError(f'n must be >= 0, got {n}'). - When
not roots, raisesValueError('denom must be a non-constant polynomial'). - When
rho == 0, raisesValueError('denom has a zero root: not an ordinary-generating-function singularity'). - When
abs(rho.imag) > 1e-09 * max(1.0, abs(rho.real)), raisesValueError('dominant pole is complex; the coefficient asymptotic is oscillatory'). - When
dprime == 0, raisesValueError("dominant pole is not simple (denom'(rho) = 0)").
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · simple geometric
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_simple_geometric(self) -> None:
# 1/(1 - 2z) has [z^n] = 2^n exactly (single real pole).
assert dominant_pole_coefficient_asymptotic([1], [1, -2], 12) == pytest.approx(4096.0)python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestDominantPole::test_simple_geometric" -qRegression example · complex dominant pole raises
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_complex_dominant_pole_raises(self) -> None:
# 1/(1 + z^2) has poles at +/- i (purely imaginary, oscillatory).
with pytest.raises(ValueError):
dominant_pole_coefficient_asymptotic([1], [1, 0, 1], 5)python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_complex_dominant_pole_raises -qRead the implementation
def dominant_pole_coefficient_asymptotic(
numer: Sequence[Rational], denom: Sequence[Rational], n: int
) -> float:
r"""Leading coefficient asymptotic ``c * rho^{-n}`` of a rational OGF (numerical).
For ``f = numer/denom`` (ascending order) with a **simple, real, dominant** pole
``rho`` (the smallest-modulus denominator root), singularity analysis gives
``[z^n] f ~ c rho^{-n}`` with residue-derived ``c = -numer(rho) / (rho
denom'(rho))``. Numerical (the pole comes from :func:`_polynomial_roots`); raises if
the dominant pole is complex (an oscillatory asymptotic needs the conjugate pair).
The exact coefficients themselves are available -- exactly -- from
:func:`rational_ogf_coefficients`; this is the closed-form *growth law*.
"""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
roots = _polynomial_roots([complex(Fraction(x)) for x in denom])
if not roots:
raise ValueError("denom must be a non-constant polynomial")
rho = min(roots, key=abs)
if rho == 0:
raise ValueError("denom has a zero root: not an ordinary-generating-function singularity")
if abs(rho.imag) > 1e-9 * max(1.0, abs(rho.real)):
raise ValueError("dominant pole is complex; the coefficient asymptotic is oscillatory")
num_val = sum(complex(Fraction(numer[i])) * rho**i for i in range(len(numer)))
dprime = sum(i * complex(Fraction(denom[i])) * rho ** (i - 1) for i in range(1, len(denom)))
if dprime == 0:
raise ValueError("dominant pole is not simple (denom'(rho) = 0)")
c = -num_val / (rho * dprime)
return c.real * rho.real ** (-n)euler_enclosure
omnibias.difference.euler_enclosureSource ↗euler_enclosure(n: int) -> IntervalCertified signed enclosure of the (secant) Euler number E_n (even n >= 2).
E_{2m} = (-1)^m \, 2^{2m+2} (2m)! \, beta(2m+1) / pi^{2m+1}, composing the exact
factors, the certified dirichlet_beta_odd_enclosure, and PI_IV. Provably
contains the exact E_n with relative width -> 0 (beta(2m+1) -> 1).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
IntervalExplicit validation & failure cases
- When
n < 2 or n % 2 == 1, raisesValueError(f'euler_enclosure is defined for even n >= 2, got {n}'). - When
n > _FACTORIAL_FLOAT_LIMIT, raisesValueError(f'euler_enclosure overflows float for n > {_FACTORIAL_FLOAT_LIMIT}; a log-space enclosure is out of scope').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qRegression example · euler enclosure contains mpmath
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_euler_enclosure_contains_mpmath(n: int) -> None:
assert euler_enclosure(n).contains(float(mpmath.eulernum(n)))python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_euler_enclosure_contains_mpmath -qRead the implementation
def euler_enclosure(n: int) -> Interval:
r"""Certified signed enclosure of the (secant) Euler number ``E_n`` (even ``n >= 2``).
``E_{2m} = (-1)^m \, 2^{2m+2} (2m)! \, beta(2m+1) / pi^{2m+1}``, composing the exact
factors, the certified :func:`dirichlet_beta_odd_enclosure`, and ``PI_IV``. Provably
contains the exact ``E_n`` with relative width ``-> 0`` (``beta(2m+1) -> 1``).
"""
if n < 2 or n % 2 == 1:
raise ValueError(f"euler_enclosure is defined for even n >= 2, got {n}")
if n > _FACTORIAL_FLOAT_LIMIT:
raise ValueError(
f"euler_enclosure overflows float for n > {_FACTORIAL_FLOAT_LIMIT}; "
"a log-space enclosure is out of scope"
)
m = n // 2
# Fold the tiny 2^{2m+2} / pi^{2m+1} ratio in *before* the large (2m)! so no
# intermediate overflows float (2^{n+2}*(2m)! alone overflows around n~130
# even though the final E_n stays representable to n~180).
scale = Interval.from_rational(2 ** (n + 2)) * PI_IV.pow_int(n + 1).reciprocal()
magnitude = scale * Interval.from_rational(factorial(n)) * dirichlet_beta_odd_enclosure(n + 1)
return magnitude if m % 2 == 0 else -magnitude # sign (-1)^mexponential_generating_coeffs
omnibias.difference.exponential_generating_coeffsSource ↗exponential_generating_coeffs(seq: Sequence[Rational]) -> tuple[Fraction, ...]EGF coefficients a_n / n! of a sequence a_0, a_1, ... (exact).
Parameters
| Name | Type & default | Contract |
|---|---|---|
seqpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · egf ogf round trip
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_egf_ogf_round_trip() -> None:
seq = [3, 1, 4, 1, 5, 9, 2, 6]
egf = exponential_generating_coeffs(seq)
assert egf[0] == 3 and egf[1] == 1 and egf[2] == Fraction(4, 2)
assert list(ordinary_from_exponential(egf)) == [Fraction(x) for x in seq]python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_egf_ogf_round_trip" -qRead the implementation
def exponential_generating_coeffs(seq: Sequence[Rational]) -> tuple[Fraction, ...]:
r"""EGF coefficients ``a_n / n!`` of a sequence ``a_0, a_1, ...`` (exact)."""
return tuple(Fraction(a) / factorial(n) for n, a in enumerate(seq))log_bell_number_asymptotic_refined
omnibias.difference.log_bell_number_asymptotic_refinedSource ↗log_bell_number_asymptotic_refined(n: int) -> floatRefined log Bell-number saddle-point (R = W(n+1) + Canfield q_n).
Uses the Moser--Wyman / Szekeres--Binet convention R e^R = n + 1 (numerically
superior to r e^r = n):
B_n \approx \frac{n!\,e^{e^R - 1}}{R^{n}\sqrt{2\pi(n+1)(R+1)}}\; q_n,
with the Canfield correction q_n = 1 - e^{-R}/12 (1 - 3/(2R) - 10/R^2 - 9/R^3
+ 1/R^4)/(1 + 1/R)^3 (B_n / E_n = 1 + O(e^{-R/5})). Roughly ~90x tighter
than ~omnibias.difference._core.asymptotics.log_bell_number_asymptotic
at n = 30 (~1e-4 vs ~1e-2 relative error). Still **numerical** -- for a
rigorous bound use bell_dobinski_enclosure.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
n < 1, raisesValueError(f'n must be >= 1, got {n}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · recommended fallback raises when window too small
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_recommended_fallback_raises_when_window_too_small() -> None:
with pytest.raises(ValueError, match="widen n_max"):
recommended_bell_fallback_n(1e-9, n_max=200)python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_recommended_fallback_raises_when_window_too_small" -qRegression example · bell value asymptotic matches log form small n
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_bell_value_asymptotic_matches_log_form_small_n() -> None:
for n in (5, 20, 60):
assert bell_number_asymptotic_refined(n) == pytest.approx(
mpmath.e ** log_bell_number_asymptotic_refined(n), rel=1e-12
)python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_bell_value_asymptotic_matches_log_form_small_n -qRead the implementation
def log_bell_number_asymptotic_refined(n: int) -> float:
r"""Refined log Bell-number saddle-point (``R = W(n+1)`` + Canfield ``q_n``).
Uses the Moser--Wyman / Szekeres--Binet convention ``R e^R = n + 1`` (numerically
superior to ``r e^r = n``):
.. math::
B_n \approx \frac{n!\,e^{e^R - 1}}{R^{n}\sqrt{2\pi(n+1)(R+1)}}\; q_n,
with the Canfield correction ``q_n = 1 - e^{-R}/12 (1 - 3/(2R) - 10/R^2 - 9/R^3
+ 1/R^4)/(1 + 1/R)^3`` (``B_n / E_n = 1 + O(e^{-R/5})``). Roughly ~90x tighter
than :func:`~omnibias.difference._core.asymptotics.log_bell_number_asymptotic`
at ``n = 30`` (~1e-4 vs ~1e-2 relative error). Still **numerical** -- for a
rigorous bound use :func:`bell_dobinski_enclosure`.
"""
if n < 1:
raise ValueError(f"n must be >= 1, got {n}")
big_r = _lambert_w(float(n + 1))
log_e = (
lgamma(n + 1)
+ ((n + 1) / big_r - 1.0)
- n * log(big_r)
- 0.5 * log(2.0 * pi * (n + 1) * (big_r + 1.0))
)
e_neg_r = big_r / (n + 1.0) # e^{-R} since R e^R = n + 1
q = 1.0 - e_neg_r / 12.0 * (
1.0 - 1.5 / big_r - 10.0 / big_r**2 - 9.0 / big_r**3 + 1.0 / big_r**4
) / (1.0 + 1.0 / big_r) ** 3
return log_e + log(q)ordinary_from_exponential
omnibias.difference.ordinary_from_exponentialSource ↗ordinary_from_exponential(egf_coeffs: Sequence[Rational]) -> tuple[Fraction, ...]Recover the sequence a_n = n! c_n from EGF coefficients c_n (inverse).
Parameters
| Name | Type & default | Contract |
|---|---|---|
egf_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · egf ogf round trip
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_egf_ogf_round_trip() -> None:
seq = [3, 1, 4, 1, 5, 9, 2, 6]
egf = exponential_generating_coeffs(seq)
assert egf[0] == 3 and egf[1] == 1 and egf[2] == Fraction(4, 2)
assert list(ordinary_from_exponential(egf)) == [Fraction(x) for x in seq]python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_egf_ogf_round_trip" -qRead the implementation
def ordinary_from_exponential(egf_coeffs: Sequence[Rational]) -> tuple[Fraction, ...]:
r"""Recover the sequence ``a_n = n! c_n`` from EGF coefficients ``c_n`` (inverse)."""
return tuple(Fraction(c) * factorial(n) for n, c in enumerate(egf_coeffs))rational_ogf_coefficients
omnibias.difference.rational_ogf_coefficientsSource ↗rational_ogf_coefficients(numer: Sequence[Rational], denom: Sequence[Rational], count: int) -> tuple[Fraction, ...]Power-series coefficients [x^0..x^{count-1}] of numer(x) / denom(x) (exact).
Both polynomials are given in **ascending** order ([c_0, c_1, ...]); the
denominator's constant term must be non-zero. This is the exact linear-recurrence
unrolling c_n = (num_n - sum_{k>=1} den_k c_{n-k}) / den_0 -- e.g. the Fibonacci
OGF x / (1 - x - x^2) (numer=[0, 1], denom=[1, -1, -1]) yields
0, 1, 1, 2, 3, 5, ....
Parameters
| Name | Type & default | Contract |
|---|---|---|
numerpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
denompositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
countpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
count < 0, raisesValueError(f'count must be >= 0, got {count}'). - When
not den or den[0] == 0, raisesValueError('denom must be non-empty with a non-zero constant term').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · rational ogf rejects zero constant denom
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_rational_ogf_rejects_zero_constant_denom() -> None:
with pytest.raises(ValueError, match="non-zero constant term"):
rational_ogf_coefficients([1], [0, 1], 4)python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_rational_ogf_rejects_zero_constant_denom" -qRegression example · rational ogf recovers geometric
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_rational_ogf_recovers_geometric() -> None:
# 1 / (1 - 2x) -> 2^n.
geo = rational_ogf_coefficients([1], [1, -2], 8)
assert list(geo) == [1, 2, 4, 8, 16, 32, 64, 128]python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_rational_ogf_recovers_geometric -qRead the implementation
def rational_ogf_coefficients(
numer: Sequence[Rational], denom: Sequence[Rational], count: int
) -> tuple[Fraction, ...]:
r"""Power-series coefficients ``[x^0..x^{count-1}]`` of ``numer(x) / denom(x)`` (exact).
Both polynomials are given in **ascending** order (``[c_0, c_1, ...]``); the
denominator's constant term must be non-zero. This is the exact linear-recurrence
unrolling ``c_n = (num_n - sum_{k>=1} den_k c_{n-k}) / den_0`` -- e.g. the Fibonacci
OGF ``x / (1 - x - x^2)`` (``numer=[0, 1]``, ``denom=[1, -1, -1]``) yields
``0, 1, 1, 2, 3, 5, ...``.
"""
if count < 0:
raise ValueError(f"count must be >= 0, got {count}")
num = [Fraction(x) for x in numer]
den = [Fraction(x) for x in denom]
if not den or den[0] == 0:
raise ValueError("denom must be non-empty with a non-zero constant term")
coeffs: list[Fraction] = []
for n in range(count):
acc = num[n] if n < len(num) else Fraction(0)
for k in range(1, min(n, len(den) - 1) + 1):
acc -= den[k] * coeffs[n - k]
coeffs.append(acc / den[0])
return tuple(coeffs)rational_ogf_growth_base
omnibias.difference.rational_ogf_growth_baseSource ↗rational_ogf_growth_base(denom: Sequence[Rational]) -> floatExponential growth base 1/|rho| from the dominant singularity of a rational OGF.
rho is the smallest-modulus root of the (ascending-order) denominator; by
singularity analysis the coefficients grow like rho^{-n} up to a subexponential
factor. Numerical (root-finding). E.g. the Fibonacci denominator [1, -1, -1]
gives the golden ratio phi and [1, -2] (OGF 1/(1-2x)) gives 2.
Parameters
| Name | Type & default | Contract |
|---|---|---|
denompositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
not roots, raisesValueError('denom must be a non-constant polynomial'). - When
rho == 0.0, raisesValueError('denom has a zero root: not an ordinary-generating-function singularity').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · growth base geometric is two
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_growth_base_geometric_is_two() -> None:
assert abs(rational_ogf_growth_base([1, -2]) - 2.0) < 1e-10python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_growth_base_geometric_is_two" -qRegression example · growth base fibonacci is golden ratio
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_growth_base_fibonacci_is_golden_ratio() -> None:
phi = (1 + 5**0.5) / 2
assert abs(rational_ogf_growth_base([1, -1, -1]) - phi) < 1e-10python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_growth_base_fibonacci_is_golden_ratio -qRead the implementation
def rational_ogf_growth_base(denom: Sequence[Rational]) -> float:
r"""Exponential growth base ``1/|rho|`` from the dominant singularity of a rational OGF.
``rho`` is the smallest-modulus root of the (ascending-order) denominator; by
singularity analysis the coefficients grow like ``rho^{-n}`` up to a subexponential
factor. Numerical (root-finding). E.g. the Fibonacci denominator ``[1, -1, -1]``
gives the golden ratio ``phi`` and ``[1, -2]`` (OGF ``1/(1-2x)``) gives ``2``.
"""
roots = _polynomial_roots([complex(Fraction(x)) for x in denom])
if not roots:
raise ValueError("denom must be a non-constant polynomial")
rho = min(abs(r) for r in roots)
if rho == 0.0:
raise ValueError("denom has a zero root: not an ordinary-generating-function singularity")
return 1.0 / rhorecommended_bell_fallback_n
omnibias.difference.recommended_bell_fallback_nSource ↗recommended_bell_fallback_n(rel_tol: float, *, n_max: int=400) -> intSmallest n beyond which the refined saddle point stays within rel_tol.
Because bell_asymptotic_relative_error is **non-monotone** at small n (it
dips below ~1e-4 at n = 5 then rises again through n ~ 10), a naive
first-crossing search is *unsound* -- it can return an n whose immediate successors
exceed rel_tol. Instead this scans the whole window 2..n_max and returns
last_exceed + 1: the smallest n such that **every** measured m >= n in the
window satisfies err(m) <= rel_tol. That is the data-driven cutoff beyond which the
fast asymptotic may replace the slow exact Bell computation.
Raises ValueError if the tolerance is still violated at n_max (the window does
not certify the cutoff -- widen n_max); returns 2 if the tolerance already holds
across the entire window.
Parameters
| Name | Type & default | Contract |
|---|---|---|
rel_tolpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
n_maxkeyword-only | intDefault: 400 | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
rel_tol <= 0.0, raisesValueError(f'rel_tol must be > 0, got {rel_tol}'). - When
errors[-1][1] > rel_tol, raisesValueError(f'refined Bell asymptotic still exceeds rel_tol {rel_tol} at n_max={n_max} (err={errors[-1][1]:.3e}); widen n_max').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · recommended fallback raises when window too small
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_recommended_fallback_raises_when_window_too_small() -> None:
with pytest.raises(ValueError, match="widen n_max"):
recommended_bell_fallback_n(1e-9, n_max=200)python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_recommended_fallback_raises_when_window_too_small" -qRegression example · recommended fallback is sound
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_recommended_fallback_is_sound(tol: float) -> None:
n0 = recommended_bell_fallback_n(tol, n_max=200)
# every measured index at/above the cutoff must satisfy the tolerance
assert all(bell_asymptotic_relative_error(n) <= tol for n in range(n0, 201))python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_recommended_fallback_is_sound -qRead the implementation
def recommended_bell_fallback_n(rel_tol: float, *, n_max: int = 400) -> int:
r"""Smallest ``n`` beyond which the refined saddle point stays within ``rel_tol``.
Because :func:`bell_asymptotic_relative_error` is **non-monotone** at small ``n`` (it
dips below ``~1e-4`` at ``n = 5`` then rises again through ``n ~ 10``), a naive
first-crossing search is *unsound* -- it can return an ``n`` whose immediate successors
exceed ``rel_tol``. Instead this scans the whole window ``2..n_max`` and returns
``last_exceed + 1``: the smallest ``n`` such that **every** measured ``m >= n`` in the
window satisfies ``err(m) <= rel_tol``. That is the data-driven cutoff beyond which the
fast asymptotic may replace the slow exact Bell computation.
Raises ``ValueError`` if the tolerance is still violated at ``n_max`` (the window does
not certify the cutoff -- widen ``n_max``); returns ``2`` if the tolerance already holds
across the entire window.
"""
if rel_tol <= 0.0:
raise ValueError(f"rel_tol must be > 0, got {rel_tol}")
errors = [(n, bell_asymptotic_relative_error(n)) for n in range(2, n_max + 1)]
if errors[-1][1] > rel_tol:
raise ValueError(
f"refined Bell asymptotic still exceeds rel_tol {rel_tol} at n_max={n_max} "
f"(err={errors[-1][1]:.3e}); widen n_max"
)
last_exceed = max((n for n, e in errors if e > rel_tol), default=None)
return 2 if last_exceed is None else last_exceed + 1singular_template_coefficient
omnibias.difference.singular_template_coefficientSource ↗singular_template_coefficient(exponent: Rational, n: int) -> FractionExact [z^n] (1 - z)^{-exponent} for any rational exponent (closed-form).
The generalised binomial binom(n + exponent - 1, n) = prod_{j=0}^{n-1}
(exponent + j) / (j + 1), a product of rationals -- so the coefficient is an
**exact** ~fractions.Fraction, with no Gamma evaluation. This is the
standard-function scale whose coefficients the Flajolet-Sedgewick transfer theorem
maps a singularity onto: exponent = 1 gives the geometric 1s (simple pole),
exponent = -1/2 gives 1, -1/2, -1/8, ... (the square-root branch point behind
Catalan / tree / lattice-path counts).
Parameters
| Name | Type & default | Contract |
|---|---|---|
exponentpositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
FractionExplicit validation & failure cases
- When
n < 0, raisesValueError(f'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 · negative n raises
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_negative_n_raises(self) -> None:
with pytest.raises(ValueError):
singular_template_coefficient(1, -1)python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestSingularTemplateCoefficient::test_negative_n_raises" -qRegression example · geometric pole
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_geometric_pole(self) -> None:
# [z^n] (1 - z)^{-1} = 1 for all n.
assert all(singular_template_coefficient(1, n) == 1 for n in range(6))python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_geometric_pole -qRead the implementation
def singular_template_coefficient(exponent: Rational, n: int) -> Fraction:
r"""Exact ``[z^n] (1 - z)^{-exponent}`` for any rational ``exponent`` (closed-form).
The generalised binomial ``binom(n + exponent - 1, n) = prod_{j=0}^{n-1}
(exponent + j) / (j + 1)``, a product of rationals -- so the coefficient is an
**exact** :class:`~fractions.Fraction`, with no ``Gamma`` evaluation. This is the
standard-function scale whose coefficients the Flajolet-Sedgewick transfer theorem
maps a singularity onto: ``exponent = 1`` gives the geometric ``1``s (simple pole),
``exponent = -1/2`` gives ``1, -1/2, -1/8, ...`` (the square-root branch point behind
Catalan / tree / lattice-path counts).
"""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
alpha = Fraction(exponent)
product = Fraction(1)
for j in range(n):
product *= (alpha + j) / Fraction(j + 1)
return producttransfer_theorem
omnibias.difference.transfer_theoremSource ↗transfer_theorem(scale: Rational | float, radius: Rational | float, exponent: Rational, n: int) -> TransferEstimateTransfer an algebraic OGF singularity to its [z^n] asymptotics (certified error).
Maps the singular element scale * (1 - z/radius)^{-exponent} -- a **pole**
(exponent a positive integer) or an **algebraic** branch point (exponent a
non-integer rational) at z = radius -- to the coefficient asymptotic
[z^n] f \;\sim\; \text{scale}\;\text{radius}^{-n}\, \frac{n^{\text{exponent}-1}}{\Gamma(\text{exponent})},
returning it (~TransferEstimate.leading, numerical) alongside the **exact**
coefficient singular_template_coefficient scaled by scale * radius^{-n}
(a certified Interval) and the rigorous gap between them. exponent must
not be a non-positive integer (where the template is a polynomial and Gamma has a
pole); n >= 1.
Parameters
| Name | Type & default | Contract |
|---|---|---|
scalepositional-or-keyword | Rational | floatRequired | See the operation contract and implementation below. |
radiuspositional-or-keyword | Rational | floatRequired | See the operation contract and implementation below. |
exponentpositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
TransferEstimateExplicit validation & failure cases
- When
n < 1, raisesValueError(f'transfer_theorem needs n >= 1, got {n}'). - When
alpha <= 0 and alpha.denominator == 1, raisesValueError(f'exponent must not be a non-positive integer (template is a polynomial), got {alpha}'). - When
radius == 0, raisesValueError('radius (the singularity location) must be non-zero').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · n must be positive
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_n_must_be_positive(self) -> None:
with pytest.raises(ValueError):
transfer_theorem(1, Fraction(1, 2), 1, 0)python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestTransferTheorem::test_n_must_be_positive" -qRegression example · non positive integer exponent raises
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_non_positive_integer_exponent_raises(self) -> None:
with pytest.raises(ValueError):
transfer_theorem(1, Fraction(1, 2), 0, 5)
with pytest.raises(ValueError):
transfer_theorem(1, Fraction(1, 2), -1, 5)python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_non_positive_integer_exponent_raises -qRead the implementation
def transfer_theorem(
scale: Rational | float, radius: Rational | float, exponent: Rational, n: int
) -> TransferEstimate:
r"""Transfer an algebraic OGF singularity to its ``[z^n]`` asymptotics (certified error).
Maps the singular element ``scale * (1 - z/radius)^{-exponent}`` -- a **pole**
(``exponent`` a positive integer) or an **algebraic** branch point (``exponent`` a
non-integer rational) at ``z = radius`` -- to the coefficient asymptotic
.. math::
[z^n] f \;\sim\; \text{scale}\;\text{radius}^{-n}\,
\frac{n^{\text{exponent}-1}}{\Gamma(\text{exponent})},
returning it (:attr:`~TransferEstimate.leading`, numerical) alongside the **exact**
coefficient :func:`singular_template_coefficient` scaled by ``scale * radius^{-n}``
(a certified :class:`Interval`) and the rigorous gap between them. ``exponent`` must
not be a non-positive integer (where the template is a polynomial and ``Gamma`` has a
pole); ``n >= 1``.
"""
if n < 1:
raise ValueError(f"transfer_theorem needs n >= 1, got {n}")
alpha = Fraction(exponent)
if alpha <= 0 and alpha.denominator == 1:
raise ValueError(
f"exponent must not be a non-positive integer (template is a polynomial), got {alpha}"
)
if radius == 0:
raise ValueError("radius (the singularity location) must be non-zero")
template = singular_template_coefficient(alpha, n)
scale_iv = Interval.from_value(scale if isinstance(scale, float) else Fraction(scale))
radius_iv = Interval.from_value(radius if isinstance(radius, float) else Fraction(radius))
exact = scale_iv * radius_iv.pow_int(n).reciprocal() * Interval.from_rational(template)
a = float(alpha)
leading = float(scale) * float(radius) ** (-n) * n ** (a - 1.0) / gamma(a)
abs_error = (exact - Interval.point(leading)).mag
rel_error = abs_error / abs(leading) if leading != 0.0 else float("inf")
return TransferEstimate(n, leading, exact, abs_error, rel_error)zeta_int_enclosure
omnibias.difference.zeta_int_enclosureSource ↗zeta_int_enclosure(s: int, *, terms: int=64) -> IntervalCertified enclosure of zeta(s) = sum_{n>=1} n^{-s} for integer s >= 2.
Exact rational partial sum over terms terms plus a **two-sided** integral-test
tail bracket int_{N+1}^inf x^{-s} dx <= tail <= int_N^inf x^{-s} dx (x^{-s}
is decreasing), i.e. (N+1)^{1-s}/(s-1) <= tail <= N^{1-s}/(s-1). The returned
interval provably contains the true zeta(s).
Parameters
| Name | Type & default | Contract |
|---|---|---|
spositional-or-keyword | intRequired | See the operation contract and implementation below. |
termskeyword-only | intDefault: 64 | See the operation contract and implementation below. |
IntervalExplicit validation & failure cases
- When
s < 2, raisesValueError(f'zeta_int_enclosure requires integer s >= 2, got {s}'). - When
terms < 1, raisesValueError(f'terms must be >= 1, got {terms}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · bernoulli enclosure contains exact
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_bernoulli_enclosure_contains_exact(n: int) -> None:
assert _encloses(bernoulli_enclosure(n), bernoulli_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_bernoulli_enclosure_contains_exact[10]" -qRegression example · zeta enclosure contains mpmath
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_zeta_enclosure_contains_mpmath(s: int) -> None:
iv = zeta_int_enclosure(s)
z = mpmath.zeta(s)
assert iv.lo <= float(z) <= iv.hi
# the two-sided integral-test bracket is tight for a modest term count
assert iv.width < 1e-2python -m pytest packages/omnibias-difference/tests/test_generating.py -k test_zeta_enclosure_contains_mpmath -qRead the implementation
def zeta_int_enclosure(s: int, *, terms: int = 64) -> Interval:
r"""Certified enclosure of ``zeta(s) = sum_{n>=1} n^{-s}`` for integer ``s >= 2``.
Exact rational partial sum over ``terms`` terms plus a **two-sided** integral-test
tail bracket ``int_{N+1}^inf x^{-s} dx <= tail <= int_N^inf x^{-s} dx`` (``x^{-s}``
is decreasing), i.e. ``(N+1)^{1-s}/(s-1) <= tail <= N^{1-s}/(s-1)``. The returned
interval provably contains the true ``zeta(s)``.
"""
if s < 2:
raise ValueError(f"zeta_int_enclosure requires integer s >= 2, got {s}")
if terms < 1:
raise ValueError(f"terms must be >= 1, got {terms}")
partial = sum((Fraction(1, n**s) for n in range(1, terms + 1)), Fraction(0))
tail_hi = Fraction(1, (s - 1) * terms ** (s - 1))
tail_lo = Fraction(1, (s - 1) * (terms + 1) ** (s - 1))
tail = Interval(Interval.from_rational(tail_lo).lo, Interval.from_rational(tail_hi).hi)
return Interval.from_rational(partial) + tailRationalIdentityVerdict
omnibias.difference.RationalIdentityVerdictSource ↗class RationalIdentityVerdictDataclass 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.
A sealed special-number-identity certificate plus its Lean-kernel adjudication.
Parameters
| Name | Type & default | Contract |
|---|---|---|
certificatedataclass field | CertRequired | See the operation contract and implementation below. |
obligationdataclass field | str | NoneRequired | See the operation contract and implementation below. |
leandataclass field | LeanCheckResultRequired | See the operation contract and implementation below. |
Executed regression · zeta value identity earns theorem prover verified
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_zeta_value_identity_earns_theorem_prover_verified(self) -> None:
verdict = check_identity_certificate(zeta_negative_odd_identity(2, _ZETA_NEG[2]))
assert verdict.theorem_prover_verifiedpython -m pytest "packages/omnibias-difference/tests/test_identities.py::TestRealLeanKernelPass::test_zeta_value_identity_earns_theorem_prover_verified" -qFields & methods
certificatefield
certificate: CertDeclared Cert field on RationalIdentityVerdict. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗obligationfield
obligation: str | NoneDeclared str | None field on RationalIdentityVerdict. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗leanfield
lean: LeanCheckResultDeclared LeanCheckResult field on RationalIdentityVerdict. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗theorem_prover_verifiedproperty
theorem_prover_verified(self) -> boolTrue only on a genuine Lean lake build pass (never forged).
Returns: bool
Executed regression · zeta value identity earns theorem prover verified
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_zeta_value_identity_earns_theorem_prover_verified(self) -> None:
verdict = check_identity_certificate(zeta_negative_odd_identity(2, _ZETA_NEG[2]))
assert verdict.theorem_prover_verifiedpython -m pytest "packages/omnibias-difference/tests/test_identities.py::TestRealLeanKernelPass::test_zeta_value_identity_earns_theorem_prover_verified" -qMethod implementation
def theorem_prover_verified(self) -> bool:
"""``True`` only on a genuine Lean ``lake build`` pass (never forged)."""
return self.lean.verifiedsealed_okproperty
sealed_ok(self) -> boolWhether the certificate's tamper-evident digest matches its body.
Returns: bool
Executed regression · theorem prover verified is never forged
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_theorem_prover_verified_is_never_forged(self) -> None:
verdict = check_identity_certificate(bernoulli_recurrence_identity(4))
assert verdict.theorem_prover_verified == verdict.lean.verified
assert verdict.obligation_generated and verdict.sealed_ok
if not lean_check_available():
assert not verdict.lean.available
assert not verdict.theorem_prover_verifiedpython -m pytest "packages/omnibias-difference/tests/test_identities.py::TestSealingAndHonesty::test_theorem_prover_verified_is_never_forged" -qMethod implementation
def sealed_ok(self) -> bool:
"""Whether the certificate's tamper-evident digest matches its body."""
return verify_certificate_digest(self.certificate)obligation_generatedproperty
obligation_generated(self) -> boolWhether a finite, Lean-checkable obligation was produced.
Returns: bool
Executed regression · theorem prover verified is never forged
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_theorem_prover_verified_is_never_forged(self) -> None:
verdict = check_identity_certificate(bernoulli_recurrence_identity(4))
assert verdict.theorem_prover_verified == verdict.lean.verified
assert verdict.obligation_generated and verdict.sealed_ok
if not lean_check_available():
assert not verdict.lean.available
assert not verdict.theorem_prover_verifiedpython -m pytest "packages/omnibias-difference/tests/test_identities.py::TestSealingAndHonesty::test_theorem_prover_verified_is_never_forged" -qMethod implementation
def obligation_generated(self) -> bool:
"""Whether a finite, Lean-checkable obligation was produced."""
return self.obligation is not NoneRead the implementation
class RationalIdentityVerdict:
"""A sealed special-number-identity certificate plus its Lean-kernel adjudication."""
certificate: Cert
obligation: str | None
lean: LeanCheckResult
@property
def theorem_prover_verified(self) -> bool:
"""``True`` only on a genuine Lean ``lake build`` pass (never forged)."""
return self.lean.verified
@property
def sealed_ok(self) -> bool:
"""Whether the certificate's tamper-evident digest matches its body."""
return verify_certificate_digest(self.certificate)
@property
def obligation_generated(self) -> bool:
"""Whether a finite, Lean-checkable obligation was produced."""
return self.obligation is not Nonebernoulli_recurrence_identity
omnibias.difference.bernoulli_recurrence_identitySource ↗bernoulli_recurrence_identity(n: int) -> CertCertificate for sum_{k=0}^{n-1} C(n,k) B_k = 0 (n >= 2).
Scales the B_k to their common denominator D so the obligation is the
exact integer identity sum_k C(n,k) (B_k D) = 0.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
CertExplicit validation & failure cases
- When
n < 2, raisesValueError(f'Bernoulli recurrence needs n >= 2, got {n}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · bernoulli recurrence earns theorem prover verified
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_bernoulli_recurrence_earns_theorem_prover_verified(self) -> None:
verdict = check_identity_certificate(bernoulli_recurrence_identity(6))
assert verdict.lean.available
assert verdict.theorem_prover_verified # a genuine kernel passpython -m pytest "packages/omnibias-difference/tests/test_identities.py::TestRealLeanKernelPass::test_bernoulli_recurrence_earns_theorem_prover_verified" -qRegression example · bernoulli recurrence is zero
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_bernoulli_recurrence_is_zero(self, n: int) -> None:
cert = bernoulli_recurrence_identity(n)
assert _lhs_sum(cert) == cert["payload"]["rhs"] == 0
# Independent check of the classical recurrence in exact rationals.
assert sum(comb(n, k) * bernoulli_number_exact(k) for k in range(n)) == 0python -m pytest packages/omnibias-difference/tests/test_identities.py -k test_bernoulli_recurrence_is_zero -qRead the implementation
def bernoulli_recurrence_identity(n: int) -> Cert:
r"""Certificate for ``sum_{k=0}^{n-1} C(n,k) B_k = 0`` (``n >= 2``).
Scales the ``B_k`` to their common denominator ``D`` so the obligation is the
exact integer identity ``sum_k C(n,k) (B_k D) = 0``.
"""
if n < 2:
raise ValueError(f"Bernoulli recurrence needs n >= 2, got {n}")
bs = [bernoulli_number_exact(k) for k in range(n)]
den = 1
for b in bs:
den = lcm(den, b.denominator)
terms: list[_IntTerm] = [(comb(n, k), int(bs[k] * den)) for k in range(n)]
meta = {"identity": "bernoulli_recurrence", "n": n, "common_denominator": den, "label": "closed-form"}
return _identity_certificate(f"sum_k C({n},k) B_k = 0", terms, 0, meta=meta)bernoulli_sign_certificate
omnibias.difference.bernoulli_sign_certificateSource ↗bernoulli_sign_certificate(m: int) -> CertCertificate that sign(B_2m) = (-1)^{m+1} (the EM remainder-sign driver).
The Euler-Maclaurin remainder after the B_2m correction term has the sign of
B_2m; this seals the numerator (over the positive denominator) in a point
interval so the kernel's sign obligation (enclosed_quantity_pos /
enclosed_quantity_neg) certifies the alternation +,-,+,.... The magnitude
may round in float, but the sign -- all that the obligation needs -- does not.
Parameters
| Name | Type & default | Contract |
|---|---|---|
mpositional-or-keyword | intRequired | See the operation contract and implementation below. |
CertExplicit validation & failure cases
- When
m < 1, raisesValueError(f'm must be >= 1, got {m}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · domain guards
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_domain_guards(self) -> None:
with pytest.raises(ValueError, match="n >= 2"):
bernoulli_recurrence_identity(1)
with pytest.raises(ValueError, match="m >= 1"):
euler_recurrence_identity(0)
with pytest.raises(ValueError, match="m must be >= 1"):
bernoulli_sign_certificate(0)python -m pytest "packages/omnibias-difference/tests/test_identities.py::TestInputGuards::test_domain_guards" -qRegression example · bernoulli sign obligation alternates
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_bernoulli_sign_obligation_alternates(self) -> None:
# sign(B_2m) = (-1)^{m+1}: +, -, +, - ... drives the EM remainder sign.
pos = generate_obligation(bernoulli_sign_certificate(1)) # B_2 = 1/6 > 0
neg = generate_obligation(bernoulli_sign_certificate(2)) # B_4 = -1/30 < 0
assert pos is not None and "enclosed_quantity_pos" in pos
assert neg is not None and "enclosed_quantity_neg" in negpython -m pytest packages/omnibias-difference/tests/test_identities.py -k test_bernoulli_sign_obligation_alternates -qRead the implementation
def bernoulli_sign_certificate(m: int) -> Cert:
r"""Certificate that ``sign(B_2m) = (-1)^{m+1}`` (the EM remainder-sign driver).
The Euler-Maclaurin remainder after the ``B_2m`` correction term has the sign of
``B_2m``; this seals the numerator (over the positive denominator) in a point
interval so the kernel's sign obligation (``enclosed_quantity_pos`` /
``enclosed_quantity_neg``) certifies the alternation ``+,-,+,...``. The magnitude
may round in ``float``, but the sign -- all that the obligation needs -- does not.
"""
if m < 1:
raise ValueError(f"m must be >= 1, got {m}")
b = bernoulli_number_exact(2 * m)
numerator = b.numerator # denominator > 0, so sign(B_2m) = sign(numerator)
expected_sign = "+" if (-1) ** (m + 1) > 0 else "-"
claim = f"sign(B_{2 * m}) = {expected_sign} (Euler-Maclaurin remainder-sign driver)"
meta = {"identity": "bernoulli_sign", "m": m, "expected_sign": expected_sign, "label": "closed-form"}
return interval_certificate(claim, Interval.point(float(numerator)), honesty={"unproven_claim": False}, meta=meta)check_identity_certificate
omnibias.difference.check_identity_certificateSource ↗check_identity_certificate(cert: Cert, *, timeout: float=600.0, start: Path | None=None) -> RationalIdentityVerdictGenerate the obligation for cert and run the Lean-kernel bridge on it.
theorem_prover_verified is set only on a real kernel pass; with no Lean
toolchain the bridge degrades gracefully, so this is safe in a normal CI run.
Parameters
| Name | Type & default | Contract |
|---|---|---|
certpositional-or-keyword | CertRequired | See the operation contract and implementation below. |
timeoutkeyword-only | floatDefault: 600.0 | See the operation contract and implementation below. |
startkeyword-only | Path | NoneDefault: None | See the operation contract and implementation below. |
RationalIdentityVerdictExecuted regression · zeta value identity earns theorem prover verified
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_zeta_value_identity_earns_theorem_prover_verified(self) -> None:
verdict = check_identity_certificate(zeta_negative_odd_identity(2, _ZETA_NEG[2]))
assert verdict.theorem_prover_verifiedpython -m pytest "packages/omnibias-difference/tests/test_identities.py::TestRealLeanKernelPass::test_zeta_value_identity_earns_theorem_prover_verified" -qRegression example · bernoulli recurrence earns theorem prover verified
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_bernoulli_recurrence_earns_theorem_prover_verified(self) -> None:
verdict = check_identity_certificate(bernoulli_recurrence_identity(6))
assert verdict.lean.available
assert verdict.theorem_prover_verified # a genuine kernel passpython -m pytest packages/omnibias-difference/tests/test_identities.py -k test_bernoulli_recurrence_earns_theorem_prover_verified -qRead the implementation
def check_identity_certificate(
cert: Cert, *, timeout: float = 600.0, start: Path | None = None
) -> RationalIdentityVerdict:
"""Generate the obligation for ``cert`` and run the Lean-kernel bridge on it.
``theorem_prover_verified`` is set only on a real kernel pass; with no Lean
toolchain the bridge degrades gracefully, so this is safe in a normal CI run.
"""
obligation = generate_obligation(cert)
lean = check_certificate(cert, timeout=timeout, start=start)
return RationalIdentityVerdict(cert, obligation, lean)euler_recurrence_identity
omnibias.difference.euler_recurrence_identitySource ↗euler_recurrence_identity(m: int) -> CertCertificate for sum_{k=0}^{m} C(2m,2k) E_{2k} = 0 (m >= 1).
The Euler (secant) numbers are integers, so no scaling is needed.
Parameters
| Name | Type & default | Contract |
|---|---|---|
mpositional-or-keyword | intRequired | See the operation contract and implementation below. |
CertExplicit validation & failure cases
- When
m < 1, raisesValueError(f'Euler recurrence needs m >= 1, got {m}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · euler recurrence is zero
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_euler_recurrence_is_zero(self, m: int) -> None:
cert = euler_recurrence_identity(m)
assert _lhs_sum(cert) == 0
assert sum(comb(2 * m, 2 * k) * euler_number_exact(2 * k) for k in range(m + 1)) == 0python -m pytest "packages/omnibias-difference/tests/test_identities.py::TestIdentitiesHoldExactly::test_euler_recurrence_is_zero[1]" -qRegression example · domain guards
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_domain_guards(self) -> None:
with pytest.raises(ValueError, match="n >= 2"):
bernoulli_recurrence_identity(1)
with pytest.raises(ValueError, match="m >= 1"):
euler_recurrence_identity(0)
with pytest.raises(ValueError, match="m must be >= 1"):
bernoulli_sign_certificate(0)python -m pytest packages/omnibias-difference/tests/test_identities.py -k test_domain_guards -qRead the implementation
def euler_recurrence_identity(m: int) -> Cert:
r"""Certificate for ``sum_{k=0}^{m} C(2m,2k) E_{2k} = 0`` (``m >= 1``).
The Euler (secant) numbers are integers, so no scaling is needed.
"""
if m < 1:
raise ValueError(f"Euler recurrence needs m >= 1, got {m}")
terms: list[_IntTerm] = [(comb(2 * m, 2 * k), euler_number_exact(2 * k)) for k in range(m + 1)]
meta = {"identity": "euler_recurrence", "m": m, "label": "closed-form"}
return _identity_certificate(f"sum_k C({2 * m},2k) E_2k = 0", terms, 0, meta=meta)rational_value_identity
omnibias.difference.rational_value_identitySource ↗rational_value_identity(claim: str, computed: Fraction, expected: Fraction, *, meta: dict[str, Any] | None=None) -> CertCertificate that computed == expected via cross-multiplication.
For computed = p_c/q_c and expected = p_e/q_e (positive denominators),
the obligation is the exact Int equality p_c q_e - p_e q_c = 0.
Parameters
| Name | Type & default | Contract |
|---|---|---|
claimpositional-or-keyword | strRequired | See the operation contract and implementation below. |
computedpositional-or-keyword | FractionRequired | See the operation contract and implementation below. |
expectedpositional-or-keyword | FractionRequired | See the operation contract and implementation below. |
metakeyword-only | dict[str, Any] | NoneDefault: None | See the operation contract and implementation below. |
CertExecuted regression · zeta value identity earns theorem prover verified
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_zeta_value_identity_earns_theorem_prover_verified(self) -> None:
verdict = check_identity_certificate(zeta_negative_odd_identity(2, _ZETA_NEG[2]))
assert verdict.theorem_prover_verifiedpython -m pytest "packages/omnibias-difference/tests/test_identities.py::TestRealLeanKernelPass::test_zeta_value_identity_earns_theorem_prover_verified" -qRegression example · euler recurrence is zero
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_euler_recurrence_is_zero(self, m: int) -> None:
cert = euler_recurrence_identity(m)
assert _lhs_sum(cert) == 0
assert sum(comb(2 * m, 2 * k) * euler_number_exact(2 * k) for k in range(m + 1)) == 0python -m pytest packages/omnibias-difference/tests/test_identities.py -k test_euler_recurrence_is_zero -qRead the implementation
def rational_value_identity(
claim: str, computed: Fraction, expected: Fraction, *, meta: dict[str, Any] | None = None
) -> Cert:
r"""Certificate that ``computed == expected`` via cross-multiplication.
For ``computed = p_c/q_c`` and ``expected = p_e/q_e`` (positive denominators),
the obligation is the exact ``Int`` equality ``p_c q_e - p_e q_c = 0``.
"""
pc, qc = computed.numerator, computed.denominator
pe, qe = expected.numerator, expected.denominator
terms: list[_IntTerm] = [(qe, pc), (-qc, pe)]
payload_meta: dict[str, Any] = {"computed": str(computed), "expected": str(expected), "label": "closed-form"}
if meta:
payload_meta.update(meta)
return _identity_certificate(claim, terms, 0, meta=payload_meta)zeta_negative_odd_identity
omnibias.difference.zeta_negative_odd_identitySource ↗zeta_negative_odd_identity(m: int, expected: Fraction) -> CertCertificate that zeta(1-2m) = -B_2m/(2m) equals a textbook expected.
Computes the right-hand side from the exact Bernoulli number and cross-checks it
against the supplied literature value (e.g. zeta(-1) = -1/12), so a wrong
Bernoulli scaling or sign would be caught by the kernel.
Parameters
| Name | Type & default | Contract |
|---|---|---|
mpositional-or-keyword | intRequired | See the operation contract and implementation below. |
expectedpositional-or-keyword | FractionRequired | See the operation contract and implementation below. |
CertExplicit validation & failure cases
- When
m < 1, raisesValueError(f'm must be >= 1, got {m}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · zeta value identity earns theorem prover verified
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_zeta_value_identity_earns_theorem_prover_verified(self) -> None:
verdict = check_identity_certificate(zeta_negative_odd_identity(2, _ZETA_NEG[2]))
assert verdict.theorem_prover_verifiedpython -m pytest "packages/omnibias-difference/tests/test_identities.py::TestRealLeanKernelPass::test_zeta_value_identity_earns_theorem_prover_verified" -qRegression example · zeta negative odd matches textbook
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_zeta_negative_odd_matches_textbook(self, m: int) -> None:
cert = zeta_negative_odd_identity(m, _ZETA_NEG[m])
assert _lhs_sum(cert) == 0 # -B_2m/(2m) == textbook value
assert -bernoulli_number_exact(2 * m) / Fraction(2 * m) == _ZETA_NEG[m]python -m pytest packages/omnibias-difference/tests/test_identities.py -k test_zeta_negative_odd_matches_textbook -qRead the implementation
def zeta_negative_odd_identity(m: int, expected: Fraction) -> Cert:
r"""Certificate that ``zeta(1-2m) = -B_2m/(2m)`` equals a textbook ``expected``.
Computes the right-hand side from the exact Bernoulli number and cross-checks it
against the supplied literature value (e.g. ``zeta(-1) = -1/12``), so a wrong
Bernoulli scaling or sign would be caught by the kernel.
"""
if m < 1:
raise ValueError(f"m must be >= 1, got {m}")
computed = -bernoulli_number_exact(2 * m) / Fraction(2 * m)
meta = {"identity": "zeta_negative_odd", "m": m, "s": 1 - 2 * m}
return rational_value_identity(f"zeta({1 - 2 * m}) = -B_{2 * m}/{2 * m}", computed, expected, meta=meta)IrregularStencil
omnibias.difference.IrregularStencilSource ↗class IrregularStencilDataclass 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.
Exact rational irregular stencil (scale-free weights A_{i,p}).
Parameters
| Name | Type & default | Contract |
|---|---|---|
requestdataclass field | StencilRequestRequired | See the operation contract and implementation below. |
weightsdataclass field | tuple[tuple[Fraction, ...], ...]Required | See the operation contract and implementation below. |
accuracydataclass field | intRequired | See the operation contract and implementation below. |
leading_coeffdataclass field | FractionRequired | See the operation contract and implementation below. |
weight_magnitudedataclass field | FractionRequired | See the operation contract and implementation below. |
Executed regression · to rational stencil seals consistency
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_to_rational_stencil_seals_consistency() -> None:
"""01-04 generator output is a 01-11 rational obligation."""
from omnibias.core.proof import seal_stencil_certificate, stencil_consistency_obligation
req = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
st = solve_irregular_stencil(req)
assert st is not None
rat = st.to_rational_stencil(name="birkhoff_from_generator")
obl = stencil_consistency_obligation(rat)
assert obl.holds
assert rat.computed_leading() == Fraction(5, 18)
report = seal_stencil_certificate(rat, run_lean=False)
assert report.mathlib_verified is False
assert report.certificate["payload"]["type"] == "rational_stencil_consistency"python -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_to_rational_stencil_seals_consistency" -qFields & methods
requestfield
request: StencilRequestDeclared StencilRequest field on IrregularStencil. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗weightsfield
weights: tuple[tuple[Fraction, ...], ...]Declared tuple[tuple[Fraction, ...], ...] field on IrregularStencil. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗accuracyfield
accuracy: intDeclared int field on IrregularStencil. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗leading_coefffield
leading_coeff: FractionDeclared Fraction field on IrregularStencil. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗weight_magnitudefield
weight_magnitude: FractionDeclared Fraction field on IrregularStencil. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗to_rational_stencilmethod
to_rational_stencil(self, *, name: str='irregular') -> AnyExact-Q view for theory 01-11 Lean obligations.
leading_coeff on the returned stencil is omitted so the
sealer certifies the computed C_N moment, not a later
unmatched residual.
Parameters
| Name | Type & default | Contract |
|---|---|---|
namekeyword-only | strDefault: 'irregular' | See the operation contract and implementation below. |
Returns: Any
Executed regression · to rational stencil seals consistency
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_to_rational_stencil_seals_consistency() -> None:
"""01-04 generator output is a 01-11 rational obligation."""
from omnibias.core.proof import seal_stencil_certificate, stencil_consistency_obligation
req = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
st = solve_irregular_stencil(req)
assert st is not None
rat = st.to_rational_stencil(name="birkhoff_from_generator")
obl = stencil_consistency_obligation(rat)
assert obl.holds
assert rat.computed_leading() == Fraction(5, 18)
report = seal_stencil_certificate(rat, run_lean=False)
assert report.mathlib_verified is False
assert report.certificate["payload"]["type"] == "rational_stencil_consistency"python -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_to_rational_stencil_seals_consistency" -qMethod implementation
def to_rational_stencil(self, *, name: str = "irregular") -> Any:
"""Exact-``Q`` view for theory 01-11 Lean obligations.
``leading_coeff`` on the returned stencil is omitted so the
sealer certifies the computed ``C_N`` moment, not a later
unmatched residual.
"""
from omnibias.core.proof.obligations.rational_stencil import RationalStencil
return RationalStencil(
self.request.nodes,
self.request.orders,
self.weights,
self.request.target_order,
leading_coeff=None,
name=name,
)Read the implementation
class IrregularStencil:
"""Exact rational irregular stencil (scale-free weights ``A_{i,p}``)."""
request: StencilRequest
weights: tuple[tuple[Fraction, ...], ...]
accuracy: int
leading_coeff: Fraction
weight_magnitude: Fraction
def to_rational_stencil(self, *, name: str = "irregular") -> Any:
"""Exact-``Q`` view for theory 01-11 Lean obligations.
``leading_coeff`` on the returned stencil is omitted so the
sealer certifies the computed ``C_N`` moment, not a later
unmatched residual.
"""
from omnibias.core.proof.obligations.rational_stencil import RationalStencil
return RationalStencil(
self.request.nodes,
self.request.orders,
self.weights,
self.request.target_order,
leading_coeff=None,
name=name,
)StencilRequest
omnibias.difference.StencilRequestSource ↗class StencilRequestDataclass 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.
A Birkhoff finite-difference request.
Parameters
nodes: Dimensionless node locations c_i (physical nodes are c_i h).
orders: Available derivative orders at each node (non-empty, unique, >= 0).
target_order: Derivative order q to recover at the expansion point 0.
Parameters
| Name | Type & default | Contract |
|---|---|---|
nodesdataclass field | tuple[Fraction, ...]Required | Dimensionless node locations c_i (physical nodes are c_i h). |
ordersdataclass field | tuple[tuple[int, ...], ...]Required | Available derivative orders at each node (non-empty, unique, >= 0). |
target_orderdataclass field | intRequired | Derivative order q to recover at the expansion point 0. |
Executed regression · request rejects duplicate nodes
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_request_rejects_duplicate_nodes() -> None:
with pytest.raises(ValueError, match="distinct"):
StencilRequest((Fraction(0), Fraction(0)), ((0,), (1,)), 0)python -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_request_rejects_duplicate_nodes" -qRegression example · g1 reproduces signs exact forward and central
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_reproduces_signs_exact_forward_and_central() -> None:
h = Fraction(1, 7)
for order in (0, 1, 2, 3):
for kind in ("forward", "central"):
req = _uniform_value_request(order, kind)
st = solve_irregular_stencil(req)
assert st is not None, (order, kind)
phys = physical_weights(st, h)
flat = tuple(w[0] for w in phys)
expected = signs_exact(order, h)
assert flat == expected, (order, kind, flat, expected)python -m pytest packages/omnibias-difference/tests/test_irregular.py -k test_g1_reproduces_signs_exact_forward_and_central -qFields & methods
nodesfield
nodes: tuple[Fraction, ...]Dimensionless node locations c_i (physical nodes are c_i h).
ordersfield
orders: tuple[tuple[int, ...], ...]Available derivative orders at each node (non-empty, unique, >= 0).
target_orderfield
target_order: intDerivative order q to recover at the expansion point 0.
__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
not nodes, raisesValueError('StencilRequest requires at least one node'). - When
len(nodes) != len(self.orders), raisesValueError('nodes and orders must have the same length'). - When
len(set(nodes)) != len(nodes), raisesValueError('nodes must be distinct'). - When
not seq, raisesValueError(f'orders[{i}] must be non-empty'). - When
any((p < 0 for p in seq)), raisesValueError(f'orders[{i}] must be >= 0'). - When
len(set(seq)) != len(seq), raisesValueError(f'orders[{i}] must be unique'). - When
q < 0, raisesValueError(f'target_order must be >= 0, got {q}').
Executed regression · request rejects duplicate nodes
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_request_rejects_duplicate_nodes() -> None:
with pytest.raises(ValueError, match="distinct"):
StencilRequest((Fraction(0), Fraction(0)), ((0,), (1,)), 0)python -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_request_rejects_duplicate_nodes" -qMethod implementation
def __post_init__(self) -> None:
nodes = tuple(_as_frac(c) for c in self.nodes)
if not nodes:
raise ValueError("StencilRequest requires at least one node")
if len(nodes) != len(self.orders):
raise ValueError("nodes and orders must have the same length")
if len(set(nodes)) != len(nodes):
raise ValueError("nodes must be distinct")
cleaned: list[tuple[int, ...]] = []
for i, ords in enumerate(self.orders):
seq = tuple(int(p) for p in ords)
if not seq:
raise ValueError(f"orders[{i}] must be non-empty")
if any(p < 0 for p in seq):
raise ValueError(f"orders[{i}] must be >= 0")
if len(set(seq)) != len(seq):
raise ValueError(f"orders[{i}] must be unique")
cleaned.append(tuple(sorted(seq)))
q = int(self.target_order)
if q < 0:
raise ValueError(f"target_order must be >= 0, got {q}")
object.__setattr__(self, "nodes", nodes)
object.__setattr__(self, "orders", tuple(cleaned))
object.__setattr__(self, "target_order", q)n_conditionsproperty
n_conditions(self) -> intSee the class contract above and the exact method implementation below.
Returns: int
Method implementation
def n_conditions(self) -> int:
return sum(len(o) for o in self.orders)pairsmethod
pairs(self) -> tuple[tuple[int, int], ...](node_index, order) pairs in request order.
Returns: tuple[tuple[int, int], ...]
Executed regression · g1 reproduces signs exact forward and central
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_reproduces_signs_exact_forward_and_central() -> None:
h = Fraction(1, 7)
for order in (0, 1, 2, 3):
for kind in ("forward", "central"):
req = _uniform_value_request(order, kind)
st = solve_irregular_stencil(req)
assert st is not None, (order, kind)
phys = physical_weights(st, h)
flat = tuple(w[0] for w in phys)
expected = signs_exact(order, h)
assert flat == expected, (order, kind, flat, expected)python -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_g1_reproduces_signs_exact_forward_and_central" -qMethod implementation
def pairs(self) -> tuple[tuple[int, int], ...]:
"""``(node_index, order)`` pairs in request order."""
out: list[tuple[int, int]] = []
for i, ords in enumerate(self.orders):
for p in ords:
out.append((i, p))
return tuple(out)Read the implementation
class StencilRequest:
"""A Birkhoff finite-difference request.
Parameters
----------
nodes:
Dimensionless node locations ``c_i`` (physical nodes are ``c_i h``).
orders:
Available derivative orders at each node (non-empty, unique, ``>= 0``).
target_order:
Derivative order ``q`` to recover at the expansion point ``0``.
"""
nodes: tuple[Fraction, ...]
orders: tuple[tuple[int, ...], ...]
target_order: int
def __post_init__(self) -> None:
nodes = tuple(_as_frac(c) for c in self.nodes)
if not nodes:
raise ValueError("StencilRequest requires at least one node")
if len(nodes) != len(self.orders):
raise ValueError("nodes and orders must have the same length")
if len(set(nodes)) != len(nodes):
raise ValueError("nodes must be distinct")
cleaned: list[tuple[int, ...]] = []
for i, ords in enumerate(self.orders):
seq = tuple(int(p) for p in ords)
if not seq:
raise ValueError(f"orders[{i}] must be non-empty")
if any(p < 0 for p in seq):
raise ValueError(f"orders[{i}] must be >= 0")
if len(set(seq)) != len(seq):
raise ValueError(f"orders[{i}] must be unique")
cleaned.append(tuple(sorted(seq)))
q = int(self.target_order)
if q < 0:
raise ValueError(f"target_order must be >= 0, got {q}")
object.__setattr__(self, "nodes", nodes)
object.__setattr__(self, "orders", tuple(cleaned))
object.__setattr__(self, "target_order", q)
@property
def n_conditions(self) -> int:
return sum(len(o) for o in self.orders)
def pairs(self) -> tuple[tuple[int, int], ...]:
"""``(node_index, order)`` pairs in request order."""
out: list[tuple[int, int]] = []
for i, ords in enumerate(self.orders):
for p in ords:
out.append((i, p))
return tuple(out)apply_irregular_stencil
omnibias.difference.apply_irregular_stencilSource ↗apply_irregular_stencil(stencil: IrregularStencil, h: Fraction | int, samples: Sequence[Sequence[float]]) -> floatEvaluate sum a_{i,p} f^{(p)}(c_i h) in float (numerical register).
Parameters
| Name | Type & default | Contract |
|---|---|---|
stencilpositional-or-keyword | IrregularStencilRequired | See the operation contract and implementation below. |
hpositional-or-keyword | Fraction | intRequired | See the operation contract and implementation below. |
samplespositional-or-keyword | Sequence[Sequence[float]]Required | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
len(row_a) != len(row_s), raisesValueError('samples must match per-node orders').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g3 certificate covers grid and random
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_certificate_covers_grid_and_random() -> None:
req = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
st = solve_irregular_stencil(req)
assert st is not None
rng = random.Random(0)
hs = [0.2 / (k + 1) for k in range(12)] + [rng.uniform(0.01, 0.2) for _ in range(12)]
for h in hs:
hh = Fraction(h).limit_denominator(10_000)
h_f = float(hh)
samples = ((math.exp(-h_f),), (1.0,), (math.exp(h_f),))
est = apply_irregular_stencil(st, hh, samples)
err = abs(est - 1.0)
# |f'''| = exp on [-h, h], so M_3 <= exp(h)
bound = Interval.point(math.exp(h_f))
cert = certified_irregular_error(st, h=hh, deriv_bound=bound, estimate=est)
assert err <= cert.error_bound + 1e-15, (h_f, err, cert.error_bound)python -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_g3_certificate_covers_grid_and_random" -qRegression example · g2 empirical rate battery
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_empirical_rate_battery() -> None:
"""Measured log-log rate within 0.15 of reported accuracy over three halvings."""
req = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
st = solve_irregular_stencil(req)
assert st is not None
hs = [0.1, 0.05, 0.025, 0.0125]
def _rate(fn_samples, truth: float) -> float:
errs = []
for h in hs:
samples = fn_samples(h)
est = apply_irregular_stencil(st, Fraction(h).limit_denominator(), samples)
errs.append(abs(est - truth))
log_h = np.log(np.asarray(hs, dtype=float))
log_e = np.log(np.asarray(errs, dtype=float))
slope, _ = np.polyfit(log_h, log_e, 1)
return float(slope)
rate_exp = _rate(
lambda h: ((math.exp(-h),), (1.0,), (math.exp(h),)),
1.0,
)
rate_sin = _rate(
lambda h: ((math.sin(-h),), (0.0,), (math.cos(h),)),
1.0,
)
def _inv_samples(h: float) -> tuple[tuple[float, ...], ...]:
# f = 1/(1+x), f' = -1/(1+x)^2, f'(0) = -1
return ((1.0 / (1.0 - h),), (1.0,), (-1.0 / (1.0 + h) ** 2,))
rate_inv = _rate(_inv_samples, -1.0)
for rate in (rate_exp, rate_sin, rate_inv):
assert abs(rate - st.accuracy) <= 0.15, (rate, st.accuracy)python -m pytest packages/omnibias-difference/tests/test_irregular.py -k test_g2_empirical_rate_battery -qRead the implementation
def apply_irregular_stencil(
stencil: IrregularStencil,
h: Fraction | int,
samples: Sequence[Sequence[float]],
) -> float:
"""Evaluate ``sum a_{i,p} f^{(p)}(c_i h)`` in float (numerical register)."""
phys = physical_weights(stencil, h)
acc = 0.0
for row_a, row_s in zip(phys, samples, strict=True):
if len(row_a) != len(row_s):
raise ValueError("samples must match per-node orders")
for a, val in zip(row_a, row_s, strict=True):
acc += float(a) * float(val)
return acccertified_irregular_error
omnibias.difference.certified_irregular_errorSource ↗certified_irregular_error(stencil: IrregularStencil, *, h: Fraction | int, deriv_bound: Interval, estimate: float=0.0, z: float=0.0, name: str='irregular') -> FiniteDifferenceCertificate|E| <= |C| h^r M_N, outward rounded, as a FiniteDifferenceCertificate.
deriv_bound encloses f^{(q+r)} (or a bound on its magnitude) over the
hull of the physical nodes. Truncation only; float cancellation in the
applied stencil is a separate register.
Parameters
| Name | Type & default | Contract |
|---|---|---|
stencilpositional-or-keyword | IrregularStencilRequired | See the operation contract and implementation below. |
hkeyword-only | Fraction | intRequired | See the operation contract and implementation below. |
deriv_boundkeyword-only | IntervalRequired | See the operation contract and implementation below. |
estimatekeyword-only | floatDefault: 0.0 | See the operation contract and implementation below. |
zkeyword-only | floatDefault: 0.0 | See the operation contract and implementation below. |
namekeyword-only | strDefault: 'irregular' | See the operation contract and implementation below. |
FiniteDifferenceCertificateExplicit validation & failure cases
- When
hh == 0, raisesValueError('h must be nonzero').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g3 certificate covers grid and random
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_certificate_covers_grid_and_random() -> None:
req = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
st = solve_irregular_stencil(req)
assert st is not None
rng = random.Random(0)
hs = [0.2 / (k + 1) for k in range(12)] + [rng.uniform(0.01, 0.2) for _ in range(12)]
for h in hs:
hh = Fraction(h).limit_denominator(10_000)
h_f = float(hh)
samples = ((math.exp(-h_f),), (1.0,), (math.exp(h_f),))
est = apply_irregular_stencil(st, hh, samples)
err = abs(est - 1.0)
# |f'''| = exp on [-h, h], so M_3 <= exp(h)
bound = Interval.point(math.exp(h_f))
cert = certified_irregular_error(st, h=hh, deriv_bound=bound, estimate=est)
assert err <= cert.error_bound + 1e-15, (h_f, err, cert.error_bound)python -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_g3_certificate_covers_grid_and_random" -qRead the implementation
def certified_irregular_error(
stencil: IrregularStencil,
*,
h: Fraction | int,
deriv_bound: Interval,
estimate: float = 0.0,
z: float = 0.0,
name: str = "irregular",
) -> FiniteDifferenceCertificate:
r"""``|E| <= |C| h^r M_N``, outward rounded, as a :class:`FiniteDifferenceCertificate`.
``deriv_bound`` encloses ``f^{(q+r)}`` (or a bound on its magnitude) over the
hull of the physical nodes. Truncation only; float cancellation in the
applied stencil is a separate register.
"""
hh = _as_frac(h)
if hh == 0:
raise ValueError("h must be nonzero")
r = int(stencil.accuracy)
coeff_iv = Interval.from_rational(abs(stencil.leading_coeff))
h_iv = Interval.from_rational(hh)
hr = h_iv**r if r >= 1 else Interval.from_rational(1)
mag_f = Interval(-deriv_bound.mag, deriv_bound.mag)
err_iv = coeff_iv * hr * mag_f
error_bound = float(err_iv.mag)
enclosure = Interval.point(float(estimate))
return FiniteDifferenceCertificate(
name,
stencil.request.target_order,
float(z),
float(hh),
"irregular",
float(estimate),
enclosure,
error_bound,
r,
)is_poised_exact
omnibias.difference.is_poised_exactSource ↗is_poised_exact(request: StencilRequest) -> boolAuthoritative poisedness oracle: exact rank of the system over Q.
Parameters
| Name | Type & default | Contract |
|---|---|---|
requestpositional-or-keyword | StencilRequestRequired | See the operation contract and implementation below. |
boolExecuted regression · worked example exact rationals
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_exact_rationals() -> None:
"""Spec §5: f'(0) from f(-h), f(0), f'(h)."""
req = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
st = solve_irregular_stencil(req)
assert st is not None
h = Fraction(1, 10)
phys = physical_weights(st, h)
assert phys == ((Fraction(-2, 3) / h,), (Fraction(2, 3) / h,), (Fraction(1, 3),))
assert st.leading_coeff == Fraction(5, 18)
assert st.accuracy == 2
assert polya_screen(req) is True
assert is_poised_exact(req) is Truepython -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_worked_example_exact_rationals" -qRegression example · g4 poisedness curated set
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_poisedness_curated_set() -> None:
hermite = StencilRequest(
(Fraction(-1), Fraction(1)),
((0, 1), (0, 1)),
target_order=1,
)
worked = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
gap = StencilRequest((Fraction(0),), ((0, 2),), target_order=1)
# Pólya passes (two values + a derivative) but the even-even residual
# makes the Vandermonde singular: f(-1), f'(0), f(1).
polya_not_rank = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (1,), (0,)),
target_order=0,
)
poised = (hermite, worked)
unpoised = (gap, polya_not_rank)
for req in poised:
assert polya_screen(req) is True
assert is_poised_exact(req) is True
assert solve_irregular_stencil(req) is not None
assert polya_screen(gap) is False
assert is_poised_exact(gap) is False
assert polya_screen(polya_not_rank) is True # necessary, not sufficient
assert is_poised_exact(polya_not_rank) is False
for req in unpoised:
assert solve_irregular_stencil(req) is None
for req in poised:
assert polya_screen(req) is not Falsepython -m pytest packages/omnibias-difference/tests/test_irregular.py -k test_g4_poisedness_curated_set -qRead the implementation
def is_poised_exact(request: StencilRequest) -> bool:
"""Authoritative poisedness oracle: exact rank of the system over ``Q``."""
mat, rhs = _vandermonde(request)
return _solve_over_q(mat, rhs) is not Nonephysical_weights
omnibias.difference.physical_weightsSource ↗physical_weights(stencil: IrregularStencil, h: Fraction | int) -> tuple[tuple[Fraction, ...], ...]a_{i,p} = A_{i,p} / h^{q-p}.
Parameters
| Name | Type & default | Contract |
|---|---|---|
stencilpositional-or-keyword | IrregularStencilRequired | See the operation contract and implementation below. |
hpositional-or-keyword | Fraction | intRequired | See the operation contract and implementation below. |
tuple[tuple[Fraction, ...], ...]Explicit validation & failure cases
- When
hh == 0, raisesValueError('h must be nonzero').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g1 reproduces signs exact forward and central
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_reproduces_signs_exact_forward_and_central() -> None:
h = Fraction(1, 7)
for order in (0, 1, 2, 3):
for kind in ("forward", "central"):
req = _uniform_value_request(order, kind)
st = solve_irregular_stencil(req)
assert st is not None, (order, kind)
phys = physical_weights(st, h)
flat = tuple(w[0] for w in phys)
expected = signs_exact(order, h)
assert flat == expected, (order, kind, flat, expected)python -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_g1_reproduces_signs_exact_forward_and_central" -qRegression example · worked example exact rationals
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_exact_rationals() -> None:
"""Spec §5: f'(0) from f(-h), f(0), f'(h)."""
req = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
st = solve_irregular_stencil(req)
assert st is not None
h = Fraction(1, 10)
phys = physical_weights(st, h)
assert phys == ((Fraction(-2, 3) / h,), (Fraction(2, 3) / h,), (Fraction(1, 3),))
assert st.leading_coeff == Fraction(5, 18)
assert st.accuracy == 2
assert polya_screen(req) is True
assert is_poised_exact(req) is Truepython -m pytest packages/omnibias-difference/tests/test_irregular.py -k test_worked_example_exact_rationals -qRead the implementation
def physical_weights(stencil: IrregularStencil, h: Fraction | int) -> tuple[tuple[Fraction, ...], ...]:
"""``a_{i,p} = A_{i,p} / h^{q-p}``."""
hh = _as_frac(h)
if hh == 0:
raise ValueError("h must be nonzero")
q = stencil.request.target_order
out: list[tuple[Fraction, ...]] = []
for ords, row in zip(stencil.request.orders, stencil.weights, strict=True):
phys: list[Fraction] = []
for p, a in zip(ords, row, strict=True):
phys.append(a / (hh ** (q - p)))
out.append(tuple(phys))
return tuple(out)polya_screen
omnibias.difference.polya_screenSource ↗polya_screen(request: StencilRequest) -> boolCheap necessary condition. False proves not poised; True proves nothing.
Parameters
| Name | Type & default | Contract |
|---|---|---|
requestpositional-or-keyword | StencilRequestRequired | See the operation contract and implementation below. |
boolExecuted regression · worked example exact rationals
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_exact_rationals() -> None:
"""Spec §5: f'(0) from f(-h), f(0), f'(h)."""
req = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
st = solve_irregular_stencil(req)
assert st is not None
h = Fraction(1, 10)
phys = physical_weights(st, h)
assert phys == ((Fraction(-2, 3) / h,), (Fraction(2, 3) / h,), (Fraction(1, 3),))
assert st.leading_coeff == Fraction(5, 18)
assert st.accuracy == 2
assert polya_screen(req) is True
assert is_poised_exact(req) is Truepython -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_worked_example_exact_rationals" -qRegression example · g4 poisedness curated set
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_poisedness_curated_set() -> None:
hermite = StencilRequest(
(Fraction(-1), Fraction(1)),
((0, 1), (0, 1)),
target_order=1,
)
worked = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
gap = StencilRequest((Fraction(0),), ((0, 2),), target_order=1)
# Pólya passes (two values + a derivative) but the even-even residual
# makes the Vandermonde singular: f(-1), f'(0), f(1).
polya_not_rank = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (1,), (0,)),
target_order=0,
)
poised = (hermite, worked)
unpoised = (gap, polya_not_rank)
for req in poised:
assert polya_screen(req) is True
assert is_poised_exact(req) is True
assert solve_irregular_stencil(req) is not None
assert polya_screen(gap) is False
assert is_poised_exact(gap) is False
assert polya_screen(polya_not_rank) is True # necessary, not sufficient
assert is_poised_exact(polya_not_rank) is False
for req in unpoised:
assert solve_irregular_stencil(req) is None
for req in poised:
assert polya_screen(req) is not Falsepython -m pytest packages/omnibias-difference/tests/test_irregular.py -k test_g4_poisedness_curated_set -qRead the implementation
def polya_screen(request: StencilRequest) -> bool:
"""Cheap necessary condition. ``False`` proves not poised; ``True`` proves nothing."""
max_p = 0
for ords in request.orders:
if ords:
max_p = max(max_p, max(ords))
n_cols = max_p + 1
counts = [0] * n_cols
for ords in request.orders:
for p in ords:
counts[p] += 1
for j in range(n_cols):
total = sum(counts[: j + 1])
if total < j + 1:
return False
return Truesolve_irregular_stencil
omnibias.difference.solve_irregular_stencilSource ↗solve_irregular_stencil(request: StencilRequest) -> IrregularStencil | NoneExact rational solve. None when the scheme is not poised.
Parameters
| Name | Type & default | Contract |
|---|---|---|
requestpositional-or-keyword | StencilRequestRequired | See the operation contract and implementation below. |
IrregularStencil | NoneExecuted regression · g1 reproduces signs exact forward and central
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_reproduces_signs_exact_forward_and_central() -> None:
h = Fraction(1, 7)
for order in (0, 1, 2, 3):
for kind in ("forward", "central"):
req = _uniform_value_request(order, kind)
st = solve_irregular_stencil(req)
assert st is not None, (order, kind)
phys = physical_weights(st, h)
flat = tuple(w[0] for w in phys)
expected = signs_exact(order, h)
assert flat == expected, (order, kind, flat, expected)python -m pytest "packages/omnibias-difference/tests/test_irregular.py::test_g1_reproduces_signs_exact_forward_and_central" -qRegression example · worked example exact rationals
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_exact_rationals() -> None:
"""Spec §5: f'(0) from f(-h), f(0), f'(h)."""
req = StencilRequest(
(Fraction(-1), Fraction(0), Fraction(1)),
((0,), (0,), (1,)),
target_order=1,
)
st = solve_irregular_stencil(req)
assert st is not None
h = Fraction(1, 10)
phys = physical_weights(st, h)
assert phys == ((Fraction(-2, 3) / h,), (Fraction(2, 3) / h,), (Fraction(1, 3),))
assert st.leading_coeff == Fraction(5, 18)
assert st.accuracy == 2
assert polya_screen(req) is True
assert is_poised_exact(req) is Truepython -m pytest packages/omnibias-difference/tests/test_irregular.py -k test_worked_example_exact_rationals -qRead the implementation
def solve_irregular_stencil(request: StencilRequest) -> IrregularStencil | None:
"""Exact rational solve. ``None`` when the scheme is not poised."""
mat, rhs = _vandermonde(request)
flat = _solve_over_q(mat, rhs)
if flat is None:
return None
packed = _pack_weights(request, flat)
accuracy, coeff = _leading(request, flat)
mag = max((abs(a) for a in flat), default=Fraction(0))
return IrregularStencil(
request=request,
weights=packed,
accuracy=int(accuracy),
leading_coeff=coeff,
weight_magnitude=mag,
)pade_approximant
omnibias.difference.pade_approximantSource ↗pade_approximant(coeffs: Sequence[Rational], m: int, n: int) -> tuple[tuple[Fraction, ...], tuple[Fraction, ...]]Exact Pade approximant [m/n]: numerator P (deg m), denominator Q (deg n).
Given Taylor coefficients c_0, ..., c_{m+n} of f, returns (P, Q) (both
ascending-order tuples, Q_0 = 1) with P/Q = f + O(x^{m+n+1}). Solves the
exact-rational linear system sum_{j=1}^{n} Q_j c_{m+i-j} = -c_{m+i} (i = 1..n)
for the denominator, then reads off P_i = sum_{j=0}^{i} Q_j c_{i-j}. Requires
len(coeffs) >= m + n + 1.
Parameters
| Name | Type & default | Contract |
|---|---|---|
coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
mpositional-or-keyword | intRequired | See the operation contract and implementation below. |
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[tuple[Fraction, ...], tuple[Fraction, ...]]Explicit validation & failure cases
- When
m < 0 or n < 0, raisesValueError(f'm and n must be >= 0, got m={m}, n={n}'). - When
len(c) < m + n + 1, raisesValueError(f'need >= {m + n + 1} coefficients for a [{m}/{n}] Pade, got {len(c)}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · too few coeffs raises
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_too_few_coeffs_raises(self) -> None:
with pytest.raises(ValueError):
pade_approximant([Fraction(1), Fraction(1)], 2, 2)python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestPadeApproximant::test_too_few_coeffs_raises" -qRegression example · matches series through order
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_matches_series_through_order(self) -> None:
c = [Fraction(1, factorial(k)) for k in range(7)] # exp
p, q = pade_approximant(c, 3, 3)
assert rational_series(p, q, 6) == tuple(c)python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_matches_series_through_order -qRead the implementation
def pade_approximant(
coeffs: Sequence[Rational], m: int, n: int
) -> tuple[tuple[Fraction, ...], tuple[Fraction, ...]]:
r"""Exact Pade approximant ``[m/n]``: numerator ``P`` (deg ``m``), denominator ``Q`` (deg ``n``).
Given Taylor coefficients ``c_0, ..., c_{m+n}`` of ``f``, returns ``(P, Q)`` (both
ascending-order tuples, ``Q_0 = 1``) with ``P/Q = f + O(x^{m+n+1})``. Solves the
exact-rational linear system ``sum_{j=1}^{n} Q_j c_{m+i-j} = -c_{m+i}`` (``i = 1..n``)
for the denominator, then reads off ``P_i = sum_{j=0}^{i} Q_j c_{i-j}``. Requires
``len(coeffs) >= m + n + 1``.
"""
if m < 0 or n < 0:
raise ValueError(f"m and n must be >= 0, got m={m}, n={n}")
c = [_frac(v) for v in coeffs]
if len(c) < m + n + 1:
raise ValueError(f"need >= {m + n + 1} coefficients for a [{m}/{n}] Pade, got {len(c)}")
def cc(i: int) -> Fraction:
return c[i] if 0 <= i < len(c) else Fraction(0)
if n > 0:
amat = [[cc(m + i - j) for j in range(1, n + 1)] for i in range(1, n + 1)]
bvec = [-cc(m + i) for i in range(1, n + 1)]
qtail = _solve_rational(amat, bvec)
else:
qtail = []
q = [Fraction(1), *qtail]
p = [sum((q[j] * cc(i - j) for j in range(0, min(i, n) + 1)), Fraction(0)) for i in range(m + 1)]
return tuple(p), tuple(q)pade_certified_remainder
omnibias.difference.pade_certified_remainderSource ↗pade_certified_remainder(numer: Sequence[Rational], denom: Sequence[Rational], taylor_ivs: Sequence[Interval], radius: float, *, tail_bound: float, tail_ratio: float) -> IntervalRigorous bound on |f(x) - P(x)/Q(x)| for |x| <= radius.
taylor_ivs are certified enclosures a_0..a_M of f's Taylor coefficients
(M >= m + n), and |a_k| <= tail_bound * tail_ratio^k for every k > M.
The residual W(x) = Q(x) f(x) - P(x) vanishes through order m + n by
construction, so W_k = sum_{j<=n} Q_j a_{k-j} for k > m + n; the finite part
(m+n < k <= M) is summed as intervals and the k > M tail is geometrically
majorised (needs radius * tail_ratio < 1). Dividing by the rigorous lower bound
|Q(x)| >= |Q_0| - sum_{j>=1} |Q_j| radius^j > 0 gives the certified remainder --
outward-rounded, no fudge factor.
Parameters
| Name | Type & default | Contract |
|---|---|---|
numerpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
denompositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
taylor_ivspositional-or-keyword | Sequence[Interval]Required | See the operation contract and implementation below. |
radiuspositional-or-keyword | floatRequired | See the operation contract and implementation below. |
tail_boundkeyword-only | floatRequired | See the operation contract and implementation below. |
tail_ratiokeyword-only | floatRequired | See the operation contract and implementation below. |
IntervalExplicit validation & failure cases
- When
radius <= 0.0, raisesValueError(f'radius must be > 0, got {radius}'). - When
not 0.0 <= tail_ratio, raisesValueError(f'tail_ratio must be >= 0, got {tail_ratio}'). - When
radius * tail_ratio >= 1.0, raisesValueError('need radius * tail_ratio < 1 for a convergent geometric tail'). - When
big_m < m + n, raisesValueError(f'need >= {m + n + 1} Taylor enclosures, got {big_m + 1}'). - When
q_lo <= 0.0, raisesValueError('cannot certify |Q| > 0 over the disc; shrink radius').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · remainder reuses pade
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_remainder_reuses_pade() -> None:
rem = remainder_on_safe_disc(_geom(2.0, 6), numer_deg=0, denom_deg=1, radius=0.2, tail_bound=1.0, tail_ratio=2.0)
assert rem.lo <= 0.0 <= rem.hi
assert rem.mag < 1.0python -m pytest "packages/omnibias-difference/tests/test_singularity_tracking.py::test_remainder_reuses_pade" -qRegression example · divergent tail raises
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_divergent_tail_raises(self) -> None:
c = [Fraction(1, factorial(k)) for k in range(13)]
p, q = pade_approximant(c, 3, 3)
ivs = [Interval.from_rational(Fraction(1, factorial(k))) for k in range(13)]
with pytest.raises(ValueError):
pade_certified_remainder(p, q, ivs, 3.0, tail_bound=1.0, tail_ratio=0.5)python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_divergent_tail_raises -qRead the implementation
def pade_certified_remainder(
numer: Sequence[Rational],
denom: Sequence[Rational],
taylor_ivs: Sequence[Interval],
radius: float,
*,
tail_bound: float,
tail_ratio: float,
) -> Interval:
r"""Rigorous bound on ``|f(x) - P(x)/Q(x)|`` for ``|x| <= radius``.
``taylor_ivs`` are certified enclosures ``a_0..a_M`` of ``f``'s Taylor coefficients
(``M >= m + n``), and ``|a_k| <= tail_bound * tail_ratio^k`` for every ``k > M``.
The residual ``W(x) = Q(x) f(x) - P(x)`` vanishes through order ``m + n`` by
construction, so ``W_k = sum_{j<=n} Q_j a_{k-j}`` for ``k > m + n``; the finite part
(``m+n < k <= M``) is summed as intervals and the ``k > M`` tail is geometrically
majorised (needs ``radius * tail_ratio < 1``). Dividing by the rigorous lower bound
``|Q(x)| >= |Q_0| - sum_{j>=1} |Q_j| radius^j > 0`` gives the certified remainder --
outward-rounded, no fudge factor.
"""
if radius <= 0.0:
raise ValueError(f"radius must be > 0, got {radius}")
if not 0.0 <= tail_ratio:
raise ValueError(f"tail_ratio must be >= 0, got {tail_ratio}")
if radius * tail_ratio >= 1.0:
raise ValueError("need radius * tail_ratio < 1 for a convergent geometric tail")
q = [_frac(v) for v in denom]
p = [_frac(v) for v in numer]
m = len(p) - 1
n = len(q) - 1
big_m = len(taylor_ivs) - 1
if big_m < m + n:
raise ValueError(f"need >= {m + n + 1} Taylor enclosures, got {big_m + 1}")
r_iv = Interval.from_value(radius)
# Finite residual W_k = sum_{j=0}^{n} Q_j a_{k-j} for m+n < k <= M.
w_finite = Interval.point(0.0)
for k in range(m + n + 1, big_m + 1):
wk = Interval.point(0.0)
for j in range(0, n + 1):
if 0 <= k - j <= big_m:
wk = wk + Interval.from_rational(q[j]) * taylor_ivs[k - j]
w_finite = w_finite + Interval(-wk.mag, wk.mag) * r_iv.pow_int(k)
# Tail k > M: |W_k| <= tail_bound * (sum_j |Q_j| tail_ratio^{-j}) * tail_ratio^k.
qsum = sum(
(abs(float(q[j])) * tail_ratio ** (-j) if tail_ratio > 0 else abs(float(q[j])))
for j in range(0, n + 1)
)
sr = radius * tail_ratio
tail_geo = tail_bound * qsum * (sr ** (big_m + 1)) / (1.0 - sr) if sr > 0 else 0.0
w_tail = Interval(-tail_geo, tail_geo)
numerator_bound = (w_finite + w_tail).mag
# Rigorous lower bound on |Q(x)| over |x| <= radius.
q_lo = abs(float(q[0])) - sum(abs(float(q[j])) * radius**j for j in range(1, n + 1))
if q_lo <= 0.0:
raise ValueError("cannot certify |Q| > 0 over the disc; shrink radius")
return Interval(-numerator_bound / q_lo, numerator_bound / q_lo)pade_evaluate
omnibias.difference.pade_evaluateSource ↗pade_evaluate(numer: Sequence[Rational], denom: Sequence[Rational], x: Rational) -> FractionEvaluate the Pade rational P(x)/Q(x) at a rational x (exact).
Parameters
| Name | Type & default | Contract |
|---|---|---|
numerpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
denompositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
xpositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
FractionExplicit validation & failure cases
- When
den == 0, raisesZeroDivisionError(f'Pade denominator vanishes at x={x}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · interval eval 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_interval_eval_soundness(self) -> None:
c = [Fraction(1, factorial(k)) for k in range(7)]
p, q = pade_approximant(c, 3, 3)
box = pade_evaluate_interval(p, q, Interval(0.2, 0.3))
assert box.contains(float(pade_evaluate(p, q, Fraction(1, 4))))python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestPadeCertifiedRemainder::test_interval_eval_soundness" -qRegression example · recovers rational exactly
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_recovers_rational_exactly(self) -> None:
# 1/(1 - z/2) = sum (z/2)^k; its [1/1] Pade is exact.
c = [Fraction(1, 2**k) for k in range(3)]
p, q = pade_approximant(c, 1, 1)
assert pade_evaluate(p, q, Fraction(1, 3)) == Fraction(1) / (1 - Fraction(1, 6))python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_recovers_rational_exactly -qRead the implementation
def pade_evaluate(
numer: Sequence[Rational], denom: Sequence[Rational], x: Rational
) -> Fraction:
r"""Evaluate the Pade rational ``P(x)/Q(x)`` at a rational ``x`` (exact)."""
den = _poly_eval(denom, x)
if den == 0:
raise ZeroDivisionError(f"Pade denominator vanishes at x={x}")
return _poly_eval(numer, x) / denpade_evaluate_interval
omnibias.difference.pade_evaluate_intervalSource ↗pade_evaluate_interval(numer: Sequence[Rational], denom: Sequence[Rational], x: Interval) -> IntervalEvaluate P(x)/Q(x) over an Interval x (outward-rounded).
Parameters
| Name | Type & default | Contract |
|---|---|---|
numerpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
denompositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
xpositional-or-keyword | IntervalRequired | See the operation contract and implementation below. |
IntervalExecuted regression · interval eval 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_interval_eval_soundness(self) -> None:
c = [Fraction(1, factorial(k)) for k in range(7)]
p, q = pade_approximant(c, 3, 3)
box = pade_evaluate_interval(p, q, Interval(0.2, 0.3))
assert box.contains(float(pade_evaluate(p, q, Fraction(1, 4))))python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestPadeCertifiedRemainder::test_interval_eval_soundness" -qRead the implementation
def pade_evaluate_interval(
numer: Sequence[Rational], denom: Sequence[Rational], x: Interval
) -> Interval:
r"""Evaluate ``P(x)/Q(x)`` over an :class:`Interval` ``x`` (outward-rounded)."""
return _poly_eval_interval(numer, x) * _poly_eval_interval(denom, x).reciprocal()rational_series
omnibias.difference.rational_seriesSource ↗rational_series(numer: Sequence[Rational], denom: Sequence[Rational], order: int) -> tuple[Fraction, ...]Maclaurin coefficients [x^0..x^order] of numer/denom (exact long division).
Parameters
| Name | Type & default | Contract |
|---|---|---|
numerpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
denompositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
order < 0, raisesValueError(f'order must be >= 0, got {order}'). - When
not q or q[0] == 0, raisesValueError('denominator must have a non-zero constant term').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · matches series through order
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_matches_series_through_order(self) -> None:
c = [Fraction(1, factorial(k)) for k in range(7)] # exp
p, q = pade_approximant(c, 3, 3)
assert rational_series(p, q, 6) == tuple(c)python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestPadeApproximant::test_matches_series_through_order" -qRead the implementation
def rational_series(
numer: Sequence[Rational], denom: Sequence[Rational], order: int
) -> tuple[Fraction, ...]:
r"""Maclaurin coefficients ``[x^0..x^order]`` of ``numer/denom`` (exact long division)."""
if order < 0:
raise ValueError(f"order must be >= 0, got {order}")
p = [_frac(v) for v in numer]
q = [_frac(v) for v in denom]
if not q or q[0] == 0:
raise ValueError("denominator must have a non-zero constant term")
out: list[Fraction] = []
for i in range(order + 1):
acc = p[i] if i < len(p) else Fraction(0)
for j in range(1, min(i, len(q) - 1) + 1):
acc -= q[j] * out[i - j]
out.append(acc / q[0])
return tuple(out)thiele_evaluate
omnibias.difference.thiele_evaluateSource ↗thiele_evaluate(xs: Sequence[Rational], coeffs: Sequence[Rational], x: Rational) -> FractionEvaluate a Thiele continued fraction (from thiele_interpolation) at x.
Parameters
| Name | Type & default | Contract |
|---|---|---|
xspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
xpositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
FractionExplicit validation & failure cases
- When
not a, raisesValueError('coeffs must be non-empty'). - When
val == 0, raisesZeroDivisionError(f'Thiele continued fraction has a pole near x={x}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · interpolates exactly
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_interpolates_exactly(self) -> None:
xs = [0, 1, 2, 3]
ys = [1, 3, 2, 5]
a = thiele_interpolation(xs, ys)
assert all(thiele_evaluate(xs, a, x) == Fraction(y) for x, y in zip(xs, ys, strict=True))python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestThiele::test_interpolates_exactly" -qRegression example · reciprocal function
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_reciprocal_function(self) -> None:
# Attainable data from a generic smooth function.
xs = [Fraction(1), Fraction(2), Fraction(4), Fraction(8)]
ys = [x * x + 1 for x in xs]
a = thiele_interpolation(xs, ys)
assert thiele_evaluate(xs, a, Fraction(3)) == Fraction(10)python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_reciprocal_function -qRead the implementation
def thiele_evaluate(
xs: Sequence[Rational], coeffs: Sequence[Rational], x: Rational
) -> Fraction:
r"""Evaluate a Thiele continued fraction (from :func:`thiele_interpolation`) at ``x``."""
xf = [_frac(v) for v in xs]
a = [_frac(v) for v in coeffs]
if not a:
raise ValueError("coeffs must be non-empty")
xq = _frac(x)
val = a[-1]
for j in range(len(a) - 2, -1, -1):
if val == 0:
raise ZeroDivisionError(f"Thiele continued fraction has a pole near x={x}")
val = a[j] + (xq - xf[j]) / val
return valthiele_interpolation
omnibias.difference.thiele_interpolationSource ↗thiele_interpolation(xs: Sequence[Rational], ys: Sequence[Rational]) -> tuple[Fraction, ...]Thiele continued-fraction coefficients from samples (exact rational).
Returns a_0, ..., a_{N-1} for the interpolating continued fraction f(x) = a_0 +
(x - x_0)/(a_1 + (x - x_1)/(a_2 + ...)), built from the reciprocal-difference table
(a_k = rho_k(x_0) - rho_{k-2}(x_0)). Raises ZeroDivisionError at an
*unattainable point* (a reciprocal difference with a zero denominator -- e.g. sampling
a low-degree rational at too many nodes); thiele_evaluate inverts it.
Parameters
| Name | Type & default | Contract |
|---|---|---|
xspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
yspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
len(xf) != len(yf), raisesValueError('xs and ys must have equal length'). - When
len(set(xf)) != len(xf), raisesValueError('interpolation nodes must be distinct'). - When
denom == 0, raisesZeroDivisionError('unattainable point in the Thiele continued fraction').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · distinct nodes required
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_distinct_nodes_required(self) -> None:
with pytest.raises(ValueError):
thiele_interpolation([0, 1, 1], [1, 2, 3])python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestThiele::test_distinct_nodes_required" -qRegression example · interpolates exactly
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_interpolates_exactly(self) -> None:
xs = [0, 1, 2, 3]
ys = [1, 3, 2, 5]
a = thiele_interpolation(xs, ys)
assert all(thiele_evaluate(xs, a, x) == Fraction(y) for x, y in zip(xs, ys, strict=True))python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_interpolates_exactly -qRead the implementation
def thiele_interpolation(
xs: Sequence[Rational], ys: Sequence[Rational]
) -> tuple[Fraction, ...]:
r"""Thiele continued-fraction coefficients from samples (exact rational).
Returns ``a_0, ..., a_{N-1}`` for the interpolating continued fraction ``f(x) = a_0 +
(x - x_0)/(a_1 + (x - x_1)/(a_2 + ...))``, built from the reciprocal-difference table
(``a_k = rho_k(x_0) - rho_{k-2}(x_0)``). Raises :class:`ZeroDivisionError` at an
*unattainable point* (a reciprocal difference with a zero denominator -- e.g. sampling
a low-degree rational at too many nodes); :func:`thiele_evaluate` inverts it.
"""
xf = [_frac(v) for v in xs]
yf = [_frac(v) for v in ys]
if len(xf) != len(yf):
raise ValueError("xs and ys must have equal length")
if len(set(xf)) != len(xf):
raise ValueError("interpolation nodes must be distinct")
size = len(xf)
rho = [[Fraction(0)] * size for _ in range(size)]
for i in range(size):
rho[i][0] = yf[i]
for j in range(1, size):
for i in range(size - j):
denom = rho[i][j - 1] - rho[i + 1][j - 1]
if denom == 0:
raise ZeroDivisionError("unattainable point in the Thiele continued fraction")
correction = rho[i + 1][j - 2] if j >= 2 else Fraction(0)
rho[i][j] = correction + (xf[i] - xf[i + j]) / denom
return tuple(rho[0][k] - (rho[0][k - 2] if k >= 2 else Fraction(0)) for k in range(size))associated_sequence
omnibias.difference.associated_sequenceSource ↗associated_sequence(f_coeffs: Sequence[Rational], n: int) -> list[tuple[Fraction, ...]]The associated (binomial-type) sequence of the delta series f (exact).
The g = 1 Sheffer case: sum_n p_n(x) t^n/n! = exp(x fbar(t)), so p_n satisfies
the binomial identity p_n(x + y) = sum_k C(n, k) p_k(x) p_{n-k}(y). f = t gives the
monomials x^n; f = e^t - 1 gives the falling factorials; f = log(1 + t) gives
the Bell / Touchard polynomials (rows of Stirling numbers of the second kind).
Parameters
| Name | Type & default | Contract |
|---|---|---|
f_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
list[tuple[Fraction, ...]]Executed regression · associated of t are monomials
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_associated_of_t_are_monomials() -> None:
seq = associated_sequence((0, 1), N)
for n in range(N + 1):
assert tuple(seq[n]) == tuple([Fraction(0)] * n + [Fraction(1)])python -m pytest "packages/omnibias-difference/tests/test_sheffer.py::test_associated_of_t_are_monomials" -qRegression example · sheffer bernoulli pair is bernoulli polynomial
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_sheffer_bernoulli_pair_is_bernoulli_polynomial(n: int) -> None:
# Bernoulli polynomials are Sheffer for (g, f) = ((e^t-1)/t, t) (an Appell sequence).
seq = sheffer_sequence(_bernoulli_g(N), (0, 1), N)
assert tuple(seq[n]) == bernoulli_polynomial(n)python -m pytest packages/omnibias-difference/tests/test_sheffer.py -k test_sheffer_bernoulli_pair_is_bernoulli_polynomial -qRead the implementation
def associated_sequence(
f_coeffs: Sequence[Rational], n: int
) -> list[tuple[Fraction, ...]]:
r"""The associated (binomial-type) sequence of the delta series ``f`` (exact).
The ``g = 1`` Sheffer case: ``sum_n p_n(x) t^n/n! = exp(x fbar(t))``, so ``p_n`` satisfies
the binomial identity ``p_n(x + y) = sum_k C(n, k) p_k(x) p_{n-k}(y)``. ``f = t`` gives the
monomials ``x^n``; ``f = e^t - 1`` gives the falling factorials; ``f = log(1 + t)`` gives
the Bell / Touchard polynomials (rows of Stirling numbers of the second kind).
"""
return sheffer_sequence((1,), f_coeffs, n)Other public import paths
omnibias.difference.associated_sequenceomnibias.difference.umbral.associated_sequence
delta_operator_apply
omnibias.difference.delta_operator_applySource ↗delta_operator_apply(f_coeffs: Sequence[Rational], coeffs: Sequence[Rational]) -> tuple[Fraction, ...]Apply the operator Q = f(D) = sum_k f_k D^k to a polynomial (exact on polynomials).
f_coeffs are the ascending coefficients of the indicator series f (a delta series
for a genuine delta operator, but any series is accepted); coeffs are the ascending
coefficients of the polynomial. D is the ordinary derivative.
Parameters
| Name | Type & default | Contract |
|---|---|---|
f_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · delta operator D is derivative
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_delta_operator_D_is_derivative() -> None:
# Q = f(D) with f = t is just D.
p = (Fraction(2), Fraction(-1), Fraction(3), Fraction(1))
assert delta_operator_apply((0, 1), p) == (Fraction(-1), Fraction(6), Fraction(3))python -m pytest "packages/omnibias-difference/tests/test_sheffer.py::test_delta_operator_D_is_derivative" -qRegression example · pincherle is commutator with multiplication
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_pincherle_is_commutator_with_multiplication(seed: int) -> None:
# [f(D), X] = f'(D): (Q X - X Q) p == delta_operator_apply(pincherle_derivative(f), p).
rng = random.Random(90 + seed)
f = [Fraction(0)] + [Fraction(rng.randint(-3, 3), rng.randint(1, 3)) for _ in range(N)]
p = tuple(Fraction(rng.randint(-4, 4)) for _ in range(rng.randint(1, 6)))
def mul_x(poly: tuple[Fraction, ...]) -> tuple[Fraction, ...]:
return (Fraction(0),) + poly
def strip(poly: tuple[Fraction, ...]) -> tuple[Fraction, ...]:
out = list(poly)
while len(out) > 1 and out[-1] == 0:
out.pop()
return tuple(out)
qxp = delta_operator_apply(f, mul_x(p))
xqp = mul_x(delta_operator_apply(f, p))
width = max(len(qxp), len(xqp))
left = list(qxp) + [Fraction(0)] * (width - len(qxp))
right = list(xqp) + [Fraction(0)] * (width - len(xqp))
commutator = strip(tuple(a - b for a, b in zip(left, right, strict=True)))
assert commutator == delta_operator_apply(pincherle_derivative(f), p)python -m pytest packages/omnibias-difference/tests/test_sheffer.py -k test_pincherle_is_commutator_with_multiplication -qRead the implementation
def delta_operator_apply(
f_coeffs: Sequence[Rational], coeffs: Sequence[Rational]
) -> tuple[Fraction, ...]:
r"""Apply the operator ``Q = f(D) = sum_k f_k D^k`` to a polynomial (exact on polynomials).
``f_coeffs`` are the ascending coefficients of the indicator series ``f`` (a delta series
for a genuine delta operator, but any series is accepted); ``coeffs`` are the ascending
coefficients of the polynomial. ``D`` is the ordinary derivative.
"""
f = [_frac(v) for v in f_coeffs]
result = [Fraction(0)] * len(coeffs)
deriv = [_frac(v) for v in coeffs] # D^0 p
for fk in f:
if fk and deriv:
for j, c in enumerate(deriv):
result[j] += fk * c
deriv = _poly_derivative(deriv)
return _trim(result)Other public import paths
omnibias.difference.delta_operator_applyomnibias.difference.umbral.delta_operator_apply
pincherle_derivative
omnibias.difference.pincherle_derivativeSource ↗pincherle_derivative(f_coeffs: Sequence[Rational]) -> tuple[Fraction, ...]The Pincherle derivative of Q = f(D): the series of Q' = QX - XQ = f'(D) (exact).
Returns the ascending coefficients of f' (the formal derivative of the indicator
series). The operator identity [f(D), X] = f'(D) follows from [D, X] = 1.
Parameters
| Name | Type & default | Contract |
|---|---|---|
f_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · q pincherle reduces to classical
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_q_pincherle_reduces_to_classical() -> None:
assert q_pincherle_derivative(_F, ONE) == pincherle_derivative(_F)python -m pytest "packages/omnibias-qcalculus/tests/test_qumbral.py::test_q_pincherle_reduces_to_classical" -qRegression example · q to one collapse matches classical umbral
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_q_to_one_collapse_matches_classical_umbral() -> None:
# q-Stirling rows.
for n in range(N + 1):
assert tuple(int(x) for x in q_stirling_second_row(n, ONE)) == stirling_second_row(n)
# transforms.
coeffs = [Fraction(1), Fraction(-2), Fraction(3), Fraction(0), Fraction(4)]
assert q_monomial_to_falling(coeffs, ONE) == monomial_to_falling(coeffs)
assert q_falling_to_monomial(coeffs, ONE) == falling_to_monomial(coeffs)
# q-Appell -> Appell.
constants = [Fraction(1), Fraction(-3), Fraction(2), Fraction(5)]
assert [tuple(p) for p in q_appell_sequence(constants, ONE)] == [
tuple(p) for p in appell_sequence(constants)
]
# q-Sheffer -> Sheffer, q-Pincherle -> Pincherle.
assert [tuple(p) for p in q_sheffer_sequence(_G, _F, 5, ONE)] == [
tuple(p) for p in sheffer_sequence(_G, _F, 5)
]
assert q_pincherle_derivative(_F, ONE) == pincherle_derivative(_F)python -m pytest packages/omnibias-qcalculus/tests/test_qumbral.py -k test_q_to_one_collapse_matches_classical_umbral -qRead the implementation
def pincherle_derivative(f_coeffs: Sequence[Rational]) -> tuple[Fraction, ...]:
r"""The Pincherle derivative of ``Q = f(D)``: the series of ``Q' = QX - XQ = f'(D)`` (exact).
Returns the ascending coefficients of ``f'`` (the formal derivative of the indicator
series). The operator identity ``[f(D), X] = f'(D)`` follows from ``[D, X] = 1``.
"""
return tuple(_poly_derivative([_frac(v) for v in f_coeffs]))Other public import paths
omnibias.difference.pincherle_derivativeomnibias.difference.umbral.pincherle_derivative
sheffer_sequence
omnibias.difference.sheffer_sequenceSource ↗sheffer_sequence(g_coeffs: Sequence[Rational], f_coeffs: Sequence[Rational], n: int) -> list[tuple[Fraction, ...]]The Sheffer sequence s_0(x) .. s_n(x) for the pair (g, f) (exact).
g is an invertible series (g(0) != 0) and f a delta series (f(0) = 0,
f'(0) != 0); both are ascending ordinary-power-series coefficient lists. The sequence
is read off the generating function
\sum_{n\ge 0} s_n(x)\,\frac{t^n}{n!} = \frac{1}{g(\bar f(t))}\, e^{x\,\bar f(t)},
where fbar is the compositional inverse of f. Returns a list of ascending
x-coefficient tuples. Special cases: f = t gives the Appell sequence of 1/g
(see omnibias.difference.appell_sequence); g = 1 gives the associated
(binomial-type) sequence (see associated_sequence).
Parameters
| Name | Type & default | Contract |
|---|---|---|
g_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
f_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
list[tuple[Fraction, ...]]Explicit validation & failure cases
- When
n < 0, raisesValueError(f'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 · associated of t are monomials
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_associated_of_t_are_monomials() -> None:
seq = associated_sequence((0, 1), N)
for n in range(N + 1):
assert tuple(seq[n]) == tuple([Fraction(0)] * n + [Fraction(1)])python -m pytest "packages/omnibias-difference/tests/test_sheffer.py::test_associated_of_t_are_monomials" -qRegression example · q sheffer reduces to classical
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_q_sheffer_reduces_to_classical() -> None:
q_seq = [tuple(p) for p in q_sheffer_sequence(_G, _F, 5, ONE)]
classical = [tuple(p) for p in sheffer_sequence(_G, _F, 5)]
assert q_seq == classicalpython -m pytest packages/omnibias-qcalculus/tests/test_qumbral.py -k test_q_sheffer_reduces_to_classical -qRead the implementation
def sheffer_sequence(
g_coeffs: Sequence[Rational], f_coeffs: Sequence[Rational], n: int
) -> list[tuple[Fraction, ...]]:
r"""The Sheffer sequence ``s_0(x) .. s_n(x)`` for the pair ``(g, f)`` (exact).
``g`` is an invertible series (``g(0) != 0``) and ``f`` a delta series (``f(0) = 0``,
``f'(0) != 0``); both are ascending ordinary-power-series coefficient lists. The sequence
is read off the generating function
.. math::
\sum_{n\ge 0} s_n(x)\,\frac{t^n}{n!} = \frac{1}{g(\bar f(t))}\, e^{x\,\bar f(t)},
where ``fbar`` is the compositional inverse of ``f``. Returns a list of ascending
``x``-coefficient tuples. Special cases: ``f = t`` gives the Appell sequence of ``1/g``
(see :func:`omnibias.difference.appell_sequence`); ``g = 1`` gives the associated
(binomial-type) sequence (see :func:`associated_sequence`).
"""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
sheffer_classify(g_coeffs, f_coeffs) # validates the (g, f) pair, raises otherwise
fbar = compositional_inverse(f_coeffs, n)
a_series = series_reciprocal(compose_series(g_coeffs, fbar, n), n) # 1 / g(fbar)
a_coeffs = [a_series[j] if j < len(a_series) else Fraction(0) for j in range(n + 1)]
fbar_pow = _series_powers(fbar, n) # fbar^m coefficients, m = 0 .. n
result: list[tuple[Fraction, ...]] = []
for degree in range(n + 1):
poly = [Fraction(0)] * (degree + 1)
for m in range(degree + 1):
acc = Fraction(0)
for j in range(degree - m + 1):
aj = a_coeffs[j]
if aj:
acc += aj * fbar_pow[m][degree - j]
poly[m] = acc / factorial(m)
fact = factorial(degree)
result.append(tuple(fact * c for c in poly))
return resultOther public import paths
omnibias.difference.sheffer_sequenceomnibias.difference.umbral.sheffer_sequence
shift_polynomial
omnibias.difference.shift_polynomialSource ↗shift_polynomial(coeffs: Sequence[Rational], a: Rational) -> tuple[Fraction, ...]Apply the shift operator E^a: return the coefficients of P(x + a) (exact).
Parameters
| Name | Type & default | Contract |
|---|---|---|
coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
apositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · shift polynomial exact
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_shift_polynomial_exact() -> None:
# (x^2 + 1) shifted by 3 -> x^2 + 6x + 10.
assert shift_polynomial((Fraction(1), Fraction(0), Fraction(1)), 3) == (
Fraction(10),
Fraction(6),
Fraction(1),
)python -m pytest "packages/omnibias-difference/tests/test_sheffer.py::test_shift_polynomial_exact" -qRegression example · shift polynomial matches evaluation
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_shift_polynomial_matches_evaluation(seed: int) -> None:
rng = random.Random(70 + seed)
coeffs = tuple(Fraction(rng.randint(-5, 5)) for _ in range(rng.randint(1, 6)))
a = Fraction(rng.randint(-3, 3), rng.randint(1, 3))
shifted = shift_polynomial(coeffs, a)
for x in (Fraction(-2), Fraction(0), Fraction(3, 2), Fraction(4)):
assert _eval(shifted, x) == _eval(coeffs, x + a)python -m pytest packages/omnibias-difference/tests/test_sheffer.py -k test_shift_polynomial_matches_evaluation -qRead the implementation
def shift_polynomial(coeffs: Sequence[Rational], a: Rational) -> tuple[Fraction, ...]:
r"""Apply the shift operator ``E^a``: return the coefficients of ``P(x + a)`` (exact)."""
c = [_frac(v) for v in coeffs]
af = _frac(a)
out = [Fraction(0)] * len(c)
for i, ci in enumerate(c):
if not ci:
continue
for j in range(i + 1):
out[j] += ci * comb(i, j) * af ** (i - j)
return tuple(out)Other public import paths
omnibias.difference.shift_polynomialomnibias.difference.umbral.shift_polynomial
umbral_composition
omnibias.difference.umbral_compositionSource ↗umbral_composition(s_seq: Sequence[Sequence[Rational]], r_seq: Sequence[Sequence[Rational]]) -> list[tuple[Fraction, ...]]Umbral composition (s # r)_n(x) = sum_k s_{n,k} r_k(x) (exact).
s_seq is a polynomial sequence given as ascending-coefficient rows (s_{n,k} is the
x^k coefficient of s_n); r_seq is another such sequence, substituted for the
powers of x. r_seq must supply a row for every degree that appears in s_seq.
For Sheffer sequences this is the group operation dual to composing the delta series.
Parameters
| Name | Type & default | Contract |
|---|---|---|
s_seqpositional-or-keyword | Sequence[Sequence[Rational]]Required | See the operation contract and implementation below. |
r_seqpositional-or-keyword | Sequence[Sequence[Rational]]Required | See the operation contract and implementation below. |
list[tuple[Fraction, ...]]Explicit validation & failure cases
- When
k >= len(r_seq), raisesValueError(f'r_seq needs a row for degree {k}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · q umbral composition is q independent
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_q_umbral_composition_is_q_independent() -> None:
# Delegates to the classical (q-independent) umbral composition.
ff = q_associated_sequence([Fraction(0), Fraction(1), Fraction(1, 2), Fraction(1, 6)], 4, Fraction(2, 3))
bell = q_associated_sequence([Fraction(0), Fraction(1), Fraction(-1, 2), Fraction(1, 3)], 4, Fraction(2, 3))
assert q_umbral_composition(ff, bell) == umbral_composition(ff, bell)python -m pytest "packages/omnibias-qcalculus/tests/test_qumbral.py::test_q_umbral_composition_is_q_independent" -qRegression example · umbral composition inverse gives monomials
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_umbral_composition_inverse_gives_monomials() -> None:
# Falling factorials (assoc of e^t - 1) umbral-composed with the Bell polynomials
# (assoc of log(1 + t), the compositional inverse) recover the monomials x^n.
ff = associated_sequence(_exp_minus_one(N), N)
bell = associated_sequence(_log_one_plus(N), N)
comp = umbral_composition(ff, bell)
for n in range(N + 1):
assert tuple(comp[n]) == tuple([Fraction(0)] * n + [Fraction(1)])python -m pytest packages/omnibias-difference/tests/test_sheffer.py -k test_umbral_composition_inverse_gives_monomials -qRead the implementation
def umbral_composition(
s_seq: Sequence[Sequence[Rational]], r_seq: Sequence[Sequence[Rational]]
) -> list[tuple[Fraction, ...]]:
r"""Umbral composition ``(s # r)_n(x) = sum_k s_{n,k} r_k(x)`` (exact).
``s_seq`` is a polynomial sequence given as ascending-coefficient rows (``s_{n,k}`` is the
``x^k`` coefficient of ``s_n``); ``r_seq`` is another such sequence, substituted for the
powers of ``x``. ``r_seq`` must supply a row for every degree that appears in ``s_seq``.
For Sheffer sequences this is the group operation dual to composing the delta series.
"""
out: list[tuple[Fraction, ...]] = []
for row in s_seq:
poly: list[Fraction] = [Fraction(0)]
for k, s_nk in enumerate(row):
if not s_nk:
continue
if k >= len(r_seq):
raise ValueError(f"r_seq needs a row for degree {k}")
r_k = r_seq[k]
if len(r_k) > len(poly):
poly.extend([Fraction(0)] * (len(r_k) - len(poly)))
for j, c in enumerate(r_k):
poly[j] += _frac(s_nk) * _frac(c)
out.append(tuple(poly))
return outOther public import paths
omnibias.difference.umbral_compositionomnibias.difference.umbral.umbral_composition
umbral_functional
omnibias.difference.umbral_functionalSource ↗umbral_functional(moments: Sequence[Rational], coeffs: Sequence[Rational]) -> FractionThe linear functional <L | sum_k p_k x^k> = sum_k p_k mu_k (exact).
moments are mu_k = <L | x^k>; coeffs are the ascending coefficients of the
polynomial. With mu_k = a^k this is evaluation at a; with mu_k = k! it is the
Borel/umbral evaluation. Needs a moment for every coefficient.
Parameters
| Name | Type & default | Contract |
|---|---|---|
momentspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
FractionExplicit validation & failure cases
- When
len(p) > len(mu), raisesValueError('need a moment mu_k for every polynomial coefficient').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · umbral functional needs enough moments
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_umbral_functional_needs_enough_moments() -> None:
with pytest.raises(ValueError):
umbral_functional([Fraction(1)], (Fraction(1), Fraction(2)))python -m pytest "packages/omnibias-difference/tests/test_sheffer.py::test_umbral_functional_needs_enough_moments" -qRegression example · umbral functional evaluation
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_umbral_functional_evaluation() -> None:
# Moments mu_k = a^k realise the evaluation functional L(p) = p(a).
p = (Fraction(2), Fraction(-1), Fraction(3), Fraction(1))
a = Fraction(3, 2)
moments = [a**k for k in range(len(p))]
assert umbral_functional(moments, p) == _eval(p, a)python -m pytest packages/omnibias-difference/tests/test_sheffer.py -k test_umbral_functional_evaluation -qRead the implementation
def umbral_functional(moments: Sequence[Rational], coeffs: Sequence[Rational]) -> Fraction:
r"""The linear functional ``<L | sum_k p_k x^k> = sum_k p_k mu_k`` (exact).
``moments`` are ``mu_k = <L | x^k>``; ``coeffs`` are the ascending coefficients of the
polynomial. With ``mu_k = a^k`` this is evaluation at ``a``; with ``mu_k = k!`` it is the
Borel/umbral evaluation. Needs a moment for every coefficient.
"""
p = [_frac(v) for v in coeffs]
mu = [_frac(v) for v in moments]
if len(p) > len(mu):
raise ValueError("need a moment mu_k for every polynomial coefficient")
return sum((p[k] * mu[k] for k in range(len(p))), Fraction(0))Other public import paths
omnibias.difference.umbral_functionalomnibias.difference.umbral.umbral_functional
accuracy_order
omnibias.difference.accuracy_orderSource ↗accuracy_order(stencil: Stencil) -> intThe truncation-error order p: 1 for forward, 2 for central.
Parameters
| Name | Type & default | Contract |
|---|---|---|
stencilpositional-or-keyword | StencilRequired | See the operation contract and implementation below. |
intExecuted regression · honesty labels are correct
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_honesty_labels_are_correct() -> None:
enc = D.certified_derivative_enclosure("tanh", 0.0, 2)
assert enc.label == "closed-form"
est = D.finite_difference_estimate("tanh", 0.0, 2, 1e-2)
assert est.label == "numerical"
cert = D.certified_fd_error("tanh", 0.0, 2, 1e-2)
assert "closed-form" in cert.label and "numerical" in cert.labelpython -m pytest "packages/omnibias-difference/tests/test_scope.py::test_honesty_labels_are_correct" -qRead the implementation
def accuracy_order(stencil: Stencil) -> int:
"""The truncation-error order ``p``: ``1`` for forward, ``2`` for central."""
if stencil == "forward":
return 1
if stencil == "central":
return 2
raise ValueError(f"unknown stencil {stencil!r}; expected one of {_STENCILS}")offsets_exact
omnibias.difference.offsets_exactSource ↗offsets_exact(order: int, delta: Fraction, stencil: Stencil='central') -> tuple[Fraction, ...]Exact Fraction bias offsets b_j for the chosen stencil.
Parameters
| Name | Type & default | Contract |
|---|---|---|
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
deltapositional-or-keyword | FractionRequired | See the operation contract and implementation below. |
stencilpositional-or-keyword | StencilDefault: 'central' | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
order < 0, raisesValueError(f'order must be >= 0, got {order}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · honesty labels are correct
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_honesty_labels_are_correct() -> None:
enc = D.certified_derivative_enclosure("tanh", 0.0, 2)
assert enc.label == "closed-form"
est = D.finite_difference_estimate("tanh", 0.0, 2, 1e-2)
assert est.label == "numerical"
cert = D.certified_fd_error("tanh", 0.0, 2, 1e-2)
assert "closed-form" in cert.label and "numerical" in cert.labelpython -m pytest "packages/omnibias-difference/tests/test_scope.py::test_honesty_labels_are_correct" -qRead the implementation
def offsets_exact(order: int, delta: Fraction, stencil: Stencil = "central") -> tuple[Fraction, ...]:
"""Exact ``Fraction`` bias offsets ``b_j`` for the chosen stencil."""
if order < 0:
raise ValueError(f"order must be >= 0, got {order}")
d = Fraction(delta)
if stencil == "forward":
return tuple(Fraction(j) * d for j in range(order + 1))
if stencil == "central":
half = Fraction(order, 2)
return tuple((Fraction(j) - half) * d for j in range(order + 1))
raise ValueError(f"unknown stencil {stencil!r}; expected one of {_STENCILS}")signs_exact
omnibias.difference.signs_exactSource ↗signs_exact(order: int, delta: Fraction) -> tuple[Fraction, ...]Exact Fraction finite-difference signs s_j = (-1)^{m-j} C(m,j)/delta^m.
order = 0 returns (1,) (the identity single-bias unit); delta is
then ignored.
Parameters
| Name | Type & default | Contract |
|---|---|---|
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
deltapositional-or-keyword | FractionRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
order < 0, raisesValueError(f'order must be >= 0, got {order}'). - When
delta <= 0, raisesValueError(f'delta must be > 0 for order >= 1 (got delta={delta})').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · honesty labels are correct
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_honesty_labels_are_correct() -> None:
enc = D.certified_derivative_enclosure("tanh", 0.0, 2)
assert enc.label == "closed-form"
est = D.finite_difference_estimate("tanh", 0.0, 2, 1e-2)
assert est.label == "numerical"
cert = D.certified_fd_error("tanh", 0.0, 2, 1e-2)
assert "closed-form" in cert.label and "numerical" in cert.labelpython -m pytest "packages/omnibias-difference/tests/test_scope.py::test_honesty_labels_are_correct" -qRegression example · g1 reproduces signs exact forward and central
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_reproduces_signs_exact_forward_and_central() -> None:
h = Fraction(1, 7)
for order in (0, 1, 2, 3):
for kind in ("forward", "central"):
req = _uniform_value_request(order, kind)
st = solve_irregular_stencil(req)
assert st is not None, (order, kind)
phys = physical_weights(st, h)
flat = tuple(w[0] for w in phys)
expected = signs_exact(order, h)
assert flat == expected, (order, kind, flat, expected)python -m pytest packages/omnibias-difference/tests/test_irregular.py -k test_g1_reproduces_signs_exact_forward_and_central -qRead the implementation
def signs_exact(order: int, delta: Fraction) -> tuple[Fraction, ...]:
r"""Exact ``Fraction`` finite-difference signs ``s_j = (-1)^{m-j} C(m,j)/delta^m``.
``order = 0`` returns ``(1,)`` (the identity single-bias unit); ``delta`` is
then ignored.
"""
if order < 0:
raise ValueError(f"order must be >= 0, got {order}")
if order == 0:
return (Fraction(1),)
if delta <= 0:
raise ValueError(f"delta must be > 0 for order >= 1 (got delta={delta})")
inv = Fraction(1) / (Fraction(delta) ** order)
return tuple(Fraction((-1) ** (order - j)) * comb(order, j) * inv for j in range(order + 1))stencil_offsets
omnibias.difference.stencil_offsetsSource ↗stencil_offsets(order: int, delta: float, stencil: Stencil='central') -> tuple[float, ...]Bias offsets b_j as float for the chosen stencil.
Parameters
| Name | Type & default | Contract |
|---|---|---|
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
deltapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
stencilpositional-or-keyword | StencilDefault: 'central' | See the operation contract and implementation below. |
tuple[float, ...]Executed regression · honesty labels are correct
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_honesty_labels_are_correct() -> None:
enc = D.certified_derivative_enclosure("tanh", 0.0, 2)
assert enc.label == "closed-form"
est = D.finite_difference_estimate("tanh", 0.0, 2, 1e-2)
assert est.label == "numerical"
cert = D.certified_fd_error("tanh", 0.0, 2, 1e-2)
assert "closed-form" in cert.label and "numerical" in cert.labelpython -m pytest "packages/omnibias-difference/tests/test_scope.py::test_honesty_labels_are_correct" -qRead the implementation
def stencil_offsets(order: int, delta: float, stencil: Stencil = "central") -> tuple[float, ...]:
"""Bias offsets ``b_j`` as ``float`` for the chosen stencil."""
_validate(order, delta)
return tuple(float(b) for b in offsets_exact(order, Fraction(delta), stencil))stencil_signs
omnibias.difference.stencil_signsSource ↗stencil_signs(order: int, delta: float, stencil: Stencil='central') -> tuple[float, ...]Finite-difference signs as float (magnitudes are stencil-independent).
Parameters
| Name | Type & default | Contract |
|---|---|---|
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
deltapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
stencilpositional-or-keyword | StencilDefault: 'central' | See the operation contract and implementation below. |
tuple[float, ...]Explicit validation & failure cases
- When
stencil not in _STENCILS, raisesValueError(f'unknown stencil {stencil!r}; expected one of {_STENCILS}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · honesty labels are correct
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_honesty_labels_are_correct() -> None:
enc = D.certified_derivative_enclosure("tanh", 0.0, 2)
assert enc.label == "closed-form"
est = D.finite_difference_estimate("tanh", 0.0, 2, 1e-2)
assert est.label == "numerical"
cert = D.certified_fd_error("tanh", 0.0, 2, 1e-2)
assert "closed-form" in cert.label and "numerical" in cert.labelpython -m pytest "packages/omnibias-difference/tests/test_scope.py::test_honesty_labels_are_correct" -qRegression example · residual 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_residual_parity(name: str) -> None:
delta = 1e-2
zt = torch.tensor(_XS, dtype=torch.float64)
zj = jnp.asarray(_XS)
rt = DT.finite_difference_residual(name, zt, 2, delta, "central").detach().numpy()
rj = np.asarray(DJ.finite_difference_residual(name, zj, 2, delta, "central"))
sign_mag = sum(abs(s) for s in stencil_signs(2, delta, "central"))
assert np.max(np.abs(rt - rj)) < 1e-12 * sign_mag + 1e-12python -m pytest packages/omnibias-difference/tests/test_parity.py -k test_residual_parity -qRead the implementation
def stencil_signs(order: int, delta: float, stencil: Stencil = "central") -> tuple[float, ...]:
"""Finite-difference signs as ``float`` (magnitudes are stencil-independent)."""
_validate(order, delta)
if stencil not in _STENCILS:
raise ValueError(f"unknown stencil {stencil!r}; expected one of {_STENCILS}")
return tuple(float(s) for s in signs_exact(order, Fraction(delta)))bell_number
omnibias.difference.bell_numberSource ↗bell_number(n: int) -> intThe n-th Bell number sum_k S(n, k) (re-exported from omnibias.core.bell).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExecuted regression · bell numbers exact
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_bell_numbers_exact() -> None:
assert [bell_number(n) for n in range(7)] == [1, 1, 2, 5, 15, 52, 203]python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_bell_numbers_exact" -qRegression example · stirling second row sums to bell
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_stirling_second_row_sums_to_bell(n: int) -> None:
assert sum(stirling_second_row(n)) == bell_number(n)python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_stirling_second_row_sums_to_bell -qRead the implementation
def bell_number(n: int) -> int:
"""The ``n``-th Bell number ``sum_k S(n, k)`` (re-exported from ``omnibias.core.bell``)."""
return _bell_number(n)falling_factorial_coeffs
omnibias.difference.falling_factorial_coeffsSource ↗falling_factorial_coeffs(n: int) -> tuple[int, ...]Coefficients of the falling factorial (x)_n = x (x-1) ... (x-n+1).
Returns (c_0, ..., c_n) with (x)_n = sum_k c_k x^k; these are the signed
Stirling numbers of the first kind c_k = s(n, k). Computed directly by the
product prod_{j=0}^{n-1} (x - j) (an independent cross-check of
stirling_first_signed).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[int, ...]Explicit validation & failure cases
- When
n < 0, raisesValueError(f'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 · falling factorial is signed stirling first
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_falling_factorial_is_signed_stirling_first(n: int) -> None:
assert falling_factorial_coeffs(n) == stirling_first_signed_row(n)python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_falling_factorial_is_signed_stirling_first[0]" -qRegression example · associated of exp minus one is falling factorial
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_associated_of_exp_minus_one_is_falling_factorial(n: int) -> None:
# e^t - 1 is the delta series of the forward difference: its associated
# (binomial-type) sequence is the falling factorial (x)_n.
seq = associated_sequence(_exp_minus_one(N), N)
assert tuple(seq[n]) == tuple(Fraction(c) for c in falling_factorial_coeffs(n))python -m pytest packages/omnibias-difference/tests/test_sheffer.py -k test_associated_of_exp_minus_one_is_falling_factorial -qRead the implementation
def falling_factorial_coeffs(n: int) -> tuple[int, ...]:
r"""Coefficients of the falling factorial ``(x)_n = x (x-1) ... (x-n+1)``.
Returns ``(c_0, ..., c_n)`` with ``(x)_n = sum_k c_k x^k``; these are the signed
Stirling numbers of the first kind ``c_k = s(n, k)``. Computed directly by the
product ``prod_{j=0}^{n-1} (x - j)`` (an independent cross-check of
:func:`stirling_first_signed`).
"""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
poly = [1]
for j in range(n):
nxt = [0] * (len(poly) + 1)
for k, c in enumerate(poly):
nxt[k + 1] += c
nxt[k] -= j * c
poly = nxt
return tuple(poly)rising_factorial_coeffs
omnibias.difference.rising_factorial_coeffsSource ↗rising_factorial_coeffs(n: int) -> tuple[int, ...]Coefficients of the rising factorial x^(n) = x (x+1) ... (x+n-1).
Returns (c_0, ..., c_n) with x^(n) = sum_k c_k x^k; these are the
unsigned Stirling numbers of the first kind c_k = |s(n, k)|.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[int, ...]Explicit validation & failure cases
- When
n < 0, raisesValueError(f'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 · rising factorial is unsigned stirling first
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_rising_factorial_is_unsigned_stirling_first(n: int) -> None:
assert rising_factorial_coeffs(n) == tuple(
stirling_first_unsigned(n, k) for k in range(n + 1)
)python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_rising_factorial_is_unsigned_stirling_first[0]" -qRead the implementation
def rising_factorial_coeffs(n: int) -> tuple[int, ...]:
r"""Coefficients of the rising factorial ``x^(n) = x (x+1) ... (x+n-1)``.
Returns ``(c_0, ..., c_n)`` with ``x^(n) = sum_k c_k x^k``; these are the
unsigned Stirling numbers of the first kind ``c_k = |s(n, k)|``.
"""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}")
poly = [1]
for j in range(n):
nxt = [0] * (len(poly) + 1)
for k, c in enumerate(poly):
nxt[k + 1] += c
nxt[k] += j * c
poly = nxt
return tuple(poly)stirling_first_signed
omnibias.difference.stirling_first_signedSource ↗stirling_first_signed(n: int, k: int) -> intSigned Stirling number of the first kind s(n, k) = B_{n,k}((-1)^{i-1}(i-1)!).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
n < 0 or k < 0, raisesValueError(f'n, k must be >= 0, got n={n}, k={k}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · falling factorial is signed stirling first
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_falling_factorial_is_signed_stirling_first(n: int) -> None:
assert falling_factorial_coeffs(n) == stirling_first_signed_row(n)python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_falling_factorial_is_signed_stirling_first[0]" -qRead the implementation
def stirling_first_signed(n: int, k: int) -> int:
"""Signed Stirling number of the first kind ``s(n, k) = B_{n,k}((-1)^{i-1}(i-1)!)``."""
if n < 0 or k < 0:
raise ValueError(f"n, k must be >= 0, got n={n}, k={k}")
return _bell_partial_eval(n, k, lambda i: (-1) ** (i - 1) * factorial(i - 1))stirling_first_signed_row
omnibias.difference.stirling_first_signed_rowSource ↗stirling_first_signed_row(n: int) -> tuple[int, ...]The row (s(n, 0), ..., s(n, n)) (signed first kind).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[int, ...]Executed regression · falling factorial is signed stirling first
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_falling_factorial_is_signed_stirling_first(n: int) -> None:
assert falling_factorial_coeffs(n) == stirling_first_signed_row(n)python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_falling_factorial_is_signed_stirling_first[0]" -qRegression example · stirling first signed exact rows
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_stirling_first_signed_exact_rows() -> None:
assert stirling_first_signed_row(4) == (0, -6, 11, -6, 1)
assert stirling_first_signed_row(5) == (0, 24, -50, 35, -10, 1)python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_stirling_first_signed_exact_rows -qRead the implementation
def stirling_first_signed_row(n: int) -> tuple[int, ...]:
"""The row ``(s(n, 0), ..., s(n, n))`` (signed first kind)."""
return tuple(stirling_first_signed(n, k) for k in range(n + 1))stirling_first_unsigned
omnibias.difference.stirling_first_unsignedSource ↗stirling_first_unsigned(n: int, k: int) -> intUnsigned Stirling number of the first kind c(n, k) = |s(n, k)| = B_{n,k}((i-1)!).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
n < 0 or k < 0, raisesValueError(f'n, k must be >= 0, got n={n}, k={k}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · rising factorial is unsigned stirling first
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_rising_factorial_is_unsigned_stirling_first(n: int) -> None:
assert rising_factorial_coeffs(n) == tuple(
stirling_first_unsigned(n, k) for k in range(n + 1)
)python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_rising_factorial_is_unsigned_stirling_first[0]" -qRead the implementation
def stirling_first_unsigned(n: int, k: int) -> int:
"""Unsigned Stirling number of the first kind ``c(n, k) = |s(n, k)| = B_{n,k}((i-1)!)``."""
if n < 0 or k < 0:
raise ValueError(f"n, k must be >= 0, got n={n}, k={k}")
return _bell_partial_eval(n, k, lambda i: factorial(i - 1))stirling_second
omnibias.difference.stirling_secondSource ↗stirling_second(n: int, k: int) -> intStirling number of the second kind S(n, k) = B_{n,k}(1, ..., 1).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
n < 0 or k < 0, raisesValueError(f'n, k must be >= 0, got n={n}, k={k}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · stirling second row sums to bell
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_stirling_second_row_sums_to_bell(n: int) -> None:
assert sum(stirling_second_row(n)) == bell_number(n)python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_stirling_second_row_sums_to_bell[0]" -qRegression example · stirling second fixed k asymptotic converges
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_stirling_second_fixed_k_asymptotic_converges() -> None:
# S(n, k) ~ k^n / k! as n -> inf, for fixed k.
def ratio(n: int, k: int) -> float:
return stirling_second(n, k) / stirling_second_asymptotic(n, k)
assert ratio(25, 4) > ratio(15, 4) > ratio(8, 4)
assert 0.99 < ratio(25, 4) <= 1.0python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_stirling_second_fixed_k_asymptotic_converges -qRead the implementation
def stirling_second(n: int, k: int) -> int:
"""Stirling number of the second kind ``S(n, k) = B_{n,k}(1, ..., 1)``."""
if n < 0 or k < 0:
raise ValueError(f"n, k must be >= 0, got n={n}, k={k}")
return _bell_partial_eval(n, k, lambda _i: 1)stirling_second_row
omnibias.difference.stirling_second_rowSource ↗stirling_second_row(n: int) -> tuple[int, ...]The row (S(n, 0), ..., S(n, n)).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[int, ...]Executed regression · stirling second row sums to bell
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_stirling_second_row_sums_to_bell(n: int) -> None:
assert sum(stirling_second_row(n)) == bell_number(n)python -m pytest "packages/omnibias-difference/tests/test_special_numbers.py::test_stirling_second_row_sums_to_bell[0]" -qRegression example · stirling second exact rows
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_stirling_second_exact_rows() -> None:
assert stirling_second_row(0) == (1,)
assert stirling_second_row(4) == (0, 1, 7, 6, 1)
assert stirling_second_row(5) == (0, 1, 15, 25, 10, 1)python -m pytest packages/omnibias-difference/tests/test_special_numbers.py -k test_stirling_second_exact_rows -qRead the implementation
def stirling_second_row(n: int) -> tuple[int, ...]:
"""The row ``(S(n, 0), ..., S(n, n))``."""
return tuple(stirling_second(n, k) for k in range(n + 1))ShefferClass
omnibias.difference.ShefferClassSource ↗class ShefferClassDataclass 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.
Classification of a Sheffer sequence from its defining pair (g, f).
Parameters
| Name | Type & default | Contract |
|---|---|---|
kinddataclass field | strRequired | See the operation contract and implementation below. |
is_appelldataclass field | boolRequired | See the operation contract and implementation below. |
is_associateddataclass field | boolRequired | See the operation contract and implementation below. |
Fields & methods
is_appellfield
is_appell: boolDeclared bool field on ShefferClass. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗is_associatedfield
is_associated: boolDeclared bool field on ShefferClass. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗Read the implementation
class ShefferClass:
"""Classification of a Sheffer sequence from its defining pair ``(g, f)``."""
kind: str # "appell" | "associated" | "sheffer"
is_appell: bool
is_associated: boolOther public import paths
omnibias.difference.ShefferClassomnibias.difference.umbral.ShefferClass
appell_sequence
omnibias.difference.appell_sequenceSource ↗appell_sequence(constants: Sequence[Rational]) -> list[tuple[Fraction, ...]]Appell sequence p_n(x) = sum_k C(n, k) a_{n-k} x^k from constants a_j = p_j(0).
An Appell sequence satisfies p_n'(x) = n p_{n-1}(x); it is the h -> 0
(Sheffer) shift-invariant family whose evaluation functional is fixed by the
moments a_j. Bernoulli polynomials are the Appell sequence of the Bernoulli
numbers; a = (1, 0, 0, ...) gives the monomials x^n.
Parameters
| Name | Type & default | Contract |
|---|---|---|
constantspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
list[tuple[Fraction, ...]]Executed regression · appell of delta is monomials
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_appell_of_delta_is_monomials() -> None:
seq = appell_sequence([Fraction(1)] + [Fraction(0)] * 4)
for n in range(5):
expected = tuple([Fraction(0)] * n + [Fraction(1)])
assert tuple(seq[n]) == expectedpython -m pytest "packages/omnibias-difference/tests/test_umbral.py::test_appell_of_delta_is_monomials" -qRegression example · binomial transform inverse
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_binomial_transform_inverse(seed: int) -> None:
rng = random.Random(200 + seed)
seq = [Fraction(rng.randint(-6, 6)) for _ in range(rng.randint(1, 7))]
assert inverse_binomial_transform(binomial_transform(seq)) == tuple(seq)python -m pytest packages/omnibias-difference/tests/test_umbral.py -k test_binomial_transform_inverse -qRead the implementation
def appell_sequence(constants: Sequence[Rational]) -> list[tuple[Fraction, ...]]:
r"""Appell sequence ``p_n(x) = sum_k C(n, k) a_{n-k} x^k`` from constants ``a_j = p_j(0)``.
An Appell sequence satisfies ``p_n'(x) = n p_{n-1}(x)``; it is the ``h -> 0``
(Sheffer) shift-invariant family whose evaluation functional is fixed by the
moments ``a_j``. Bernoulli polynomials are the Appell sequence of the Bernoulli
numbers; ``a = (1, 0, 0, ...)`` gives the monomials ``x^n``.
"""
a = [_frac(v) for v in constants]
return [
tuple(Fraction(comb(n, k)) * a[n - k] for k in range(n + 1)) for n in range(len(a))
]Other public import paths
omnibias.difference.appell_sequenceomnibias.difference.umbral.appell_sequence
binomial_coefficient
omnibias.difference.binomial_coefficientSource ↗binomial_coefficient(x: Rational, k: int) -> FractionGeneralised binomial C(x, k) = (x)_k / k! for a rational x.
Parameters
| Name | Type & default | Contract |
|---|---|---|
xpositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
FractionExplicit validation & failure cases
- When
k < 0, raisesValueError(f'k must be >= 0, got {k}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · newton interpolation reproduces polynomial
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_newton_interpolation_reproduces_polynomial(seed: int) -> None:
rng = random.Random(seed)
deg = rng.randint(0, 5)
coeffs = [Fraction(rng.randint(-4, 4)) for _ in range(deg + 1)]
def poly(x: int) -> Fraction:
return _eval(tuple(coeffs), Fraction(x))
samples = [poly(i) for i in range(deg + 1)]
fwd = newton_forward_coeffs(samples)
# reproduces the polynomial exactly at nodes and well outside them
for x in (-3, -1, 0, 1, 2, deg + 5, 10):
assert newton_forward_value(fwd, Fraction(x)) == poly(x)python -m pytest "packages/omnibias-difference/tests/test_umbral.py::test_newton_interpolation_reproduces_polynomial[0]" -qRead the implementation
def binomial_coefficient(x: Rational, k: int) -> Fraction:
r"""Generalised binomial ``C(x, k) = (x)_k / k!`` for a rational ``x``."""
if k < 0:
raise ValueError(f"k must be >= 0, got {k}")
xf = _frac(x)
num = Fraction(1)
for j in range(k):
num *= xf - j
return num / factorial(k)Other public import paths
omnibias.difference.binomial_coefficientomnibias.difference.umbral.binomial_coefficient
binomial_transform
omnibias.difference.binomial_transformSource ↗binomial_transform(seq: Sequence[Rational]) -> tuple[Fraction, ...]Binomial transform b_n = sum_k C(n, k) a_k.
Parameters
| Name | Type & default | Contract |
|---|---|---|
seqpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · binomial transform inverse
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_binomial_transform_inverse(seed: int) -> None:
rng = random.Random(200 + seed)
seq = [Fraction(rng.randint(-6, 6)) for _ in range(rng.randint(1, 7))]
assert inverse_binomial_transform(binomial_transform(seq)) == tuple(seq)python -m pytest "packages/omnibias-difference/tests/test_umbral.py::test_binomial_transform_inverse[0]" -qRegression example · q transforms reduce to classical
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_q_transforms_reduce_to_classical() -> None:
coeffs = [Fraction(1), Fraction(-2), Fraction(3), Fraction(0), Fraction(4)]
assert q_monomial_to_falling(coeffs, ONE) == monomial_to_falling(coeffs)
assert q_falling_to_monomial(coeffs, ONE) == falling_to_monomial(coeffs)
seq = [Fraction(1), Fraction(3), Fraction(-2), Fraction(5), Fraction(0), Fraction(-1)]
assert q_binomial_transform(seq, ONE) == binomial_transform(seq)
assert q_inverse_binomial_transform(seq, ONE) == inverse_binomial_transform(seq)python -m pytest packages/omnibias-qcalculus/tests/test_qumbral.py -k test_q_transforms_reduce_to_classical -qRead the implementation
def binomial_transform(seq: Sequence[Rational]) -> tuple[Fraction, ...]:
r"""Binomial transform ``b_n = sum_k C(n, k) a_k``."""
a = [_frac(v) for v in seq]
return tuple(
sum((Fraction(comb(n, k)) * a[k] for k in range(n + 1)), Fraction(0))
for n in range(len(a))
)Other public import paths
omnibias.difference.binomial_transformomnibias.difference.umbral.binomial_transform
compose_series
omnibias.difference.compose_seriesSource ↗compose_series(outer: Sequence[Rational], inner: Sequence[Rational], order: int) -> tuple[Fraction, ...]Coefficients [t^0..t^order] of outer(inner(t)) with inner(0) = 0 (exact).
Horner in the composition algebra: requires a *delta series* inner (zero
constant term) so the composition is a well-defined formal power series.
Parameters
| Name | Type & default | Contract |
|---|---|---|
outerpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
innerpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
order < 0, raisesValueError(f'order must be >= 0, got {order}'). - When
g and g[0] != 0, raisesValueError('inner series must have zero constant term (inner(0) = 0)').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · associated of t are monomials
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_associated_of_t_are_monomials() -> None:
seq = associated_sequence((0, 1), N)
for n in range(N + 1):
assert tuple(seq[n]) == tuple([Fraction(0)] * n + [Fraction(1)])python -m pytest "packages/omnibias-difference/tests/test_sheffer.py::test_associated_of_t_are_monomials" -qRegression example · inverse round trip
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_inverse_round_trip(self) -> None:
h = [0, 1, 2, 3, 1]
hbar = compositional_inverse(h, 5)
composed = compose_series(h, hbar, 5)
assert composed[:2] == (Fraction(0), Fraction(1))
assert all(c == 0 for c in composed[2:])python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_inverse_round_trip -qRead the implementation
def compose_series(
outer: Sequence[Rational], inner: Sequence[Rational], order: int
) -> tuple[Fraction, ...]:
r"""Coefficients ``[t^0..t^order]`` of ``outer(inner(t))`` with ``inner(0) = 0`` (exact).
Horner in the composition algebra: requires a *delta series* ``inner`` (zero
constant term) so the composition is a well-defined formal power series.
"""
if order < 0:
raise ValueError(f"order must be >= 0, got {order}")
f = [_frac(v) for v in outer]
g = [_frac(v) for v in inner]
if g and g[0] != 0:
raise ValueError("inner series must have zero constant term (inner(0) = 0)")
result = [Fraction(0)] * (order + 1)
if f:
result[0] = f[0]
gpow = [Fraction(0)] * (order + 1)
gpow[0] = Fraction(1) # inner^0 = 1
for k in range(1, len(f)):
nextpow = [Fraction(0)] * (order + 1)
for i in range(order + 1):
if gpow[i] == 0:
continue
for j in range(1, len(g)):
if i + j > order:
break
nextpow[i + j] += gpow[i] * g[j]
gpow = nextpow
for i in range(order + 1):
if gpow[i] != 0:
result[i] += f[k] * gpow[i]
return tuple(result)Other public import paths
omnibias.difference.compose_seriesomnibias.difference.umbral.compose_series
compositional_inverse
omnibias.difference.compositional_inverseSource ↗compositional_inverse(series: Sequence[Rational], order: int) -> tuple[Fraction, ...]Compositional inverse sbar with series(sbar(t)) = t (exact, series(0)=0).
Requires a delta series with series[1] != 0. Solves order by order using
compose_series; e.g. the inverse of t/(1-t) is t/(1+t).
Parameters
| Name | Type & default | Contract |
|---|---|---|
seriespositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
order < 0, raisesValueError(f'order must be >= 0, got {order}'). - When
len(h) < 2 or h[0] != 0 or h[1] == 0, raisesValueError("series must be a delta series: series(0) = 0 and series'(0) != 0").
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · associated of t are monomials
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_associated_of_t_are_monomials() -> None:
seq = associated_sequence((0, 1), N)
for n in range(N + 1):
assert tuple(seq[n]) == tuple([Fraction(0)] * n + [Fraction(1)])python -m pytest "packages/omnibias-difference/tests/test_sheffer.py::test_associated_of_t_are_monomials" -qRegression example · compositional inverse
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_compositional_inverse(self) -> None:
# inverse of t/(1-t) is t/(1+t).
inv = compositional_inverse([0, 1, 1, 1, 1, 1], 5)
assert inv == (Fraction(0), Fraction(1), Fraction(-1), Fraction(1), Fraction(-1), Fraction(1))python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_compositional_inverse -qRead the implementation
def compositional_inverse(series: Sequence[Rational], order: int) -> tuple[Fraction, ...]:
r"""Compositional inverse ``sbar`` with ``series(sbar(t)) = t`` (exact, ``series(0)=0``).
Requires a delta series with ``series[1] != 0``. Solves order by order using
:func:`compose_series`; e.g. the inverse of ``t/(1-t)`` is ``t/(1+t)``.
"""
if order < 0:
raise ValueError(f"order must be >= 0, got {order}")
h = [_frac(v) for v in series]
if len(h) < 2 or h[0] != 0 or h[1] == 0:
raise ValueError("series must be a delta series: series(0) = 0 and series'(0) != 0")
hbar = [Fraction(0)] * (order + 1)
if order >= 1:
hbar[1] = Fraction(1) / h[1]
for k in range(2, order + 1):
current = compose_series(h, hbar, k)
hbar[k] = -current[k] / h[1]
return tuple(hbar)Other public import paths
omnibias.difference.compositional_inverseomnibias.difference.umbral.compositional_inverse
connection_constants
omnibias.difference.connection_constantsSource ↗connection_constants(source: Sequence[Sequence[Rational]], target: Sequence[Sequence[Rational]]) -> list[tuple[Fraction, ...]]Connection constants c[n][k] with source_n = sum_k c[n][k] target_k (exact).
Both bases are graded polynomial sequences given as ascending coefficient lists with
deg target_k = k (a triangular basis, e.g. monomials or falling factorials), so the
change of basis is an exact back-substitution. E.g. with target the falling
factorials this recovers the Stirling-second-kind connection x^n = sum_k S(n,k)(x)_k.
Parameters
| Name | Type & default | Contract |
|---|---|---|
sourcepositional-or-keyword | Sequence[Sequence[Rational]]Required | See the operation contract and implementation below. |
targetpositional-or-keyword | Sequence[Sequence[Rational]]Required | See the operation contract and implementation below. |
list[tuple[Fraction, ...]]Explicit validation & failure cases
- When
lead == 0, raisesValueError(f'target[{k}] must have non-zero degree-{k} coefficient (graded basis)'). - When
k >= len(tgt), raisesValueError('target basis is too short for the source degree').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · non graded target raises
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_non_graded_target_raises(self) -> None:
# target[1] = [1, 0] has a zero degree-1 coefficient -> not a graded basis.
with pytest.raises(ValueError):
connection_constants([[Fraction(1), Fraction(1)]], [[Fraction(1)], [Fraction(1), Fraction(0)]])python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestConnectionConstants::test_non_graded_target_raises" -qRegression example · monomials to falling is stirling second
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_monomials_to_falling_is_stirling_second(self) -> None:
# x^n = sum_k S(n, k) (x)_k.
def falling(k: int) -> list[Fraction]:
coeffs = [Fraction(1)]
for j in range(k):
nxt = [Fraction(0)] * (len(coeffs) + 1)
for i, ci in enumerate(coeffs):
nxt[i] += -Fraction(j) * ci
nxt[i + 1] += ci
coeffs = nxt
return coeffs
target = [falling(k) for k in range(6)]
source = [[Fraction(0)] * n + [Fraction(1)] for n in range(6)]
cc = connection_constants(source, target)
for n in range(6):
for k in range(n + 1):
assert cc[n][k] == stirling_second(n, k)python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_monomials_to_falling_is_stirling_second -qRead the implementation
def connection_constants(
source: Sequence[Sequence[Rational]], target: Sequence[Sequence[Rational]]
) -> list[tuple[Fraction, ...]]:
r"""Connection constants ``c[n][k]`` with ``source_n = sum_k c[n][k] target_k`` (exact).
Both bases are graded polynomial sequences given as ascending coefficient lists with
``deg target_k = k`` (a triangular basis, e.g. monomials or falling factorials), so the
change of basis is an exact back-substitution. E.g. with ``target`` the falling
factorials this recovers the Stirling-second-kind connection ``x^n = sum_k S(n,k)(x)_k``.
"""
src = [[_frac(v) for v in poly] for poly in source]
tgt = [[_frac(v) for v in poly] for poly in target]
for k, poly in enumerate(tgt):
lead = poly[k] if k < len(poly) else Fraction(0)
if lead == 0:
raise ValueError(f"target[{k}] must have non-zero degree-{k} coefficient (graded basis)")
def coeff(poly: list[Fraction], i: int) -> Fraction:
return poly[i] if i < len(poly) else Fraction(0)
out: list[tuple[Fraction, ...]] = []
for poly in src:
degree = len(poly) - 1
residual = [coeff(poly, i) for i in range(degree + 1)]
row = [Fraction(0)] * (degree + 1)
for k in range(degree, -1, -1):
if k >= len(tgt):
raise ValueError("target basis is too short for the source degree")
ck = residual[k] / coeff(tgt[k], k)
row[k] = ck
if ck != 0:
for i in range(k + 1):
residual[i] -= ck * coeff(tgt[k], i)
out.append(tuple(row))
return outOther public import paths
omnibias.difference.connection_constantsomnibias.difference.umbral.connection_constants
falling_to_monomial
omnibias.difference.falling_to_monomialSource ↗falling_to_monomial(coeffs: Sequence[Rational]) -> tuple[Fraction, ...]Rewrite sum_k a_k (x)_k in the monomial basis sum_j c_j x^j.
Uses (x)_k = sum_j s(k, j) x^j (signed Stirling first kind), so
c_j = sum_k a_k s(k, j). Exact inverse of monomial_to_falling.
Parameters
| Name | Type & default | Contract |
|---|---|---|
coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · monomial falling are mutual inverses
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_monomial_falling_are_mutual_inverses(seed: int) -> None:
rng = random.Random(100 + seed)
coeffs = [Fraction(rng.randint(-5, 5)) for _ in range(rng.randint(1, 6))]
fall = monomial_to_falling(coeffs)
back = falling_to_monomial(fall)
assert back == tuple(coeffs)python -m pytest "packages/omnibias-difference/tests/test_umbral.py::test_monomial_falling_are_mutual_inverses[0]" -qRegression example · falling to monomial is signed stirling first
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_falling_to_monomial_is_signed_stirling_first(n: int) -> None:
# (x)_n = sum_k s(n, k) x^k, so the monomial coeffs of (x)_n are the s(n, .) row.
falling = [Fraction(0)] * n + [Fraction(1)]
assert falling_to_monomial(falling) == tuple(Fraction(s) for s in stirling_first_signed_row(n))python -m pytest packages/omnibias-difference/tests/test_umbral.py -k test_falling_to_monomial_is_signed_stirling_first -qRead the implementation
def falling_to_monomial(coeffs: Sequence[Rational]) -> tuple[Fraction, ...]:
r"""Rewrite ``sum_k a_k (x)_k`` in the monomial basis ``sum_j c_j x^j``.
Uses ``(x)_k = sum_j s(k, j) x^j`` (signed Stirling first kind), so
``c_j = sum_k a_k s(k, j)``. Exact inverse of :func:`monomial_to_falling`.
"""
a = [_frac(v) for v in coeffs]
d = len(a)
return tuple(
sum((a[k] * stirling_first_signed(k, j) for k in range(j, d)), Fraction(0))
for j in range(d)
)Other public import paths
omnibias.difference.falling_to_monomialomnibias.difference.umbral.falling_to_monomial
forward_difference
omnibias.difference.forward_differenceSource ↗forward_difference(values: Sequence[Rational], order: int=1) -> tuple[Fraction, ...]Apply the forward-difference operator Delta f(i) = f(i+1) - f(i) order times.
Returns a tuple shorter by order (Delta^order of the value list).
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuespositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
orderpositional-or-keyword | intDefault: 1 | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
order < 0, raisesValueError(f'order must be >= 0, got {order}'). - When
order > len(values), raisesValueError(f'order {order} exceeds the number of values {len(values)}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · forward difference of monomial is factorial
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_forward_difference_of_monomial_is_factorial() -> None:
# Delta^m of (i^m) is the constant m!.
for m in range(1, 7):
values = [Fraction(i**m) for i in range(m + 1)]
diffs = forward_difference(values, m)
assert diffs == (Fraction(factorial(m)),)python -m pytest "packages/omnibias-difference/tests/test_umbral.py::test_forward_difference_of_monomial_is_factorial" -qRead the implementation
def forward_difference(values: Sequence[Rational], order: int = 1) -> tuple[Fraction, ...]:
r"""Apply the forward-difference operator ``Delta f(i) = f(i+1) - f(i)`` ``order`` times.
Returns a tuple shorter by ``order`` (``Delta^order`` of the value list).
"""
if order < 0:
raise ValueError(f"order must be >= 0, got {order}")
if order > len(values):
raise ValueError(f"order {order} exceeds the number of values {len(values)}")
seq = [_frac(v) for v in values]
for _ in range(order):
seq = [seq[i + 1] - seq[i] for i in range(len(seq) - 1)]
return tuple(seq)Other public import paths
omnibias.difference.forward_differenceomnibias.difference.umbral.forward_difference
inverse_binomial_transform
omnibias.difference.inverse_binomial_transformSource ↗inverse_binomial_transform(seq: Sequence[Rational]) -> tuple[Fraction, ...]Inverse binomial transform a_n = sum_k (-1)^{n-k} C(n, k) b_k.
Parameters
| Name | Type & default | Contract |
|---|---|---|
seqpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · binomial transform inverse
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_binomial_transform_inverse(seed: int) -> None:
rng = random.Random(200 + seed)
seq = [Fraction(rng.randint(-6, 6)) for _ in range(rng.randint(1, 7))]
assert inverse_binomial_transform(binomial_transform(seq)) == tuple(seq)python -m pytest "packages/omnibias-difference/tests/test_umbral.py::test_binomial_transform_inverse[0]" -qRegression example · q transforms reduce to classical
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_q_transforms_reduce_to_classical() -> None:
coeffs = [Fraction(1), Fraction(-2), Fraction(3), Fraction(0), Fraction(4)]
assert q_monomial_to_falling(coeffs, ONE) == monomial_to_falling(coeffs)
assert q_falling_to_monomial(coeffs, ONE) == falling_to_monomial(coeffs)
seq = [Fraction(1), Fraction(3), Fraction(-2), Fraction(5), Fraction(0), Fraction(-1)]
assert q_binomial_transform(seq, ONE) == binomial_transform(seq)
assert q_inverse_binomial_transform(seq, ONE) == inverse_binomial_transform(seq)python -m pytest packages/omnibias-qcalculus/tests/test_qumbral.py -k test_q_transforms_reduce_to_classical -qRead the implementation
def inverse_binomial_transform(seq: Sequence[Rational]) -> tuple[Fraction, ...]:
r"""Inverse binomial transform ``a_n = sum_k (-1)^{n-k} C(n, k) b_k``."""
b = [_frac(v) for v in seq]
return tuple(
sum(
(Fraction((-1) ** (n - k) * comb(n, k)) * b[k] for k in range(n + 1)),
Fraction(0),
)
for n in range(len(b))
)Other public import paths
omnibias.difference.inverse_binomial_transformomnibias.difference.umbral.inverse_binomial_transform
monomial_to_falling
omnibias.difference.monomial_to_fallingSource ↗monomial_to_falling(coeffs: Sequence[Rational]) -> tuple[Fraction, ...]Rewrite sum_j c_j x^j in the falling-factorial basis sum_k a_k (x)_k.
Uses x^j = sum_k S(j, k) (x)_k (Stirling second kind), so
a_k = sum_j c_j S(j, k).
Parameters
| Name | Type & default | Contract |
|---|---|---|
coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · monomial falling are mutual inverses
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_monomial_falling_are_mutual_inverses(seed: int) -> None:
rng = random.Random(100 + seed)
coeffs = [Fraction(rng.randint(-5, 5)) for _ in range(rng.randint(1, 6))]
fall = monomial_to_falling(coeffs)
back = falling_to_monomial(fall)
assert back == tuple(coeffs)python -m pytest "packages/omnibias-difference/tests/test_umbral.py::test_monomial_falling_are_mutual_inverses[0]" -qRegression example · monomial to falling is stirling second
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_monomial_to_falling_is_stirling_second(n: int) -> None:
# x^n = sum_k S(n, k) (x)_k, so the falling coeffs of x^n are the S(n, .) row.
monomial = [Fraction(0)] * n + [Fraction(1)]
assert monomial_to_falling(monomial) == tuple(Fraction(s) for s in stirling_second_row(n))python -m pytest packages/omnibias-difference/tests/test_umbral.py -k test_monomial_to_falling_is_stirling_second -qRead the implementation
def monomial_to_falling(coeffs: Sequence[Rational]) -> tuple[Fraction, ...]:
r"""Rewrite ``sum_j c_j x^j`` in the falling-factorial basis ``sum_k a_k (x)_k``.
Uses ``x^j = sum_k S(j, k) (x)_k`` (Stirling second kind), so
``a_k = sum_j c_j S(j, k)``.
"""
c = [_frac(v) for v in coeffs]
d = len(c)
return tuple(
sum((c[j] * stirling_second(j, k) for j in range(k, d)), Fraction(0)) for k in range(d)
)Other public import paths
omnibias.difference.monomial_to_fallingomnibias.difference.umbral.monomial_to_falling
newton_forward_coeffs
omnibias.difference.newton_forward_coeffsSource ↗newton_forward_coeffs(values: Sequence[Rational]) -> tuple[Fraction, ...]Leading finite differences Delta^k f(0) for k = 0 .. len-1.
Delta^k f(0) = sum_{j=0}^{k} (-1)^{k-j} C(k, j) f(j) -- the coefficients of
Newton's forward-difference interpolation of the samples f(0), f(1), ....
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuespositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
tuple[Fraction, ...]Executed regression · q newton reduces to classical
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_q_newton_reduces_to_classical() -> None:
poly = (Fraction(2), Fraction(-1), Fraction(3), Fraction(1))
samples = [_eval(poly, Fraction(j)) for j in range(len(poly))]
assert q_newton_forward_coeffs(samples, ONE) == newton_forward_coeffs(samples)python -m pytest "packages/omnibias-qcalculus/tests/test_qumbral.py::test_q_newton_reduces_to_classical" -qRegression example · newton interpolation reproduces polynomial
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_newton_interpolation_reproduces_polynomial(seed: int) -> None:
rng = random.Random(seed)
deg = rng.randint(0, 5)
coeffs = [Fraction(rng.randint(-4, 4)) for _ in range(deg + 1)]
def poly(x: int) -> Fraction:
return _eval(tuple(coeffs), Fraction(x))
samples = [poly(i) for i in range(deg + 1)]
fwd = newton_forward_coeffs(samples)
# reproduces the polynomial exactly at nodes and well outside them
for x in (-3, -1, 0, 1, 2, deg + 5, 10):
assert newton_forward_value(fwd, Fraction(x)) == poly(x)python -m pytest packages/omnibias-difference/tests/test_umbral.py -k test_newton_interpolation_reproduces_polynomial -qRead the implementation
def newton_forward_coeffs(values: Sequence[Rational]) -> tuple[Fraction, ...]:
r"""Leading finite differences ``Delta^k f(0)`` for ``k = 0 .. len-1``.
``Delta^k f(0) = sum_{j=0}^{k} (-1)^{k-j} C(k, j) f(j)`` -- the coefficients of
Newton's forward-difference interpolation of the samples ``f(0), f(1), ...``.
"""
vals = [_frac(v) for v in values]
n = len(vals)
return tuple(
sum((Fraction((-1) ** (k - j) * comb(k, j)) * vals[j] for j in range(k + 1)), Fraction(0))
for k in range(n)
)Other public import paths
omnibias.difference.newton_forward_coeffsomnibias.difference.umbral.newton_forward_coeffs
newton_forward_value
omnibias.difference.newton_forward_valueSource ↗newton_forward_value(coeffs: Sequence[Rational], x: Rational) -> FractionEvaluate Newton's forward interpolation sum_k coeffs[k] C(x, k) at x.
With coeffs = newton_forward_coeffs(f-samples) this reproduces the unique
interpolating polynomial exactly at every integer node (and everywhere, if the
samples came from a polynomial of degree < len(coeffs)).
Parameters
| Name | Type & default | Contract |
|---|---|---|
coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
xpositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
FractionExecuted regression · newton interpolation reproduces polynomial
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_newton_interpolation_reproduces_polynomial(seed: int) -> None:
rng = random.Random(seed)
deg = rng.randint(0, 5)
coeffs = [Fraction(rng.randint(-4, 4)) for _ in range(deg + 1)]
def poly(x: int) -> Fraction:
return _eval(tuple(coeffs), Fraction(x))
samples = [poly(i) for i in range(deg + 1)]
fwd = newton_forward_coeffs(samples)
# reproduces the polynomial exactly at nodes and well outside them
for x in (-3, -1, 0, 1, 2, deg + 5, 10):
assert newton_forward_value(fwd, Fraction(x)) == poly(x)python -m pytest "packages/omnibias-difference/tests/test_umbral.py::test_newton_interpolation_reproduces_polynomial[0]" -qRead the implementation
def newton_forward_value(coeffs: Sequence[Rational], x: Rational) -> Fraction:
r"""Evaluate Newton's forward interpolation ``sum_k coeffs[k] C(x, k)`` at ``x``.
With ``coeffs = newton_forward_coeffs(f-samples)`` this reproduces the unique
interpolating polynomial exactly at every integer node (and everywhere, if the
samples came from a polynomial of degree ``< len(coeffs)``).
"""
return sum(
(_frac(c) * binomial_coefficient(x, k) for k, c in enumerate(coeffs)), Fraction(0)
)Other public import paths
omnibias.difference.newton_forward_valueomnibias.difference.umbral.newton_forward_value
riordan_array
omnibias.difference.riordan_arraySource ↗riordan_array(d_coeffs: Sequence[Rational], h_coeffs: Sequence[Rational], size: int) -> tuple[tuple[Fraction, ...], ...]Lower-triangular Riordan array T[n, k] = [t^n] d(t) h(t)^k (exact, size x size).
A proper Riordan array needs d(0) != 0 and h(0) = 0, h'(0) != 0 (so it is
lower-triangular with a non-zero diagonal). (d, h) = (1/(1-t), t/(1-t)) gives
Pascal's triangle; (1, t/(1-t)) gives the binomial C(n-1, k-1) array.
Parameters
| Name | Type & default | Contract |
|---|---|---|
d_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
h_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
sizepositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[tuple[Fraction, ...], ...]Explicit validation & failure cases
- When
size < 1, raisesValueError(f'size must be >= 1, got {size}'). - When
not d or d[0] == 0, raisesValueError('Riordan array needs d(0) != 0'). - When
len(h) < 2 or h[0] != 0 or h[1] == 0, raisesValueError("Riordan array needs h(0) = 0 and h'(0) != 0").
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · improper array raises
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_improper_array_raises(self) -> None:
with pytest.raises(ValueError):
riordan_array([0, 1], [0, 1], 4) # d(0) == 0python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestRiordan::test_improper_array_raises" -qRegression example · pascal triangle
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_pascal_triangle(self) -> None:
d = series_reciprocal([1, -1], 6) # 1/(1-t)
h = (Fraction(0), *series_reciprocal([1, -1], 5)) # t/(1-t)
matrix = riordan_array(d, h, 6)
for n in range(6):
for k in range(6):
assert matrix[n][k] == (Fraction(comb(n, k)) if k <= n else Fraction(0))python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_pascal_triangle -qRead the implementation
def riordan_array(
d_coeffs: Sequence[Rational], h_coeffs: Sequence[Rational], size: int
) -> tuple[tuple[Fraction, ...], ...]:
r"""Lower-triangular Riordan array ``T[n, k] = [t^n] d(t) h(t)^k`` (exact, ``size x size``).
A proper Riordan array needs ``d(0) != 0`` and ``h(0) = 0``, ``h'(0) != 0`` (so it is
lower-triangular with a non-zero diagonal). ``(d, h) = (1/(1-t), t/(1-t))`` gives
Pascal's triangle; ``(1, t/(1-t))`` gives the binomial ``C(n-1, k-1)`` array.
"""
if size < 1:
raise ValueError(f"size must be >= 1, got {size}")
d = [_frac(v) for v in d_coeffs]
h = [_frac(v) for v in h_coeffs]
if not d or d[0] == 0:
raise ValueError("Riordan array needs d(0) != 0")
if len(h) < 2 or h[0] != 0 or h[1] == 0:
raise ValueError("Riordan array needs h(0) = 0 and h'(0) != 0")
def _mul(a: list[Fraction], b: list[Fraction]) -> list[Fraction]:
out = [Fraction(0)] * size
for i in range(min(len(a), size)):
if a[i] == 0:
continue
for j in range(min(len(b), size - i)):
out[i + j] += a[i] * b[j]
return out
dd = ([*d] + [Fraction(0)] * size)[:size]
hh = ([*h] + [Fraction(0)] * size)[:size]
col = [Fraction(0)] * size
col[0] = Fraction(1) # h^0
matrix = [[Fraction(0)] * size for _ in range(size)]
for k in range(size):
dcol = _mul(dd, col) # d * h^k
for n in range(size):
matrix[n][k] = dcol[n]
col = _mul(col, hh)
return tuple(tuple(row) for row in matrix)Other public import paths
omnibias.difference.riordan_arrayomnibias.difference.umbral.riordan_array
riordan_inverse
omnibias.difference.riordan_inverseSource ↗riordan_inverse(d_coeffs: Sequence[Rational], h_coeffs: Sequence[Rational], order: int) -> tuple[tuple[Fraction, ...], tuple[Fraction, ...]]Riordan group inverse (d, h)^{-1} = (1 / (d o hbar), hbar) (exact).
hbar is the compositional inverse of h; the product of (d, h) with its
inverse is the identity Riordan array (1, t).
Parameters
| Name | Type & default | Contract |
|---|---|---|
d_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
h_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[tuple[Fraction, ...], tuple[Fraction, ...]]Executed regression · group product inverse identity
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_group_product_inverse_identity(self) -> None:
d = [Fraction(1)] * 6 # 1/(1-t)
h = [Fraction(0), *([Fraction(1)] * 5)] # t/(1-t)
d_inv, h_inv = riordan_inverse(d, h, 5)
prod_d, prod_h = riordan_product((d, h), (d_inv, h_inv), 5)
assert prod_d[0] == 1 and all(c == 0 for c in prod_d[1:])
assert prod_h[:2] == (Fraction(0), Fraction(1)) and all(c == 0 for c in prod_h[2:])python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestRiordan::test_group_product_inverse_identity" -qRead the implementation
def riordan_inverse(
d_coeffs: Sequence[Rational], h_coeffs: Sequence[Rational], order: int
) -> tuple[tuple[Fraction, ...], tuple[Fraction, ...]]:
r"""Riordan group inverse ``(d, h)^{-1} = (1 / (d o hbar), hbar)`` (exact).
``hbar`` is the compositional inverse of ``h``; the product of ``(d, h)`` with its
inverse is the identity Riordan array ``(1, t)``.
"""
hbar = compositional_inverse(h_coeffs, order)
d_on_hbar = compose_series(d_coeffs, hbar, order)
d_inv = series_reciprocal(d_on_hbar, order)
return d_inv, hbarOther public import paths
omnibias.difference.riordan_inverseomnibias.difference.umbral.riordan_inverse
riordan_product
omnibias.difference.riordan_productSource ↗riordan_product(left: tuple[Sequence[Rational], Sequence[Rational]], right: tuple[Sequence[Rational], Sequence[Rational]], order: int) -> tuple[tuple[Fraction, ...], tuple[Fraction, ...]]Riordan group product (d1, h1) * (d2, h2) = (d1 * (d2 o h1), h2 o h1) (exact).
The Fundamental Theorem of Riordan Arrays as a group law on the defining series
(matrix multiplication of the two arrays), truncated to order + 1 terms.
Parameters
| Name | Type & default | Contract |
|---|---|---|
leftpositional-or-keyword | tuple[Sequence[Rational], Sequence[Rational]]Required | See the operation contract and implementation below. |
rightpositional-or-keyword | tuple[Sequence[Rational], Sequence[Rational]]Required | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[tuple[Fraction, ...], tuple[Fraction, ...]]Executed regression · group product inverse identity
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_group_product_inverse_identity(self) -> None:
d = [Fraction(1)] * 6 # 1/(1-t)
h = [Fraction(0), *([Fraction(1)] * 5)] # t/(1-t)
d_inv, h_inv = riordan_inverse(d, h, 5)
prod_d, prod_h = riordan_product((d, h), (d_inv, h_inv), 5)
assert prod_d[0] == 1 and all(c == 0 for c in prod_d[1:])
assert prod_h[:2] == (Fraction(0), Fraction(1)) and all(c == 0 for c in prod_h[2:])python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestRiordan::test_group_product_inverse_identity" -qRead the implementation
def riordan_product(
left: tuple[Sequence[Rational], Sequence[Rational]],
right: tuple[Sequence[Rational], Sequence[Rational]],
order: int,
) -> tuple[tuple[Fraction, ...], tuple[Fraction, ...]]:
r"""Riordan group product ``(d1, h1) * (d2, h2) = (d1 * (d2 o h1), h2 o h1)`` (exact).
The Fundamental Theorem of Riordan Arrays as a group law on the defining series
(matrix multiplication of the two arrays), truncated to ``order + 1`` terms.
"""
d1, h1 = ([_frac(v) for v in left[0]], [_frac(v) for v in left[1]])
d2, h2 = ([_frac(v) for v in right[0]], [_frac(v) for v in right[1]])
d2_on_h1 = compose_series(d2, h1, order)
prod = [Fraction(0)] * (order + 1)
for i in range(min(len(d1), order + 1)):
if d1[i] == 0:
continue
for j in range(order + 1 - i):
prod[i + j] += d1[i] * d2_on_h1[j]
d_out = tuple(prod)
h_out = compose_series(h2, h1, order)
return d_out, h_outOther public import paths
omnibias.difference.riordan_productomnibias.difference.umbral.riordan_product
series_reciprocal
omnibias.difference.series_reciprocalSource ↗series_reciprocal(series: Sequence[Rational], order: int) -> tuple[Fraction, ...]Coefficients [t^0..t^order] of 1 / series with series(0) != 0 (exact).
Parameters
| Name | Type & default | Contract |
|---|---|---|
seriespositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[Fraction, ...]Explicit validation & failure cases
- When
order < 0, raisesValueError(f'order must be >= 0, got {order}'). - When
not a or a[0] == 0, raisesValueError('series must have a non-zero constant term').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · reciprocal zero constant raises
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_reciprocal_zero_constant_raises(self) -> None:
with pytest.raises(ValueError):
series_reciprocal([0, 1], 3)python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestSeriesOps::test_reciprocal_zero_constant_raises" -qRegression example · series reciprocal
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_series_reciprocal(self) -> None:
# 1/(1 - t) = 1 + t + t^2 + ...
assert series_reciprocal([1, -1], 5) == tuple(Fraction(1) for _ in range(6))python -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_series_reciprocal -qRead the implementation
def series_reciprocal(series: Sequence[Rational], order: int) -> tuple[Fraction, ...]:
r"""Coefficients ``[t^0..t^order]`` of ``1 / series`` with ``series(0) != 0`` (exact)."""
if order < 0:
raise ValueError(f"order must be >= 0, got {order}")
a = [_frac(v) for v in series]
if not a or a[0] == 0:
raise ValueError("series must have a non-zero constant term")
b = [Fraction(0)] * (order + 1)
b[0] = Fraction(1) / a[0]
for k in range(1, order + 1):
acc = Fraction(0)
for j in range(1, min(k, len(a) - 1) + 1):
acc += a[j] * b[k - j]
b[k] = -acc / a[0]
return tuple(b)Other public import paths
omnibias.difference.series_reciprocalomnibias.difference.umbral.series_reciprocal
sheffer_classify
omnibias.difference.sheffer_classifySource ↗sheffer_classify(g_coeffs: Sequence[Rational], f_coeffs: Sequence[Rational]) -> ShefferClassClassify the Sheffer sequence for the pair (g, f) (exact).
A Sheffer sequence is defined by an invertible series g (g(0) != 0) and a
delta series f (f(0) = 0, f'(0) != 0). This classifies it as:
- **appell** --
f(t) = t(the sequence satisfiesp_n'(x) = n p_{n-1}(x); Bernoulli / Euler / Hermite polynomials), - **associated** (binomial type) --
g(t) = 1(p_n(x+y) = sum_k C(n,k) p_k(x) p_{n-k}(y); falling factorials, Abel / Touchard polynomials), - **sheffer** -- the general case (e.g. Laguerre, actuarial polynomials).
Raises if (g, f) is not a valid Sheffer pair.
Parameters
| Name | Type & default | Contract |
|---|---|---|
g_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
f_coeffspositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
ShefferClassExplicit validation & failure cases
- When
not g or g[0] == 0, raisesValueError('g must be invertible: g(0) != 0'). - When
len(f) < 2 or f[0] != 0 or f[1] == 0, raisesValueError("f must be a delta series: f(0) = 0 and f'(0) != 0").
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · invalid g raises
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_invalid_g_raises(self) -> None:
with pytest.raises(ValueError):
sheffer_classify([0, 1], [0, 1])python -m pytest "packages/omnibias-difference/tests/test_singularity_pade_sheffer.py::TestSheffer::test_invalid_g_raises" -qRegression example · appell
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_appell(self) -> None:
cls = sheffer_classify([1, 2, 3], [0, 1])
assert cls.kind == "appell" and cls.is_appellpython -m pytest packages/omnibias-difference/tests/test_singularity_pade_sheffer.py -k test_appell -qRead the implementation
def sheffer_classify(
g_coeffs: Sequence[Rational], f_coeffs: Sequence[Rational]
) -> ShefferClass:
r"""Classify the Sheffer sequence for the pair ``(g, f)`` (exact).
A Sheffer sequence is defined by an invertible series ``g`` (``g(0) != 0``) and a
delta series ``f`` (``f(0) = 0``, ``f'(0) != 0``). This classifies it as:
* **appell** -- ``f(t) = t`` (the sequence satisfies ``p_n'(x) = n p_{n-1}(x)``;
Bernoulli / Euler / Hermite polynomials),
* **associated** (binomial type) -- ``g(t) = 1`` (``p_n(x+y) = sum_k C(n,k) p_k(x)
p_{n-k}(y)``; falling factorials, Abel / Touchard polynomials),
* **sheffer** -- the general case (e.g. Laguerre, actuarial polynomials).
Raises if ``(g, f)`` is not a valid Sheffer pair.
"""
g = [_frac(v) for v in g_coeffs]
f = [_frac(v) for v in f_coeffs]
if not g or g[0] == 0:
raise ValueError("g must be invertible: g(0) != 0")
if len(f) < 2 or f[0] != 0 or f[1] == 0:
raise ValueError("f must be a delta series: f(0) = 0 and f'(0) != 0")
is_appell = _is_identity_delta(f)
is_associated = _is_unit_constant(g)
if is_appell:
kind = "appell"
elif is_associated:
kind = "associated"
else:
kind = "sheffer"
return ShefferClass(kind=kind, is_appell=is_appell, is_associated=is_associated)Other public import paths
omnibias.difference.sheffer_classifyomnibias.difference.umbral.sheffer_classify