#!/usr/bin/env python3
r"""banana-4loop-evaluate.py -- the four-loop equal-mass banana I_{11111} (a Calabi-Yau
threefold: Picard-Fuchs operator AESZ #34 of the Hulek-Verrill family), d = 2-2eps,
m^2 = 1.  Standalone evaluator of the explicit log-Frobenius form of the complete
five-master Laurent window eps^{-4}..eps^0 at any Euclidean point p^2 < 0.

REQUIREMENTS: python3 with the mpmath library.  Nothing else -- no network, no
computer-algebra system, no reduction software, no data files: everything a run needs
(the exact connection, the boundary vector, the held-out reference values) is written
into this file, and a sha256 pin of that block is checked before any computation.

THE MASTERS (propagators k_i^2 - 1, i = 1..4, and (k1+k2+k3+k4-p)^2 - 1; irreducible
numerators D6 = (k1-p)^2 and D10 = (k1+k2)^2):
    m0 = I[1,1,1,1,0]                 = tadpole^4 = Gamma(eps)^4       (exact)
    m1 = I[1,1,1,1,1]                 = the top banana I_{11111}
    m2 = I[1,1,1,1,1] with D6^2 in the numerator
    m3 = I[1,1,1,1,1] with D10^2 in the numerator
    m4 = I[1,1,1,1,1] with D6^3 in the numerator
Measure d^dk/(i pi^{d/2}) per loop, no e^{gamma_E eps} prefactor (the raw convention
of the auxiliary-mass-flow references).  A run prints the window eps^{-4}..eps^0 of all
five masters; the poles of m1 vanish identically, so its finite part is the value.

THE FORM.  Let z = -1/p^2 (the MUM point z = 0 is p^2 -> infinity), L = log z, and
M-hat = diag(z^a) e^{4 gamma_E eps} (m0..m4) with a = (0,-1,1,1,2).  The masters obey
an exact first-order theta-system   theta M-hat = C(z,eps) M-hat   (theta = z d/dz)
whose integer polynomial data are written below: C = Num(z)/den(z) with
den = 20 (1+z)(1+9z)(1+25z), graded over the window.  Its eps^0 maximal-cut block is
the Picard-Fuchs operator
    L4 = th^4 + z (35 th^4 + 70 th^3 + 63 th^2 + 28 th + 5)
             + z^2 (259 th^4 + 1036 th^3 + 1580 th^2 + 1088 th + 285)
             + 225 z^3 (th+1)^2 (th+2)^2,                          th = z d/dz,
whose holomorphic solution is the Hulek-Verrill period  varpi_0(z) = sum_n A_n (-z)^n,
A_n = sum_{i+j+k+l+m=n} (n!/(i! j! k! l! m!))^2 = 1, 5, 45, 545, 7885, ...  The system is
regular at z = 0 with a nilpotent residue C0 (nilpotency index 8, checked exactly in
integers at every load), so the full solution is the explicit log-Frobenius series
    F(z) = sum_{n>=0} z^n sum_{j=0}^{7} F_{n,j} L^j,          F_0(L) = exp(C0 L) v,
with every F_{n,j} generated by the exact linear recursion
    (n den(0) - Num(0)) F_{n,j} = [ sum_{m=1..6} (Num_m - den_m ((n-m) + d/dL)) F_{n-m} ]_j
                                  - den(0) (j+1) F_{n,j+1}.
THE BOUNDARY VECTOR v (the complete MUM datum, e^{4 gamma_E eps} frame) is derived, not
fit: requiring (i) the tadpole block Gamma(1+eps)^4 e^{4 gamma_E eps}, (ii) the vanishing
of the top master's pole window, and (iii) the n = 0 log-tower to reproduce the classical
large-momentum boundary of the equal-mass banana (Boenisch-Duhr-Fischbach-Klemm-Nega,
arXiv:2108.05310; Poegel-Wang-Weinzierl, arXiv:2211.04292, the alternating Gamma-product
sum over hard and soft regions) gives a rank-25 linear system through the C0 log-chains
whose unique solution is
    m0:  eps^{-4..0} = 1, 0, 2 z2, -(4/3) z3, 6 z4         (= Gamma(1+eps)^4 e^{4 gamma_E eps})
    m1:  0, 0, 0, 0, 0
    m2:  -1, -2, -2-2 z2, -2-4 z2+(4/3) z3, -50-4 z2+(104/3) z3-6 z4
    m3:  -3/2, -1, -3 z2, -2 z2+2 z3, -60+(52/3) z3-9 z4
    m4:  1, 3, 9/2+2 z2, 21/4+6 z2-(4/3) z3, 453/8+9 z2-52 z3+6 z4
with z_k = zeta(k).  An independent extraction (backward transport of a recorded
p^2 = -11 value onto the Frobenius basis, integer-relation search layer by layer, two
precisions) returned the same expressions.

EVALUATION.  The local series is summed at z0 = 1/128 and continued to the target by
eps-graded Taylor transport of the same exact connection along the Euclidean axis (the
system's poles sit at p^2 in {0, 1, 9, 25} only; the physical layers are regular at
p^2 = 0 and the nearest true singularity is p^2 = 25); the window is then mapped back to
the raw convention by the exact e^{-4 gamma_E eps} mixing.  Every truncation is certified
at run time and fail-closed: the local series is accepted only when a trailing-8-term
geometric tail envelope (ratio r = 25 z0, the exact distance to the nearest z-frame pole)
beats 10^-(dps+12); each transport step is accepted only when its own trailing-8-term
envelope (ratio |h|/R, R the exact distance to the pole set) beats the same tolerance;
a miss continues the SAME recursion exactly to 8x the starting depth and then refuses
(RuntimeError, nonzero exit).  The accepted per-step bounds are summed into the printed
certified BOUND on every value.  The starting depths are seeds only, never the answer.

WHAT A RUN CHECKS (every check is a RAISING gate: a miss names itself and exits 1):
  * structural: the embedded connection's denominator is 20(1+z)(1+9z)(1+25z) and its
    residue Num(0)/20 is nilpotent of index exactly 8, both checked in exact integers;
  * the tadpole tower m0 against the exact expansion of Gamma(eps)^4 (analytic, no
    stored digits involved);
  * the held-out references: independent auxiliary-mass-flow (AMFlow) towers of all
    21 non-vanishing layers at p^2 = -2 and p^2 = -7 (about 67 digits each, capped by
    their own precision) and 100-digit Bessel-moment references for m1 at eps^0.  None
    of these entered the construction of the form;
  * positive controls: the AESZ-34 recurrence returning the Hulek-Verrill integers
    1, 5, 45, 545, 7885, 127905; |L4[varpi_0]| at z = 1/128; the n = 0 log-tower against
    the literature Gamma-product at L = -3; and the three-loop sibling identity
    int_0^inf x K_0(x)^4 dx = 7 zeta(3)/8 (the p^2 = 0 value of the three-loop K3 banana,
    computed by live quadrature);
  * --bessel (opt-in, alone or with --full): the live independent oracle
    I_{11111}|_{eps^0} = -16 int_0^inf x J_0(x sqrt(-p^2)) K_0(x)^5 dx, computed by
    quadrature at run time at a 115-digit working cap; it shares no code path with the
    connection or with the AMFlow references.  Bessel-K quadrature at that precision is
    slow (many minutes per point), which is why it is not part of --full by default.

MODES
  python3 banana-4loop-evaluate.py            # QUICK default: p^2 = -2 at 30 quoted digits
                                              #   (+30 working), all gates, cheap controls
  python3 banana-4loop-evaluate.py --full     # the paper's held-out table against the
                                              #   stored references: p^2 = -2 and -7 at
                                              #   100 digits, full-depth controls (minutes)
  python3 banana-4loop-evaluate.py --full --bessel   # adds the table's live-oracle rows
                                              #   (long: the 115-digit quadratures run
                                              #   many minutes per point)
  python3 banana-4loop-evaluate.py --dps 60 --pp -5 --pp=-11/2   # any Euclidean points
  python3 banana-4loop-evaluate.py --check    # two-precision self-agreement gate: the run
                                              #   is repeated at dps+60 guard digits and the
                                              #   worst nonzero layer must agree to dps+10
                                              #   (long at 100 digits)
  python3 banana-4loop-evaluate.py --mutate   # control: one connection entry perturbed
                                              #   by 1e-6; the held-out gate MUST collapse
                                              #   and the run MUST exit nonzero
The quick default finishes in about a minute on a laptop-class machine (mpmath on its
gmpy2 backend; the pure-Python backend takes roughly half again as long) and prints its
first line at once; --full takes a few minutes; --bessel and --check at 100 digits are
long runs (tens of minutes).  Each mode prints its own measured wall time.

THE PAPER'S TABLE (the four-loop equal-mass banana section of the portfolio paper) was
produced by this form at 100 working digits at the two held-out points and reads, for
p^2 = -2 / -7: m1 eps^0 vs AMFlow 67 / 67 digits; worst of the 21 layers vs AMFlow
67 / 67; m1 eps^0 vs the 100-digit Bessel references 99 / 100; m1 eps^0 vs the live
Bessel quadrature 116 / 116 (saturating the oracle's 115-digit cap); self-agreement at
sixty guard digits 125 (p^2 = -7); mutation control 67 -> 3 at both points.  --full
recomputes the first three rows and gates each against the printed value (floor: printed
value minus one digit); --full --bessel adds the fourth; --check and --mutate reproduce
the last two.

HONESTY NOTES
  * The AMFlow comparisons are capped at about 67 digits by the references' own precision
    and the Bessel-reference comparisons at 100 digits by the stored strings; only the
    live Bessel oracle and the two-precision self-agreement grow with dps.  The quick
    default certifies 30 digits and typically agrees with the references to about 55.
  * Only Euclidean p^2 < 0 is evaluated (the transport axis is singularity-free there);
    the physical region p^2 > 0 is not part of this script.
  * The quadratures (--bessel, the K_0^4 control) are gate legs only: they never enter
    the value path.

EXIT CODES: 0 every check passed; 1 a check failed or a certified bound could not be met
(what --mutate must produce); 2 usage error (e.g. a point with p^2 >= 0); 3 the embedded
data block does not match its sha256 pin (a tampered or truncated copy; refused before
any computation).
"""
import argparse, hashlib, json, sys, time
from fractions import Fraction

EXIT_OK, EXIT_GATE, EXIT_USAGE, EXIT_PIN = 0, 1, 2, 3

# ---------------------------------------------------------------------------
# The embedded data block: the exact theta-system in both frames (integer polynomial
# coefficients as strings), the rescale exponents, the derived boundary constants
# (named in the zeta-ring), and the held-out reference values.  Pinned below.
# ---------------------------------------------------------------------------
DATA_TEXT = r"""{"pp_frame":{"den":["0","-4500","5180","-700","20"],"num":{"5,0":["-7050","-2600","50"],"5,5":["-3650","-9810","-1110","-150"],"5,10":["4050","650"],"5,15":["0","-200"],"5,20":["-400"],"6,0":["19450","1300","-750"],"6,1":["-7050","-2600","50"],"6,5":["9650","14090","5270","430"],"6,6":["-3650","-9810","-1110","-150"],"6,10":["-10850","-2150"],"6,11":["4050","650"],"6,15":["0","1200"],"6,16":["0","-200"],"6,20":["1200"],"6,21":["-400"],"7,0":["-4200","5000","1200"],"7,1":["19450","1300","-750"],"7,2":["-7050","-2600","50"],"7,5":["-600","5760","-1080","-240"],"7,6":["9650","14090","5270","430"],"7,7":["-3650","-9810","-1110","-150"],"7,10":["900","900"],"7,11":["-10850","-2150"],"7,12":["4050","650"],"7,15":["0","-1200"],"7,16":["0","1200"],"7,17":["0","-200"],"7,20":["-300"],"7,21":["1200"],"7,22":["-400"],"8,0":["-600","7400","1200"],"8,1":["-4200","5000","1200"],"8,2":["19450","1300","-750"],"8,3":["-7050","-2600","50"],"8,5":["-600","5760","-1080","-240"],"8,6":["-600","5760","-1080","-240"],"8,7":["9650","14090","5270","430"],"8,8":["-3650","-9810","-1110","-150"],"8,10":["900","900"],"8,11":["900","900"],"8,12":["-10850","-2150"],"8,13":["4050","650"],"8,15":["0","-1200"],"8,16":["0","-1200"],"8,17":["0","1200"],"8,18":["0","-200"],"8,20":["-300"],"8,21":["-300"],"8,22":["1200"],"8,23":["-400"],"9,0":["3000","9800","1200"],"9,1":["-600","7400","1200"],"9,2":["-4200","5000","1200"],"9,3":["19450","1300","-750"],"9,4":["-7050","-2600","50"],"9,5":["-600","5760","-1080","-240"],"9,6":["-600","5760","-1080","-240"],"9,7":["-600","5760","-1080","-240"],"9,8":["9650","14090","5270","430"],"9,9":["-3650","-9810","-1110","-150"],"9,10":["900","900"],"9,11":["900","900"],"9,12":["900","900"],"9,13":["-10850","-2150"],"9,14":["4050","650"],"9,15":["0","-1200"],"9,16":["0","-1200"],"9,17":["0","-1200"],"9,18":["0","1200"],"9,19":["0","-200"],"9,20":["-300"],"9,21":["-300"],"9,22":["-300"],"9,23":["1200"],"9,24":["-400"],"10,0":["-7050","-43760","-9700","-960","30"],"10,5":["-3650","-43190","-39876","-5980","-1498","-14"],"10,10":["4050","21710","4190","130"],"10,15":["0","-200","-1040","-40"],"10,20":["-400","-2080","-80"],"11,0":["41950","72040","18580","-4440","-130"],"11,1":["-7050","-43760","-9700","-960","30"],"11,5":["14150","64490","79452","26292","3966","66"],"11,6":["-3650","-43190","-39876","-5980","-1498","-14"],"11,10":["-15350","-53390","-14050","-410"],"11,11":["4050","21710","4190","130"],"11,15":["0","1200","6240","240"],"11,16":["0","-200","-1040","-40"],"11,20":["1200","6240","240"],"11,21":["-400","-2080","-80"],"12,0":["-4200","-16840","26360","7240","240"],"12,1":["41950","72040","18580","-4440","-130"],"12,2":["-7050","-43760","-9700","-960","30"],"12,5":["-600","2640","28752","-4704","-1464","-48"],"12,6":["14150","64490","79452","26292","3966","66"],"12,7":["-3650","-43190","-39876","-5980","-1498","-14"],"12,10":["900","5580","4860","180"],"12,11":["-15350","-53390","-14050","-410"],"12,12":["4050","21710","4190","130"],"12,15":["0","-1200","-6240","-240"],"12,16":["0","1200","6240","240"],"12,17":["0","-200","-1040","-40"],"12,20":["-300","-1560","-60"],"12,21":["1200","6240","240"],"12,22":["-400","-2080","-80"],"13,0":["-600","4280","39560","7720","240"],"13,1":["-4200","-16840","26360","7240","240"],"13,2":["41950","72040","18580","-4440","-130"],"13,3":["-7050","-43760","-9700","-960","30"],"13,5":["-600","2640","28752","-4704","-1464","-48"],"13,6":["-600","2640","28752","-4704","-1464","-48"],"13,7":["14150","64490","79452","26292","3966","66"],"13,8":["-3650","-43190","-39876","-5980","-1498","-14"],"13,10":["900","5580","4860","180"],"13,11":["900","5580","4860","180"],"13,12":["-15350","-53390","-14050","-410"],"13,13":["4050","21710","4190","130"],"13,15":["0","-1200","-6240","-240"],"13,16":["0","-1200","-6240","-240"],"13,17":["0","1200","6240","240"],"13,18":["0","-200","-1040","-40"],"13,20":["-300","-1560","-60"],"13,21":["-300","-1560","-60"],"13,22":["1200","6240","240"],"13,23":["-400","-2080","-80"],"14,0":["3000","25400","52760","8200","240"],"14,1":["-600","4280","39560","7720","240"],"14,2":["-4200","-16840","26360","7240","240"],"14,3":["41950","72040","18580","-4440","-130"],"14,4":["-7050","-43760","-9700","-960","30"],"14,5":["-600","2640","28752","-4704","-1464","-48"],"14,6":["-600","2640","28752","-4704","-1464","-48"],"14,7":["-600","2640","28752","-4704","-1464","-48"],"14,8":["14150","64490","79452","26292","3966","66"],"14,9":["-3650","-43190","-39876","-5980","-1498","-14"],"14,10":["900","5580","4860","180"],"14,11":["900","5580","4860","180"],"14,12":["900","5580","4860","180"],"14,13":["-15350","-53390","-14050","-410"],"14,14":["4050","21710","4190","130"],"14,15":["0","-1200","-6240","-240"],"14,16":["0","-1200","-6240","-240"],"14,17":["0","-1200","-6240","-240"],"14,18":["0","1200","6240","240"],"14,19":["0","-200","-1040","-40"],"14,20":["-300","-1560","-60"],"14,21":["-300","-1560","-60"],"14,22":["-300","-1560","-60"],"14,23":["1200","6240","240"],"14,24":["-400","-2080","-80"],"15,0":["-36675","-30520","6610","-880","25"],"15,5":["-20775","-61165","-10702","-1538","-27","-1"],"15,10":["23175","6815","85","5"],"15,15":["0","-1200","-80"],"15,20":["-2400","-160"],"16,0":["111075","18680","-970","-800","15"],"16,1":["-36675","-30520","6610","-880","25"],"16,5":["56775","91045","35302","5162","131","1"],"16,6":["-20775","-61165","-10702","-1538","-27","-1"],"16,10":["-63975","-18535","-685","-5"],"16,11":["23175","6815","85","5"],"16,15":["0","7200","480"],"16,16":["0","-1200","-80"],"16,20":["7200","480"],"16,21":["-2400","-160"],"17,0":["-25200","28320","9200","480"],"17,1":["111075","18680","-970","-800","15"],"17,2":["-36675","-30520","6610","-880","25"],"17,5":["-3600","34320","-4176","-1872","-96"],"17,6":["56775","91045","35302","5162","131","1"],"17,7":["-20775","-61165","-10702","-1538","-27","-1"],"17,10":["5400","5760","360"],"17,11":["-63975","-18535","-685","-5"],"17,12":["23175","6815","85","5"],"17,15":["0","-7200","-480"],"17,16":["0","7200","480"],"17,17":["0","-1200","-80"],"17,20":["-1800","-120"],"17,21":["7200","480"],"17,22":["-2400","-160"],"18,0":["-3600","44160","10160","480"],"18,1":["-25200","28320","9200","480"],"18,2":["111075","18680","-970","-800","15"],"18,3":["-36675","-30520","6610","-880","25"],"18,5":["-3600","34320","-4176","-1872","-96"],"18,6":["-3600","34320","-4176","-1872","-96"],"18,7":["56775","91045","35302","5162","131","1"],"18,8":["-20775","-61165","-10702","-1538","-27","-1"],"18,10":["5400","5760","360"],"18,11":["5400","5760","360"],"18,12":["-63975","-18535","-685","-5"],"18,13":["23175","6815","85","5"],"18,15":["0","-7200","-480"],"18,16":["0","-7200","-480"],"18,17":["0","7200","480"],"18,18":["0","-1200","-80"],"18,20":["-1800","-120"],"18,21":["-1800","-120"],"18,22":["7200","480"],"18,23":["-2400","-160"],"19,0":["18000","60000","11120","480"],"19,1":["-3600","44160","10160","480"],"19,2":["-25200","28320","9200","480"],"19,3":["111075","18680","-970","-800","15"],"19,4":["-36675","-30520","6610","-880","25"],"19,5":["-3600","34320","-4176","-1872","-96"],"19,6":["-3600","34320","-4176","-1872","-96"],"19,7":["-3600","34320","-4176","-1872","-96"],"19,8":["56775","91045","35302","5162","131","1"],"19,9":["-20775","-61165","-10702","-1538","-27","-1"],"19,10":["5400","5760","360"],"19,11":["5400","5760","360"],"19,12":["5400","5760","360"],"19,13":["-63975","-18535","-685","-5"],"19,14":["23175","6815","85","5"],"19,15":["0","-7200","-480"],"19,16":["0","-7200","-480"],"19,17":["0","-7200","-480"],"19,18":["0","7200","480"],"19,19":["0","-1200","-80"],"19,20":["-1800","-120"],"19,21":["-1800","-120"],"19,22":["-1800","-120"],"19,23":["7200","480"],"19,24":["-2400","-160"],"20,0":["-7050","-113390","-102340","-23420","430","10"],"20,5":["-3650","-90780","-181014","-83624","-16270","-1532","38"],"20,10":["4050","52040","58700","5640","-110"],"20,15":["0","-200","-2760","-2200","40"],"20,20":["-400","-5520","-4400","80"],"21,0":["167950","116770","229020","7380","-9290","170"],"21,1":["-7050","-113390","-102340","-23420","430","10"],"21,5":["14150","159180","311178","212584","51322","5388","-138"],"21,6":["-3650","-90780","-181014","-83624","-16270","-1532","38"],"21,10":["-10850","-160880","-138660","-22880","470"],"21,11":["4050","52040","58700","5640","-110"],"21,15":["0","1200","16560","13200","-240"],"21,16":["0","-200","-2760","-2200","40"],"21,20":["-3300","21740","12500","-220"],"21,21":["-400","-5520","-4400","80"],"22,0":["49800","-115120","32400","72160","12200","-240"],"22,1":["167950","116770","229020","7380","-9290","170"],"22,2":["-7050","-113390","-102340","-23420","430","10"],"22,5":["-600","-2520","71808","48336","-16344","-2424","48"],"22,6":["14150","159180","311178","212584","51322","5388","-138"],"22,7":["-3650","-90780","-181014","-83624","-16270","-1532","38"],"22,10":["900","13320","22320","9720","-180"],"22,11":["-10850","-160880","-138660","-22880","470"],"22,12":["4050","52040","58700","5640","-110"],"22,15":["0","-1200","-16560","-13200","240"],"22,16":["0","1200","16560","13200","-240"],"22,17":["0","-200","-2760","-2200","40"],"22,20":["-300","-4140","-3300","60"],"22,21":["-3300","21740","12500","-220"],"22,22":["-400","-5520","-4400","80"],"23,0":["53400","-63040","105120","97840","11720","-240"],"23,1":["49800","-115120","32400","72160","12200","-240"],"23,2":["167950","116770","229020","7380","-9290","170"],"23,3":["-7050","-113390","-102340","-23420","430","10"],"23,5":["-600","-2520","71808","48336","-16344","-2424","48"],"23,6":["-600","-2520","71808","48336","-16344","-2424","48"],"23,7":["14150","159180","311178","212584","51322","5388","-138"],"23,8":["-3650","-90780","-181014","-83624","-16270","-1532","38"],"23,10":["900","13320","22320","9720","-180"],"23,11":["900","13320","22320","9720","-180"],"23,12":["-10850","-160880","-138660","-22880","470"],"23,13":["4050","52040","58700","5640","-110"],"23,15":["0","-1200","-16560","-13200","240"],"23,16":["0","-1200","-16560","-13200","240"],"23,17":["0","1200","16560","13200","-240"],"23,18":["0","-200","-2760","-2200","40"],"23,20":["-300","-4140","-3300","60"],"23,21":["-300","-4140","-3300","60"],"23,22":["-3300","21740","12500","-220"],"23,23":["-400","-5520","-4400","80"],"24,0":["57000","-10960","177840","123520","11240","-240"],"24,1":["53400","-63040","105120","97840","11720","-240"],"24,2":["49800","-115120","32400","72160","12200","-240"],"24,3":["167950","116770","229020","7380","-9290","170"],"24,4":["-7050","-113390","-102340","-23420","430","10"],"24,5":["-600","-2520","71808","48336","-16344","-2424","48"],"24,6":["-600","-2520","71808","48336","-16344","-2424","48"],"24,7":["-600","-2520","71808","48336","-16344","-2424","48"],"24,8":["14150","159180","311178","212584","51322","5388","-138"],"24,9":["-3650","-90780","-181014","-83624","-16270","-1532","38"],"24,10":["900","13320","22320","9720","-180"],"24,11":["900","13320","22320","9720","-180"],"24,12":["900","13320","22320","9720","-180"],"24,13":["-10850","-160880","-138660","-22880","470"],"24,14":["4050","52040","58700","5640","-110"],"24,15":["0","-1200","-16560","-13200","240"],"24,16":["0","-1200","-16560","-13200","240"],"24,17":["0","-1200","-16560","-13200","240"],"24,18":["0","1200","16560","13200","-240"],"24,19":["0","-200","-2760","-2200","40"],"24,20":["-300","-4140","-3300","60"],"24,21":["-300","-4140","-3300","60"],"24,22":["-300","-4140","-3300","60"],"24,23":["-3300","21740","12500","-220"],"24,24":["-400","-5520","-4400","80"]}},"z_frame":{"den":["20","700","5180","4500"],"num":{"5,0":["50","2600","-7050"],"5,5":["130","-1810","4630","-8150"],"5,10":["-650","4050"],"5,15":["200"],"5,20":["-400"],"6,0":["-750","-1300","19450"],"6,1":["50","2600","-7050"],"6,5":["-430","5270","-14090","9650"],"6,6":["130","-1810","4630","-8150"],"6,10":["2150","-10850"],"6,11":["-650","4050"],"6,15":["-1200"],"6,16":["200"],"6,20":["1200"],"6,21":["-400"],"7,0":["1200","-5000","-4200"],"7,1":["-750","-1300","19450"],"7,2":["50","2600","-7050"],"7,5":["240","-1080","-5760","-600"],"7,6":["-430","5270","-14090","9650"],"7,7":["130","-1810","4630","-8150"],"7,10":["-900","900"],"7,11":["2150","-10850"],"7,12":["-650","4050"],"7,15":["1200"],"7,16":["-1200"],"7,17":["200"],"7,20":["-300"],"7,21":["1200"],"7,22":["-400"],"8,0":["1200","-7400","-600"],"8,1":["1200","-5000","-4200"],"8,2":["-750","-1300","19450"],"8,3":["50","2600","-7050"],"8,5":["240","-1080","-5760","-600"],"8,6":["240","-1080","-5760","-600"],"8,7":["-430","5270","-14090","9650"],"8,8":["130","-1810","4630","-8150"],"8,10":["-900","900"],"8,11":["-900","900"],"8,12":["2150","-10850"],"8,13":["-650","4050"],"8,15":["1200"],"8,16":["1200"],"8,17":["-1200"],"8,18":["200"],"8,20":["-300"],"8,21":["-300"],"8,22":["1200"],"8,23":["-400"],"9,0":["1200","-9800","3000"],"9,1":["1200","-7400","-600"],"9,2":["1200","-5000","-4200"],"9,3":["-750","-1300","19450"],"9,4":["50","2600","-7050"],"9,5":["240","-1080","-5760","-600"],"9,6":["240","-1080","-5760","-600"],"9,7":["240","-1080","-5760","-600"],"9,8":["-430","5270","-14090","9650"],"9,9":["130","-1810","4630","-8150"],"9,10":["-900","900"],"9,11":["-900","900"],"9,12":["-900","900"],"9,13":["2150","-10850"],"9,14":["-650","4050"],"9,15":["1200"],"9,16":["1200"],"9,17":["1200"],"9,18":["-1200"],"9,19":["200"],"9,20":["-300"],"9,21":["-300"],"9,22":["-300"],"9,23":["1200"],"9,24":["-400"],"10,0":["30","960","-9700","43760","-7050"],"10,5":["14","-1498","5980","-39876","43190","-3650"],"10,10":["-110","4890","-16530","8550"],"10,15":["40","-1040","200"],"10,20":["-80","2080","-400"],"11,0":["-130","4440","18580","-72040","41950"],"11,1":["30","960","-9700","43760","-7050"],"11,5":["-66","3966","-26292","79452","-64490","14150"],"11,6":["14","-1498","5980","-39876","43190","-3650"],"11,10":["410","-14050","53390","-15350"],"11,11":["-110","4890","-16530","8550"],"11,15":["-240","6240","-1200"],"11,16":["40","-1040","200"],"11,20":["240","-6240","1200"],"11,21":["-80","2080","-400"],"12,0":["240","-7240","26360","16840","-4200"],"12,1":["-130","4440","18580","-72040","41950"],"12,2":["30","960","-9700","43760","-7050"],"12,5":["48","-1464","4704","28752","-2640","-600"],"12,6":["-66","3966","-26292","79452","-64490","14150"],"12,7":["14","-1498","5980","-39876","43190","-3650"],"12,10":["-180","4860","-5580","900"],"12,11":["410","-14050","53390","-15350"],"12,12":["-110","4890","-16530","8550"],"12,15":["240","-6240","1200"],"12,16":["-240","6240","-1200"],"12,17":["40","-1040","200"],"12,20":["-60","1560","-300"],"12,21":["240","-6240","1200"],"12,22":["-80","2080","-400"],"13,0":["240","-7720","39560","-4280","-600"],"13,1":["240","-7240","26360","16840","-4200"],"13,2":["-130","4440","18580","-72040","41950"],"13,3":["30","960","-9700","43760","-7050"],"13,5":["48","-1464","4704","28752","-2640","-600"],"13,6":["48","-1464","4704","28752","-2640","-600"],"13,7":["-66","3966","-26292","79452","-64490","14150"],"13,8":["14","-1498","5980","-39876","43190","-3650"],"13,10":["-180","4860","-5580","900"],"13,11":["-180","4860","-5580","900"],"13,12":["410","-14050","53390","-15350"],"13,13":["-110","4890","-16530","8550"],"13,15":["240","-6240","1200"],"13,16":["240","-6240","1200"],"13,17":["-240","6240","-1200"],"13,18":["40","-1040","200"],"13,20":["-60","1560","-300"],"13,21":["-60","1560","-300"],"13,22":["240","-6240","1200"],"13,23":["-80","2080","-400"],"14,0":["240","-8200","52760","-25400","3000"],"14,1":["240","-7720","39560","-4280","-600"],"14,2":["240","-7240","26360","16840","-4200"],"14,3":["-130","4440","18580","-72040","41950"],"14,4":["30","960","-9700","43760","-7050"],"14,5":["48","-1464","4704","28752","-2640","-600"],"14,6":["48","-1464","4704","28752","-2640","-600"],"14,7":["48","-1464","4704","28752","-2640","-600"],"14,8":["-66","3966","-26292","79452","-64490","14150"],"14,9":["14","-1498","5980","-39876","43190","-3650"],"14,10":["-180","4860","-5580","900"],"14,11":["-180","4860","-5580","900"],"14,12":["-180","4860","-5580","900"],"14,13":["410","-14050","53390","-15350"],"14,14":["-110","4890","-16530","8550"],"14,15":["240","-6240","1200"],"14,16":["240","-6240","1200"],"14,17":["240","-6240","1200"],"14,18":["-240","6240","-1200"],"14,19":["40","-1040","200"],"14,20":["-60","1560","-300"],"14,21":["-60","1560","-300"],"14,22":["-60","1560","-300"],"14,23":["240","-6240","1200"],"14,24":["-80","2080","-400"],"15,0":["25","880","6610","30520","-36675"],"15,5":["1","-27","1538","-10702","61165","-20775"],"15,10":["-5","85","-6815","23175"],"15,15":["20","620","6380","4500"],"15,20":["0","160","-2400"],"16,0":["15","800","-970","-18680","111075"],"16,1":["25","880","6610","30520","-36675"],"16,5":["-1","131","-5162","35302","-91045","56775"],"16,6":["1","-27","1538","-10702","61165","-20775"],"16,10":["5","-685","18535","-63975"],"16,11":["-5","85","-6815","23175"],"16,15":["0","480","-7200"],"16,16":["20","620","6380","4500"],"16,20":["0","-480","7200"],"16,21":["0","160","-2400"],"17,0":["0","-480","9200","-28320","-25200"],"17,1":["15","800","-970","-18680","111075"],"17,2":["25","880","6610","30520","-36675"],"17,5":["0","-96","1872","-4176","-34320","-3600"],"17,6":["-1","131","-5162","35302","-91045","56775"],"17,7":["1","-27","1538","-10702","61165","-20775"],"17,10":["0","360","-5760","5400"],"17,11":["5","-685","18535","-63975"],"17,12":["-5","85","-6815","23175"],"17,15":["0","-480","7200"],"17,16":["0","480","-7200"],"17,17":["20","620","6380","4500"],"17,20":["0","120","-1800"],"17,21":["0","-480","7200"],"17,22":["0","160","-2400"],"18,0":["0","-480","10160","-44160","-3600"],"18,1":["0","-480","9200","-28320","-25200"],"18,2":["15","800","-970","-18680","111075"],"18,3":["25","880","6610","30520","-36675"],"18,5":["0","-96","1872","-4176","-34320","-3600"],"18,6":["0","-96","1872","-4176","-34320","-3600"],"18,7":["-1","131","-5162","35302","-91045","56775"],"18,8":["1","-27","1538","-10702","61165","-20775"],"18,10":["0","360","-5760","5400"],"18,11":["0","360","-5760","5400"],"18,12":["5","-685","18535","-63975"],"18,13":["-5","85","-6815","23175"],"18,15":["0","-480","7200"],"18,16":["0","-480","7200"],"18,17":["0","480","-7200"],"18,18":["20","620","6380","4500"],"18,20":["0","120","-1800"],"18,21":["0","120","-1800"],"18,22":["0","-480","7200"],"18,23":["0","160","-2400"],"19,0":["0","-480","11120","-60000","18000"],"19,1":["0","-480","10160","-44160","-3600"],"19,2":["0","-480","9200","-28320","-25200"],"19,3":["15","800","-970","-18680","111075"],"19,4":["25","880","6610","30520","-36675"],"19,5":["0","-96","1872","-4176","-34320","-3600"],"19,6":["0","-96","1872","-4176","-34320","-3600"],"19,7":["0","-96","1872","-4176","-34320","-3600"],"19,8":["-1","131","-5162","35302","-91045","56775"],"19,9":["1","-27","1538","-10702","61165","-20775"],"19,10":["0","360","-5760","5400"],"19,11":["0","360","-5760","5400"],"19,12":["0","360","-5760","5400"],"19,13":["5","-685","18535","-63975"],"19,14":["-5","85","-6815","23175"],"19,15":["0","-480","7200"],"19,16":["0","-480","7200"],"19,17":["0","-480","7200"],"19,18":["0","480","-7200"],"19,19":["20","620","6380","4500"],"19,20":["0","120","-1800"],"19,21":["0","120","-1800"],"19,22":["0","120","-1800"],"19,23":["0","-480","7200"],"19,24":["0","160","-2400"],"20,0":["-10","430","23420","-102340","113390","-7050"],"20,5":["38","1532","-16270","83624","-181014","90780","-3650"],"20,10":["-110","-5640","58700","-52040","4050"],"20,15":["40","2200","-2760","200"],"20,20":["-40","-3000","15880","8600"],"21,0":["-170","-9290","-7380","229020","-116770","167950"],"21,1":["-10","430","23420","-102340","113390","-7050"],"21,5":["-138","-5388","51322","-212584","311178","-159180","14150"],"21,6":["38","1532","-16270","83624","-181014","90780","-3650"],"21,10":["470","22880","-138660","160880","-10850"],"21,11":["-110","-5640","58700","-52040","4050"],"21,15":["-240","-13200","16560","-1200"],"21,16":["40","2200","-2760","200"],"21,20":["220","12500","-21740","-3300"],"21,21":["-40","-3000","15880","8600"],"22,0":["240","12200","-72160","32400","115120","49800"],"22,1":["-170","-9290","-7380","229020","-116770","167950"],"22,2":["-10","430","23420","-102340","113390","-7050"],"22,5":["48","2424","-16344","-48336","71808","2520","-600"],"22,6":["-138","-5388","51322","-212584","311178","-159180","14150"],"22,7":["38","1532","-16270","83624","-181014","90780","-3650"],"22,10":["-180","-9720","22320","-13320","900"],"22,11":["470","22880","-138660","160880","-10850"],"22,12":["-110","-5640","58700","-52040","4050"],"22,15":["240","13200","-16560","1200"],"22,16":["-240","-13200","16560","-1200"],"22,17":["40","2200","-2760","200"],"22,20":["-60","-3300","4140","-300"],"22,21":["220","12500","-21740","-3300"],"22,22":["-40","-3000","15880","8600"],"23,0":["240","11720","-97840","105120","63040","53400"],"23,1":["240","12200","-72160","32400","115120","49800"],"23,2":["-170","-9290","-7380","229020","-116770","167950"],"23,3":["-10","430","23420","-102340","113390","-7050"],"23,5":["48","2424","-16344","-48336","71808","2520","-600"],"23,6":["48","2424","-16344","-48336","71808","2520","-600"],"23,7":["-138","-5388","51322","-212584","311178","-159180","14150"],"23,8":["38","1532","-16270","83624","-181014","90780","-3650"],"23,10":["-180","-9720","22320","-13320","900"],"23,11":["-180","-9720","22320","-13320","900"],"23,12":["470","22880","-138660","160880","-10850"],"23,13":["-110","-5640","58700","-52040","4050"],"23,15":["240","13200","-16560","1200"],"23,16":["240","13200","-16560","1200"],"23,17":["-240","-13200","16560","-1200"],"23,18":["40","2200","-2760","200"],"23,20":["-60","-3300","4140","-300"],"23,21":["-60","-3300","4140","-300"],"23,22":["220","12500","-21740","-3300"],"23,23":["-40","-3000","15880","8600"],"24,0":["240","11240","-123520","177840","10960","57000"],"24,1":["240","11720","-97840","105120","63040","53400"],"24,2":["240","12200","-72160","32400","115120","49800"],"24,3":["-170","-9290","-7380","229020","-116770","167950"],"24,4":["-10","430","23420","-102340","113390","-7050"],"24,5":["48","2424","-16344","-48336","71808","2520","-600"],"24,6":["48","2424","-16344","-48336","71808","2520","-600"],"24,7":["48","2424","-16344","-48336","71808","2520","-600"],"24,8":["-138","-5388","51322","-212584","311178","-159180","14150"],"24,9":["38","1532","-16270","83624","-181014","90780","-3650"],"24,10":["-180","-9720","22320","-13320","900"],"24,11":["-180","-9720","22320","-13320","900"],"24,12":["-180","-9720","22320","-13320","900"],"24,13":["470","22880","-138660","160880","-10850"],"24,14":["-110","-5640","58700","-52040","4050"],"24,15":["240","13200","-16560","1200"],"24,16":["240","13200","-16560","1200"],"24,17":["240","13200","-16560","1200"],"24,18":["-240","-13200","16560","-1200"],"24,19":["40","2200","-2760","200"],"24,20":["-60","-3300","4140","-300"],"24,21":["-60","-3300","4140","-300"],"24,22":["-60","-3300","4140","-300"],"24,23":["220","12500","-21740","-3300"],"24,24":["-40","-3000","15880","8600"]}},"rescale_a":[0,-1,1,1,2],"constants_named":{"0,-4":{"1":"1"},"0,-3":{},"0,-2":{"z2":"2"},"0,-1":{"z3":"-4/3"},"0,0":{"z4":"6"},"1,-4":{},"1,-3":{},"1,-2":{},"1,-1":{},"1,0":{},"2,-4":{"1":"-1"},"2,-3":{"1":"-2"},"2,-2":{"1":"-2","z2":"-2"},"2,-1":{"1":"-2","z2":"-4","z3":"4/3"},"2,0":{"1":"-50","z2":"-4","z3":"104/3","z4":"-6"},"3,-4":{"1":"-3/2"},"3,-3":{"1":"-1"},"3,-2":{"z2":"-3"},"3,-1":{"z2":"-2","z3":"2"},"3,0":{"1":"-60","z3":"52/3","z4":"-9"},"4,-4":{"1":"1"},"4,-3":{"1":"3"},"4,-2":{"1":"9/2","z2":"2"},"4,-1":{"1":"21/4","z2":"6","z3":"-4/3"},"4,0":{"1":"453/8","z2":"9","z3":"-52","z4":"6"}},"gate_amflow_heldout":{"-2":{"0,-4":"0.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999948398","0,-3":"-2.3088626596061314424260483603296097241686373437596943952230689395394709071106586837477882531669868658030280051","0,-2":"5.9552915241582022674918394241340041917132369244106348206777831627581412903724551049573639240681199551914671214","0,-1":"-11.249961739225280199971549027011689132771264106466026557278235543753520854139542226381583945090295707521082238","0,0":"20.147423583662158774752631835604440822313098315879883502473476112112100242775262906636702997599948891498563540","1,0":"-39.374358516940218859656507967746135822279959247934525023677415656424721432088800598579803881090976194342726745","2,-4":"2.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999980554116113","2,-3":"-10.926587978818394327278145080988829172505912031279083185669206818618412721331976051243364759002564756469428889","2,-2":"23.101325210899132572179711713720451471814260148270682042925625246432307499560000049764417185063723247688717697","2,-1":"-52.335600675884123900177811336252645268492190642001841373653563524135244095450310072295769066298916328186253038","2,0":"235.19839793333772799953325541924649068438043186709531909775879741729092437433414323287900757712874284882969505","3,-4":"4.5000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022281251850","3,-3":"-8.3898819682275914909172176214832437587588680469186247785038102279276190819979640768650471398225079520980745778","3,-2":"29.181086539499647318861180687943799414372291472328467902603886353332693992454730604925798827349653859651809919","3,-1":"-53.876283395440276461870630295591860783224676036593710632957976198150857612675403279510716588157457479764508055","3,0":"-57.295042514924710167169475050627118708988225749550009824114737421729510814357129227934626947658918879325599955","4,-4":"21.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003678834198","4,-3":"-52.486115851728760290947015566921804207541384218953582299684447730328889049323832358703553317449608822573680457","4,-2":"136.29657264574677338703282134813252692265252478766210881512572217607885072626419193928276131605248070999712660","4,-1":"-259.68808793957595615422198398444070800338676862094848577600021694893544491267085237982951356700460996461195419","4,0":"190.55949787744978005992486535085409014649303387190524641452983310356732408664903668479742060767123432380139610"},"-7":{"0,-4":"0.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999948398","0,-3":"-2.3088626596061314424260483603296097241686373437596943952230689395394709071106586837477882531669868658030280051","0,-2":"5.9552915241582022674918394241340041917132369244106348206777831627581412903724551049573639240681199551914671214","0,-1":"-11.249961739225280199971549027011689132771264106466026557278235543753520854139542226381583945090295707521082238","0,0":"20.147423583662158774752631835604440822313098315879883502473476112112100242775262906636702997599948891498563540","1,0":"-38.084997568345478989740156686915017553346761314816188201884862429888538861390042724471147663336277820491154665","2,-4":"-1.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999971122467122","2,-3":"-9.3822746807877371151479032793407805516627253124806112095538621209210581857786826325044234944061545485826231721","2,-2":"6.4134941861694356589809981963465277549344489638144518917673988280363101188043113627010687553390402459576290538","2,-1":"-42.550080625278431150977976839238144280081865916181112841809528037554343657409086672569174524813779238797091016","2,0":"102.35033564730945592722436329482365960044581914478379646527571308734636533541580216073685143247646634860879850","3,-4":"-2.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999994456247739","3,-3":"3.9265879788183943272781450809888291725059120312790831856692068186184127213319760512433647593588751275222606069","3,-2":"-3.9392865936562124751973731914131834026337987419528212763641426696560111497853892636005526886509593581252756751","3,-1":"0.72197202795831370045679028632578675399362013984831444323987456620984234152223109816209194557989211737286082524","3,0":"-56.611976947691830212718543852940270374050599555182514836277708198395945065726287113968397307769941216916016309","4,-4":"26.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000051315202773","4,-3":"0.96957085024058249692274263143014717161542906224794572420020757197375641512287422255750540450629819061736340431","4,-2":"148.49695739213924096679887504737791581025728206533514722901515691980394821593365302288431541707446990634004632","4,-1":"-68.518249963231625888561574294462169658227137114746862585392123577403760501701015548927531890509975838033372127","4,0":"-5021.9535198400340669081179937281634471710423455261594273880370052390466465027799878598168745035213557609913538"}},"gate_bessel_100d":{"-2":"-39.37435851694021885965650796774613582227995924793452502367741565642542762527029746632840821495859534","-7":"-38.08499756834547898974015668691501755334676131481618820188486242988924502402851995314207725439272947"}}"""
DATA_SHA256 = "8fe414140dc5c70e429ab2ce60dbfa46789b083f73b74d6db827772a22e003e5"


def check_pin():
    """sha256 of the embedded data block against the pin.  Exit 3 on mismatch, before
    any computation."""
    got = hashlib.sha256(DATA_TEXT.encode("ascii")).hexdigest()
    if got != DATA_SHA256:
        sys.stderr.write("REFUSED (exit %d): embedded data block sha256 %s... does not match "
                         "the pin %s... -- this copy of the script is tampered or truncated; "
                         "nothing was computed\n" % (EXIT_PIN, got[:16], DATA_SHA256[:16]))
        sys.exit(EXIT_PIN)
    return got


DATA = json.loads(DATA_TEXT)

STATE = [(i, K) for i in range(5) for K in range(-4, 1)]
IDX = {s: n for n, s in enumerate(STATE)}
NS = len(STATE)
JMAX = 7

# certified-truncation knobs: the depth formulas below are STARTING SEEDS only; every
# truncation is gated at run time by a trailing-window geometric tail bound and
# escalates by exact continuation of the same recurrence, refusing at the cap.
TAILWIN = 8       # trailing-term window for the geometric tail envelope
TGUARD = 12       # certified tail: tol = 10^-(quoted_dps + TGUARD)
ESC = 1.5         # depth escalation factor (exact continuation of the recurrence)
NCAP_MULT = 8     # escalation cap = NCAP_MULT * starting depth (fail-closed)
CHK_MARGIN = 10   # --check floor = dps + CHK_MARGIN
CHK_ROUNDS = 3    # --check auto-deepen rounds (x2 both leg guards per round)
GUARD = 30        # working guard digits on top of the quoted dps
QUICK_DPS = 30    # quoted digits of the quick default
FULL_DPS = 100    # quoted digits of --full (the paper's table)
QUICK_PP = ["-2"]
FULL_PP = ["-2", "-7"]

# The paper's printed held-out table (digits of agreement at 100 working digits); --full
# gates each recomputed row at (printed - 1).
PAPER_TABLE = {
    "-2": {"amflow_m1": 67, "amflow_worst": 67, "bessel_ref": 99, "bessel_live": 116},
    "-7": {"amflow_m1": 67, "amflow_worst": 67, "bessel_ref": 100, "bessel_live": 116},
}
PAPER_MUTATE_TO = 3     # printed collapse: 67 -> 3 digits at both points
PAPER_SELF_AGREE = 125  # printed self-agreement at sixty guard digits, p^2 = -7

# raw-mantissa arithmetic (bit-identical to the mpf operators at the same precision and
# rounding; used in the two hot loops so the run stays laptop-class)
from mpmath.libmp import mpf_add, mpf_mul, mpf_div, mpf_neg, from_int, fzero, fone


# ---------- structural checks on the embedded data (exact integers) ----------
def structural_checks():
    """den(z) = 20(1+z)(1+9z)(1+25z) and Num(0)/20 nilpotent of index exactly 8, both in
    exact integer arithmetic.  A miss means a corrupted data block -> exit 3."""
    zf = DATA["z_frame"]
    den = [int(c) for c in zf["den"]]
    if den != [20, 700, 5180, 4500]:
        sys.stderr.write("REFUSED (exit %d): z-frame denominator %s is not "
                         "20(1+z)(1+9z)(1+25z)\n" % (EXIT_PIN, den))
        sys.exit(EXIT_PIN)
    N0 = {}
    for k, cl in zf["num"].items():
        n, m = map(int, k.split(","))
        c0 = int(cl[0])
        if c0:
            N0[(n, m)] = c0

    def smul(A, B):
        out = {}
        for (i, j), a in A.items():
            for (jj, k), b in B.items():
                if jj == j:
                    out[(i, k)] = out.get((i, k), 0) + a * b
        return {k: v for k, v in out.items() if v}
    P = dict(N0)
    idx = None
    for p in range(2, 10):
        P = smul(P, N0)
        if not P:
            idx = p
            break
    if idx != 8:
        sys.stderr.write("REFUSED (exit %d): residue Num(0)/20 is not nilpotent of index 8 "
                         "(found %s)\n" % (EXIT_PIN, idx))
        sys.exit(EXIT_PIN)
    return idx


def _load(mp):
    def rat(s):
        if "/" in s:
            p, q = s.split("/")
            return mp.mpf(int(p)) / mp.mpf(int(q))
        return mp.mpf(int(s))

    def frame(fr):
        den = [rat(c) for c in fr["den"]]
        num = {}
        for k, cl in fr["num"].items():
            n, m = map(int, k.split(","))
            num[(n, m)] = [rat(c) for c in cl]
        return den, num
    return rat, frame


# ---------- polynomial / series helpers ----------
def poly_shift(mp, c, t0):
    out = list(c)
    n = len(c)
    for i in range(n - 1):
        for j in range(n - 2, i - 1, -1):
            out[j] = out[j] + t0 * out[j + 1]
    return out


def series_inv_raw(c, order, prec, rnd):
    inv0 = mpf_div(fone, c[0], prec, rnd)
    out = [inv0] + [fzero] * order
    for n in range(1, order + 1):
        s = fzero
        for k in range(1, min(n, len(c) - 1) + 1):
            s = mpf_add(s, mpf_mul(c[k], out[n - k], prec, rnd), prec, rnd)
        out[n] = mpf_neg(mpf_mul(inv0, s, prec, rnd))
    return out


def series_mul_raw(a, b, order, prec, rnd):
    out = [fzero] * (order + 1)
    for i, ai in enumerate(a[: order + 1]):
        if ai == fzero:
            continue
        for j in range(0, min(order - i, len(b) - 1) + 1):
            out[i + j] = mpf_add(out[i + j], mpf_mul(ai, b[j], prec, rnd), prec, rnd)
    return out


# ---------- transport (p^2-frame) ----------
def transport(mp, den, num, y0, t0, t1, order0, ratio, tol):
    """eps-graded Taylor transport with PER-STEP CERTIFIED tail gates.  order0 is a
    STARTING seed only.  Step rule h = min(|t1-t|, ratio*R), R = exact distance to the
    connection's pole set {0,1,9,25} (den = 20 t (t-1)(t-9)(t-25)), so the local Taylor
    series has certified ratio r = |h|/R <= ratio < 1; a step is accepted only when
        bound = max(|a_n h^n| over the trailing TAILWIN orders, all 25 comps) * r/(1-r)
    beats tol.  On a miss the SAME Taylor recursion is continued EXACTLY (x ESC depth) up
    to NCAP_MULT*order0, then RuntimeError naming step/t/h/r/bound/tol/N/cap.  Accepted
    per-step bounds accumulate into err_sum (sup norm over the 25-layer window).
    Returns (y, nsteps, err_sum, worst_step_bound, max_order_used)."""
    prec, rnd = mp.mp._prec_rounding
    t = mp.mpf(t0)
    y = [mp.mpf(v)._mpf_ for v in y0]
    nst = 0
    ncap = NCAP_MULT * order0
    err_sum = mp.mpf(0)
    worst = mp.mpf(0)
    omax = order0
    while abs(t - t1) > 0:
        R = min(abs(t), abs(t - 1), abs(t - 9), abs(t - 25))
        h = mp.sign(mp.mpf(t1) - t) * min(abs(mp.mpf(t1) - t), ratio * R)
        r = abs(h) / R   # certified series ratio (exact pole set; r <= ratio < 1)
        dsh = [c._mpf_ for c in poly_shift(mp, den, t)]
        csh = {key: [c._mpf_ for c in poly_shift(mp, c, t)] for key, c in num.items()}
        order = order0

        def _mtrip(ordr):
            # connection Taylor coefficients at t as sparse triples; the entries fed by the
            # tadpole columns (cx < 5) are kept apart: the tadpole rows of the connection
            # vanish, so a[j] has exactly zero tadpole components for every j >= 1 and those
            # products are exact zeros -- skipping them changes no bit of the result
            dinv = series_inv_raw(dsh, ordr, prec, rnd)
            # Mt[k][rr] = [(cx, value), ...] in the connection's entry order; Mt_rest drops
            # the tadpole columns
            Mt = [[[] for _ in range(NS)] for _ in range(ordr + 1)]
            Mt_rest = [[[] for _ in range(NS)] for _ in range(ordr + 1)]
            for (n, m), cs in csh.items():
                nc = series_mul_raw(cs, dinv, ordr, prec, rnd)
                for k in range(ordr + 1):
                    if nc[k] != fzero:
                        Mt[k][n].append((m, nc[k]))
                        if m >= 5:
                            Mt_rest[k][n].append((m, nc[k]))
            return Mt, Mt_rest

        Mtrip, Mrest = _mtrip(order)
        a = [list(y)]

        def _extend(upto, add=mpf_add, mul=mpf_mul, div=mpf_div):
            # a[j] = (sum_{k=0..j-1} M_k a[j-1-k]) / j, continued from wherever a ends; each
            # component accumulates its terms in k order, then in the connection's entry
            # order (the same summation order for every value)
            for j in range(len(a), upto + 1):
                s = []
                for rr in range(NS):
                    acc = fzero
                    for k in range(j):
                        ak = a[j - 1 - k]
                        for (cx, mv) in (Mtrip[k][rr] if k == j - 1 else Mrest[k][rr]):
                            acc = add(acc, mul(mv, ak[cx], prec, rnd), prec, rnd)
                    s.append(acc)
                jr = from_int(j)
                a.append([div(v, jr, prec, rnd) for v in s])

        _extend(order + 1)
        hraw = h._mpf_
        while True:
            hp = abs(h) ** (len(a) - TAILWIN)
            mx = mp.mpf(0)
            for j in range(len(a) - TAILWIN, len(a)):
                aj = a[j]
                mj = max(abs(mp.mp.make_mpf(v)) for v in aj) * hp
                if mj > mx:
                    mx = mj
                hp *= abs(h)
            bound = mx * r / (1 - r)
            if bound < tol:
                break
            if order >= ncap:
                raise RuntimeError(
                    f"transport: certified tail bound {mp.nstr(bound, 3)} >= tol "
                    f"{mp.nstr(tol, 2)} at step {nst} (t={mp.nstr(t, 8)}, h={mp.nstr(h, 8)}, "
                    f"r={mp.nstr(r, 4)}), Taylor order N={order} (cap {ncap}); fail-closed")
            neworder = min(ncap, int(order * ESC) + 2)
            print(f"  [transport tail-escalate: step {nst} order {order}->{neworder} "
                  f"(bound {mp.nstr(bound, 3)} >= tol {mp.nstr(tol, 2)})]", file=sys.stderr)
            order = neworder
            Mtrip, Mrest = _mtrip(order)   # exact continuation: same shifted polys, longer series
            _extend(order + 1)
        ynew = [fzero] * NS
        hp = fone
        for nn in range(len(a)):
            an = a[nn]
            for rr in range(NS):
                ynew[rr] = mpf_add(ynew[rr], mpf_mul(an[rr], hp, prec, rnd), prec, rnd)
            hp = mpf_mul(hp, hraw, prec, rnd)
        y = ynew
        t += h
        nst += 1
        err_sum += bound
        if bound > worst:
            worst = bound
        if order > omax:
            omax = order
        if nst > 1000:
            raise RuntimeError("transport: step overflow")
    return [mp.mp.make_mpf(v) for v in y], nst, err_sum, worst, omax


# ---------- MUM local solution (z-frame), single physical vector ----------
def local_solution(mp, den, num, v, Nloc0, z0, tol, scale):
    """MUM log-Frobenius local series with a CERTIFIED tail gate.  Nloc0 is a STARTING
    seed only.  The z-frame denominator factors exactly as 20(1+z)(1+9z)(1+25z), so the
    nearest singularity to the MUM point sits at |z| = 1/25 and r = 25*z0 (< 1, asserted)
    certifies the geometric envelope of the local solution at z0.  The series is accepted
    only when
        bound = max(|term_n| over trailing TAILWIN n, all comps) * r/(1-r)
    (term_n = sum_j F_{n,j} L0^j z0^n) satisfies bound*scale < tol, scale = sup_i
    z0^{-a_i} covering the raw-frame rescale; on a miss the SAME Frobenius recursion is
    continued exactly (x ESC) to NCAP_MULT*Nloc0, then RuntimeError (fail-closed).
    The linear solve (n den(0) - Num(0)) X = B uses the exact finite Neumann series of
    the nilpotent residue (index 8, checked in integers at load).
    Returns (out, err_scaled, N_used)."""
    prec, rnd = mp.mp._prec_rounding
    d0 = den[0]
    denc = list(den) + [mp.mpf(0)] * (7 - len(den))
    denr = [c._mpf_ for c in denc]
    d0r = d0._mpf_
    # sparse integer matrices Num_k (k = 0..6) as (row, col, raw value)
    numk = [[] for _ in range(7)]
    for (n, m), c in num.items():
        for k in range(min(7, len(c))):
            if c[k] != 0:
                numk[k].append((n, m, c[k]._mpf_))
    N0 = numk[0]

    def matvec(M, x):
        out = [fzero] * NS
        for (rr, cx, mv) in M:
            out[rr] = mpf_add(out[rr], mpf_mul(mv, x[cx], prec, rnd), prec, rnd)
        return out

    def axpy(alpha, x, y):   # y + alpha*x
        return [mpf_add(y[k], mpf_mul(alpha, x[k], prec, rnd), prec, rnd) for k in range(NS)]

    def solve_A(n, B):
        # (n d0 I - N0)^{-1} B = sum_{k=0}^{7} N0^k B / (n d0)^{k+1}   (N0 nilpotent, index 8)
        nd0 = mpf_mul(from_int(n), d0r, prec, rnd)
        u = [mpf_div(b, nd0, prec, rnd) for b in B]
        x = list(u)
        for _ in range(7):
            u = [mpf_div(w, nd0, prec, rnd) for w in matvec(N0, u)]
            x = [mpf_add(x[k], u[k], prec, rnd) for k in range(NS)]
        return x

    # F0(L) = e^{C0 L} v,  C0 = N0/d0
    F = []
    F0 = []
    X = [mp.mpf(c)._mpf_ for c in v]
    fact = 1
    for j in range(JMAX + 1):
        fr = from_int(fact)
        F0.append([mpf_div(x, fr, prec, rnd) for x in X])
        X = [mpf_div(w, d0r, prec, rnd) for w in matvec(N0, X)]
        fact *= (j + 1)
    F.append(F0)

    def _add_next():
        n = len(F)
        RHS = [[fzero] * NS for _ in range(JMAX + 1)]
        for m_ in range(1, min(n, 6) + 1):
            Fnm = F[n - m_]
            Nm = numk[m_]
            dm = denr[m_]
            for j in range(JMAX + 1):
                T = matvec(Nm, Fnm[j])
                if dm != fzero:
                    c1 = mpf_neg(mpf_mul(dm, from_int(n - m_), prec, rnd))
                    T = axpy(c1, Fnm[j], T)
                    if j + 1 <= JMAX:
                        c2 = mpf_neg(mpf_mul(dm, from_int(j + 1), prec, rnd))
                        T = axpy(c2, Fnm[j + 1], T)
                RHS[j] = [mpf_add(RHS[j][k], T[k], prec, rnd) for k in range(NS)]
        Fn = [None] * (JMAX + 1)
        for j in range(JMAX, -1, -1):
            B = RHS[j]
            if j + 1 <= JMAX:
                c3 = mpf_neg(mpf_mul(d0r, from_int(j + 1), prec, rnd))
                B = axpy(c3, Fn[j + 1], B)
            Fn[j] = solve_A(n, B)
        F.append(Fn)

    for n in range(1, Nloc0 + 1):
        _add_next()
    L0 = mp.log(z0)
    L0r = L0._mpf_
    z0r = z0._mpf_
    r = 25 * z0   # certified: exact z-frame poles at z = -1, -1/9, -1/25
    if not r < 1:
        raise RuntimeError("local series point z0 outside the certified radius 1/25")
    ncap = NCAP_MULT * Nloc0

    def _term(n):
        Lp = fone
        acc = [fzero] * NS
        for j in range(JMAX + 1):
            acc = axpy(Lp, F[n][j], acc)
            Lp = mpf_mul(Lp, L0r, prec, rnd)
        return acc

    def _termmax(n):
        acc = _term(n)
        return max(abs(mp.mp.make_mpf(a)) for a in acc) * z0 ** n

    while True:
        mx = mp.mpf(0)
        for n in range(len(F) - TAILWIN, len(F)):
            mn = _termmax(n)
            if mn > mx:
                mx = mn
        bound = mx * r / (1 - r)
        if bound * scale < tol:
            break
        if len(F) - 1 >= ncap:
            raise RuntimeError(
                f"local Frobenius series: certified tail bound "
                f"{mp.nstr(bound * scale, 3)} >= tol {mp.nstr(tol, 2)} at z0={mp.nstr(z0, 6)} "
                f"(r=25*z0={mp.nstr(r, 4)}), N={len(F) - 1} (cap {ncap}); fail-closed")
        target = min(ncap, int((len(F) - 1) * ESC) + 2)
        print(f"  [local-series tail-escalate: N {len(F) - 1}->{target} "
              f"(bound {mp.nstr(bound * scale, 3)} >= tol {mp.nstr(tol, 2)})]", file=sys.stderr)
        while len(F) - 1 < target:
            _add_next()

    out = [fzero] * NS
    zp = fone
    for n in range(len(F)):
        out = axpy(zp, _term(n), out)
        zp = mpf_mul(zp, z0r, prec, rnd)
    return [mp.mp.make_mpf(o) for o in out], bound * scale, len(F) - 1


# ---------- eps-series ----------
def exp_gamma_series(mp, nmax, c):
    g = c * mp.euler
    out = [mp.mpf(1)]
    for n in range(1, nmax + 1):
        out.append(out[-1] * g / n)
    return out


def layer_mix(mp, vec, mixer):
    out = [mp.mpf(0)] * NS
    for n, (i, K) in enumerate(STATE):
        s = mp.mpf(0)
        for r in range(0, K + 5):
            if r < len(mixer):
                s += mixer[r] * vec[IDX[(i, K - r)]]
        out[n] = s
    return out


def constants_vector(mp):
    zv = {"1": mp.mpf(1), "z2": mp.zeta(2), "z3": mp.zeta(3), "z4": mp.zeta(4)}
    rat, _ = _load(mp)
    v = []
    for (i, K) in STATE:
        c = DATA["constants_named"].get(f"{i},{K}") or {}
        v.append(sum(rat(fr) * zv[nm] for nm, fr in c.items()) if c else mp.mpf(0))
    return v


def gamma4_series(mp, nmax=4):
    """Exact Taylor coefficients of Gamma(1+eps)^4 = exp(-4 gamma_E eps + 4 sum_{k>=2}
    (-1)^k zeta(k) eps^k / k) through eps^nmax; Gamma(eps)^4 = eps^-4 times this."""
    l = [mp.mpf(0), -4 * mp.euler] + [4 * (-1) ** k * mp.zeta(k) / k for k in range(2, nmax + 1)]
    E = [mp.mpf(1)]
    for n in range(1, nmax + 1):
        E.append(sum(k * l[k] * E[n - k] for k in range(1, n + 1)) / n)
    return E


# ---------- main computation ----------
def compute(mp, pp_targets, mutate=0.0, verbose=False, qdps=None):
    """returns ({pp_key: {(i,K) -> value}}, {pp_key: certificate}) in the raw convention;
    one shared local series + one sequential transport pass through the targets (sorted
    deep-to-shallow).  pp_targets: dict key -> mpf value.  qdps = the QUOTED digit count
    the run must certify (tol = 10^-(qdps+TGUARD)); defaults to mp.mp.dps - GUARD.
    Certificate per point: value-level |err| <= (local tail + accumulated per-step
    transport tails) * l1(mixer)."""
    rat, frame = _load(mp)
    denz, numz = frame(DATA["z_frame"])
    denp, nump = frame(DATA["pp_frame"])
    if mutate:
        key = (IDX[(1, 0)], IDX[(2, 0)])   # connection entry feeding m1 eps^0 from m2 eps^0
        nump[key] = [c * (1 + mp.mpf(mutate)) for c in nump[key]]
    dps = mp.mp.dps
    if qdps is None:
        qdps = max(dps - GUARD, 1)
    tol = mp.mpf(10) ** (-(qdps + TGUARD))
    # STARTING SEEDS only: certified/escalated at run time.
    Nloc = int((dps + 12) / 0.709) + 8
    # near-optimal step economy: minimize steps*order^2 s.t. ratio^(order+1) <= 1e-(dps+10)
    order = int(1.2 * dps) + 25
    ratio = mp.mpf(10) ** (-mp.mpf(dps + 10) / (order + 1))
    z0 = mp.mpf(1) / 128
    a = DATA["rescale_a"]
    scale = z0 ** (-max(a))   # sup_i |z0^{-a_i}| = 128^2, covers the raw-frame rescale
    v = constants_vector(mp)
    t0 = time.time()
    fh, errL, Nused = local_solution(mp, denz, numz, v, Nloc, z0, tol, scale)
    t_loc = time.time() - t0
    # to raw-master frame at p^2 = -128 (still e^{4 gamma_E eps}-normalized)
    y = [fh[n] / z0 ** a[i] for n, (i, K) in enumerate(STATE)]
    mixer = exp_gamma_series(mp, 6, -4)
    l1mix = sum(abs(mixer[rr]) for rr in range(5))   # layer_mix uses orders 0..4 only
    out = {}
    cert = {}
    t = mp.mpf(-128)
    t0 = time.time()
    nst_tot = 0
    errT = mp.mpf(0)
    wstep = mp.mpf(0)
    omax = order
    for key in sorted(pp_targets, key=lambda k: pp_targets[k]):
        tgt = pp_targets[key]
        y, nst, errs, ws, om = transport(mp, denp, nump, y, t, tgt, order, ratio, tol)
        nst_tot += nst
        errT += errs
        wstep = max(wstep, ws)
        omax = max(omax, om)
        t = tgt
        yr = layer_mix(mp, y, mixer)
        out[key] = {s: yr[n] for n, s in enumerate(STATE)}
        cert[key] = {"bound": (errL + errT) * l1mix, "local": errL, "transport": errT,
                     "worst_step": wstep, "tol": tol, "Nloc": Nused, "order": omax}
    if verbose:
        print(f"  [local series N={Nused}: {t_loc:.1f} s; transport {nst_tot} steps, "
              f"Taylor order {omax}: {time.time()-t0:.1f} s]", flush=True)
    return out, cert


def digits(mp, a, b):
    """digits of agreement -log10 |a-b|/|b|, capped at the working precision (no printed
    count ever exceeds the digits the arithmetic carried)."""
    cap = float(mp.mp.dps)
    if b == 0:
        return cap if a == 0 else min(cap, float(-mp.log10(abs(a))))
    d = abs(a - b) / abs(b)
    return min(cap, float(-mp.log10(d))) if d > 0 else cap


def gate(name, measured, floor, unit="d"):
    """RAISING gate: print the verdict, raise (-> exit 1) below the floor."""
    if not (measured >= floor):
        raise RuntimeError(f"{name}: {measured:.1f} {unit} < floor {floor:.1f} {unit}")
    print(f"  [gate] {name}: {measured:.1f} {unit} >= {floor:.1f} {unit}  PASS", flush=True)


# ---------- positive controls ----------
def run_controls(mp, adps):
    """Positive controls.  adps = working precision of the K_0^4 quadrature (the paper's
    control ran at its 90-digit cap; the quick default uses a shallower one)."""
    print("== positive controls ==", flush=True)
    # B1: the AESZ-34 recurrence returns the Hulek-Verrill integers
    # L4 = sum_k z^k Q_k(th): Q0=th^4, Q1=35th^4+70th^3+63th^2+28th+5,
    # Q2=259th^4+1036th^3+1580th^2+1088th+285, Q3=225(th+1)^2(th+2)^2
    Q = [[0, 0, 0, 0, 1], [5, 28, 63, 70, 35], [285, 1088, 1580, 1036, 259],
         [900, 2700, 2925, 1350, 225]]
    A_n = [1]
    NN = 40
    for n in range(1, NN + 1):
        s = 0
        for m in range(1, 4):
            if n - m >= 0:
                s += sum(Q[m][j] * (n - m) ** j for j in range(5)) * A_n[n - m] * (-1) ** (m + 1)
        if s % n ** 4:
            raise RuntimeError(f"AESZ-34 recurrence: non-integer A_{n}")
        A_n.append(s // n ** 4)
    if A_n[:6] != [1, 5, 45, 545, 7885, 127905]:
        raise RuntimeError(f"AESZ-34 recurrence: Hulek-Verrill integers not reproduced ({A_n[:6]})")
    print(f"  [control] AESZ-34 recurrence -> Hulek-Verrill integers {A_n[:6]}  PASS", flush=True)
    # B2: L4 annihilates varpi_0 at z = 1/128 to truncation level
    zt = mp.mpf(1) / 128
    l4 = mp.mpf(0)
    for k in range(4):
        for j in range(5):
            if Q[k][j]:
                sj = sum(mp.mpf(A_n[n]) * (-1) ** n * n ** j * zt ** (n + k) for n in range(NN + 1))
                l4 += Q[k][j] * sj
    l4d = float(-mp.log10(abs(l4))) if l4 != 0 else 999.0
    gate(f"[control] |L4[varpi_0]| at z=1/128, N={NN} ({mp.nstr(abs(l4), 3)}, truncation level) -log10",
         l4d, 20.0)
    # C: the n=0 log-tower against the literature Gamma-product at L = -3
    rat, frame = _load(mp)
    denz, numz = frame(DATA["z_frame"])
    N0 = mp.matrix(NS, NS)
    for (n, m), c in numz.items():
        N0[n, m] = c[0]
    C0 = N0 / denz[0]
    v = mp.matrix(constants_vector(mp))
    Lval = mp.mpf(-3)
    acc = mp.matrix(NS, 1)
    X = v.copy()
    fact = mp.mpf(1)
    for j in range(12):
        if j > 0:
            X = C0 * X
            fact *= j
        acc += X * (Lval ** j / fact)
    NE = 8
    tot = [mp.mpf(0)] * (NE + 1)
    for j in range(5):
        lg = [mp.mpf(0)] * (NE + 1)
        for k in range(2, NE + 1):
            lg[k] = mp.zeta(k) * (-1) ** k / k * ((4 - j) + (1 + j) * (-1) ** k + j ** k - (-(j + 1)) ** k)
        G = [mp.mpf(1)] + [mp.mpf(0)] * NE
        for n in range(1, NE + 1):
            s = mp.mpf(0)
            for k in range(2, n + 1):
                s += k * lg[k] * G[n - k]
            G[n] = s / n
        E = [mp.mpf(1)]
        for n in range(1, NE + 1):
            E.append(E[-1] * j * Lval / n)
        pref = 5 * mp.binomial(4, j) * (-1) ** j
        for n in range(NE + 1):
            tot[n] += pref * sum(E[k] * G[n - k] for k in range(n + 1))
    dd = digits(mp, acc[IDX[(1, 0)]], -tot[4])
    gate("[control] n=0 log-tower of m1-hat vs the literature Gamma-product (eps^4 layer, L=-3)",
         dd, min(mp.mp.dps, 100) - 12)
    # A: the three-loop sibling identity int_0^inf x K0(x)^4 dx = 7 zeta(3)/8 (live quadrature)
    old = mp.mp.dps
    mp.mp.dps = adps
    try:
        t0 = time.time()
        f = lambda x: x * mp.besselk(0, x) ** 4
        L = int(mp.mp.dps * 2.303 / 4) + 20
        knots = [0, mp.mpf(1) / 2, 1, 2, 4, 8, 16, 32]
        knots = [k for k in knots if k < L] + [L]
        val = mp.quad(f, knots)
        ref = 7 * mp.zeta(3) / 8
        da = digits(mp, val, ref)
        gate(f"[control] three-loop sibling int x K0^4 dx = 7 zeta(3)/8 (quadrature at {adps} dps, "
             f"{time.time()-t0:.1f} s)", da, adps - 20)
    finally:
        mp.mp.dps = old


def bessel_oracle(mp, pp, res, qcap=115):
    """Live independent oracle: m1|eps^0 = -16 int_0^inf x J_0(x sqrt(-p^2)) K_0(x)^5 dx by
    quadrature, fail-closed refine-until-agree (double refinement must agree to
    10^-(qd+10), degree escalation to a cap, refuse there).  Gate leg only; the working
    precision is capped at qcap digits (Bessel-K evaluation slows sharply beyond)."""
    old = mp.mp.dps
    mp.mp.dps = min(old, qcap)
    try:
        s = -pp
        L = int((mp.mp.dps) * 2.303 / 5) + 25
        f = lambda x: x * mp.besselj(0, x * mp.sqrt(s)) * mp.besselk(0, x) ** 5
        t0 = time.time()
        knots = [0, mp.mpf(1) / 2, 1, 2, 3, 4] + list(range(5, L, 2)) + [L]
        qd = max(mp.mp.dps - 15, 30)
        md, prev = 6, None
        while True:
            vq = mp.quad(f, knots, maxdegree=md)
            if prev is not None and abs(vq - prev) < mp.mpf(10) ** (-(qd + 10)):
                MJ = vq
                break
            if md >= 12:
                raise RuntimeError(
                    f"--bessel quadrature: double-refinement agreement {mp.nstr(abs(vq - prev), 3)} "
                    f">= tol 1e-{qd + 10} at maxdegree {md} (cap 12); fail-closed")
            prev, md = vq, md + 2
        live = -16 * MJ
        return digits(mp, res[(1, 0)], live), time.time() - t0, mp.mp.dps
    finally:
        mp.mp.dps = old


def parse_pp(s):
    fr = Fraction(s)
    if fr >= 0:
        raise ValueError(s)
    return fr


def main():
    ap = argparse.ArgumentParser(
        description="four-loop equal-mass banana I_11111 (CY3, AESZ #34): explicit log-Frobenius "
                    "form, all five masters eps^-4..eps^0 at Euclidean p^2 < 0.")
    ap.add_argument("--dps", type=int, default=None,
                    help=f"quoted digits (default {QUICK_DPS}; {FULL_DPS} under --full); +{GUARD} working guard")
    ap.add_argument("--pp", action="append", default=None,
                    help="Euclidean p^2 < 0 as an integer or rational (repeatable; write --pp=-7/2); "
                         f"default {QUICK_PP} (quick) or {FULL_PP} (--full)")
    ap.add_argument("--full", action="store_true",
                    help="the paper's held-out table against the stored references: both points at 100 "
                         "digits, full-depth controls (minutes); add --bessel for the live-oracle rows")
    ap.add_argument("--check", action="store_true",
                    help="two-precision self-agreement gate: rerun at dps+60 guard digits (long)")
    ap.add_argument("--bessel", action="store_true",
                    help="live Bessel-moment oracle for m1 eps^0 by quadrature (long at high dps: many minutes "
                         "per point at the 115-digit cap)")
    ap.add_argument("--control", action="store_true", help="full-depth positive controls (implied by --full)")
    ap.add_argument("--no-controls", action="store_true", help="skip the positive controls")
    ap.add_argument("--mutate", action="store_true",
                    help="control: perturb one connection entry by 1e-6; the held-out gate must collapse "
                         "and the run must exit nonzero")
    args = ap.parse_args()

    print("== four-loop equal-mass banana I_11111 (CY3, AESZ #34): explicit log-Frobenius form ==", flush=True)
    pin = check_pin()
    nil = structural_checks()
    print(f"[data] embedded connection + boundary + references sha256 {pin[:16]}... matches the pin; "
          f"den = 20(1+z)(1+9z)(1+25z), residue nilpotent of index {nil} (exact integers)", flush=True)

    import mpmath as mp
    qdps = args.dps if args.dps is not None else (FULL_DPS if args.full else QUICK_DPS)
    if qdps < 10:
        print(f"usage: --dps must be >= 10 (got {qdps})", file=sys.stderr)
        return EXIT_USAGE
    pps_in = args.pp if args.pp else (FULL_PP if args.full else QUICK_PP)
    try:
        pp_fr = {s: parse_pp(s) for s in pps_in}
    except (ValueError, ZeroDivisionError):
        print(f"usage: every --pp must be a rational p^2 < 0 (Euclidean); got {pps_in}", file=sys.stderr)
        return EXIT_USAGE
    mode = "FULL (the paper's held-out table)" if args.full else "QUICK"
    print(f"mode: {mode} -- p^2 in {pps_in}, quoted dps {qdps} (+{GUARD} working guard)"
          + (f"; live Bessel oracle {'ON' if args.bessel else 'off (add --bessel)'}" if args.full
             else f"; --full = both points at {FULL_DPS} digits against the stored references"),
          flush=True)

    mp.mp.dps = qdps + GUARD   # working guard; results quoted at qdps
    pp_targets = {s: mp.mpf(fr.numerator) / fr.denominator for s, fr in pp_fr.items()}
    t_all = time.time()

    if not args.no_controls:
        run_controls(mp, adps=90 if (args.full or args.control) else 40)

    print("== value path ==", flush=True)
    t0 = time.time()
    allres, cert = compute(mp, pp_targets, verbose=True, qdps=qdps)
    print(f"  [wall {time.time()-t0:.1f} s for {len(pp_targets)} point(s) at dps {qdps} (+{GUARD} guard)]", flush=True)

    chk = None
    if args.check:
        # ACTING two-precision gate: the self-agreement must reach qdps + CHK_MARGIN; on a
        # miss BOTH legs auto-deepen (x2 guards -> genuinely different internal depths, all
        # runtime-certified) and the check re-runs, up to CHK_ROUNDS rounds, then refuses.
        g1, g2 = GUARD, GUARD + 60
        rnd = 0
        # m1's eps^{-4..-1} vanish IDENTICALLY in the form; numerically they are truncation
        # noise at any precision -- treat below-threshold values as zero-consistent.
        zero_tol = mp.mpf(10) ** (-qdps + 5)
        while True:
            if rnd == 0:
                legA = allres
            else:
                mp.mp.dps = qdps + g1
                legA, _ = compute(mp, pp_targets, qdps=qdps)
            mp.mp.dps = qdps + g2
            t0 = time.time()
            legB, _ = compute(mp, pp_targets, qdps=qdps)
            tB = time.time() - t0
            mp.mp.dps = qdps + GUARD
            worsts = {}
            for key in pp_targets:
                w = 999.0
                for s in legA[key]:
                    va, vb = legA[key][s], legB[key][s]
                    if max(abs(va), abs(vb)) < zero_tol:
                        continue
                    w = min(w, digits(mp, va, vb))
                worsts[key] = w
            overall = min(worsts.values())
            if overall >= qdps + CHK_MARGIN:
                chk = (worsts, g2 - g1, rnd, tB)
                break
            if rnd >= CHK_ROUNDS:
                raise RuntimeError(
                    f"--check: worst self-agreement {overall:.1f} d < required {qdps + CHK_MARGIN} d "
                    f"after {rnd} auto-deepen round(s) (leg guards +{g1}/+{g2}); refusing to certify")
            rnd += 1
            g1 *= 2
            g2 *= 2
            print(f"  [--check auto-deepen round {rnd}: legs -> dps+{g1} vs dps+{g2} "
                  f"(worst {overall:.1f} d < {qdps + CHK_MARGIN} d)]", flush=True)

    allresm = None
    if args.mutate:
        print("== --mutate control: one connection entry (m1 eps^0 <- m2 eps^0) perturbed by 1e-6 ==", flush=True)
        allresm, _ = compute(mp, pp_targets, mutate=1e-6, qdps=qdps, verbose=True)

    E4 = gamma4_series(mp, 4)
    floor_ref = min(qdps, 50) - 10
    for key in sorted(pp_targets, key=lambda k: pp_targets[k]):
        res = allres[key]
        print(f"p^2 = {key}", flush=True)
        for i in range(5):
            for K in range(-4, 1):
                if i == 1 and K < 0:
                    continue
                print(f"  m{i} eps^{K:+d} = {mp.nstr(res[(i, K)], qdps)}")
        c_ = cert[key]
        print(f"  certified BOUND: value-level |err| <= {mp.nstr(c_['bound'], 3)} (abs, sup over the "
              f"window; local {mp.nstr(c_['local'], 3)} + transport {mp.nstr(c_['transport'], 3)}, "
              f"l1-mixed; per-step tol {mp.nstr(c_['tol'], 2)}, worst step {mp.nstr(c_['worst_step'], 3)}; "
              f"local N={c_['Nloc']}, Taylor order {c_['order']})", flush=True)
        # analytic gate: the tadpole tower against the exact Gamma(eps)^4 expansion
        dtad = min(digits(mp, res[(0, -4 + n)], E4[n]) for n in range(5))
        gate("tadpole tower m0 eps^-4..0 vs exact Gamma(eps)^4 expansion (analytic; worst layer)",
             dtad, qdps - 2)
        if chk is not None:
            worsts, delta, rnd, tB = chk
            gate(f"--check two-precision self-agreement (worst nonzero layer, legs dps+{GUARD} vs dps+{GUARD + delta}"
                 f"{', ' + str(rnd) + ' auto-deepen round(s)' if rnd else ''}; deep leg {tB:.0f} s)",
                 worsts[key], qdps + CHK_MARGIN)
        g = DATA["gate_amflow_heldout"].get(key)
        b = DATA["gate_bessel_100d"].get(key)
        if g is None:
            print(f"  (no held-out reference at p^2 = {key}; references exist at p^2 = -2 and -7 -- "
                  f"the certified BOUND and the tadpole gate are the checks here)", flush=True)
        else:
            worst, w_m1 = 999.0, None
            for kk, sval in g.items():
                i, K = map(int, kk.split(","))
                d = digits(mp, res[(i, K)], mp.mpf(sval))
                worst = min(worst, d)
                if (i, K) == (1, 0):
                    w_m1 = d
            db = digits(mp, res[(1, 0)], mp.mpf(b)) if b else None
            print(f"  held-out references: m1 eps^0 vs independent AMFlow tower {w_m1:.1f} d; worst of the 21 "
                  f"layers {worst:.1f} d" + (f"; m1 eps^0 vs 100-digit Bessel reference {db:.1f} d" if db else "")
                  + " (AMFlow references carry about 67 digits, the Bessel strings 100)", flush=True)
            gate(f"m1 eps^0 vs held-out AMFlow reference (p^2 = {key})", w_m1, floor_ref)
            gate(f"worst of the 21 layers vs held-out AMFlow tower (p^2 = {key})", worst, floor_ref)
            if db is not None:
                gate(f"m1 eps^0 vs 100-digit Bessel reference (p^2 = {key})", db, floor_ref)
            if args.full and key in PAPER_TABLE and qdps >= FULL_DPS:
                P = PAPER_TABLE[key]
                gate(f"paper table row reproduced: m1 eps^0 vs AMFlow (printed {P['amflow_m1']}, p^2 = {key})",
                     w_m1, P["amflow_m1"] - 1)
                gate(f"paper table row reproduced: worst layer vs AMFlow (printed {P['amflow_worst']}, p^2 = {key})",
                     worst, P["amflow_worst"] - 1)
                if db is not None:
                    gate(f"paper table row reproduced: m1 eps^0 vs 100-digit Bessel reference "
                         f"(printed {P['bessel_ref']}, p^2 = {key})", db, P["bessel_ref"] - 1)
            if allresm is not None:
                dm = digits(mp, allresm[key][(1, 0)], mp.mpf(g["1,0"]))
                print(f"  --mutate control: m1 eps^0 vs held-out reference {w_m1:.1f} d -> {dm:.1f} d after the "
                      f"1e-6 connection perturbation (paper: 67 -> {PAPER_MUTATE_TO})", flush=True)
                gate(f"MUTATED run, m1 eps^0 vs held-out AMFlow reference (p^2 = {key}; this gate MUST fail)",
                     dm, floor_ref)
        if args.bessel:
            dl, tq, qd = bessel_oracle(mp, pp_targets[key], res)
            print(f"  live Bessel oracle -16 int x J0(x sqrt(-p^2)) K0(x)^5 dx at {qd} dps ({tq:.1f} s): "
                  f"m1 eps^0 agrees to {dl:.1f} d", flush=True)
            gate(f"m1 eps^0 vs live independent Bessel quadrature (p^2 = {key})", dl, min(qdps, qd) - 15)
            if args.full and key in PAPER_TABLE and qdps >= FULL_DPS:
                gate(f"paper table row reproduced: live Bessel oracle (printed {PAPER_TABLE[key]['bessel_live']}, "
                     f"p^2 = {key})", dl, PAPER_TABLE[key]["bessel_live"] - 1)
    if allresm is not None:
        # a --mutate run whose points carry no held-out reference cannot demonstrate the collapse
        raise RuntimeError("--mutate: no held-out reference at the requested point(s); the collapse could "
                           "not be demonstrated -- refusing rather than exiting clean")
    print(f"[wall] total {time.time()-t_all:.1f} s (this run, measured)", flush=True)
    if not args.full:
        print(f"(--full reproduces the paper's held-out table against the stored references: p^2 = -2 and -7 "
              f"at {FULL_DPS} digits; --bessel adds the live-oracle rows; --check the two-precision "
              f"self-agreement gate)", flush=True)
    elif not args.bessel:
        print("(--full --bessel adds the table's live Bessel-oracle rows; --check its self-agreement row)", flush=True)
    print("ALL CHECKS PASSED (exit 0)", flush=True)
    return EXIT_OK


if __name__ == "__main__":
    try:
        sys.exit(main())
    except RuntimeError as e:
        print(f"REFUSED (exit {EXIT_GATE}): {e}", file=sys.stderr, flush=True)
        sys.exit(EXIT_GATE)
