#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""v917 -- PRIME.KR4.DRIVER.CERT.01: THE CERTIFIED LOCALIZED RATE
DETECTION OF THE DRIVER -- the round-123 driver zero of xi_Q
(Q = x^2 + 5y^2) fires in the peeled rate channel at depth m* = 14
with certified LB = 1.000137 > 1, localized to its own violation
window, with the exact matched-pin algebra, the band-peel price
collapse (x65) and the quantified detection-cost law -- promoted with
a disclosed recomputed/pinned split.

GRADE (carried verbatim, never upgraded): CERT-GIVEN-AUDIT -- the
certification is rigorous GIVEN the audit comparator (Cauchy
enclosure against the FD log-derivative of the incomplete-gamma
xi_Q) PLUS the DECLARED tail and peel models (the Lambda-tail
constant K_hat and the per-zero peel position boxes are declared
models, not theorems).  The deep read is DISGUISE-ADJACENT by the
round-120 tau-screen typing: it is an Euler-computable truncated
windowed Weil transform -- the Krein carrier plays no role at depth
(on Q it cannot exist past the round-123 collapse at t = 2.988,
which is exactly why the deep route is direct).  These typings are
part of the claim, not caveats to be dropped.

THE RESULT (run-of-record driver_cert_probe.py, frozen SPEC_SHA
bcc64cb371dff9c8, 32/33 gates, 876.9 s, re-run reproduced with
identical SPEC_SHA and the identical single failing gate):
  THE PASSPORT -- the driver rho = 0.9329696975 + 15.6682495313 i,
  SOURCE-LOCATED from the Lambda_Q sieve alone (locator gamma dev
  6.6e-5 against its own 2e-2 box), then audit-polished (typed WARD:
  |xi_Q| = 3.4e-50); delta = 0.4329697, gamma = 15.6682495, excess
  eps = delta^2/gamma^2 = 7.636143e-4, matched pin a* = delta^2 +
  gamma^2 = 245.681506, violation window (232.4783, 259.6345)
  containing both a* and 256, unpeeled depth price m_2 = ln 2 *
  gamma^2/delta^2 = 907.7.
  THE EXACT ALGEBRA (recomputed here, symbolically AND at dps 200):
  at the matched pin the driver's radius-4 weight is EXACTLY 1 and
  its rate v* = 4 y*(1 - y*) = 1 + eps is EXACTLY REAL
  (y* = (gamma + i delta)/(2 gamma); the a^2/z weight-sum rigidity
  y(z) + y(a^2/z) = 1 holds identically).
  THE FIRE -- peeling the resonant on-line band gamma in
  (7.90, 31.40) (15 on-line pairs + the 29.98 off-line pair,
  audit-polished, winding-count-complete 15 == 15 / 2 == 2, every
  peel |xi_Q|-verified: phantom peel, the ONE false-fire mechanism,
  is doubly gate-excluded) caps the bulk at v_edge = 0.639 and
  collapses the crossing from m_2 = 908 to m_c = 14 (x65): certified
  LB_m = (d'_m - Err_m)/(d'_{m-1} + Err_{m-1}) > 1 at m* = 14/15/16
  (1.000137/1.000402/1.000554), Err ~ 2.1e-12 at the firing depths,
  sup dev meas 8.242e-59 <= cond 2.909e-55, certified depth
  m_cert = 32 (the table cap; rounds 120/123 stood at 14/8).
  LOCALIZED from m*_loc = 15: d-diff - Err > B_out (the exact
  outside-window skirt + the unknown-zone bound with vmax = 0.386 at
  (gamma, delta) = (45, 1.1)).  THE CENSUS PREMISE, STATED EXACTLY
  (correction of record, bughunt III round 130, note CDXXXII -- NOT
  "every off-line zero below 45 is located"): delta >= 0.01 census
  boxes + band-straddle completeness + the window-width argument --
  max|v(a0)| = 0.646 < 1 on the census-blind strip (delta < 0.01
  outside the band), any |v| > 1 zero must sit at gamma in
  (15.645, 15.703) INSIDE the straddle-boxed band, and blind-strip
  contributions to the depth diffs are negative where |v| >= 0.1
  and <= 1e-40 otherwise: hidden zeros can only MASK the fire,
  never fake it.  With that premise plus the Euler-region bound
  0.650 < 1 and 0 real zeros, the violating window CONTAINS a* --
  it is the DRIVER.  LB converges to v* to six digits by m = 25.
  THE COST LAW (the quantified instrument theorem, given-audit): the
  peeled rate instrument fires at m* ~ ln(B_band/eps)/ln(1/v_edge)
  with sieve price ln N ~ (m* ln Q + ln(a0/tol))/(sigma_edge -
  theta) -- POLYNOMIAL in 1/eps through the band choice, not the
  naive ln2/eps depth; measured 3.19 certified depths per unit ln N
  (sigma_edge = sqrt(a*/2) = 11.083, theta_Q = 0.94, Q = 24).  The
  route table, honest: carrier brute DEAD on Q (collapse at 2.988)
  and unaffordable anyway (L ~ 340, e^340 atoms); direct brute
  without peel m_2 = 908 => N ~ 1e124 UNAFFORDABLE; pole-read
  MEASURED-FAILS on the real world (Pade dev 6.2); resummation fails
  unpeeled (Aitken 0.9946) and works exactly peeled (1.000764 = v*):
  THE PEEL IS THE RESUMMATION.  The executed route needed only
  N = 2e5 sieve atoms.

THE HONEST CAVEAT, carried (the probe's single failing gate): G11
(locator relocates 4/4) FAILED as pre-declared possible -- the weak
round-117 witness (excess 2.930e-5) sits BELOW the source-locator's
measured excess threshold at N = 2e5 (the found zeros have excesses
7.64e-4 / 2.13e-4 / 5.39e-5; the threshold sits between 5.39e-5 and
2.93e-5).  The locator is therefore typed 3/4 MEASURED INSTRUMENT
(estimates + boxes), and NO 4/4 relocation claim is promoted.  The
locator nulls are clean (ZETA/ZK/SMOOTH 0/0/0 off-line candidates),
the planted driver clone is found, Q-scramble typed INFO.

PINNING DISCLOSURE (the recomputed/pinned split, exact):
  RECOMPUTED IN-RUN: the round-117 window-formula identity and the
  matched-pin algebra (sympy-symbolic AND dps-200 numeric); the
  exact Pascal-diagonal dictionary (binomial transform of the
  moments == y v^m, exact in rationals -- the peel arithmetic); the
  r_Q = t + u decomposition ward (n <= 4000) and the Lambda_Q
  recursion to n = 20000 with the lam-stats regression (max
  |Lambda_Q| = 1547.610, negative share 0.0337, psi_Q(1000)/1000 =
  0.9475); the passport arithmetic (eps, v*, a*, m_2, window); the
  band geometry (v_edge = 0.639 at the outer band edge, no on-line
  spectrum below the band, vmax_unk = 0.386); the FULL LB/
  localization/convergence recomputation from the pinned depth
  table; the cost-law arithmetic (3.19 depths per unit ln N, the
  x65 collapse, the route prices); the located-zero excess ladder
  and the G11 threshold placement; the min-cut BFS.
  PINNED FROM RUN-OF-RECORD (driver_cert_probe.run2.log, 32/33,
  SPEC bcc64cb371dff9c8): the 33-row deep depth table (d'_m peeled
  read values, Err_m budgets, B_out skirts -- the 457 s K = 128
  audit contour at dps 130 is not re-runnable in-suite), sup
  meas/cond (8.242e-59 / 2.909e-55), the polished band census (15
  on-line ordinates + 2 off-line pairs, winding-complete), the
  locator table and nulls, the controls (ZETA UB 0.605116, ZK UB
  0.615882, plant fires m* = 15, smooth monotone-decay, conditioning
  3.61e-17), Z1 no-transcription (9.11e-1 > 1e-6), and the strip
  census (4 off-line pairs below 45, 0 real zeros, Euler bound
  0.650).

NOT RH EVIDENCE -- in either direction.  This module says NOTHING
about the Riemann Hypothesis for zeta: the min-cut is unchanged
(flows 4/4, classes {MEAS, OMEGA-POS}; the rate certificate has no
path into RH or R4-HYP); a certified detector is a falsifier, not a
prover -- for zeta any finite (N, m) proves nothing (the
all-m/dense-a/all-L omega absorbs every finite certificate).  The
zeros themselves are classical (Potter--Titchmarsh 1935 computed the
first off-line zeros of THIS form; Davenport--Heilbronn 1936;
Bombieri--Mueller 1987): KNOWN-FALSEHOOD, NEW-INSTRUMENT (a
certified rate-channel detection with a-window localization and a
priced cost law from raw r_Q(n) counts: new-in-corpus certain,
plausibly world-new as an instrument class).  NO RH CLAIM.

PROVENANCE: discovery probe driver_cert_probe.py (round 125, note
CDXXVI, contract PRIME.KR4.DRIVER.CERT.01, SPEC_SHA
bcc64cb371dff9c8, 32/33 with the single pre-declared G11 fail,
876.9 s, verdict DRC-RATE-DETECTION(m* = 14, LB = 1.000137,
localized YES, m_cert = 32, x65) + PASSPORT + LOCATOR-3/4 +
SRCPEEL-SILENT + ROUTES + CONTROLS + MINCUT-UNCHANGED + Z1-CLEAN;
re-run green-as-typed at promotion with identical SPEC_SHA and the
identical failing gate); driver located in round 123 (v916);
instrument lineage rounds 117/118/120.  Python-only per
GATE.WOLFRAM.02 (sympy exact algebra, mpmath, sieve).
"""
from __future__ import annotations

import math
import time
from fractions import Fraction

import mpmath as mp

T_ALL = time.time()

# ------------------------------------------------------------ frozen pins
SPEC_SHA_PROBE = "bcc64cb371dff9c8"
DPS_LAM = 100
NCUT_WARD = 4000
NCUT_STATS = 20000
BAR_STATS = (0.05, 0.005, 0.002)
PIN_LAM_STATS = (1547.610, 0.0337, 0.9475)

# the polished passport (audit-polished driver; WARD-typed)
PIN_DELTA = "0.4329696975"
PIN_GAMMA = "15.6682495313"
PIN_LOC_GAMMA_DEV = 6.6e-5     # source-locator vs polish (box 2e-2)
PIN_EPS = 7.636143e-4
PIN_VSTAR = 1.00076361
PIN_ASTAR = 245.681506
PIN_WINDOW = (232.4783, 259.6345)
PIN_M2 = 907.7
BAR_M2 = (900.0, 916.0)
# band + census
BAND = (7.90, 31.40)
PIN_V_EDGE = 0.639
PIN_ONL_BAND = (9.2086, 10.5711, 12.4948, 13.0985, 17.5961, 18.9014,
                19.8090, 21.4021, 21.8876, 23.5392, 24.6432, 25.5254,
                26.5525, 27.5817, 29.2644)      # 15 polished on-line
PIN_OFFLINE = ((0.4330, 15.6682), (0.4377, 29.9834),
               (0.1969, 36.3741), (0.3232, 44.0001))   # (delta, gamma)
PIN_VMAX_UNK = 0.386           # |4y(1-y)| at (gamma, delta) = (45, 1.1)
# N = 2e5 truncation + declared Abel-model tail read (driver_cert
# G26) -- a valid UPPER bound; the true full sum is 0.645728 and
# v916's 0.664 is the same construction at N = 2e4 (bughunt CDXXXII)
PIN_EULER_BOUND = 0.650
# the deep certified depth table (PINNED from run-of-record; m, d'_m
# peeled read = audit to the printed digits, Err_m, LB_m, B_out(m))
DEPTH_TABLE = (
    (0, "1.332787e+01", "1.17e-12", None, "3.7e+01"),
    (1, "3.782761e+00", "1.10e-12", "0.283823", "3.7e+01"),
    (2, "2.149436e+00", "1.35e-12", "0.568219", "1.4e+01"),
    (3, "1.548727e+00", "1.62e-12", "0.720527", "5.5e+00"),
    (4, "1.280640e+00", "1.82e-12", "0.826899", "2.1e+00"),
    (5, "1.150440e+00", "1.95e-12", "0.898332", "8.2e-01"),
    (6, "1.084077e+00", "2.04e-12", "0.942314", "3.2e-01"),
    (7, "1.049247e+00", "2.09e-12", "0.967871", "1.2e-01"),
    (8, "1.030684e+00", "2.13e-12", "0.982308", "4.7e-02"),
    (9, "1.020773e+00", "2.14e-12", "0.990384", "1.8e-02"),
    (10, "1.015566e+00", "2.15e-12", "0.994899", "7.0e-03"),
    (11, "1.012960e+00", "2.15e-12", "0.997434", "2.7e-03"),
    (12, "1.011809e+00", "2.15e-12", "0.998863", "1.0e-03"),
    (13, "1.011479e+00", "2.14e-12", "0.999674", "4.0e-04"),
    (14, "1.011618e+00", "2.13e-12", "1.000137", "1.6e-04"),
    (15, "1.012024e+00", "2.13e-12", "1.000402", "6.0e-05"),
    (16, "1.012585e+00", "2.11e-12", "1.000554", "2.3e-05"),
    (17, "1.013234e+00", "2.10e-12", "1.000642", "9.0e-06"),
    (18, "1.013936e+00", "2.09e-12", "1.000693", "3.5e-06"),
    (19, "1.014668e+00", "2.08e-12", "1.000722", "1.3e-06"),
    (20, "1.015419e+00", "2.07e-12", "1.000739", "5.2e-07"),
    (21, "1.016180e+00", "2.05e-12", "1.000749", "2.0e-07"),
    (22, "1.016947e+00", "2.04e-12", "1.000755", "7.7e-08"),
    (23, "1.017719e+00", "2.02e-12", "1.000759", "3.0e-08"),
    (24, "1.018493e+00", "2.01e-12", "1.000761", "1.1e-08"),
    (25, "1.019269e+00", "1.99e-12", "1.000762", "4.4e-09"),
    (26, "1.020046e+00", "1.98e-12", "1.000763", "1.7e-09"),
    (27, "1.020824e+00", "1.96e-12", "1.000763", "6.6e-10"),
    (28, "1.021604e+00", "1.95e-12", "1.000763", "2.5e-10"),
    (29, "1.022384e+00", "1.93e-12", "1.000763", "9.8e-11"),
    (30, "1.023164e+00", "1.92e-12", "1.000764", "3.8e-11"),
    (31, "1.023945e+00", "2.02e-12", "1.000764", "1.5e-11"),
    (32, "1.024727e+00", "4.85e-12", "1.000764", "5.6e-12"),
)
PIN_MSTAR = 14
PIN_MLOC = 15
PIN_MCERT = 32
PIN_MARGINS = (1.37e-4, 4.02e-4, 5.54e-4)
PIN_SUP_MEAS = 8.242e-59
PIN_SUP_COND = 2.909e-55
# cost law + routes
THETA_Q = 0.94
Q_RATE = 24                    # Q = 4x(1+x) at x = 2 (RA_FRAC = 0.5)
PIN_DEPTHS_PER_LNN = 3.19
PIN_B_BAND = 3.05              # route-table bulk constant (pinned model)
PIN_MC_PRED = 18.5
PIN_LNN_BRUTE = 285.9
PIN_L_CARRIER_LAW = 2.7        # round-120 carrier depths per unit L
# controls (pinned)
PIN_ZETA_UB = 0.605116
PIN_ZK_UB = 0.615882
PIN_PLANT_MSTAR = 15
BAR_PLANT_DM = 8
PIN_COND_SHIFT = 3.61e-17
BAR_COND_HI = 1e-8
PIN_Z1_WORST = 9.11e-1
PIN_SMOOTH_RATIOS = (0.475, 0.750, 0.833, 0.875, 0.900, 0.917)
# locator record (G11 FAILED pre-declared: witness NOT FOUND)
PIN_LOC_FOUND = ((15.7, 6.6e-5), (30.0, 8.3e-4), (44.0, 8.0e-3))
BAR_LOC_G = 2e-2
MINCUT_EDGES = (("UNCOND", "DRV-SIEVE-MEAS"),
                ("DRV-SIEVE-MEAS", "DRV-LOCATOR-MEAS"),
                ("DRV-SIEVE-MEAS", "DRV-RATE-CERT"),
                ("DRV-LOCATOR-MEAS", "KR4-FALSIFIER-VALIDATED"),
                ("DRV-RATE-CERT", "KR4-FALSIFIER-VALIDATED"),
                ("UNCOND", "WEYL-PINS-MEAS"),
                ("HAUS-CELLS-FIN", "FORMA-HYP"),
                ("PICK-FLOORS-FIN", "SV-HYP"),
                ("DIAG-BOUNDS-FIN", "R4-HYP"))

N_CHECKS = 13
EXPECTED = "DRIVER-RATE-DETECTION-CERTIFIED(m* = 14, LB = 1.000137, " \
    "localized from m*_loc = 15, x65 band-peel collapse; " \
    "CERT-GIVEN-AUDIT + declared tail/peel models; DISGUISE-ADJACENT " \
    "value channel; locator 3/4 with the G11 caveat carried; " \
    "NOT RH evidence)"

CHECKS: list[tuple[str, bool]] = []
FAILS: list[str] = []


def check(name, ok, detail=""):
    ok = bool(ok)
    CHECKS.append((name, ok))
    if not ok:
        FAILS.append(name.split()[0])
    print("  [%s] %-52s %s" % ("PASS" if ok else "FAIL", name, detail))
    return ok


def section(title):
    print("\n" + "=" * 74)
    print(title)
    print("=" * 74)


CHI20 = {1: 1, 3: 1, 7: 1, 9: 1, 11: -1, 13: -1, 17: -1, 19: -1}
CHI4 = {1: 1, 3: -1}
CHI5 = {1: 1, 2: -1, 3: -1, 4: 1}


def sieve_rq(ncut):
    r = [0] * (ncut + 1)
    b = 0
    while 5 * b * b <= ncut:
        a = 0
        while a * a + 5 * b * b <= ncut:
            q = a * a + 5 * b * b
            if q >= 1:
                r[q] += (2 if a else 1) * (2 if b else 1)
            a += 1
        b += 1
    return r


def sieve_tu(ncut):
    t = [0] * (ncut + 1)
    u = [0] * (ncut + 1)
    for d in range(1, ncut + 1):
        c20v = CHI20.get(d % 20, 0)
        c4 = CHI4.get(d % 4, 0)
        for m in range(d, ncut + 1, d):
            if c20v:
                t[m] += c20v
            if c4:
                u[m] += c4 * CHI5.get((m // d) % 5, 0)
    return t, u


def lam_from_coeffs(r, ncut, dps):
    with mp.workdps(dps):
        lam = [mp.mpf(0)] * (ncut + 1)
        pre = [mp.mpf(0)] * (ncut + 1)
        r1 = mp.mpf(r[1])
        logs = {}
        for n in range(2, ncut + 1):
            if n not in logs:
                logs[n] = mp.log(n)
            lam[n] = (r[n] * logs[n] - pre[n]) / r1
            if lam[n] != 0:
                ln = lam[n]
                for m in range(2 * n, ncut + 1, n):
                    if r[m // n]:
                        pre[m] += ln * r[m // n]
    return lam


def v_online(gamma, a0):
    """On-line rate v = 4y(1-y), y = a0/(a0 + gamma^2)."""
    y = a0 / (a0 + gamma * gamma)
    return 4 * y * (1 - y)


def v_offline_abs(delta, gamma, a0, dps=60):
    """|4 y (1-y)| for the off-line atom y = a0/(a0 - mu^2)."""
    with mp.workdps(dps):
        mu = mp.mpc(delta, gamma)
        y = mp.mpf(repr(a0)) / (mp.mpf(repr(a0)) - mu * mu)
        return float(abs(4 * y * (1 - y)))


def part():
    import sympy as sp

    # ================================================ A: exact algebra
    section("A. THE EXACT ALGEBRA (symbolic + dps-200; the peel "
            "arithmetic)")
    d_s, g_s, a_s = sp.symbols("delta gamma a", positive=True)
    z = (d_s + sp.I * g_s) ** 2
    # exact real/abs of z = mu^2 (gated, then substituted):
    rez = d_s ** 2 - g_s ** 2
    az = d_s ** 2 + g_s ** 2
    re_ok = sp.expand(sp.re(z) - rez) == 0
    im_ok = sp.expand(sp.im(z) - 2 * d_s * g_s) == 0
    abs_ok = sp.expand(az ** 2 - (rez ** 2 + (2 * d_s * g_s) ** 2)) == 0
    # a+- = Re z + 2|z| +- sqrt((Re z + |z|)(Re z + 3|z|)); the affine
    # parts agree termwise and both radicals are nonnegative, so the
    # identity reduces to the exact square comparison:
    aff_ok = sp.expand((rez + 2 * az)
                       - (3 * d_s ** 2 + g_s ** 2)) == 0
    rad_ok = sp.expand((2 * d_s * sp.sqrt(2 * d_s ** 2
                                          + g_s ** 2)) ** 2
                       - (rez + az) * (rez + 3 * az)) == 0
    id_lo = id_hi = re_ok and im_ok and abs_ok and aff_ok and rad_ok
    with mp.workdps(120):
        psi_half_dev = float(abs(mp.digamma(mp.mpf(1) / 2) + mp.euler
                                 + 2 * mp.log(2)))
    check("A1 window-formula identity + psi(1/2) exact",
          id_lo and id_hi and psi_half_dev <= 1e-110,
          "a+- = 3d^2+g^2 +- 2d sqrt(2d^2+g^2) == Re z + 2|z| +- "
          "sqrt((Re z+|z|)(Re z+3|z|)), z = mu^2: sympy-exact both "
          "branches; psi(1/2) = -gamma_E - 2 log 2 dev %.0e"
          % psi_half_dev)

    a0_sym = d_s ** 2 + g_s ** 2
    ystar = sp.simplify(a0_sym / (a0_sym - z))
    y_id = sp.simplify(ystar - (g_s + sp.I * d_s) / (2 * g_s)) == 0
    vstar = sp.simplify(4 * ystar * (1 - ystar))
    v_id = sp.simplify(vstar - (1 + d_s ** 2 / g_s ** 2)) == 0
    zz = sp.symbols("z")
    y_of = a_s / (a_s - zz)
    rig = sp.simplify(y_of + y_of.subs(zz, a_s ** 2 / zz) - 1) == 0
    with mp.workdps(200):
        de = mp.mpf(PIN_DELTA)
        ga = mp.mpf(PIN_GAMMA)
        mu = mp.mpc(de, ga)
        a0 = de * de + ga * ga
        ystar_n = a0 / (a0 - mu * mu)
        vstar_n = 4 * ystar_n * (1 - ystar_n)
        im_v = float(abs(mp.im(vstar_n)))
        wsum_n = float(abs(ystar_n + a0 / (a0 - mp.conj(mu) ** 2) - 1))
    check("A2 matched-pin algebra: weight EXACTLY 1, v* EXACTLY REAL",
          y_id and v_id and rig and im_v <= 1e-125
          and wsum_n <= 1e-125,
          "y* = (gamma + i delta)/(2 gamma), v* = 1 + delta^2/gamma^2 "
          "sympy-exact; y(z) + y(a^2/z) == 1 identically; at the "
          "pinned driver |Im v*| = %.1e, |y* + y*bar - 1| = %.1e "
          "(<= 1e-125)" % (im_v, wsum_n))

    ok_dict = True
    y_onl = Fraction(3, 10)
    v_onl = 4 * y_onl * (1 - y_onl)
    for m in range(0, 21):
        dm = Fraction(4) ** m * sum(
            (-1) ** j * math.comb(m, j) * y_onl ** (m + j + 1)
            for j in range(m + 1))
        ok_dict = ok_dict and dm == y_onl * v_onl ** m
    y_off = sp.Rational(1, 5) + sp.I * sp.Rational(1, 7)
    v_off = 4 * y_off * (1 - y_off)
    for m in range(0, 13):
        dm = 4 ** m * sum((-1) ** j * sp.binomial(m, j)
                          * y_off ** (m + j + 1) for j in range(m + 1))
        pair = sp.simplify(2 * sp.re(sp.expand(dm))
                           - 2 * sp.re(sp.expand(y_off * v_off ** m)))
        ok_dict = ok_dict and pair == 0
    check("A3 Pascal-diagonal dictionary EXACT (the peel arithmetic)",
          ok_dict,
          "d'_m = 4^m sum_j (-1)^j C(m,j) b_{m+j} == y v^m exact in "
          "rationals, on-line m <= 20 and off-line pair m <= 12: "
          "subtracting a zero's closed form is exact at every depth")

    t0 = time.time()
    rq = sieve_rq(NCUT_STATS)
    tt, uu = sieve_tu(NCUT_WARD)
    dec_ok = all(rq[n] == tt[n] + uu[n] for n in range(1, NCUT_WARD + 1))
    lam_q = lam_from_coeffs(rq, NCUT_STATS, DPS_LAM)
    with mp.workdps(DPS_LAM):
        mx = max(float(abs(lam_q[n])) for n in range(2, NCUT_STATS + 1))
        neg = sum(1 for n in range(2, NCUT_STATS + 1) if lam_q[n] < 0)
        share = neg / (NCUT_STATS - 1)
        psi1000 = float(mp.fsum(lam_q[n] for n in range(2, 1001)))
    check("A4 sieve wards: r_Q = t + u exact + lam-stats regression",
          dec_ok and abs(mx - PIN_LAM_STATS[0]) <= BAR_STATS[0]
          and abs(share - PIN_LAM_STATS[1]) <= BAR_STATS[1]
          and abs(psi1000 / 1000 - PIN_LAM_STATS[2]) <= BAR_STATS[2],
          "r_Q == 1*chi_-20 + chi_-4*chi_5 all n <= %d; max|Lambda_Q| "
          "(n <= %d) = %.3f (rec %.3f), neg share %.4f (rec %.4f), "
          "psi_Q(1000)/1000 = %.4f (rec %.4f) (%.1f s)"
          % (NCUT_WARD, NCUT_STATS, mx, PIN_LAM_STATS[0], share,
             PIN_LAM_STATS[1], psi1000 / 1000, PIN_LAM_STATS[2],
             time.time() - t0))

    with mp.workdps(60):
        de = mp.mpf(PIN_DELTA)
        ga = mp.mpf(PIN_GAMMA)
        a0 = de * de + ga * ga
        eps = de * de / (ga * ga)
        vst = 1 + eps
        m2 = float(mp.log(2) / eps)
        disc = mp.sqrt(2 * de * de + ga * ga)
        w_lo = float(3 * de * de + ga * ga - 2 * de * disc)
        w_hi = float(3 * de * de + ga * ga + 2 * de * disc)
    check("A5 the passport recomputed from the polished driver",
          abs(float(a0) - PIN_ASTAR) <= 1e-4
          and abs(float(eps) - PIN_EPS) <= 1e-9
          and abs(float(vst) - PIN_VSTAR) <= 1e-7
          and BAR_M2[0] <= m2 <= BAR_M2[1]
          and abs(m2 - PIN_M2) <= 0.1
          and abs(w_lo - PIN_WINDOW[0]) <= 0.01
          and abs(w_hi - PIN_WINDOW[1]) <= 0.01
          and w_lo < float(a0) < w_hi and w_lo < 256 < w_hi
          and PIN_LOC_GAMMA_DEV <= 2e-2,
          "a* = %.6f, eps = %.6e, v* = %.8f, m_2 = %.1f in [%d, %d]; "
          "window (%.4f, %.4f) contains a* and 256; source-located "
          "gamma dev %.1e vs 2e-2 box, then audit-polished (WARD)"
          % (float(a0), float(eps), float(vst), m2, int(BAR_M2[0]),
             int(BAR_M2[1]), w_lo, w_hi, PIN_LOC_GAMMA_DEV))

    # ================================================ B: fire + law
    section("B. THE CERTIFIED FIRE (pinned depth table, recomputed "
            "arithmetic)")
    a0f = float(a0)
    v_lo_edge = v_online(BAND[0], a0f)
    v_hi_edge = v_online(BAND[1], a0f)
    vmax_unk = v_offline_abs(1.1, 45.0, a0f)
    check("B1 band geometry: v_edge and the unknown-zone bound",
          abs(v_hi_edge - PIN_V_EDGE) <= 2e-3
          and min(PIN_ONL_BAND) > BAND[0]
          and max(PIN_ONL_BAND) < BAND[1]
          and len(PIN_ONL_BAND) == 15
          and abs(vmax_unk - PIN_VMAX_UNK) <= 2e-3
          and PIN_EULER_BOUND < 1,
          "v(31.40) = %.4f (pinned %.3f) caps the unpeeled bulk (no "
          "on-line ordinate below %.2f: lowest polished = %.4f); "
          "vmax_unk(45, 1.1) = %.4f (pinned %.3f); Euler-region bound "
          "%.3f < 1" % (v_hi_edge, PIN_V_EDGE, BAND[0],
                        min(PIN_ONL_BAND), vmax_unk, PIN_VMAX_UNK,
                        PIN_EULER_BOUND))

    tab = [(m, float(mp.mpf(dv)), float(mp.mpf(ev)),
            (float(mp.mpf(lb)) if lb is not None else None),
            float(mp.mpf(bo))) for m, dv, ev, lb, bo in DEPTH_TABLE]
    lb_dev = 0.0
    fire_ok = True
    for m, dv, ev, lb, _bo in tab[1:]:
        dp, ep = tab[m - 1][1], tab[m - 1][2]
        lb_rec = (dv - ev) / (dp + ep)
        lb_dev = max(lb_dev, abs(lb_rec - lb))
    lbs = {m: lb for m, _d, _e, lb, _b in tab[1:]}
    fire_ok = all(lbs[m] > 1 for m in (14, 15, 16)) \
        and all(lbs[m] <= 1 for m in range(1, 14))
    margins = tuple(lbs[m] - 1 for m in (14, 15, 16))
    marg_ok = all(abs(margins[i] - PIN_MARGINS[i]) <= 5e-6
                  for i in range(3))
    check("B2 THE FIRE at m* = 14: LB > 1, three consecutive depths",
          lb_dev <= 5e-6 and fire_ok and marg_ok
          and PIN_SUP_MEAS <= PIN_SUP_COND,
          "LB recomputed from the pinned d'/Err columns, max dev "
          "%.1e; LB(14/15/16) = %.6f/%.6f/%.6f > 1, margins %.2e/"
          "%.2e/%.2e; onset exactly m* = %d; sup meas %.3e <= cond "
          "%.3e" % (lb_dev, lbs[14], lbs[15], lbs[16], margins[0],
                    margins[1], margins[2], PIN_MSTAR, PIN_SUP_MEAS,
                    PIN_SUP_COND))

    loc = {}
    for m, dv, ev, _lb, bo in tab[1:]:
        dp, ep = tab[m - 1][1], tab[m - 1][2]
        loc[m] = (dv - dp - ev - ep) > bo
    onset = next((m for m in range(1, 31)
                  if loc.get(m) and loc.get(m + 1) and loc.get(m + 2)),
                 None)
    check("B3 LOCALIZED from m*_loc = 15: the window contains a*",
          onset == PIN_MLOC and not loc[14],
          "d-diff - Err > B_out for 3 consecutive m from %s (pinned "
          "%d; m = 14 still under the skirt %.1e): with the gated "
          "census premise (delta >= 0.01 boxes + band-straddle "
          "completeness + the window-width argument, note CDXXXII; "
          "vmax_unk %.3f) the "
          "violating window contains a* = %.2f -- IT IS THE DRIVER"
          % (onset, PIN_MLOC, tab[14][4], PIN_VMAX_UNK, a0f))

    conv25 = abs(lbs[25] - float(vst))
    conv32 = abs(lbs[32] - float(vst))
    check("B4 convergence + certified depth: LB -> v* to six digits",
          conv25 <= 5e-6 and conv32 <= 2e-6 and tab[-1][0] == PIN_MCERT
          and max(ev for _m, _d, ev, _l, _b in tab[13:17]) <= 2.2e-12,
          "|LB(25) - v*| = %.1e, |LB(32) - v*| = %.1e; certified "
          "depth m_cert = %d (table cap; rounds 120/123 stood at "
          "14/8); Err at the firing depths <= 2.2e-12"
          % (conv25, conv32, PIN_MCERT))

    sigma_edge = math.sqrt(a0f / 2)
    dpl = (sigma_edge - THETA_Q) / math.log(Q_RATE)
    mc_pred = math.log(PIN_B_BAND / PIN_EPS) / math.log(1 / PIN_V_EDGE)
    lnn_brute = PIN_M2 * math.log(Q_RATE) / (sigma_edge - THETA_Q)
    l_carrier = PIN_M2 / PIN_L_CARRIER_LAW
    collapse = PIN_M2 / PIN_MSTAR
    check("B5 the detection-cost law (polynomial in 1/eps via the "
          "band)",
          abs(dpl - PIN_DEPTHS_PER_LNN) <= 0.01
          and abs(mc_pred - PIN_MC_PRED) <= 0.1
          and abs(lnn_brute - PIN_LNN_BRUTE) <= 3.0
          and 330 <= l_carrier <= 345
          and 63 <= collapse <= 66,
          "m* ~ ln(B_band/eps)/ln(1/v_edge) = %.1f (measured m_c = "
          "%d); %.2f certified depths per unit ln N (sigma_edge = "
          "%.3f, theta = %.2f, Q = %d); routes priced: unpeeled "
          "brute ln N ~ %.0f => N ~ 1e124 UNAFFORDABLE, carrier "
          "L ~ %.0f => e^%d atoms DEAD+UNAFFORDABLE, the peel "
          "collapsed the depth price x%.0f and needed N = 2e5"
          % (mc_pred, PIN_MSTAR, dpl, sigma_edge, THETA_Q, Q_RATE,
             lnn_brute, l_carrier, int(l_carrier), collapse))

    # ================================================ C: controls + typing
    section("C. CONTROLS, THE G11 CAVEAT, NOT-RH TYPING (pinned)")
    smooth_ok = all(0 <= r < 1 for r in PIN_SMOOTH_RATIOS)
    check("C1 controls: nulls silent, plant fires, conditioning "
          "bounded",
          PIN_ZETA_UB < 1 and PIN_ZK_UB < 1
          and abs(PIN_PLANT_MSTAR - PIN_MSTAR) <= BAR_PLANT_DM
          and 0 < PIN_COND_SHIFT <= BAR_COND_HI
          and smooth_ok and PIN_Z1_WORST > 1e-6,
          "ZETA max certified UB %.6f < 1, ZK %.6f < 1 through "
          "m_cert %d; ZK+plant (exact driver clone) fires at m* = %d "
          "(|dm| = %d <= %d); smooth world monotone-decay (no fire "
          "possible); conditioning %.2e in (0, 1e-8]; Z1 worst "
          "%.2e > 1e-6 (no transcription)"
          % (PIN_ZETA_UB, PIN_ZK_UB, PIN_MCERT, PIN_PLANT_MSTAR,
             abs(PIN_PLANT_MSTAR - PIN_MSTAR), BAR_PLANT_DM,
             PIN_COND_SHIFT, PIN_Z1_WORST))

    with mp.workdps(60):
        excs = [float(mp.mpf(repr(d)) ** 2 / mp.mpf(repr(g)) ** 2)
                for d, g in PIN_OFFLINE]
    found_excs = [excs[0], excs[1], excs[3]]      # driver, 29.98, 44.00
    wit_exc = excs[2]
    check("C2 THE G11 CAVEAT carried: locator 3/4, witness below "
          "threshold",
          all(g_dev <= BAR_LOC_G for _g, g_dev in PIN_LOC_FOUND)
          and min(found_excs) > wit_exc
          and abs(min(found_excs) - 5.39e-5) <= 2e-6
          and abs(wit_exc - 2.93e-5) <= 2e-6,
          "found: gamma devs %.1e/%.1e/%.1e <= 2e-2; the witness "
          "(excess %.2e) sits BELOW the measured threshold at "
          "N = 2e5 (between %.2e and %.2e): the pre-declared 4/4 "
          "gate FAILED and NO 4/4 claim is promoted -- the locator "
          "is a 3/4 MEASURED instrument"
          % (PIN_LOC_FOUND[0][1], PIN_LOC_FOUND[1][1],
             PIN_LOC_FOUND[2][1], wit_exc, min(found_excs), wit_exc))

    adj = {}
    for a, b in MINCUT_EDGES:
        adj.setdefault(a, []).append(b)
    seen = {"DRV-RATE-CERT"}
    stack = ["DRV-RATE-CERT"]
    while stack:
        u = stack.pop()
        for v in adj.get(u, []):
            if v not in seen:
                seen.add(v)
                stack.append(v)
    check("C3 min-cut unchanged: the certificate has NO path into RH",
          "RH" not in seen and "FORMA-HYP" not in seen
          and "R4-HYP" not in seen and "SV-HYP" not in seen,
          "BFS from DRV-RATE-CERT reaches %s; record flows 4/4, "
          "classes {MEAS, OMEGA-POS}: a certified detector is a "
          "falsifier, not a prover -- for zeta any finite (N, m) "
          "proves nothing; NOT RH evidence in either direction"
          % sorted(seen - {"DRV-RATE-CERT"}))
    return 0


def run():
    global CHECKS, FAILS
    CHECKS = []
    FAILS = []
    print("=" * 74)
    print("v917 -- PRIME.KR4.DRIVER.CERT.01 (the certified localized "
          "rate detection")
    print("of the driver 0.9330 + 15.6682i: FIRE at m* = 14, LB = "
          "1.000137 > 1,")
    print("localized from m*_loc = 15, band-peel x65; grade "
          "CERT-GIVEN-AUDIT with")
    print("declared tail/peel models, DISGUISE-ADJACENT value "
          "channel; locator 3/4")
    print("with the G11 caveat carried; NO RH claim)")
    print("=" * 74)
    rc = part()
    n_run, fails = len(CHECKS), list(FAILS)
    verdict = EXPECTED if (rc == 0 and not fails) else "MIXED"
    ok = (rc == 0 and n_run == N_CHECKS and not fails
          and verdict == EXPECTED)
    print("\n" + "=" * 74)
    print("v917: %d/%d checks passed | runtime %.1f s"
          % (n_run - len(fails), n_run, time.time() - T_ALL))
    print("verdict %s" % verdict)
    print("PINNING: exact algebra + dictionary + sieve wards + "
          "passport + band")
    print("geometry + LB/localization/cost-law arithmetic RECOMPUTED; "
          "the deep depth")
    print("table, audit contour, band census, locator, controls "
          "PINNED from")
    print("driver_cert_probe.run2.log (SPEC %s, 32/33, the single "
          "G11 fail" % SPEC_SHA_PROBE)
    print("pre-declared and carried).  NOT RH evidence; NO RH claim.")
    print("[%s] PATTERN GATE: expected %d checks, zero fails "
          "(got %d, fails %s)"
          % ("PASS" if ok else "FAIL", N_CHECKS, n_run,
             fails or "none"))
    print("--- PRIME.KR4.DRIVER.CERT.01 certified rate detection: "
          "%d passed, %d failed ---" % (n_run - len(fails), len(fails)))
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(run())
