diff --git a/.github/workflows/c8-window-coefficient-d5.yml b/.github/workflows/c8-window-coefficient-d5.yml new file mode 100644 index 000000000..8abbd67d3 --- /dev/null +++ b/.github/workflows/c8-window-coefficient-d5.yml @@ -0,0 +1,79 @@ +name: C8 window coefficient d5 + +'on': + pull_request: + paths: + - 'frontiers/c8_window_coefficient_d5_20261001/**' + - '.github/workflows/c8-window-coefficient-d5.yml' + - 'imports/lifetime_parent_20260925/UNIFORM_MATRIX_CAP_AND_LIFETIME.md' + - 'coefficients/side24_v1/PROOF.md' + workflow_dispatch: + +permissions: + contents: read + +jobs: + certify-and-reject-mutants: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: '3.11.16' + - name: Verify sources and pins, replay both modes, reject mutants + env: + PYTHONDONTWRITEBYTECODE: '1' + run: | + set -euo pipefail + python -B -S - <<'PY' + import concurrent.futures, hashlib, json, pathlib, subprocess, sys + root = pathlib.Path('frontiers/c8_window_coefficient_d5_20261001').resolve() + manifest_doc = json.loads((root / 'SOURCE_FILES.json').read_text()) + manifest = manifest_doc['files'] + present = sorted(p.name for p in root.iterdir()) + expected_names = sorted([e['path'] for e in manifest] + ['SOURCE_FILES.json']) + if present != expected_names: + raise ValueError('packet tree differs from manifest: ' + repr(present)) + for entry in manifest: + path = root / entry['path'] + if pathlib.PurePosixPath(entry['path']).name != entry['path'] or path.is_symlink(): + raise ValueError('flat regular source required: ' + entry['path']) + data = path.read_bytes() + if len(data) != entry['bytes'] or hashlib.sha256(data).hexdigest() != entry['sha256']: + raise ValueError('source identity mismatch: ' + entry['path']) + # main-resident pins: the consumed sources must be the cited bytes + for pin in manifest_doc['pins_on_main']: + if not pin.get('workflow_checked'): + continue + p = pathlib.Path(pin['path']) + if p.is_symlink() or not p.is_file(): + raise ValueError('pinned source missing: ' + pin['path']) + data = p.read_bytes() + blob = hashlib.sha1(b'blob %d\0' % len(data) + data).hexdigest() + if blob != pin['git_blob']: + raise ValueError('pinned source drifted: ' + pin['path'] + ' ' + blob) + script = str(root / 'window_coefficient_d5.py') + expected = (root / 'RESULTS.json').read_bytes() + mutants = ['image-shells', 'd4-floor', 'sandwich-swap', 'window-scale', 'trace-slope', 'moment-recurrence', 'remainder-dropped', 'parts-sign', 'schur-sign', 'tau-cross', 'sphere', 'tilt-gamma', 'layer-dropped'] + def mutant_rc(args): + flags, m = args + return m, flags, subprocess.run([sys.executable, *flags, script, '--mutant', m], + capture_output=True, timeout=1500).returncode + for flags in (['-B', '-S'], ['-B', '-O', '-S']): + out = subprocess.run([sys.executable, *flags, script], + check=True, capture_output=True, timeout=1500).stdout + if out != expected: + raise RuntimeError('output differs from RESULTS.json under ' + ' '.join(flags)) + doc = json.loads(out) + if not (doc['passed'] and len(doc['checks']) == 18 and all(doc['checks'].values())): + raise RuntimeError('certification did not pass under ' + ' '.join(flags)) + with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: + for m, fl, rc in pool.map(mutant_rc, [(flags, m) for m in mutants]): + if rc != 1: + raise RuntimeError('mutant ' + m + ' not rejected under ' + ' '.join(fl)) + print(json.dumps({'scientific_effect': 'NONE', 'mathematical_acceptance': False, 'certified_enclosures': True, 'C8': 'OPEN'})) + PY + git diff --exit-code diff --git a/frontiers/c8_window_coefficient_d5_20261001/NOTE.md b/frontiers/c8_window_coefficient_d5_20261001/NOTE.md new file mode 100644 index 000000000..8399c6baf --- /dev/null +++ b/frontiers/c8_window_coefficient_d5_20261001/NOTE.md @@ -0,0 +1,354 @@ +# The compact-window coefficient `c_{B,K}` in `d = 5`: reference value and transfer to the torus for every `L ≥ 10` and every frame + +**Object** `CL-C8-WINDOW-COEFFICIENT-D5-20261001-v1` · **scientific effect NONE** · declarative record, `executed: false` · +base `main 3e0a91b` · claim: Math-#209 comment 5923710923. + +Companions (not on `main`): +- Math-#209: the `d = 4` record, whose total-trace reduction and Taylor quadrature this record extends to `m = 4`. +- Math-#205: Lemma S. +- Math-#197: the interval toolkit and the `d = 3` reference closed form. +- Math-#200: `c_{5,ref}` and the `d = 5` image-bound constant. +- Math-#202: the closed form of `D_4`. + +Catalog entry C8 stays OPEN; no register, GRAPH, STATUS or catalog surface is touched. Same GitHub account as every lane: zero +organizational-independence credit. Claude reads of this record count for nothing. The author will not merge. + +## 0. Statement + +Let `f` be the unit-variance stationary Gaussian field on `R⁵/(LZ⁵)` with the parent kernel `K_L` of [LP] §1. Let `B = [b_−, b_+]` +be a birth window and `K = [k_−, k_+]` a gap window, compact and of positive length with a positive gap floor: +`−∞ < b_− < b_+ < ∞` and `0 < k_− < k_+ < ∞`. This is [LP] Theorem B's hypothesis (lines 16 and 37 of the pinned [LP]). Let +`c^(5)_{B,K}` be the leading coefficient of [LP] Theorem B for the pairs with birth in `B` and scaled gap in `K` ([LP] (11.3), §15; +both stated for every `d`). Windows outside that hypothesis are treated in §7. + +**Proposition (d = 5 window coefficient).** +- **Reference kernel.** `c^(5)_{B,K} = c_{5,ref} F^(5)_B G_K`, with the birth factor `F^(5)_B` given by the one-dimensional integral + (2.4) below. +- **Torus.** For every `L ≥ 10` and every frame, `c^(5)_{B,K}` lies in the interval computed by `window_coefficient_d5.py` from the + entry box of radius `E^(5)_10 ≈ 8.868·10⁻¹⁰`. + +On the C8 band `B = [0, 1]`, `K = [1/2, 2]`: + +``` +c^(5)_{B,K}(reference) = 0.0000389351131406652779000208375489243154126558…, +c^(5)_{B,K}(torus, every L ≥ 10, every frame) ∈ [0.0000389350650058931493, 0.0000389351612754962131] (relative half-width 1.24e-6), +c^(5)_{B,K}(torus, L = 24) = the reference digits to about 50 places (quadrature-limited). +``` + +The same holds on every window of §5, with relative half-width at most `1.4·10⁻⁶` at `L ≥ 10`. The full window returns +`c_{5,ref}`: Math-#200's value, from Math-#202's closed form of `D_4`. + +## 1. The object and the reference law + +The setup is Math-#209 §1 with `|S⁴| = 8π²/3` and frame `(u, w_1, …, w_4)`: +- `G = ∇f ∈ R⁵`; +- `V = (f_uu, f_uw1, …, f_uw4)`; +- `A` is the `4×4` transverse Hessian; +- `t = f_uuu`. + +``` +c^(5)_{B,K} = 144 ∫_{S⁴} p_G(0) p_V(0) I_B(u) J_K(u) dσ(u), I_B(u) = E[1{f ∈ B} det(A)² 1{A ≺ 0} | V = 0]. (1.1) +``` + +For the reference kernel, `Cov V = diag(3, 1, 1, 1, 1)`, `Cov G = I` and `τ² = 6`. For the 11-vector `(f, A_11, A_12, …, A_44) | V = 0`: + +``` +C'_ref: Var f = 2/3, Cov(f, A_ii) = −2/3, Var A_ii = 8/3, Cov(A_ii, A_jj) = 2/3, Var A_ij = 1 (i ≠ j), all else 0; +A | f = b, V = 0 ~ −b I + Q, Q the 4×4 GOE (diagonal variance 2, off-diagonal 1). (1.2) +``` + +This is checked by rule `REFERENCE_EXACT`. + +## 2. The reference birth integral + +Math-#209 (2.1) in general `m` puts the window on the total trace `T = −Σ μ_i`, with factor +`√(3/(m+3)) e^{T²/(4(m+3))} [Φ(√((m+3)/2)(b_± − T/(m+3)))]`. For `m = 4`, use the ordered sector `μ_4 = −a`, `μ_3 = −a − p_1`, +`μ_2 = −a − p_1 − p_2`, `μ_1 = −a − p_1 − p_2 − p_3` and the coordinates + +``` +T = 4a + 3p_1 + 2p_2 + p_3, w = 3p_1 + 2p_2 + p_3, s = 2p_2 + p_3, q = p_3 (Jacobian 1/24, region T > w > s > q > 0). +``` + +The `4!` sectors cancel the Jacobian, and the exponent decouples exactly (checked symbolically): +`|μ|²/4 − T²/28 = 3T²/112 + w²/48 + s²/24 + q²/8`. With `Z_4 = 1536π`: + +``` +I^ref_B = (√(3/7)/(1536π)) ∫_{T>w>s>q>0} P e^{−3T²/112 − w²/48 − s²/24 − q²/8} W_B(T) dq ds dw dT, +P = Π μ_i² · Π_{i (1-eps)^(19/2)/(1+eps)^(11/2) I^ref_{B/sqrt(1-eps)} <= I'_B <= (1+eps)^(19/2)/(1-eps)^(11/2) I^ref_{B/sqrt(1+eps)}", + "epsilon": "eps = ||C' - C'_ref||_F / lambda0, lambda0 = 1/4 <= lambda_min(C'_ref) = (8 - 2 sqrt13)/3", + "image bound": "E^(5)_L = 60500 (76 L^6 + 15) exp(-L^2/2)" + } +} diff --git a/frontiers/c8_window_coefficient_d5_20261001/SOURCE_FILES.json b/frontiers/c8_window_coefficient_d5_20261001/SOURCE_FILES.json new file mode 100644 index 000000000..ee04df5ac --- /dev/null +++ b/frontiers/c8_window_coefficient_d5_20261001/SOURCE_FILES.json @@ -0,0 +1,123 @@ +{ + "schema": 1, + "object": "CL-C8-WINDOW-COEFFICIENT-D5-20261001-v1", + "scientific_effect": "NONE", + "certified": true, + "review_status": "AUTHOR_SIDE_CERTIFIED_ENCLOSURE_NONAUTHOR_READS_OPEN", + "disposition": "CERTIFIED_REFERENCE_AND_TORUS_ENCLOSURES_OF_THE_D5_WINDOW_COEFFICIENT_NO_REGISTER_CHANGE_C8_OPEN", + "declarative": true, + "executed": false, + "base": "3e0a91b69892b9717564c592e7a966492a81566a", + "claim": "https://github.com/d6g8k5htny-coder/Math-/pull/209#issuecomment-5923710923", + "pins_on_main": [ + { + "label": "LP", + "path": "imports/lifetime_parent_20260925/UNIFORM_MATRIX_CAP_AND_LIFETIME.md", + "git_blob": "dfed3b8d318a3ab1950957f393307733a4bef3f2", + "role": "(11.3) the window coefficient in every d; section 15 factorization p_(f,V)(b,0) p_G(0) phi_tau(12k), z_0 = 36 k^2 E[det(A)^2 1{A<0} | f=b, V=0]", + "workflow_checked": true + }, + { + "label": "S24", + "path": "coefficients/side24_v1/PROOF.md", + "git_blob": "44b66f04f89fcd87383b3603fa69f1feb64cdddd", + "role": "sections 1-4: the reference law A = Q + sqrt(2/3) Z I, the image-bound pattern (76|x|^6 contraction bound, normalization), the covariance-sandwich scaling argument", + "workflow_checked": true + } + ], + "companion_not_on_main": [ + { + "pr": "https://github.com/d6g8k5htny-coder/Math-/pull/197", + "commit": "3dcf612", + "path": "frontiers/c8_window_coefficient_planar_20260930/window_coefficient.py", + "git_blob": "43b4f51ba0e29c38468c40b4648f683848a3b218", + "role": "interval class, erf, arctan, Owen's T, Owen primitives G_0..G_4, incomplete gamma, gap factor G_K, library_exact (reused verbatim through Math-#205's copy; C41 PASS_TECHNICAL, review 5373681556)" + }, + { + "pr": "https://github.com/d6g8k5htny-coder/Math-/pull/205", + "commit": "01d09e9", + "path": "frontiers/c8_window_coefficient_d3_torus_20260930/window_coefficient_d3.py", + "git_blob": "ba24b3802eb0baf5ade65d49fd47ca862972f8bd", + "role": "the toolkit section and I3_ref (rule CROSSCHECK_M2_M3, m = 2) reused verbatim; Lemma S (its NOTE section 2) applied with n = 11, degree 8" + }, + { + "pr": "https://github.com/d6g8k5htny-coder/Math-/pull/199", + "commit": "617236d", + "path": "coefficients/side24_d4_20260930/cone_moment_d4.py", + "git_blob": "4787d6bf5a3bc469ae62075dde24e913b786e44a", + "role": "exact polynomial algebra (padd, pmul, pscale, pconst, pvar) reused verbatim" + }, + { + "pr": "https://github.com/d6g8k5htny-coder/Math-/pull/209", + "commit": "ea3a415", + "path": "frontiers/c8_window_coefficient_d4_20261001/window_coefficient_d4.py", + "git_blob": "f77f7d2d158f9513f23f1b55fe0f839eb112d387", + "role": "the total-trace reduction, the Taylor quadrature with the Phi factor, the d = 4 band factor F^(4)_[0,1] (rule CROSSCHECK_M2_M3, m = 3), extended here to m = 4" + }, + { + "pr": "https://github.com/d6g8k5htny-coder/Math-/pull/200", + "commit": "aa1d51e", + "path": "coefficients/side24_d5_20260930/RESULTS.json", + "git_blob": "b67c00f45d053b51c2ec15ce8d53c8a34e49a006", + "role": "c_{5,ref} digits quoted in the script (rule C5_CONSISTENT); its E_5 = 60500 (76 L^6 + 15) e^{-L^2/2} constant" + }, + { + "pr": "https://github.com/d6g8k5htny-coder/Math-/pull/202", + "commit": "4512309", + "path": "coefficients/side24_d5_closed_form_20260930/RESULTS.json", + "git_blob": "52ce9b5726b8ea92c429ea1193b1812869afe701", + "role": "the closed form of D_4 (rule D4_EXACT) and Z_4 = 1536 pi" + } + ], + "files": [ + { + "path": "NOTE.md", + "bytes": 22577, + "sha256": "063854ab42a8216ce40083976bad9fa2f5ca2c1290d0b897a754b52c5f7e6598", + "git_blob": "8399c6baf6d6dc9e2eae3a50d53abdf4d60d0651" + }, + { + "path": "RESULTS.json", + "bytes": 21231, + "sha256": "53cf8ecd2f606967fd716d6c13a6b86357ed0de26a0bf7ffb6af880ff4b6a3ce", + "git_blob": "d4719bdd9686f1ddd12b92f3ca866343ddadbfe1" + }, + { + "path": "window_coefficient_d5.py", + "bytes": 62446, + "sha256": "9f34ad2c20cb38f6bd21714583676d861040b83f9283ad170d7b0a4c9460145b", + "git_blob": "da68e6ec22310c35904a70e203cc32cb9e5b19fc" + } + ], + "revisions": [ + { + "version": "v1.1", + "finding": "Codex code review at 7ab39d2: threads 4151593189 (cancelled layers), 4151593177 (gap window), 4151593183 (module documentation)", + "review": "https://github.com/d6g8k5htny-coder/Math-/pull/213#discussion_r4151593189", + "change": "window_coefficient_d5.py: INNER_LAYERS also requires the set of generated kinds that cancel to equal exactly the two Owen-type kinds, the constant and E_{3/16}; new mutant layer-dropped (fails INNER_LAYERS alone); module docstring rewritten for d = 5. NOTE.md: section 0 states [LP] Theorem B hypothesis 0 < k_- <= k_+ < infinity; section 7 classes windows touching k = 0 or infinity and unbounded B as coefficient integrals only; sections 2, 6, 9, 10. Workflow: mutant list includes layer-dropped", + "unchanged": [ + "RESULTS.json" + ] + }, + { + "version": "v1.2", + "finding": "C43-205-H-01 (positive lengths; found on Math-#205)", + "review": "https://github.com/d6g8k5htny-coder/Math-/pull/205#pullrequestreview-5377957341", + "change": "NOTE.md: section 0 states [LP] Theorem B hypothesis as compact windows of positive length, -infinity < b_- < b_+ < infinity and 0 < k_- < k_+ < infinity (pinned [LP] lines 16 and 37); section 7 classes singleton windows outside the hypothesis. window_coefficient_d5.py: module docstring states the same hypothesis (no code change)", + "unchanged": [ + "RESULTS.json" + ] + }, + { + "version": "v1.3", + "finding": "xAI band-share wording, Math-#222 comment 5932429158", + "review": "https://github.com/d6g8k5htny-coder/Math-/pull/222#issuecomment-5932429158", + "change": "NOTE.md section 5: the column F^(d)_[0,1] relabelled as the height-window share (the same for every K); the C8 band's share of c_{d,ref}, F^(d)_[0,1] G_[1/2,2], added; section 10", + "unchanged": [ + "window_coefficient_d5.py", + "RESULTS.json", + ".github/workflows/c8-window-coefficient-d5.yml" + ] + } + ] +} diff --git a/frontiers/c8_window_coefficient_d5_20261001/window_coefficient_d5.py b/frontiers/c8_window_coefficient_d5_20261001/window_coefficient_d5.py new file mode 100644 index 000000000..da68e6ec2 --- /dev/null +++ b/frontiers/c8_window_coefficient_d5_20261001/window_coefficient_d5.py @@ -0,0 +1,1468 @@ +"""The compact-window coefficient c_{B,K} of [LP] Theorem B in d = 5: reference value and transfer to the torus for every +L >= 10 and every frame. + +Standard library only. Run from anywhere: python -B -S window_coefficient_d5.py [--mutant NAME] (about eighty seconds) +Every printed interval [lo, hi] is a rigorous enclosure: interval arithmetic over `decimal` (60 digits, directed rounding; exp +and sqrt widened by two units in the last place and checked against exact rational brackets by rule LIBRARY_EXACT), pi by +Machin, fractional powers by exact integer roots, erf and the lower incomplete gamma function by positive series with geometric +tails (and, for |x| >= 12, the enclosure 0 < erfc(x) < e^{-x^2}/(x sqrt(pi))), arctan and Owen's T by alternating series bracketed +by consecutive partial sums (the Math-#197 toolkit, unchanged), and one one-dimensional integral by an order-48 Taylor expansion +at each cell centre with a Cauchy remainder (Math-#199 section 3, as in Math-#209). + +Object ([LP] = imports/lifetime_parent_20260925/UNIFORM_MATRIX_CAP_AND_LIFETIME.md, (11.3) with the section 15 factorization, +both stated for every d, for compact windows B = [b_-, b_+] and K = [k_-, k_+] of positive length, b_- < b_+ and +0 < k_- < k_+ < infinity; frame (u, w1, ..., w4), G = grad f, V = (f_uu, f_uw1, ..., f_uw4), A the 4 x 4 transverse Hessian, +t = f_uuu): + + c^(5)_{B,K} = 144 int_{S^4} p_G(0) p_V(0) I_B(u) J_K(u) dsigma(u), I_B(u) = E[1{f in B} det(A)^2 1{A < 0} | V = 0], + J_K(u) = int_K k^(4/3) phi_tau(12 k) dk, tau^2 = Var(t | G = 0). + +Reference kernel. (f, A) | V = 0 is f ~ N(0, 2/3) and A = Q - f I with Q the 4 x 4 GOE (density ~ exp(-tr Q^2/4)) independent +of f. On the ordered eigenvalue sector of A, with total trace -T and nested differences (w, s, q) (Jacobian 1/24), the exponent +is 3T^2/112 + w^2/48 + s^2/24 + q^2/8, the birth window enters only through +W_B(T) = Phi(sqrt(7/2) (b_+ - T/7)) - Phi(sqrt(7/2) (b_- - T/7)), and only odd powers of q occur, so the q- and s-integrals are +exact; in the w-integral the Owen-type terms int_0^T e^{-w^2/48} erf(sqrt(g) w) dw (g = 1/24, 1/6) cancel identically, so + + I^ref_B = (sqrt(3/7)/(1536 pi)) int_0^inf exp(-3T^2/112) F_4(T) W_B(T) dT, F_4 elementary (polynomials, exp(-T^2/16), + erf(T/4), exp(-T^2/48) erf(T/sqrt24), exp(-T^2/48) erf(T/sqrt6), exp(-3T^2/16)), + +and B = R returns Math-#202's D_4. The same code at m = 2 returns 29/6 - sqrt6 and Math-#197's d = 3 window values, and at m = 3 +Math-#201's D_3 and Math-#209's d = 4 band factor. + +Torus. If (1-eps) C'_ref <= C' <= (1+eps) C'_ref for the covariance of the 11-vector (f, A) | V = 0, the density comparison and +the degree-8 homogeneity of det(A)^2 give (Lemma S of Math-#205 with n = 11, degree 8) + + (1-eps)^(19/2)/(1+eps)^(11/2) I^ref_{B/sqrt(1-eps)} <= I'_B <= (1+eps)^(19/2)/(1-eps)^(11/2) I^ref_{B/sqrt(1+eps)}. + +lambda_min(C'_ref) = (8 - 2 sqrt13)/3 = 0.2630 (below the d = 4 floor 3/10): eps = ||C' - C'_ref||_F / (1/4) over the entry box of +the d = 5 image bound E^(5)_L = 60500 (76 L^6 + 15) exp(-L^2/2); p_G(0), p_V(0) and tau^2 over the same box. One enclosure covers +every frame and every L >= 10. Windows touching k = 0 or infinity, unbounded B, and singleton windows (b_- = b_+ or k_- = k_+, +where the integral is zero) are evaluated as coefficient integrals only. +Scientific effect NONE. +""" +import argparse +import json +import math +import sys +import time +from decimal import Decimal, Context, ROUND_FLOOR, ROUND_CEILING, ROUND_HALF_EVEN, setcontext +from fractions import Fraction as Fr + +MUTANTS = ("image-shells", "d4-floor", "sandwich-swap", "window-scale", "trace-slope", "moment-recurrence", "remainder-dropped", + "parts-sign", "schur-sign", "tau-cross", "sphere", "tilt-gamma", "layer-dropped") +MUT = None + +PREC = 60 +CF = Context(prec=PREC, rounding=ROUND_FLOOR, Emin=-9999999, Emax=9999999) +CC = Context(prec=PREC, rounding=ROUND_CEILING, Emin=-9999999, Emax=9999999) +CE = Context(prec=PREC, rounding=ROUND_HALF_EVEN, Emin=-9999999, Emax=9999999) +# Every arithmetic step below names one of the three contexts; operator syntax on Decimals would round to the thread's +# current context, which is widened as a safety net (rule LIBRARY_EXACT checks exp, sqrt and the negation). +setcontext(Context(prec=2 * PREC + 20, rounding=ROUND_HALF_EVEN, Emin=-9999999, Emax=9999999)) +ZERO, ONE, HALF = Decimal(0), Decimal(1), Decimal("0.5") +INF = math.inf +ROOT_DIGITS = 70 +K_ORDER, RHO, CELL, T_CUT = 48, Fr(6), Fr(1, 2), Fr(80) # Taylor order, Cauchy radius, cell width, cut (Math-#199 section 3) +C5_REF_200 = "0.0132193193800849680760334875146413965210528" # Math-#200 RESULTS.json (c_{5,ref}, certified there) +F4B_209 = "0.1539033000676815392013091707812771979851002980" # Math-#209 PINNED (F^(4)_[0,1], the d = 4 band birth factor) +PINNED = {"c_5_ref": "0.0132193193800849680760334875146413965210528901", "D_4": "14.2187634589773576013064656778740783173406023160", "F5|[0,1]": "0.04371743008362033053724245662643528133240074085", "c5|[0,1]x[1/2,2] ref": "0.0000389351131406652779000208375489243154126558", "pi": "3.14159265358979323846264338327950288419716939937510"} + + +# ---------------- interval arithmetic and special functions (Math-#197 toolkit, unchanged) +def ulp(x): + if x == 0: + return Decimal(1).scaleb(-PREC - 30) + return Decimal(1).scaleb(x.adjusted() - PREC + 1) + + +class Iv: + """Closed interval [lo, hi] of Decimals; every operation encloses the exact result.""" + __slots__ = ("lo", "hi") + + def __init__(self, lo, hi=None): + if hi is None: + hi = lo + if lo > hi: + raise ValueError("empty interval") + self.lo, self.hi = lo, hi + + @staticmethod + def frac(q): + q = Fr(q) + n, d = Decimal(q.numerator), Decimal(q.denominator) + return Iv(CF.divide(n, d), CC.divide(n, d)) + + @staticmethod + def of(x): + return x if isinstance(x, Iv) else Iv.frac(x) + + def __add__(a, b): + b = Iv.of(b) + return Iv(CF.add(a.lo, b.lo), CC.add(a.hi, b.hi)) + __radd__ = __add__ + + def __neg__(a): + return Iv(a.hi.copy_negate(), a.lo.copy_negate()) # exact: unary minus would round to the default context + + def __sub__(a, b): + b = Iv.of(b) + return Iv(CF.subtract(a.lo, b.hi), CC.subtract(a.hi, b.lo)) + + def __rsub__(a, b): + return Iv.of(b) - a + + def __mul__(a, b): + b = Iv.of(b) + c = [(x, y) for x in (a.lo, a.hi) for y in (b.lo, b.hi)] + return Iv(min(CF.multiply(x, y) for x, y in c), max(CC.multiply(x, y) for x, y in c)) + __rmul__ = __mul__ + + def __truediv__(a, b): + b = Iv.of(b) + if b.lo <= 0 <= b.hi: + raise ZeroDivisionError("interval division by an interval containing 0") + c = [(x, y) for x in (a.lo, a.hi) for y in (b.lo, b.hi)] + return Iv(min(CF.divide(x, y) for x, y in c), max(CC.divide(x, y) for x, y in c)) + + def __rtruediv__(a, b): + return Iv.of(b) / a + + def sq(a): + if a.lo <= 0 <= a.hi: + return Iv(ZERO, max(CC.multiply(a.lo, a.lo), CC.multiply(a.hi, a.hi))) + return a * a + + def exp(a): + lo, hi = CE.exp(a.lo), CE.exp(a.hi) + return Iv(max(ZERO, CF.subtract(lo, CC.multiply(Decimal(2), ulp(lo)))), CC.add(hi, CC.multiply(Decimal(2), ulp(hi)))) + + def sqrt(a): + if a.lo < 0: + raise ValueError("sqrt of an interval with negative part") + lo, hi = CE.sqrt(a.lo), CE.sqrt(a.hi) + return Iv(max(ZERO, CF.subtract(lo, CC.multiply(Decimal(2), ulp(lo)))), CC.add(hi, CC.multiply(Decimal(2), ulp(hi)))) + + def width(a): + return CC.subtract(a.hi, a.lo) + + def contains(a, x): + x = Iv.of(x) + return a.lo <= x.lo and x.hi <= a.hi + + def intersects(a, b): + return a.lo <= b.hi and b.lo <= a.hi + + def mag(a): + return max(abs(a.lo), abs(a.hi)) + + def mid_float(a): + return float((a.lo + a.hi) / 2) + + def pair(a): + return [str(a.lo), str(a.hi)] + + +def hull(a, b): + return Iv(min(a.lo, b.lo), max(a.hi, b.hi)) + + +def inroot(N, n): + """floor(N ** (1/n)) for integers N >= 0, n >= 1: integer Newton iteration started above the root.""" + if N < 2: + return N + x = 1 << ((N.bit_length() + n - 1) // n) + while True: + y = ((n - 1) * x + N // pow(x, n - 1)) // n + if y >= x: + break + x = y + if not (pow(x, n) <= N < pow(x + 1, n)): + raise ValueError("integer root failed") + return x + + +def root_frac(q, n): + """Rigorous bracket of q ** (1/n) for a positive rational q, width 10^-ROOT_DIGITS.""" + q = Fr(q) + if q <= 0: + raise ValueError("root of a nonpositive number") + p, d = q.numerator, q.denominator + scale = 10 ** ROOT_DIGITS + r = inroot(p * d ** (n - 1) * scale ** n, n) + den = d * scale + return Iv(Iv.frac(Fr(r, den)).lo, Iv.frac(Fr(r + 1, den)).hi) + + +def root_iv(x, n): + """x ** (1/n) for an interval x > 0 (monotone: endpoint brackets).""" + return Iv(root_frac(Fr(x.lo), n).lo, root_frac(Fr(x.hi), n).hi) + + +def pi_interval(): + def atan_inv(n, terms): + x = Fr(1, n) + partial, sums = Iv(ZERO), [] + for m in range(terms + 2): + t = Iv.frac(x ** (2 * m + 1) / (2 * m + 1)) + partial = partial + t if m % 2 == 0 else partial - t + sums.append(partial) + return hull(sums[-1], sums[-2]) # alternating series with decreasing terms + return atan_inv(5, 44) * 16 - atan_inv(239, 22) * 4 + + +PI = pi_interval() +SQRT2 = Iv.frac(2).sqrt() +SQRT3 = Iv.frac(3).sqrt() +SQRT2PI = (2 * PI).sqrt() +SQRTPI = PI.sqrt() +TINY = Decimal(10) ** (-PREC - 8) + + +def erf_point(x, coarse=False): + """erf(x) at a Decimal point: (2/sqrt pi) exp(-x^2) sum_n 2^n x^(2n+1)/(2n+1)!!, positive terms; once the term ratio + 2x^2/(2n+3) is at most 1/2 the omitted tail is at most twice the first omitted term. coarse=True stops at that point + (a valid, wider enclosure used by TRUNCATION_NESTING); the production run continues until the tail is negligible.""" + tail = MUT != "tail-dropped" + coarse = coarse or not tail + if x < 0: + return -erf_point(-x, coarse) + if x == 0: + return Iv(ZERO) + X = Iv(x) + x2 = X * X + t, S, n = X, Iv(ZERO), 0 + while True: + S = S + t + ratio = x2 * 2 / (2 * n + 3) + t = t * ratio + n += 1 + if ratio.hi <= HALF and (coarse or t.hi < S.lo * TINY): + break + if n > 200000: + raise RuntimeError("erf series did not converge") + rest = Iv(ZERO, CC.multiply(Decimal(2), t.hi)) if tail else Iv(ZERO) + return (S + rest) * (-x2).exp() * 2 / SQRTPI + + +def erf_iv(x, coarse=False): + return Iv(erf_point(x.lo, coarse).lo, erf_point(x.hi, coarse).hi) + + +def Phi(x): + return (1 + erf_iv(x / SQRT2)) / 2 + + +def phi(x): + return (-(x.sq()) / 2).exp() / SQRT2PI + + +def atan_iv(a, N=90): + """arctan(a) for an interval 0 <= a <= 1: halve the argument, then the alternating series bracketed by consecutive + partial sums (for each fixed argument the terms decrease, so the value lies between them).""" + a1 = a / (1 + (1 + a.sq()).sqrt()) + a1sq, p, S, prev = a1.sq(), a1, Iv(ZERO), None + for n in range(N + 1): + t = p / (2 * n + 1) + prev = S + S = S + t if n % 2 == 0 else S - t + p = p * a1sq + return 2 * hull(prev, S) + + +def owen_T(h, a, N=160, bracket=True): + """Owen's T(h, a) = (1/2 pi) int_0^a exp(-h^2 (1+x^2)/2)/(1+x^2) dx for 0 <= a <= 1, by Owen's series + T = (1/2 pi)[arctan a - sum_j c_j a^(2j+1)], c_j = (-1)^j/(2j+1) [1 - exp(-h^2/2) sum_{i<=j} (h^2/2)^i/i!]. + The bracket is P(Poisson(h^2/2) > j), decreasing in j, so for fixed (h, a) the terms alternate with decreasing size and + the sum lies between consecutive partial sums; interval evaluation of both encloses it for every point of the intervals.""" + if MUT == "no-owen": + return Iv(ZERO) + h2 = h.sq() / 2 + e = (-h2).exp() + pois, term, apow, a2 = Iv(ONE), Iv(ONE), a, a.sq() + S, prev = Iv(ZERO), None + for j in range(N + 1): + if j > 0: + term = term * h2 / j + pois = pois + term + cj = apow / (2 * j + 1) * (1 - e * pois) + prev = S + S = S + cj if j % 2 == 0 else S - cj + apow = apow * a2 + val = hull(prev, S) if bracket else S + return (atan_iv(a) - val) / (2 * PI) + + +def owen_T_eval(h, a): + if MUT == "tail-dropped": + return owen_T(h, a, N=6, bracket=False) + return owen_T(h, a) + + +def SHAPE(): + """Shape parameter of the gap-window incomplete gamma factor (mutant gamma-shape perturbs it).""" + return Fr(4, 3) if MUT == "gamma-shape" else Fr(7, 6) + + +def gamma_lower_point(x, a, coarse=False): + """gamma(a, x) = int_0^x s^(a-1) e^-s ds = x^a e^-x sum_n x^n/(a (a+1) ... (a+n)), positive terms; once the term ratio + x/(a+n) is at most 1/2 the omitted tail is at most twice the first omitted term. x a Decimal point >= 0, a = 7/6 or 4/3.""" + tail = MUT != "tail-dropped" + coarse = coarse or not tail + if x == 0: + return Iv(ZERO) + X = Iv(x) + t, S, n = Iv.frac(1 / a), Iv(ZERO), 0 + while True: + S = S + t + n += 1 + ratio = X / Iv.frac(a + n) + t = t * ratio + if ratio.hi <= HALF and (coarse or t.hi < S.lo * TINY): + break + if n > 200000: + raise RuntimeError("incomplete gamma series did not converge") + rest = Iv(ZERO, CC.multiply(Decimal(2), t.hi)) if tail else Iv(ZERO) + xa = X * root_frac(Fr(x), 6) if a == Fr(7, 6) else X * root_frac(Fr(x), 3) # x^a + return xa * (-X).exp() * (S + rest) + + +def gamma_lower(x, a, coarse=False): + """gamma(a, x) for an interval x >= 0 or x = INF (monotone in x).""" + if isinstance(x, float): + return GAMMA[a] + return Iv(gamma_lower_point(x.lo, a, coarse).lo, gamma_lower_point(x.hi, a, coarse).hi) + + +def gamma_complete(a, X=Decimal(120)): + """Gamma(a) = gamma(a, X) + Gamma(a, X), 1 < a < 2, with X^(a-1) e^-X <= Gamma(a, X) <= X^(a-1) e^-X / (1 - (a-1)/X).""" + low = gamma_lower_point(X, a) + xa1 = root_frac(Fr(X), 6) if a == Fr(7, 6) else root_frac(Fr(X), 3) + up = xa1 * (-Iv(X)).exp() + return low + Iv(up.lo, (up / (1 - Iv.frac(a - 1) / Iv(X))).hi) + + +GAMMA = {Fr(7, 6): gamma_complete(Fr(7, 6)), Fr(4, 3): gamma_complete(Fr(4, 3))} +GAMMA76 = GAMMA[Fr(7, 6)] +CBRT32 = root_frac(Fr(12), 3) / 2 # (3/2)^(1/3) = 12^(1/3)/2 +C72 = 1 / (72 * root_frac(Fr(72), 6)) # 72^(-7/6) +SIGMA_REF = Iv.frac(Fr(2, 3)).sqrt() # sd of f | V=0 for the reference kernel +D2_EXACT = Iv.frac(Fr(29, 6)) - Iv.frac(6).sqrt() # SIDE24 cone moment m = 2 +C3_REF = GAMMA76 * CBRT32 * D2_EXACT / (2 * SQRT3 * PI * PI * SQRTPI) # SIDE24 (1), d = 3 + + +# ---------------- the Gaussian integrals int_{-inf}^x t^n phi(t) Phi(a t) dt, n <= 4 (Math-#197 section 2, unchanged) +def G_finite(x, a): + rho2 = 1 + a.sq() + rho = rho2.sqrt() + Phx, phx, Phax = Phi(x), phi(x), Phi(a * x) + T = owen_T_eval(x, a) + Erho = (-(rho2 * x.sq()) / 2).exp() + Phrx = Phi(rho * x) + x2 = x.sq() + G0 = Phx / 2 - T + G1 = -phx * Phax + a / (rho * SQRT2PI) * Phrx + G2 = G0 - x * phx * Phax - a / (2 * PI * rho2) * Erho + G3 = -x2 * phx * Phax + a / (2 * PI) * (-(x / rho2) * Erho + SQRT2PI / (rho2 * rho) * Phrx) + 2 * G1 + G4 = -x * x2 * phx * Phax - a / (2 * PI) * (x2 / rho2 + 2 / rho2.sq()) * Erho + 3 * G2 + return [G0, G1, G2, G3, G4] + + +def G_limit(a, sign): + if sign < 0: + return [Iv(ZERO)] * 5 + rho2 = 1 + a.sq() + rho = rho2.sqrt() + g1 = a / (rho * SQRT2PI) + return [Iv.frac(Fr(1, 2)), g1, Iv.frac(Fr(1, 2)), a / (rho2 * rho * SQRT2PI) + 2 * g1, Iv.frac(Fr(3, 2))] + + +def G_at(x, a): + """x an interval or +-INF.""" + if isinstance(x, float): + return G_limit(a, 1 if x > 0 else -1) + return G_finite(x, a) + + +def P_reg(s): + """Regularized lower incomplete gamma P(7/6, s) (s an interval >= 0 or INF).""" + a = SHAPE() + return gamma_lower(s, a) / GAMMA76 + + +def G_ref(K): + lo, hi = K + def s(k): + return k if isinstance(k, float) else 12 * Iv.frac(k * k) + return P_reg(s(hi)) - P_reg(s(lo)) + + +def library_exact(): + """exp and sqrt of the decimal module, and the interval negation, against exact rational brackets: e^-q by the + rational series of e^(-q/64) raised to the 64th power (alternating tail below the last term), sqrt by an integer root.""" + ok = True + args = [Fr(48) - Fr(51035039649098175696, 10 ** 29), Fr(3), Fr(120), Fr(1, 2), Fr(288), Fr(5, 7)] + for q in args: + g = -q / 64 + parts = [] + term, ssum = Fr(1), Fr(0) + for k in range(0, 60): + ssum += term + parts.append(ssum) + term = term * g / (k + 1) + lo, hi = min(parts[-1], parts[-2]), max(parts[-1], parts[-2]) # alternating series with decreasing terms + exact = Iv(Iv.frac(lo ** 64).lo, Iv.frac(hi ** 64).hi) # e^-q = (e^(-q/64))^64, both endpoints positive + X = Iv.frac(q) + got = (-X).exp() + ok &= got.intersects(exact) and CC.divide(got.width(), got.lo) < Decimal(10) ** (-PREC + 3) + r = root_frac(q, 2) + ok &= X.sqrt().intersects(r) and CC.divide(X.sqrt().width(), r.lo) < Decimal(10) ** (-PREC + 3) + ok &= (-X).lo == X.hi.copy_negate() and (-X).hi == X.lo.copy_negate() + return ok + + +# ---------------- the d = 3 reference birth integral with interval endpoints (Math-#197 (4.1) and its three primitives) +def endpoint(b): + return b if isinstance(b, (float, Iv)) else Iv.frac(b) + + +def I3_ref(lo, hi): + """int_lo^hi phi_{2/3}(b) m_{3,b} db, m_{3,b} = (b^3 + b) phi(b) + (b^4 + 2 b^2 + 7) Phi(b) - 4 sqrt2 exp(-b^2/4) Phi(b/sqrt2); + lo, hi are rationals, intervals or +-INF.""" + sig = SIGMA_REF + def term_i(b): + if isinstance(b, float): + return Iv(ZERO) + return -(b.sq() * 2 / 5 + Iv.frac(Fr(18, 25))) * (-(b.sq()) * 5 / 4).exp() / (2 * PI * sig) + def term_ii(b): + G = G_at(b if isinstance(b, float) else b / sig, sig) + return sig.sq().sq() * G[4] + 2 * sig.sq() * G[2] + 7 * G[0] + def term_iii(b): + G = G_at(b if isinstance(b, float) else b * SQRT2, Iv.frac(Fr(1, 2))) + return 4 / sig * G[0] + lo, hi = endpoint(lo), endpoint(hi) + cross = Iv.frac(Fr(1, 2)) if MUT == "d3-cross" else Iv(ONE) + return (term_i(hi) - term_i(lo)) + (term_ii(hi) - term_ii(lo)) - cross * (term_iii(hi) - term_iii(lo)) + + +# ---------------- exact polynomial algebra (Math-#199 cone_moment_d4.py, unchanged) +def padd(u, v): + w = dict(u) + for k, c in v.items(): + w[k] = w.get(k, Fr(0)) + c + return {k: c for k, c in w.items() if c != 0} + + +def pmul(u, v): + w = {} + for k1, c1 in u.items(): + for k2, c2 in v.items(): + k = tuple(a + b for a, b in zip(k1, k2)) + w[k] = w.get(k, Fr(0)) + c1 * c2 + return {k: c for k, c in w.items() if c != 0} + + +def pscale(u, c): + return {k: v * c for k, v in u.items() if v * c != 0} + + +def pconst(c, nvars): + return {(0,) * nvars: Fr(c)} if c != 0 else {} + + +def pvar(i, nvars): + e = [0] * nvars + e[i] = 1 + return {tuple(e): Fr(1)} + + +def plin(coeffs): + """sum_i coeffs[i] * variable_i.""" + out = {} + for i, c in enumerate(coeffs): + if c: + out = padd(out, pscale(pvar(i, len(coeffs)), Fr(c))) + return out + + +def lpadd(u, v): + n = max(len(u), len(v)) + return [(u[i] if i < len(u) else Fr(0)) + (v[i] if i < len(v) else Fr(0)) for i in range(n)] + + +def lpmul(u, v): + if not u or not v: + return [] + w = [Fr(0)] * (len(u) + len(v) - 1) + for i, a in enumerate(u): + for j, b in enumerate(v): + w[i + j] += a * b + return w + + +# ---------------- the reference birth integral as a one-dimensional integral in the total trace (NOTE section 2) +def Jk_closed(k): + """J_k(s) = int_0^s q^k e^{-q^2/8} dq for odd k: J_k = B_k + C_k(s) e^{-s^2/8} with B_k rational and C_k a rational polynomial + (list by power): J_1 = 4 - 4 e^{-s^2/8}, J_{k+2} = -4 s^{k+1} e^{-s^2/8} + 4 (k+1) J_k.""" + if k % 2 != 1: + raise ValueError("even power of q") + B, C, j = Fr(4), [Fr(-4)], 1 + while j < k: + C2 = [4 * (j + 1) * c for c in C] + [Fr(0)] * (j + 2 - len(C)) + C2[j + 1] += -4 + B, C, j = 4 * (j + 1) * B, C2, j + 2 + return B, C + + +def moments(gamma, nmax): + """M_j(T) = int_0^T s^j e^{-gamma s^2} ds = alpha_j + rho_j(T) e^{-gamma T^2} + beta_j E_gamma(T), E_gamma = (1/2) sqrt(pi/gamma) + erf(sqrt(gamma) T): M_0 = E_gamma, M_1 = (1 - e^{-gamma T^2})/(2 gamma), M_{j+2} = ((j+1) M_j - T^{j+1} e^{-gamma T^2})/(2 gamma).""" + g = Fr(gamma) + M = [(Fr(0), [], Fr(1)), (1 / (2 * g), [-1 / (2 * g)], Fr(0))] + for j in range(nmax - 1): + a, r, b = M[j] + f = Fr(j if MUT == "moment-recurrence" else j + 1) + r2 = [x * f / (2 * g) for x in r] + [Fr(0)] * (j + 2 - len(r)) + r2[j + 1] += -1 / (2 * g) + M.append((f * a / (2 * g), r2, f * b / (2 * g))) + return M + + +F_MEMO = {} + + +def F_pieces(m): + if m not in F_MEMO: + F_MEMO[m] = F_pieces_build(m) + return F_MEMO[m] + + +def F_pieces_build(m): + """The inner integrals in closed form. m = 3: on the ordered sector mu_3 = -a, mu_2 = -a-p, mu_1 = -a-p-q put T = 3a + 2p + q + (minus the trace), s = 2p + q, q (Jacobian 1/6, region T > s > q > 0); the integrand is P(T, s, q) e^{-T^2/24 - s^2/24 - q^2/8} + with P = a^2 (a+p)^2 (a+p+q)^2 pq(p+q), a = (T-s)/3, p = (s-q)/2. m = 2: mu_2 = -a, mu_1 = -a-p, T = 2a + p, p (Jacobian 1/2), + P = (T^2 - p^2)^2 p/16, exponent 3T^2/40 + p^2/8. Returns ({kind: polynomial in T}, outer gamma) with F_m(T) = sum of + poly * [1 | e^{-g T^2} | E_g(T)] by kind ('1',), ('e', g), ('E', g).""" + out = {} + + def acc(key, poly): + out[key] = lpadd(out.get(key, []), poly) + if m == 3: + T, s, q = pvar(0, 3), pvar(1, 3), pvar(2, 3) + a, p = plin([Fr(1, 3), Fr(-1, 3), 0]), plin([0, Fr(1, 2), Fr(-1, 2)]) + ap = padd(a, p) + apq = padd(ap, q) + P = pmul(pmul(pmul(a, a), pmul(ap, ap)), pmul(apq, apq)) + P = pmul(P, pmul(pmul(p, q), padd(p, q))) + U, V = {}, {} + for (i, j, k), c in P.items(): + Bk, Ck = Jk_closed(k) # raises on an even power of q + U = padd(U, {(i, j): c * Bk}) + V = padd(V, pmul({(i, j): c}, {(0, n): x for n, x in enumerate(Ck) if x})) + for W_, gam in ((U, Fr(1, 24)), (V, Fr(1, 24) + Fr(1, 8))): + Ms = moments(gam, max(j for (_, j) in W_)) + for (i, j), c in W_.items(): + a_, r_, b_ = Ms[j] + Ti = [Fr(0)] * i + [c] + acc(("1",), lpmul(Ti, [a_])) + acc(("e", gam), lpmul(Ti, r_)) + acc(("E", gam), lpmul(Ti, [b_])) + return out, Fr(1, 24) + if m == 2: + T, p = pvar(0, 2), pvar(1, 2) + d = padd(pmul(T, T), pscale(pmul(p, p), Fr(-1))) + P = pscale(pmul(pmul(d, d), p), Fr(1, 16)) + for (i, k), c in P.items(): + Bk, Ck = Jk_closed(k) + acc(("1",), lpmul([Fr(0)] * i + [c], [Bk])) + acc(("e", Fr(1, 8)), lpmul([Fr(0)] * i + [c], Ck)) + return out, Fr(3, 40) + if m == 4: + T, w, s, q = (pvar(i, 4) for i in range(4)) + a = plin([Fr(1, 4), Fr(-1, 4), 0, 0]) + p1 = plin([0, Fr(1, 3), Fr(-1, 3), 0]) + p2 = plin([0, 0, Fr(1, 2), Fr(-1, 2)]) + mus, run = [pscale(a, Fr(-1))], a + for p in (p1, p2, q): + run = padd(run, p) + mus.append(pscale(run, Fr(-1))) + P = {(0, 0, 0, 0): Fr(1)} + for mu in mus: + P = pmul(P, pmul(mu, mu)) + for i in range(4): + for j in range(i + 1, 4): + P = pmul(P, padd(mus[i], pscale(mus[j], Fr(-1)))) # mus[i] > mus[j] + U, V = {}, {} + for (i, j, k, l), c in P.items(): + Bk, Ck = Jk_closed(l) # raises on an even power of q + U = padd(U, {(i, j, k): c * Bk}) + V = padd(V, pmul({(i, j, k): c}, {(0, 0, n): x for n, x in enumerate(Ck) if x})) + mid = {} # the s-layer over (0, w): pieces in (T, w) + for W_, gam in ((U, Fr(1, 24)), (V, Fr(1, 24) + Fr(1, 8))): + Ms = moments(gam, max(k for (_, _, k) in W_)) + for (i, j, k), c in W_.items(): + a_, r_, b_ = Ms[k] + if a_: + mid[("1",)] = padd(mid.get(("1",), {}), {(i, j): c * a_}) + for n, x in enumerate(r_): + if x: + mid[("e", gam)] = padd(mid.get(("e", gam), {}), {(i, j + n): c * x}) + if b_: + mid[("E", gam)] = padd(mid.get(("E", gam), {}), {(i, j): c * b_}) + aw = Fr(1, 48) # the w-layer over (0, T) against e^{-w^2/48} + for key, poly in mid.items(): + for (i, j), c in poly.items(): + if key[0] == "1": + layer = moment_dict(aw, j) + elif key[0] == "e": + layer = moment_dict(aw + key[1], j) + else: + layer = L_dict(aw, key[1], j) + for kind, pl in layer.items(): + acc(kind, lpmul([Fr(0)] * i + [c], pl)) + if MUT == "layer-dropped": # a cancelled layer silently not derived + out.pop(("E", Fr(3, 16)), None) + return out, Fr(3, 112) + raise ValueError("m must be 2, 3 or 4") + + +def moment_dict(gamma, j): + """M_j(gamma, T) = int_0^T w^j e^{-gamma w^2} dw by kind: ('1',) constant, ('e', gamma) e^{-gamma T^2}, ('E', gamma) E_gamma(T).""" + a_, r_, b_ = moments(gamma, max(j, 1))[j] + out = {} + if a_: + out[("1",)] = [a_] + if any(r_): + out[("e", gamma)] = list(r_) + if b_: + out[("E", gamma)] = [b_] + return out + + +L_MEMO = {} + + +def L_dict(al, g, j): + """L_j(T) = int_0^T w^j e^{-al w^2} E_g(w) dw, E_g(w) = (1/2) sqrt(pi/g) erf(sqrt(g) w): L_0 = Kfun_{al,g}(T) and, by parts, + L_j = -(1/(2 al)) T^{j-1} e^{-al T^2} E_g(T) + ((j-1)/(2 al)) L_{j-2} + (1/(2 al)) M_{j-1}(al + g, T) + (the last coefficient is (1/2) sqrt(pi/g) . sqrt(g)/(al sqrt(pi)) = 1/(2 al), rational).""" + key = (al, g, j) + if key in L_MEMO: + return L_MEMO[key] + if j == 0: + res = {("K", al, g): [Fr(1)]} + else: + res = {} + + def add(kind, poly): + res[kind] = lpadd(res.get(kind, []), poly) + add(("eE", al, g), [Fr(0)] * (j - 1) + [(1 if MUT == "parts-sign" else -1) / (2 * al)]) + if j >= 2: + for kind, pl in L_dict(al, g, j - 2).items(): + add(kind, [x * Fr(j - 1) / (2 * al) for x in pl]) + for kind, pl in moment_dict(al + g, j - 1).items(): + add(kind, [x / (2 * al) for x in pl]) + L_MEMO[key] = res + return res + + +def trim(poly): + poly = list(poly) + while poly and poly[-1] == 0: + poly.pop() + return poly + + +def g_terms(m, gamma_out=None): + """g_m(T) = e^{-gamma_out T^2} F_m(T) as terms (const, polynomial, gamma, kappa): const * poly(T) e^{-gamma T^2} [erf(kappa T)].""" + pieces, g_ref = F_pieces(m) + gout = g_ref if gamma_out is None else gamma_out + terms = [] + for key, poly in sorted(pieces.items(), key=lambda kv: str(kv[0])): + poly = trim(poly) + if not poly: + continue + if key[0] == "1": + terms.append((Iv(ONE), poly, Iv.frac(gout), None)) + elif key[0] == "e": + terms.append((Iv(ONE), poly, Iv.frac(gout + key[1]), None)) + elif key[0] == "E": + terms.append(((PI / Iv.frac(key[1])).sqrt() / 2, poly, Iv.frac(gout), Iv.frac(key[1]).sqrt())) + elif key[0] == "eE": + terms.append(((PI / Iv.frac(key[2])).sqrt() / 2, poly, Iv.frac(gout + key[1]), Iv.frac(key[2]).sqrt())) + else: + raise ValueError("an Owen-type term int_0^T e^{-al w^2} E_g(w) dw survived the w-layer") + return terms + + +def F_float(pieces, T): + tot = 0.0 + for key, poly in pieces.items(): + pv = sum(float(c) * T ** i for i, c in enumerate(poly)) + if key[0] == "1": + tot += pv + elif key[0] == "e": + tot += pv * math.exp(-float(key[1]) * T * T) + elif key[0] == "E": + g = float(key[1]) + tot += pv * 0.5 * math.sqrt(math.pi / g) * math.erf(math.sqrt(g) * T) + elif key[0] == "eE": + al, g = float(key[1]), float(key[2]) + tot += pv * math.exp(-al * T * T) * 0.5 * math.sqrt(math.pi / g) * math.erf(math.sqrt(g) * T) + elif any(poly): + raise ValueError("an Owen-type term int_0^T e^{-al w^2} E_g(w) dw survived the w-layer") + return tot + + +# ---------------- Taylor quadrature with Cauchy remainders (Math-#199 section 3; factors as functions, plus Phi(alpha - beta T)) +def ipow(x, n): + r = Iv(ONE) + for _ in range(n): + r = r * x + return r + + +ERF_FAST = Decimal(12) + + +def erf_point_fast(x): + """erf at a Decimal point: the toolkit series for |x| < 12; for |x| >= 12 the enclosure [1 - e^{-x^2}/(x sqrt(pi)), 1] (with sign), + since 0 < erfc(x) < e^{-x^2}/(x sqrt(pi)) for x > 0 (here below 1.5e-64).""" + if abs(x) < ERF_FAST: + return erf_point(x) + X = Iv(abs(x)) + t = (-(X.sq())).exp() / (X * SQRTPI) + v = Iv((1 - t).lo, ONE) + return v if x > 0 else -v + + +def erf_fast(x): + return Iv(erf_point_fast(x.lo).lo, erf_point_fast(x.hi).hi) + + +def Phi_fast(x): + return (1 + erf_fast(x / SQRT2)) / 2 + + +CACHE = {} + + +def gauss_coeffs(g, s0, K): + """Taylor coefficients of exp(-g s^2) at s0: (n+1) y_{n+1} = -2 g (s0 y_n + y_{n-1}).""" + key = ("g", g.lo, g.hi, s0, K) + if key in CACHE: + return CACHE[key] + S0 = Iv.frac(s0) + y = [(-(g * S0.sq())).exp()] + prev = Iv(ZERO) + for n in range(K): + nxt = -(2 * g) * (S0 * y[n] + prev) / (n + 1) + prev = y[n] + y.append(nxt) + CACHE[key] = y + return y + + +def gauss_bound(g, s0, rho): + inner = max(Fr(0), abs(Fr(s0)) - Fr(rho)) + return (g * Iv.frac(rho * rho) - g * Iv.frac(inner * inner)).exp() # |e^{-g z^2}| = e^{-g(x^2 - y^2)}, |y| <= rho + + +def erf_coeffs(kappa, s0, K): + """erf(kappa s): value at s0, then (2 kappa/sqrt pi) times the Gaussian's coefficients divided by n + 1.""" + key = ("e", kappa.lo, kappa.hi, s0, K) + if key in CACHE: + return CACHE[key] + y = gauss_coeffs(kappa.sq(), s0, K) + pref = 2 * kappa / SQRTPI + out = [erf_fast(kappa * Iv.frac(s0))] + [pref * y[n] / (n + 1) for n in range(K)] + CACHE[key] = out + return out + + +def erf_bound(kappa, s0, rho): + return 2 * kappa / SQRTPI * Iv.frac(abs(Fr(s0)) + Fr(rho)) * (kappa.sq() * Iv.frac(Fr(rho) ** 2)).exp() + + +def poly_coeffs(c, s0, K): + out = [] + for n in range(K + 1): + v = Fr(0) + for j, cj in enumerate(c): + if j >= n: + v += cj * math.comb(j, n) * Fr(s0) ** (j - n) + out.append(Iv.frac(v)) + return out + + +def poly_bound(c, s0, rho): + r = abs(Fr(s0)) + Fr(rho) + return Iv.frac(sum(abs(cj) * r ** j for j, cj in enumerate(c))) + + +def t_mul(u, v): + K = len(u) - 1 + out = [] + for n in range(K + 1): + acc = Iv(ZERO) + for i in range(n + 1): + acc = acc + u[i] * v[n - i] + out.append(acc) + return out + + +def phi_aff_coeffs(alpha, beta, s0, K): + """Phi(alpha - beta T) at T = s0 + x (alpha, beta real intervals, beta > 0): c_0 = Phi(w0), w0 = alpha - beta s0, and + c_{n+1} = -(beta/sqrt(2 pi)) y_n/(n+1) with y the coefficients of exp(-(w0 - beta x)^2/2), (n+1) y_{n+1} = beta w0 y_n - beta^2 y_{n-1}.""" + w0 = alpha - beta * Iv.frac(s0) + y = [(-(w0.sq()) / 2).exp()] + prev = Iv(ZERO) + b2 = beta.sq() + for n in range(K): + nxt = (beta * w0 * y[n] - b2 * prev) / (n + 1) + prev = y[n] + y.append(nxt) + pref = beta / SQRT2PI + return [Phi_fast(w0)] + [-(pref * y[n] / (n + 1)) for n in range(K)] + + +def phi_aff_bound(beta, rho): + """|Phi(alpha - beta z)| <= Phi(w0) + |int_{w0}^{w} phi| <= 1 + beta rho e^{beta^2 rho^2/2}/sqrt(2 pi) on |z - s0| <= rho + (the segment from the real point w0 has |Im t| <= beta rho, and |phi(t)| <= e^{(Im t)^2/2}/sqrt(2 pi)).""" + br = beta * Iv.frac(rho) + return 1 + br * (br.sq() / 2).exp() / SQRT2PI + + +class Model: + """int_0^inf g(T) Phi(alpha - beta T) dT for g = sum const * poly(T) e^{-gamma T^2} [erf(kappa T)] (entire). On each cell of + width CELL the point Taylor coefficients of g at the centre are computed once and contracted with the cell moments, so that an + evaluation for given (alpha, beta) costs one product of coefficient vectors per cell. The remainder of the order-K Taylor + polynomial of the product is bounded by Cauchy's estimate at the centre, |c_n| <= M_g M_Phi / rho^n, summed geometrically; + beyond T_CUT the integrand is bounded by |g| (0 <= Phi <= 1, |erf| <= 1) and incomplete gamma bounds.""" + + def __init__(self, terms, K=K_ORDER, cell=CELL, T=T_CUT, rho=RHO): + self.K, self.rho = K, rho + half = cell / 2 + ncell = int(T / cell) + if ncell * cell != T or Fr(half) >= Fr(rho): + raise ValueError("bad quadrature parameters") + mom = [Iv.frac(2 * half ** (n + 1) / (n + 1)) if n % 2 == 0 else Iv(ZERO) for n in range(K + 1)] + rem_moment = Iv.frac(2 * half ** (K + 2) / (K + 2) / (1 - Fr(half) / Fr(rho))) + rho_pow = Iv.frac(Fr(rho) ** (K + 1)) + self.cells, Rsum = [], Iv(ZERO) + for c in range(ncell): + s0 = (2 * c + 1) * half + G, M = [Iv(ZERO)] * (K + 1), Iv(ZERO) + for const, poly, gam, kap in terms: + pc = t_mul(poly_coeffs(poly, s0, K), gauss_coeffs(gam, s0, K)) + Mb = poly_bound(poly, s0, rho) * gauss_bound(gam, s0, rho) + if kap is not None: + pc = t_mul(pc, erf_coeffs(kap, s0, K)) + Mb = Mb * erf_bound(kap, s0, rho) + G = [x + const * y for x, y in zip(G, pc)] + M = M + Iv(const.mag()) * Mb + Gm = [] + for j in range(K + 1): + acc = Iv(ZERO) + for i in range(j % 2, K + 1 - j, 2): + acc = acc + G[i] * mom[i + j] + Gm.append(acc) + self.cells.append((s0, Gm)) + Rsum = Rsum + M / rho_pow * rem_moment + self.Rsum = Rsum.hi + tail = Iv(ZERO) + for const, poly, gam, kap in terms: # int_T^inf t^j e^{-g t^2} dt = (1/2) g^{-(j+1)/2} Gamma((j+1)/2, g T^2) + x = gam * Iv.frac(T * T) + for j, cj in enumerate(poly): + if cj == 0: + continue + a = Fr(j + 1, 2) + if a.denominator == 2: + xa1, gpow = ipow(x, int(a - Fr(1, 2))) * x.sqrt() / x, ipow(gam, int(a)) * gam.sqrt() + else: + xa1, gpow = ipow(x, int(a) - 1), ipow(gam, int(a)) + up = xa1 * (-x).exp() # Gamma(a, x) <= x^(a-1) e^-x (a <= 1), / (1 - (a-1)/x) (a > 1) + if a > 1: + up = up / (1 - Iv.frac(a - 1) / x) + tail = tail + Iv(const.mag()) * Iv.frac(abs(cj)) * up / gpow / 2 + self.tail = tail.hi + + def integral(self, alpha=None, beta=None): + tot = Iv(ZERO) + if alpha is None: + for _, Gm in self.cells: + tot = tot + Gm[0] + R = self.Rsum + else: + for s0, Gm in self.cells: + Wc = phi_aff_coeffs(alpha, beta, s0, self.K) + for j in range(self.K + 1): + tot = tot + Wc[j] * Gm[j] + R = (Iv(self.Rsum) * phi_aff_bound(beta, self.rho)).hi + if MUT == "remainder-dropped": + R = ZERO + R = CC.add(R, self.tail) + return tot + Iv(R.copy_negate(), R) + + +MODELS = {} + + +def model(m, gamma_out=None): + key = (m, gamma_out) + if key not in MODELS: + MODELS[key] = Model(g_terms(m, gamma_out)) + return MODELS[key] + + +Z_MEHTA = {2: 8 * SQRT2PI, 3: 48 * SQRT2 * PI, 4: 1536 * PI} # Mehta's integral (Math-#199 section 1; Z_4 = 1536 pi, Math-#202) + + +class Birth: + """I_B = kappa0/Z_m int_0^inf e^{-gamma_out T^2} F_m(T) [Phi(sl (b_+ - c T)) - Phi(sl (b_- - c T))] dT for the Gaussian pair + f ~ N(0, v), g = mu f + sigma Z (A = Q - g I): conditioning on f = b and integrating the GOE shift exactly (NOTE section 2). + Reference: v = 2/3, mu = 1, sigma = 0, i.e. kappa0 = sqrt(3/(m+3)), gamma_out = 3/(4m(m+3)), sl = sqrt((m+3)/2), c = 1/(m+3).""" + + def __init__(self, m, v=Fr(2, 3), mu=Fr(1), sig2=Fr(0)): + D = 1 + m * sig2 / 2 + A = 1 / (2 * v) + m * mu * mu / (4 * D) + Bc = mu / (2 * D) + g0 = Bc * Bc / (4 * A) + (Fr(0) if MUT == "tilt-gamma" else sig2 / (8 * D)) + self.m = m + self.gamma_out = Fr(1, 4 * m) - g0 + c = Bc / (2 * A) + if MUT == "trace-slope" and sig2 == 0: + c = Fr(1, m + 2) + self.sl = Iv.frac(2 * A).sqrt() + self.beta = self.sl * Iv.frac(c) + self.pref = 1 / Iv.frac(2 * v * A * D).sqrt() / Z_MEHTA[m] + self.M = model(m, None if self.gamma_out == F_pieces(m)[1] else self.gamma_out) + self.cache = {} + + def lam(self, b): + if isinstance(b, float): + return self.M.integral() if b > 0 else Iv(ZERO) + key = (b.lo, b.hi) + if key not in self.cache: + self.cache[key] = self.M.integral(self.sl * b, self.beta) + return self.cache[key] + + def I(self, B): + lo, hi = (x if isinstance(x, (float, Iv)) else Iv.frac(x) for x in B) + return self.pref * (self.lam(hi) - self.lam(lo)) + + +def gl_nodes(n): + xs, ws = [], [] + for i in range(1, n + 1): + x = math.cos(math.pi * (i - 0.25) / (n + 0.5)) + for _ in range(100): + p0, p1 = 1.0, x + for k in range(2, n + 1): + p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k + dp = n * (x * p1 - p0) / (x * x - 1) + dx = p1 / dp + x -= dx + if abs(dx) < 1e-15: + break + xs.append(x) + ws.append(2 / ((1 - x * x) * dp * dp)) + return xs, ws + + +def M4_float(b, nodes, R=14.0): + """E[det(bI - Q)^2 1{Q < bI}] for the 4 x 4 GOE, by Gauss-Legendre over the ordered eigenvalues lambda_4 = b - a, + lambda_3 = lambda_4 - p1, lambda_2 = lambda_3 - p2, lambda_1 = lambda_2 - p3 with Mehta's density 24/Z_4 |Delta| e^{-|lambda|^2/4} + (float control, independent of the total-trace coordinates and of every exact layer).""" + xs, ws = nodes + pts = [(R * (x + 1) / 2, w * R / 2) for x, w in zip(xs, ws)] + tot = 0.0 + for a, wa in pts: + l4 = b - a + for p1, w1 in pts: + l3 = l4 - p1 + for p2, w2 in pts: + l2 = l3 - p2 + e3 = l4 * l4 + l3 * l3 + l2 * l2 + f3 = wa * w1 * w2 * (a * (a + p1) * (a + p1 + p2)) ** 2 * p1 * p2 * (p1 + p2) + for p3, w3 in pts: + l1 = l2 - p3 + tot += f3 * w3 * (a + p1 + p2 + p3) ** 2 * p3 * (p2 + p3) * (p1 + p2 + p3) * math.exp(-(e3 + l1 * l1) / 4) + return 24 / (1536 * math.pi) * tot + + +def I4_float(B, nb=12, n=28): + xs, ws = gl_nodes(nb) + nodes = gl_nodes(n) + lo, hi = float(B[0]), float(B[1]) + tot = 0.0 + for x, w in zip(xs, ws): + b = lo + (hi - lo) * (x + 1) / 2 + tot += w * math.sqrt(3 / (4 * math.pi)) * math.exp(-3 * b * b / 4) * M4_float(b, nodes) + return tot * (hi - lo) / 2 + + +def F4_direct_float(T, n=24): + """int_{T > w > s > q > 0} P(T, w, s, q) e^{-w^2/48 - s^2/24 - q^2/8} by nested Gauss-Legendre (float control of the exact layers).""" + xs, ws = gl_nodes(n) + tot = 0.0 + for xw, ww in zip(xs, ws): + w = T * (xw + 1) / 2 + for xs_, ws_ in zip(xs, ws): + s_ = w * (xs_ + 1) / 2 + for xq, wq in zip(xs, ws): + q = s_ * (xq + 1) / 2 + a, p1, p2, p3 = (T - w) / 4, (w - s_) / 3, (s_ - q) / 2, q + m4, m3, m2, m1 = a, a + p1, a + p1 + p2, a + p1 + p2 + p3 + vand = p1 * (p1 + p2) * (p1 + p2 + p3) * p2 * (p2 + p3) * p3 + tot += ww * ws_ * wq * (m4 * m3 * m2 * m1) ** 2 * vand * math.exp(-w * w / 48 - s_ * s_ / 24 - q * q / 8) * (T / 2) * (w / 2) * (s_ / 2) + return tot + + +# ---------------- the d = 5 jet of the reference kernel exp(-|z|^2/2), frame (u, w1, w2, w3, w4) +def _e(*idx): + v = [0] * 5 + for i in idx: + v[i] += 1 + return tuple(v) + + +A_PAIRS = [(i, j) for i in range(1, 5) for j in range(i, 5)] # A11 A12 A13 A14 A22 A23 A24 A33 A34 A44 +EVEN = [_e(), _e(0, 0)] + [_e(0, i) for i in range(1, 5)] + [_e(i, j) for i, j in A_PAIRS] # f, f_uu, f_uw1..4, A (16 entries) +ODD = [_e(0)] + [_e(i) for i in range(1, 5)] + [_e(0, 0, 0)] # f_u, f_w1..4, t = f_uuu +IDX_X, IDX_V = [0] + list(range(6, 16)), [1, 2, 3, 4, 5] +DIAG_A = [1 + k for k, (i, j) in enumerate(A_PAIRS) if i == j] # positions of A11, A22, A33, A44 in IDX_X +OFF_A = [1 + k for k, (i, j) in enumerate(A_PAIRS) if i != j] +N_VEC, DEGREE = 11, 8 # Lemma S: dimension of (f, A), degree of det(A)^2 + + +def dfact2(n): + r = 1 + while n > 1: + r *= n + n -= 2 + return r + + +def ref_cov(a, b): + """Cov(d^a f, d^b f) = (-1)^|a| d^(a+b) exp(-|z|^2/2) at 0 = (-1)^|a| prod_i (-1)^(al_i/2) (al_i - 1)!! (all al_i even).""" + al = [x + y for x, y in zip(a, b)] + if any(x % 2 for x in al): + return Fr(0) + v = Fr((-1) ** sum(a)) + for x in al: + v *= (-1) ** (x // 2) * dfact2(x - 1) + if MUT == "tau-cross" and sorted([a, b]) == sorted([_e(0, 0, 0), _e(0)]): + return Fr(0) + return v + + +def ref_matrix(idx): + return [[ref_cov(a, b) for b in idx] for a in idx] + + +def det_n(M): + """Determinant by Laplace expansion along the first row (n <= 5); Fractions or intervals.""" + n = len(M) + if n == 1: + return M[0][0] + if n == 2: + return M[0][0] * M[1][1] - M[0][1] * M[1][0] + tot = None + for j in range(n): + minor = [[M[i][k] for k in range(n) if k != j] for i in range(1, n)] + t = M[0][j] * det_n(minor) + tot = t if tot is None else (tot + t if j % 2 == 0 else tot - t) + return tot + + +def inv_n(M): + """Inverse by the adjugate (n <= 5); works for Fractions and for intervals.""" + n = len(M) + d = det_n(M) + cof = [[None] * n for _ in range(n)] + for i in range(n): + for j in range(n): + minor = [[M[r][c] for c in range(n) if c != j] for r in range(n) if r != i] + v = det_n(minor) + cof[i][j] = v if (i + j) % 2 == 0 else -v + return [[cof[j][i] / d for j in range(n)] for i in range(n)], d + + +def schur(C, X, V): + """Cov(X | V) = C_XX - C_XV C_VV^-1 C_VX for index lists into C (Fractions or intervals).""" + Vinv, detV = inv_n([[C[i][j] for j in V] for i in V]) + out = [] + for i in X: + row = [] + for j in X: + s = None + for p in range(len(V)): + for q in range(len(V)): + t = C[i][V[p]] * Vinv[p][q] * C[V[q]][j] + s = t if s is None else s + t + row.append(C[i][j] + s if MUT == "schur-sign" else C[i][j] - s) + out.append(row) + return out, detV + + +def sylvester_pd(M): + """Exact positive definiteness of a symmetric rational matrix (Gaussian elimination; all pivots positive).""" + n = len(M) + A = [list(map(Fr, r)) for r in M] + for k in range(n): + if A[k][k] <= 0: + return False + for i in range(k + 1, n): + f = A[i][k] / A[k][k] + for j in range(k, n): + A[i][j] -= f * A[k][j] + return True + + +C_EVEN_REF = ref_matrix(EVEN) +C_ODD_REF = ref_matrix(ODD) +CPRIME_REF, DETV_REF = schur(C_EVEN_REF, IDX_X, IDX_V) +LAMBDA0 = Fr(1, 4) + + +def shifted(M, lam): + return [[M[i][j] - (lam if i == j else 0) for j in range(len(M))] for i in range(len(M))] + + +# ---------------- image bound for the torus kernel in d = 5 +def image_bound5(L): + """E^(5)_L = 60500 (76 L^6 + 15) exp(-L^2/2): the shell |n|_inf = j carries (2j+1)^5 - (2j-1)^5 = 160 j^4 + 80 j^2 + 2 <= 242 j^4 + points with |n|^2 <= 5 j^2, so sum_{n != 0} |n|^6 exp(-L^2 |n|^2/2) <= 30250 sum_j j^10 exp(-L^2 j^2/2) <= 60500 exp(-L^2/2) + (successive terms ratio at most 2^10 exp(-3L^2/2) < 1/2 for L >= 10); the contraction bound 76|x|^6 phi(x) (q <= 6, |x| >= 1), + |D^q phi(0)| <= 15 and the normalization S >= 1 are those of Math-#197 section 3 (dimension-free); the constant is Math-#200's E_5.""" + shells = 160 if MUT == "image-shells" else 242 + L = Fr(L) + return Iv.frac(2 * shells * 125 * (76 * L ** 6 + 15)) * (-Iv.frac(L * L / 2)).exp() + + +def half_power(x, twice): + r = ipow(x, twice // 2) + return r * x.sqrt() if twice % 2 else r + + +SANDWICH_VIOLATIONS = [] + + +def scaled(b, s): + if isinstance(b, float): + return b + b = b if isinstance(b, Iv) else Iv.frac(b) + return b * s if MUT == "window-scale" else b / s + + +def sandwich(birth, B, eps): + """Lemma S with n = 11, degree 8: (1-eps)^(19/2)/(1+eps)^(11/2) I^ref_{B/sqrt(1-eps)} <= I'_B <= (1+eps)^(19/2)/(1-eps)^(11/2) + I^ref_{B/sqrt(1+eps)}.""" + e = Iv(eps) if isinstance(eps, Decimal) else Iv.of(eps) + if e.hi >= 1: + raise ValueError("eps must be below 1") + up, dn = 1 + e, 1 - e + s_up, s_dn = up.sqrt(), dn.sqrt() + su, sd = (s_dn, s_up) if MUT == "sandwich-swap" else (s_up, s_dn) + lo, hi = B + upper = half_power(up, N_VEC + DEGREE) / half_power(dn, N_VEC) * birth.I((scaled(lo, su), scaled(hi, su))) + lower = half_power(dn, N_VEC + DEGREE) / half_power(up, N_VEC) * birth.I((scaled(lo, sd), scaled(hi, sd))) + if lower.lo > upper.hi: # impossible for a correct bracket; recorded and reported by rule SANDWICH_ORDERED + SANDWICH_VIOLATIONS.append(str(B)) + return Iv(upper.lo, lower.hi) + return Iv(lower.lo, upper.hi) + + +def scaled_exact(birth, B, eta): + """Exact I'_B for C' = (1 + eta) C'_ref: (1 + eta)^4 I^ref_{B/sqrt(1+eta)} (degree-8 homogeneity of det(A)^2).""" + s = (1 + Iv.frac(eta)).sqrt() + lo, hi = B + return ipow(1 + Iv.frac(eta), DEGREE // 2) * birth.I((scaled(lo, s), scaled(hi, s))) + + +def frob_eps(Cp, Cref): + """eps = ||C' - C'_ref||_F / lambda0, entrywise supremum of the deviation over each interval entry.""" + dev2 = Iv(ZERO) + n = len(Cref) + for i in range(n): + for j in range(n): + r = Iv.frac(Cref[i][j]) + c = Cp[i][j] if isinstance(Cp[i][j], Iv) else Iv.frac(Cp[i][j]) + d = max(abs(CC.subtract(c.hi, r.lo)), abs(CF.subtract(c.lo, r.hi))) + dev2 = dev2 + Iv(d).sq() + return (dev2.sqrt() / Iv.frac(LAMBDA0)).hi + + +class Space5: + """Every covariance entry of the 5-jet (other than Var f = 1, exact by the normalization) in [ref - E, ref + E]; the odd block + (G, t) is independent of the even block (f, V, A) for any even kernel ([LP] section 15).""" + + def __init__(self, E, birth): + E = Iv.of(E) + self.birth = birth + + def box(M): + n = len(M) + Bx = [[None] * n for _ in range(n)] + for i in range(n): + for j in range(i, n): + Bx[i][j] = Bx[j][i] = Iv.frac(M[i][j]) + Iv(E.hi.copy_negate(), E.hi) + return Bx + CE_ = box(C_EVEN_REF) + CE_[0][0] = Iv(ONE) + CO = box(C_ODD_REF) + G = [[CO[i][j] for j in range(5)] for i in range(5)] + Ginv, detG = inv_n(G) + c = [CO[5][j] for j in range(5)] + self.tau2 = CO[5][5] - sum((c[i] * Ginv[i][j] * c[j] for i in range(5) for j in range(5)), Iv(ZERO)) + self.pG = 1 / (4 * PI.sq() * SQRT2PI * detG.sqrt()) # (2 pi)^(-5/2) det(Cov G)^(-1/2) + self.Cp, detV = schur(CE_, IDX_X, IDX_V) + self.pV = 1 / (4 * PI.sq() * SQRT2PI * detV.sqrt()) + self.tau43 = root_iv(self.tau2.sq(), 3) + self.eps = frob_eps(self.Cp, CPRIME_REF) + + def k_integral(self, K): + lo, hi = K + + def s(k): + return k if isinstance(k, float) else 72 * Iv.frac(k * k) / self.tau2 + a = SHAPE() + return self.tau43 * C72 * (gamma_lower(s(hi), a) - gamma_lower(s(lo), a)) / (2 * SQRT2PI) + + def coefficient(self, B, K): + sphere = 2 * PI.sq() if MUT == "sphere" else 8 * PI.sq() / 3 # |S^4| = 8 pi^2/3 + return 144 * sphere * self.pG * self.pV * sandwich(self.birth, B, self.eps) * self.k_integral(K) + + +# ---------------- a non-scalar exact test of Lemma S: the tilted pair (f, g) +TILT = (Fr(17, 25), Fr(33, 34), Fr(2261, 86700)) # v = Var f, mu, sigma^2 with mu^2 v + sigma^2 = 2/3 + + +def tilted_cprime(v, mu, sig2): + """Covariance of (f, A11, A12, ..., A44) for A = Q - (mu f + sigma Z) I.""" + s = mu * mu * v + sig2 + C = [[Fr(0)] * 11 for _ in range(11)] + C[0][0] = v + for i in DIAG_A: + C[0][i] = C[i][0] = -mu * v + for j in DIAG_A: + C[i][j] = s + (2 if i == j else 0) + for i in OFF_A: + C[i][i] = Fr(1) + return C + + +# ---------------- main +S6, S21, S14 = Iv.frac(6).sqrt(), Iv.frac(21).sqrt(), Iv.frac(14).sqrt() +ATAN2 = PI / 2 - atan_iv(Iv.frac(Fr(1, 2))) +D3_CF = (50 * PI + 200 * ATAN2 - 228) / (9 * PI) # Math-#201 +D4_CF = (Iv.frac(Fr(6695, 54)) - Iv.frac(Fr(405, 32)) * S6 # Math-#202 + - (Iv.frac(Fr(1375, 72)) * S21 + Iv.frac(Fr(6695, 27)) * atan_iv(S21 / 7) + Iv.frac(Fr(405, 16)) * S6 * atan_iv(S14 / 14)) / PI) +C5_REF = GAMMA76 * CBRT32 * D4_CF / (12 * SQRT3 * PI.sq() * PI * SQRTPI) # c_{5,ref} = Gamma(7/6) (3/2)^(1/3) D_4/(12 sqrt3 pi^(7/2)) +R8 = [Fr(3, 1024) * x for x in (11243520, 0, -522240, 0, 28800, 0, -288, 0, 1)] +R6 = [Fr(-256, 729) * x for x in (405, 0, 405, 0, 45, 0, 1)] +STATED_F4 = {("e", Fr(1, 16)): [Fr(1, 31104) * x for x in (0, -991830528, 0, 18489408, 0, -346856, 0, 729)], + ("E", Fr(1, 16)): R8, + ("eE", Fr(1, 48), Fr(1, 24)): R6, ("eE", Fr(1, 48), Fr(1, 6)): [2 * x for x in R6], + ("e", Fr(3, 16)): [Fr(512, 243) * x for x in (0, -297, 0, -42, 0, -1)]} +CANCELLED_F4 = {("1",), ("E", Fr(3, 16)), ("K", Fr(1, 48), Fr(1, 24)), ("K", Fr(1, 48), Fr(1, 6))} # generated by the derivation and zero + + +def label(W): + def f(x): + return ("inf" if x > 0 else "-inf") if isinstance(x, float) else str(x) + return "[%s,%s]" % (f(W[0]), f(W[1])) + + +def within(iv, fv, tol): + f, t = Decimal(repr(fv)), Decimal(repr(tol)) + return CE.subtract(iv.lo, f) <= t and CE.subtract(f, iv.hi) <= t + + +def common_prefix(iv): + lo, hi = str(iv.lo), str(iv.hi) + i = 0 + while i < min(len(lo), len(hi)) and lo[i] == hi[i]: + i += 1 + return lo[:i] + + +def rel_width(iv): + return CC.divide(iv.width(), CC.multiply(Decimal(2), iv.lo)) + + +def main(): + global MUT, C_EVEN_REF, C_ODD_REF, CPRIME_REF, DETV_REF, LAMBDA0 + ap = argparse.ArgumentParser() + ap.add_argument("--mutant", choices=MUTANTS) + MUT = ap.parse_args().mutant + C_EVEN_REF, C_ODD_REF = ref_matrix(EVEN), ref_matrix(ODD) # rebuilt: they depend on the mutant + CPRIME_REF, DETV_REF = schur(C_EVEN_REF, IDX_X, IDX_V) + LAMBDA0 = Fr(3, 10) if MUT == "d4-floor" else Fr(1, 4) + t0 = time.time() + checks = {} + full, fullK = (-INF, INF), (Fr(0), INF) + band, bandK = (Fr(0), Fr(1)), (Fr(1, 2), Fr(2)) + + # the reference law, exactly + stated = [[Fr(0)] * 11 for _ in range(11)] + stated[0][0] = Fr(2, 3) + for i in DIAG_A: + stated[0][i] = stated[i][0] = Fr(-2, 3) + for j in DIAG_A: + stated[i][j] = Fr(8, 3) if i == j else Fr(2, 3) + for i in OFF_A: + stated[i][i] = Fr(1) + s2 = CPRIME_REF[0][0] + mean = [CPRIME_REF[i][0] / s2 for i in range(1, 11)] + condA = [[CPRIME_REF[i][j] - CPRIME_REF[i][0] * CPRIME_REF[0][j] / s2 for j in range(1, 11)] for i in range(1, 11)] + goe = [[(Fr(2) if i + 1 in DIAG_A else Fr(1)) if i == j else Fr(0) for j in range(10)] for i in range(10)] + Ginv, detG = inv_n([[C_ODD_REF[i][j] for j in range(5)] for i in range(5)]) + tau2_ref = C_ODD_REF[5][5] - sum(C_ODD_REF[5][i] * Ginv[i][j] * C_ODD_REF[5][j] for i in range(5) for j in range(5)) + checks["REFERENCE_EXACT"] = bool(CPRIME_REF == stated and mean == [-1 if i + 1 in DIAG_A else 0 for i in range(10)] + and condA == goe and DETV_REF == 3 and detG == 1 and tau2_ref == 6 + and tilted_cprime(Fr(2, 3), Fr(1), Fr(0)) == CPRIME_REF) + checks["LAMBDA_FLOOR"] = bool(LAMBDA0 == Fr(1, 4) and sylvester_pd(shifted(CPRIME_REF, LAMBDA0)) + and sylvester_pd(shifted(CPRIME_REF, Fr(262, 1000))) + and not sylvester_pd(shifted(CPRIME_REF, Fr(263, 1000))) + and not sylvester_pd(shifted(CPRIME_REF, Fr(3, 10)))) + + # the exact inner layers: the Owen-type terms cancel, the stated closed form, and a direct float triple integral + pieces4 = F_pieces(4)[0] + nonzero = {k: trim(v) for k, v in pieces4.items() if trim(v)} + layer_ctrl = {str(T): ["%.12g" % F_float(pieces4, T), "%.12g" % F4_direct_float(float(T))] for T in (3, 6)} + cancelled = {k for k, v in pieces4.items() if not trim(v)} + checks["INNER_LAYERS"] = bool(nonzero == STATED_F4 and cancelled == CANCELLED_F4 + and all(abs(float(x) - float(y)) <= 1e-6 * abs(float(y)) for x, y in layer_ctrl.values())) + + # the reference birth integral: full window, coarse quadrature, m = 2 and m = 3, float control + ref4 = Birth(4) + I_full = ref4.I(full) + checks["D4_EXACT"] = bool(I_full.intersects(D4_CF) and I_full.width() < Decimal("1e-45") and D4_CF.width() < Decimal("1e-50")) + coarse = ref4.pref * Model(g_terms(4), K=8, cell=Fr(2), T=Fr(80), rho=Fr(6)).integral() + checks["QUAD_COARSE"] = bool(coarse.contains(D4_CF)) + ref2 = Birth(2) + cross = {} + ok = ref2.I(full).intersects(D2_EXACT) and ref2.I(full).width() < Decimal("1e-45") + for B in ((Fr(0), Fr(1)), (Fr(3), Fr(7, 2)), (-INF, Fr(0))): + x, y = ref2.I(B), I3_ref(*B) + ok &= x.intersects(y) and x.width() < Decimal("1e-45") + cross["m2 " + label(B)] = {"T_quadrature": x.pair(), "Math197_closed_form": y.pair()} + ref3 = Birth(3) + F4band = ref3.I(band) / D3_CF + ok &= ref3.I(full).intersects(D3_CF) and str(F4band.lo).startswith(F4B_209) and str(F4band.hi).startswith(F4B_209) + cross["m3 full"] = ref3.I(full).pair() + cross["m3 F^(4)_[0,1]"] = F4band.pair() + checks["CROSSCHECK_M2_M3"] = bool(ok) + fctrl = {} + ok = True + for B in ((Fr(0), Fr(1)), (Fr(1), Fr(2))): + fv, cv = I4_float(B), ref4.I(B) + ok &= within(cv, fv, 1e-8 * fv) + fctrl[label(B)] = {"float_eigenvalue_quadrature": "%.10g" % fv, "certified": cv.pair()} + checks["FLOAT_CONTROL"] = bool(ok) + + # image bound and epsilon + E10, E12, E24 = image_bound5(10), image_bound5(12), image_bound5(24) + checks["IMAGE_BOUND"] = bool(Decimal("8.86e-10") < E10.lo and E10.hi < Decimal("8.88e-10") + and Decimal("7.36e-111") < E24.lo and E24.hi < Decimal("7.37e-111") + and (Iv.frac(1024) * (-Iv.frac(150)).exp()).hi < HALF) + S0, S10, S12, S24 = Space5(0, ref4), Space5(E10, ref4), Space5(E12, ref4), Space5(E24, ref4) + checks["EPSILON"] = bool(S0.eps < Decimal("1e-55") and S10.eps < Decimal("1e-7") and S12.eps < Decimal("1e-16") + and S24.eps < Decimal("1e-55")) + + # Lemma S against exact scalar perturbations and an exact non-scalar (tilted) covariance + ok = True + for eta in (Fr(1, 50), Fr(-1, 50)): + for B in ((Fr(0), Fr(1)), (Fr(3), Fr(7, 2)), (Fr(-7, 2), Fr(-3))): + ok &= sandwich(ref4, B, Iv.frac(abs(eta))).contains(scaled_exact(ref4, B, eta)) + checks["SANDWICH_EXACT_SCALING"] = bool(ok) + tb = Birth(4, *TILT) + eps_t = frob_eps(tilted_cprime(*TILT), CPRIME_REF) + full_t = tb.I(full) + tilt = {"v_mu_sigma2": [str(x) for x in TILT], "eps": str(eps_t), "full_window": full_t.pair(), "windows": {}} + ok = full_t.intersects(D4_CF) and Decimal("0.092") < eps_t < Decimal("0.093") + for B in ((Fr(0), Fr(1)), (Fr(1), Fr(2))): + if not ok: # eps outside its certified range: no bracket is formed + break + ex, sw, rf = tb.I(B), sandwich(ref4, B, eps_t), ref4.I(B) + ok &= sw.contains(ex) and not ex.intersects(rf) + tilt["windows"][label(B)] = {"tilted_exact": ex.pair(), "sandwich": sw.pair(), "reference": rf.pair()} + checks["TILTED_EXACT"] = bool(ok) + + # the coefficient: reference, every L >= 10, L = 24 + b_windows = [(Fr(0), Fr(1)), (Fr(-1), Fr(1)), (Fr(-2), Fr(2)), (Fr(0), INF), (-INF, Fr(0)), full] + table = {} + for B in b_windows: + F5 = ref4.I(B) / D4_CF + for K in (bandK, fullK): + GK = G_ref(K) + table["B=%s K=%s" % (label(B), label(K))] = { + "F5_B": F5.pair(), "G_K": GK.pair(), "c5_ref": (C5_REF * F5 * GK).pair(), + "c5_torus_L_ge_10": S10.coefficient(B, K).pair(), "c5_torus_L_24": S24.coefficient(B, K).pair()} + F5_band = ref4.I(band) / D4_CF + c_band_ref = C5_REF * F5_band * G_ref(bandK) + c_band_0, c_band_10, c_band_24 = S0.coefficient(band, bandK), S10.coefficient(band, bandK), S24.coefficient(band, bandK) + c_full_0, c_full_10, c_full_24 = S0.coefficient(full, fullK), S10.coefficient(full, fullK), S24.coefficient(full, fullK) + checks["FACTORIZATION"] = bool(c_band_0.intersects(c_band_ref) and c_full_0.intersects(C5_REF)) + checks["C5_CONSISTENT"] = bool(str(C5_REF.lo).startswith(C5_REF_200) and str(C5_REF.hi).startswith(C5_REF_200) + and c_full_24.intersects(C5_REF) and c_full_10.contains(C5_REF)) + checks["NESTING"] = bool(c_band_10.contains(c_band_ref) and c_band_10.intersects(c_band_24) + and c_band_10.width() > c_band_24.width() * Decimal(10) ** 30 + and all(Iv(Decimal(v["c5_torus_L_ge_10"][0]), Decimal(v["c5_torus_L_ge_10"][1])).contains( + Iv(Decimal(v["c5_ref"][0]), Decimal(v["c5_ref"][1]))) for v in table.values())) + rel10 = rel_width(c_band_10) + worst = max(rel_width(Iv(Decimal(v["c5_torus_L_ge_10"][0]), Decimal(v["c5_torus_L_ge_10"][1]))) for v in table.values()) + checks["WIDTHS"] = bool(worst < Decimal("2e-6") and c_band_24.width() < c_band_24.lo * Decimal("1e-40")) + checks["SANDWICH_ORDERED"] = bool(not SANDWICH_VIOLATIONS) + checks["LIBRARY_EXACT"] = bool(library_exact()) + pinned = {"c_5_ref": C5_REF, "D_4": I_full, "F5|[0,1]": F5_band, "c5|[0,1]x[1/2,2] ref": c_band_ref, "pi": PI} + checks["PINNED"] = bool(all(str(pinned[k].lo).startswith(p) and str(pinned[k].hi).startswith(p) for k, p in PINNED.items())) + if len(checks) != 18: + raise ValueError("rule count changed") + passed = all(checks.values()) + + out = { + "object": "CL-C8-WINDOW-COEFFICIENT-D5-20261001-v1", + "scientific_effect": "NONE", + "certified": True, + "mutant": MUT, + "passed": passed, + "checks": checks, + "c8_band": {"B": "[0,1]", "K": "[1/2,2]", + "c5_reference": c_band_ref.pair(), "c5_reference_digits": common_prefix(c_band_ref), + "F5_B": F5_band.pair(), "c5_torus_every_L_ge_10_every_frame": c_band_10.pair(), + "c5_torus_L_24": c_band_24.pair(), "relative_half_width_L_ge_10": str(rel10)}, + "full_window": {"c_5_ref": C5_REF.pair(), "c5_torus_every_L_ge_10": c_full_10.pair(), "c5_torus_L_24": c_full_24.pair(), + "Math200_c_5_ref_digits": C5_REF_200}, + "windows": table, + "worst_relative_half_width_L_ge_10": str(worst), + "transfer": {"E5_10": E10.pair(), "E5_12": E12.pair(), "E5_24": E24.pair(), + "eps_L_ge_10": str(S10.eps), "eps_L_ge_12": str(S12.eps), "eps_L_24": str(S24.eps), "eps_E0": str(S0.eps), + "lambda_floor": str(LAMBDA0), "lambda_min_exact": "(8 - 2 sqrt13)/3", + "tau2_L_ge_10": S10.tau2.pair(), "pG_pV_L_ge_10": (S10.pG * S10.pV).pair()}, + "reference": {"C_prime": [[str(x) for x in r] for r in CPRIME_REF], "A_given_f_mean": [str(x) for x in mean], + "tau2": str(tau2_ref), "det_Cov_V": str(DETV_REF), + "D_4_quadrature": I_full.pair(), "D_4_closed_form_Math202": D4_CF.pair(), "coarse_quadrature": coarse.pair(), + "F_4_pieces": {"%s" % (k,): [str(x) for x in v] for k, v in sorted(nonzero.items(), key=lambda kv: str(kv[0]))}, + "cancelled_kinds": sorted("%s" % (k,) for k, v in pieces4.items() if not trim(v))}, + "layers_float_control": layer_ctrl, + "crosschecks": cross, + "float_control": fctrl, + "tilted": tilt, + "constants": {"pi": PI.pair(), "Gamma(7/6)": GAMMA76.pair(), "(3/2)^(1/3)": CBRT32.pair()}, + "exact_relations": { + "window coefficient": "c^(5)_{B,K} = 144 int_{S^4} p_G(0) p_V(0) I_B(u) J_K(u) dsigma(u), I_B = E[1{f in B} det(A)^2 1{A<0} | V=0] ([LP] (11.3), section 15)", + "reference": "(f, A) | V=0: f ~ N(0, 2/3), A = Q - f I, Q the 4x4 GOE; I^ref_B = (sqrt(3/7)/(1536 pi)) int_0^inf e^{-3T^2/112} F_4(T) [Phi(sqrt(7/2)(b_+ - T/7)) - Phi(sqrt(7/2)(b_- - T/7))] dT", + "sandwich": "(1-eps) C'_ref <= C' <= (1+eps) C'_ref => (1-eps)^(19/2)/(1+eps)^(11/2) I^ref_{B/sqrt(1-eps)} <= I'_B <= (1+eps)^(19/2)/(1-eps)^(11/2) I^ref_{B/sqrt(1+eps)}", + "epsilon": "eps = ||C' - C'_ref||_F / lambda0, lambda0 = 1/4 <= lambda_min(C'_ref) = (8 - 2 sqrt13)/3", + "image bound": "E^(5)_L = 60500 (76 L^6 + 15) exp(-L^2/2)", + }, + } + sys.stdout.write(json.dumps(out, indent=1) + "\n") + sys.stderr.write("seconds %.1f\n" % (time.time() - t0)) + sys.exit(0 if passed else 1) + + +if __name__ == "__main__": + main()