audit.py

Checks: RULER: The sign law of a stated interval property; observation; RULER: The audit world and its two roots property; RULER: The side of 1/2 is the sign of one product theorem; observation.

Cited on: RULER.

To run it: save audit.py; needs numpy.

"""audit.py -- one published deletion audit's estimator read against a
target known exactly: where its answer comes from, when it lands on the
wrong side of one half, and what a statement built on its resamples can
and cannot say when the target is not identified.

QUESTION. A mixture-proportion deletion audit (Statistical Membership
Inference, arXiv:2602.01150v2, Proposition 3.1, Lemma 3.2 and
Algorithm 1, read at source) models the audited feature distribution
as F_u = kappa F_out + (1 - kappa) F_in, F_in the member class and
F_out the non-member class, and reports kappa, the FORGETTING RATE.
For a scalar feature, with
    d = mu_out - mu_in,  B = d^2,  A = var_u - var_in,
    G = var_out - var_in + B,
it returns the minimizer of f(p) = (A - pG + p^2 B)^2 over the
candidates {0, 1} and the critical points of f in [0, 1] -- the vertex
v = G/(2B) and the real roots of B p^2 - G p + A. Only the audited
set's VARIANCE is used, never its mean. Its stated uncertainty is the
{5%, 95%} quantiles of the estimate over bootstrap resamples of the
audited set, which the source names a reference range. What does the
estimator's answer depend on, and what do statements built on its
resamples cover?

THE WORLDS.
  DEPTH CELL (a, b). Menu {2, 3} at every state, the dated fiber
  (2^a 3^b, a + b), T = a + b, every arrangement of a twos and b
  threes equally likely. The audited datum is the first move; member
  class = first move 2, non-member = first move 3. The FEATURE of a
  route is the number of 2-moves in the three positions after the
  first. So
      feat_in ~ HG(T - 1, a - 1, 3),  feat_out ~ HG(T - 1, a, 3),
      feat_u ~ HG(T, a, 3)
  (population, successes, draws), and the depth cell, unconditioned,
  is the exact mixture of the two classes at weight kappa = b/T. The
  audit's own modelling assumption holds exactly, and every moment is
  a Fraction. Cells W2 = (12, 3), kappa = 1/5 and W3 = (2, 8),
  kappa = 4/5.
  GAUSSIAN DIAL (kappa, gamma). F_in = N(0, 1), F_out = N(2, 1 +
  gamma), the audited set a genuine kappa-mixture. d = 2, B = 4,
  G = gamma + 4.

THE ARGUMENT.
  (A) THE BRIDGE (property). For ANY two-class mixture,
      var_u = kappa var_out + (1 - kappa) var_in + kappa (1 - kappa) d^2,
      so A = kappa G - kappa^2 B identically: p = kappa is a root of
      the population objective in every world, and for d != 0 the
      other is G/B - kappa. On the dial that is 1 - kappa + gamma/4:
      equal class variances give the twin {kappa, 1 - kappa}, unequal
      ones slide the second root, which leaves the box past
      gamma = 4 kappa and, for gamma >= 0, never below it. The box,
      not the objective, identifies.
  (B) THE SIDE (theorem). Write L(p) = G p - B p^2 for the level the
      objective needs at p; f(p) = (A - L(p))^2, and the candidates
      hold every critical point of f in the box and its two ends, so
      the estimate is a p in [0, 1] whose L(p) is nearest A-hat,
      B-hat >= 0 making L concave or linear. Its ends are L(0) = 0
      and L(1) = G - B, its half-box level L(1/2) = G/2 - B/4, and
          D-hat = A-hat - L-hat(1/2)
                = s_u^2 - s_in^2/2 - s_out^2/2 - dhat^2/4.
      THE MIRROR: L(p) - L(1 - p) = (2p - 1)(G - B). Take G > B; the
      other sign is this one in the mirror q = 1 - p, which turns
      A - L into (A - G + B) - ((2B - G) q - B q^2): the same family
      with 2B - G for G, the sign of G - B reversed, D-hat and the
      zone below unchanged. Then
      L' = G - 2Bp >= G - B > 0 on [0, 1/2]: L climbs from 0 to L(1/2)
      there, and on [1/2, 1] it stays at or above the lower of L(1/2)
      and L(1), both positive. If D-hat > 0, every p < 1/2 sits
      farther below A-hat than 1/2 does, and L still climbs at 1/2:
      the estimate is above 1/2. If D-hat < 0 and A-hat >= 0, L meets
      A-hat once below 1/2, and again above 1/2 exactly when
      L(1) <= A-hat; if A-hat < 0 the nearest level is L(0), at 0
      alone. So
          the estimate is above 1/2  iff  D-hat (G-hat - B-hat) > 0,
          and below 1/2  iff  D-hat (G-hat - B-hat) < 0,
      off two sets. THE SPLIT ZONE, max(0, G-hat - B-hat) <= A-hat <=
      L-hat(1/2): an in-box root on each side of 1/2, or one at 1/2
      and one beside it or on it; each zeroes f, and the winner is
      candidate order and floating-point residue. It needs
      D-hat <= 0: at D-hat > 0 the zone is empty and only a tie is
      left out. THE TIES, where the product
      is zero: at G-hat = B-hat the mirror makes L symmetric about
      1/2, so the vertex sits at 1/2 or two mirror candidates tie and
      residue picks one; at D-hat = 0 a root sits at 1/2. The engine
      reads both sets' edges to 1e-12. The off-box case (the vertex
      outside [0, 1], or B-hat = 0 != G-hat, L monotone on the box)
      and each in-box winner (the vertex, an endpoint, a lone root)
      are this law's instances. The FLIP, the estimate
      strictly across 1/2 from kappa, is D-hat < 0 at both depth cells
      for a replicate off the zone with G-hat - B-hat of the
      population's sign, where D itself is positive.
  (C) THE D-LAW (observation). D-hat draws noise from all three
      samples. By the delta method from the exact moments (the third
      entering through cov(s^2, xbar) = mu3/n),
          Var(D-hat) = [m4u + m4m/4 + m4n/4 + d^2 (vm + vn)/4
                        + d (m3n - m3m)/2]/n
                       - [vu^2 + vm^2/4 + vn^2/4](n - 3)/(n(n - 1)),
      and the flip rate is read as Phi(-D/sd(D-hat)).
  (D) THE TANGENCY (property). For a {0, 1} feature with class rates
      mu_in, mu_out and mu_u = kappa mu_out + (1 - kappa) mu_in,
      var_out - var_in = d (1 - mu_out - mu_in), so
      A - B kappa^2 = kappa d (1 - 2 mu_u): for kappa d != 0 the two
      roots coincide at kappa exactly when the audited set is
      balanced.
  (E) THE IDENTIFIED SET (the sign law's instance). Two one-sided
      statements are built from the SAME resamples as the tool's band:
      UPPER, the 95% quantile of the LARGEST in-box root (a resample
      with no in-box root contributing the box top 1), and LOWER, the
      5% quantile of the SMALLEST (no root: 0). The truth is always
      one of the population roots, so reporting the root SET omits a
      term of known sign: widening to the set can only enlarge. Per
      trial UPPER >= LOWER by construction, so the pair is never wrong
      together. The tool's own band, the {5%, 95%} quantiles of the
      argmin, chooses a mode and has no such term.

BY HAND (each a pin of a check below).
  The six laws, as (mean, variance, third, fourth central moment).
  W3: HG(9,1,3) is a coin at 1/3: 1/3, 2/9, 2/27, 2/27. HG(9,2,3)
  puts 5/12, 1/2, 1/12 on 0, 1, 2: 2/3, 7/18, 5/54, 19/54. HG(10,2,3)
  puts 7/15, 7/15, 1/15: 3/5, 28/75, 14/125, 616/1875. So d = 1/3,
  B = 1/9, A = 34/225, G = 5/18, the second root 5/2 - 4/5 = 17/10,
  D = 1/25. Both cells' second roots lie outside the box: both are
  identified.
  W2, counting the moves by 3 instead (3 - c): HG(14,11,3) puts 165,
  165, 33, 1 of 364 on 0..3: 33/14, 1089/2548, -726/4459,
  238293/499408. HG(14,12,3) puts 220, 132, 12 of 364: 18/7, 198/637,
  -660/4459, 8118/31213. HG(15,12,3) puts 220, 198, 36, 1 of 455:
  12/5, 72/175, -1944/11375, 25632/56875. So d = 3/14, B = 9/196,
  A = -1017/63700, G = -45/637, the second root -20/13 - 1/5 =
  -113/65, D = 7857/254800. Each third moment agrees with
  var (M - 2K)(M - 2w)/(M(M - 2)).
  (C)'s brackets at W3: 616/1875 + 1/54 + 19/216 + 11/648 + 1/324 =
  92153/202500 and 784/5625 + 1/81 + 49/1296 = 153521/810000; for
  A-hat alone 6794/16875 and 9556/50625. At n = 1000 sd(D-hat) is
  0.01631 and the D-law Phi(-0.04/0.01631) = 0.0071; at W2 sd(D-hat)
  is 0.02016 and the D-law 0.0631, sd(A-hat) 0.024012, P3's frozen
  rate Phi(-0.0308359/0.024012) = 0.09954 and its distance from the
  measured 0.060, (0.09954 - 0.060)/0.009467, 4.176 of its standard
  errors.
  The tangency grid, rates and weights in tenths: 729 points, d != 0
  at 648, and among those the balanced ones solve
  k n + (10 - k) m = 50, two (k, n) for each m but 5: 16.
  coefficients() on (0, 1, 2), (2, 5, 8), (0, 0, 3): variances 1, 9,
  3 and d = 4, so A = 2, G = 24, B = 16. A resample (0, 0, 0) of the
  last has A = -1.
  The estimator's 28 hand rows are HAND_ROWS, each (A, G, B) with its
  estimate, winner, in-box root count and class worked on paper: ten
  off the box (four with the vertex below it, three above, one of
  them with its root at 7/16, just under 1/2, three linear), one
  degenerate, sixteen with the vertex in the box, two of them
  with it on an end of the box (v = 0 and v = 1),
  among them the vertex on a double root, an endpoint holding a root,
  the split zone at its lower end, its upper end and inside, and two
  with G = B, the vertex at 1/2 and the two ends tied; and one
  degenerate in exact terms alone, G = 1e-16, where 0.3 - 1e-16
  rounds below 0.3 and the far end wins on that residue. Of the 28
  rows 5 are ties and 3 in the zone, 21 scored; the side is fixed by
  the class samples at 5 (three vertex winners and two endpoints
  below both levels, each off a tie), symmetric at the 2 with G = B,
  and 2 endpoints win with A on an end's level. Phi(1) is
  0.8413447461 in the tables.
  The bounds on a stack of five resamples with larger roots (0.2,
  none, 0.6, none, 0.8) and smaller (none, none, 0.1, 0.4, 0.3): the
  largest are 0.2, 1, 0.6, 0.4, 0.8, whose 95% quantile is 0.8 + 0.8
  * 0.2 = 0.96; the smallest 0.2, 0, 0.1, 0.4, 0.3, whose 5% quantile
  is 0.2 * 0.1 = 0.02.

DESIGN. Every sweep is a row function of one (cell, n) and a sweep
over rows; a law is a count of agreements set against the size of its
class, a seeded count is pinned as recorded. LEVEL: W2 and W3 at n in
{50, 200, 1000}, R = 1000 fresh replicates each (member, non-member
and audited samples of size n), no bootstrap; sample variances with
ddof 1. A replicate's class is 0 off the box, 1 to 4 by the winner
with the vertex in the box (the vertex, an endpoint, a lone root, a
root of two), 5 degenerate (B-hat = G-hat = 0, to 1e-12). The side
law is read again, alone, at the ten seeds after the recorded one,
which hold the tie at G-hat = B-hat with the far end winning: a
record that the exclusion is needed, not a fresh read.
`--seeds FIRST COUNT` reads it at any others, behind the controls.
BAND: cells DIAL(1/5,
0), DIAL(1/5, 2), the mirror DIAL(4/5, 0), W2 and W3, at the same n,
R = 200 replicates, BOOT = 200 resamples of the audited set, G and B
held at the replicate's class values as the tool does. A replicate's
arms: FIT (the tool's band, nominal 0.90), UPPER and LOWER (nominal
0.95 each), FIT3 (the band's quantiles with all three samples
resampled). The estimator scores candidates in the order 0, 1, v,
root+, root- and keeps the first strict improvement. One seed per
(cell, n).

PREDICTIONS, as frozen before the first engine, and what became of
each. The kills as frozen: P1 or P2 off, the level-set law or its
in-box replacement false; P6's coverage off, the sign law does not
survive non-identification; P7 off, the bound valid by being empty;
P9, FIT3 at or below FIT at half the rows or more. None fired.
  P0 The controls: the mixture identity and the exact roots, the
     dial's roots through the engine, the estimator at population
     coefficients, the samplers. HELD; each is a hand pin now.
  P1 Off the box the estimate's side of 1/2 is the level set's, zero
     exceptions. HELD, and is now (B)'s one expression.
  P2 With the vertex in the box, the winner decides, zero exceptions
     on a lone root's branch. HELD.
  PS (frozen on the hand rows, before any count) One expression gives
     the side in every class, the split zone alone left out: above
     1/2 iff D-hat (G-hat - B-hat) > 0. WRONG at G-hat = B-hat, a case
     the derivation skipped and the recorded seed never drew with an
     endpoint's tie going the far way: at other seeds a replicate
     with the two class variances equal had its two ends tied and
     the far one won by residue. (B) is the law restated, its proof
     by the mirror redone to cover that case. The zone's edge is
     read to 1e-12 because in floats an A-hat on L-hat(1) in exact
     terms can compute a few 1e-17 off it.
  P3 At n in {200, 1000} the flip rate is within 4 standard errors of
     Phi((L(1/2) - A)/sd(A-hat)), G and B held at the population.
     WRONG, and the error is the slate's: the event is the sign of
     D-hat at the replicate's own coefficients. The D-law replaced it
     after the first run.
  P4 Among flipped replicates at n in {200, 1000} the winner is a
     root on at least 0.90. HELD (0.916 to 1). Its other half, a
     no-root rate read as a normal tail of A-hat, held within 0.05
     and left the record with the law it tested.
  P5 (D)'s identity in Fraction on the grid. HELD.
  P6 At DIAL(1/5, 0) UPPER covers >= 0.99 with mean slack above kappa
     >= 0.45 at every n, LOWER covers >= 0.90 (0.95 less 3.2 standard
     errors at R = 200) with its slack falling; at DIAL(4/5, 0) the
     same, exchanged. HELD.
  P7 At DIAL(1/5, 2) UPPER's mean slack falls below 0.10 at n = 1000.
     HELD.
  P8 The tool's band at W2 and W3 covers at most 0.85 at each of the
     six rows. HELD.
  P9 (frozen after the first band table, before its arm) FIT3 covers
     above the tool's band at all six depth-cell rows and at least
     0.85 at n = 1000. HELD.
  The thresholds of P6 to P9 are read off the pinned rows below.

FINDINGS.
  controls  the six laws' 24 moments, both cells' coefficients, roots
            and D as by hand; at kappa = 1/5 the dial's in-box roots
            kappa and 1 - kappa + gamma/4 at gamma = 0, 1/4, 1/2 and
            4/5 (the
            box's top end, kept at this rounding) and kappa alone at
            1 and 2; the estimator at population coefficients returns
            kappa to 1.1e-16; 28 of 28 hand rows; the 15 samplers'
            means within 0.0058 of the exact ones and variances
            within 0.0039 of them as a share.
  the side  (B)'s law on 5,989 of 5,989 scored replicates: the 5,429
            off the box and 560 of the 565 in it, 2 in the split zone
            and 9 on a tie, the ties all at W2, n = 50, the 6
            degenerate among them (two of the six with G-hat 1e-16 as
            computed, zero in exact terms). At ten further seeds
            59,866 of 59,866 scored of 60,000, 47 in the zone and 91
            ties, 4 in both. Off the box
            830, 951, 1000 at W2 and 743, 906, 999 at W3; in the box
            565, by winner 102/29/32/1, 32/4/12/1, none and
            151/1/97/8, 51/0/41/2, 0/0/1/0: 553 in the first three
            classes, 370 in the first two. The side is fixed by the
            class samples alone on 363: the 370 less four endpoint
            winners with A-hat on an endpoint's level to 1e-12 and
            three with G-hat = B-hat, two with the vertex at 1/2 and
            one with the two ends tied.
  the flip  440, 275, 60 of 1000 at W2 and 322, 132, 3 at W3 against
            the D-law 0.368, 0.247, 0.063 and 0.294, 0.137, 0.007:
            +2.02, -0.40, -0.46 and -1.54 of the law's standard errors
            at n >= 200, and above it by
            0.072 and 0.028 at n = 50, where the normal reading of
            D-hat degrades. The frozen P3 gives 0.100 at W2,
            n = 1000, 4.2 of its standard errors above the 0.060
            measured. sd(D-hat) measured 0.0902, 0.0465, 0.0198 and
            0.0726, 0.0362, 0.0154 against the delta method's 0.0912,
            0.0452, 0.0202 and 0.0739, 0.0366, 0.0163. The winner of
            a flipped replicate is a root on 271, 252, 60 and 318,
            132, 3: at n = 50, 169 of W2's 440 flips are won by an
            endpoint or the vertex.
  tangency  the identity at all 729 grid points; the roots meet at 16
            of the 648 with d != 0, the 16 balanced.
  band      (counts of 200 at n = 50, 200, 1000, printed as rates;
            slacks and widths in the mean)
            DIAL(1/5,0)  FIT 174, 177, 168; UPPER 200 x3, slack 0.794,
                         0.747, 0.648; LOWER 200, 200, 186, slack
                         0.194, 0.146, 0.047. The pair's excess beyond
                         [1/5, 4/5] is 0.194, 0.146, 0.047 below and
                         0.194, 0.147, 0.048 above: it closes on the
                         span of the identified set, not on a point.
            DIAL(4/5,0)  FIT 175, 178, 166; the swap: UPPER 200, 200,
                         185, slack 0.197, 0.145, 0.045; LOWER 200 x3,
                         slack 0.797, 0.748, 0.645.
            DIAL(1/5,2)  UPPER 192, 174, 182, slack 0.558, 0.181,
                         0.047: it contracts where the second root has
                         left the box.
            W(12,3)      FIT 145, 138, 142 (width 0.712, 0.610,
                         0.367), FIT3 189, 183, 174; LOWER 196, 183,
                         166.
            W(2,8)       FIT 154, 152, 156, FIT3 189, 177, 177; UPPER
                         180, 172, 175.
            Resampling all three samples lifts the tool's band by 21
            to 45 of 200 at every depth-cell row: at an identified
            cell the band's omitted term is the class samples' noise,
            which its procedure holds fixed. The one-sided bound on
            the side of the box end nearest the truth falls short
            there too, below 180 at three of six rows; no arm
            resamples the class samples for the bounds.
A count of 200 reads to about 0.02 at nominal, one of 1000 to about
0.015 at its largest; the laws and the directions are the finding, the
counts their instance, and a pinned count is the record of this seed
on this generator.

RUN RECORD. python audit.py: 28 of 28 checks, about 7 s, peak commit
about 52 MB. The samplers' two gaps, the zone's and the ties' counts
and the ten further seeds' record were entered from the first print of
this form; every other pin was derived or recorded before it.
python audit.py --seeds 20280000 100, seeds read once, after (B) was
restated: 598,670 of 598,670 scored of 600,000, 514 in the zone, 843
ties, 18 s.
Read by breaks: of 462 single edits inside the engine's functions (a
comparison negated or its boundary moved, a sign, a small constant, a
clause or a loop cut) 427 fail a check; three pass with a printed
line moved, each a compared value inside its check's slack: the
samplers' variance at ddof 2 (0.0039 to 0.0040 inside its 3%) and two
terms of the standard error the flips' distance from the D-law is
counted in (+2.02 to +1.32 and to +1.57, inside 4); 32 pass and move
nothing: a bound never met with equality (20: a tolerance's edge,
kappa against a quantile, the zone's, the ties' and the degenerate
class's edges), a clause true at every dial gamma (5), a loop of one
or a slice past the stack's end (4), a condition an earlier one
already took (2), a relative tolerance against zero (1). The D-law's
check sits behind the controls: with their stop lifted, the D-law
read with sd(A-hat) fails it and the 4 standard errors' check.
"""

import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")

import sys
import time
from fractions import Fraction as F
from math import comb, erf, sqrt

import numpy as np

NS = (50, 200, 1000)
R_LEVEL = 1000
R_BAND = 200
BOOT = 200
TOL = 1e-12
SEED = 20260928
CHECKS = []

# (A, G, B) and, by hand: the estimate, the winner (0 end 0, 1 end 1,
# 2 vertex, 3 root+, 4 root-), the in-box root count, the class, and
# the side (B)'s expression gives, None where it is not scored
HAND_ROWS = (
    (-1.3125, -1, 1, 0.75, 3, 1, 0, True),
    (-0.3125, -1, 1, 0.25, 3, 1, 0, False),
    (1, -1, 1, 0, 0, 0, 0, False),
    (-3, -1, 1, 1, 1, 0, 0, True),
    (1.6875, 3, 1, 0.75, 4, 1, 0, True),
    (0.6875, 3, 1, 0.25, 4, 1, 0, False),
    (1.5, 2, 0, 0.75, 3, 1, 0, True),
    (-0.5, -2, 0, 0.25, 3, 1, 0, False),
    (0.3, 0, 0, 0, 0, 0, 5, None),
    (1, 1.5, 1, 0.75, 2, 0, 1, True),
    (-1, 1.5, 1, 0, 0, 0, 2, False),
    (0.3125, 1.5, 1, 0.25, 4, 1, 3, False),
    (1, 0.5, 1, 0.25, 2, 0, 1, False),
    (-1, 0.5, 1, 1, 1, 0, 2, True),
    (-0.1875, 0.5, 1, 0.75, 3, 1, 3, True),
    (0, 1.5, 1, 0, 0, 1, 2, False),
    (0.328125, 1.25, 1, 0.875, 3, 2, 4, None),
    (0.38671875, 1.25, 1, 0.6875, 3, 2, 4, True),
    (0.25, 1.25, 1, 1, 1, 2, 2, None),
    (0.375, 1.25, 1, 0.75, 3, 2, 4, None),
    (0.5625, 1.5, 1, 0.75, 2, 2, 1, True),
    (0.25, 1, 0, 0.25, 3, 1, 0, False),
    (1, 1, 1, 0.5, 2, 0, 1, None),
    (-1, 1, 1, 0, 0, 0, 2, None),
    (1.12109375, 3, 1, 0.4375, 4, 1, 0, False),
    (-0.0625, 0, 1, 0.25, 3, 1, 3, False),
    (0.9375, 2, 1, 0.75, 4, 1, 3, True),
    (0.3, 1e-16, 0, 1, 1, 0, 5, None),
)

HAND_MOMENTS = {  # (mean, variance, fourth, third), in, out, audited
    "W(12,3)": ((F(33, 14), F(1089, 2548), F(238293, 499408),
                 F(-726, 4459)),
                (F(18, 7), F(198, 637), F(8118, 31213), F(-660, 4459)),
                (F(12, 5), F(72, 175), F(25632, 56875),
                 F(-1944, 11375))),
    "W(2,8)": ((F(1, 3), F(2, 9), F(2, 27), F(2, 27)),
               (F(2, 3), F(7, 18), F(19, 54), F(5, 54)),
               (F(3, 5), F(28, 75), F(616, 1875), F(14, 125))),
}
HAND_CELLS = {  # A, G, B, the second root, D
    "W(12,3)": (F(-1017, 63700), F(-45, 637), F(9, 196), F(-113, 65),
                F(7857, 254800)),
    "W(2,8)": (F(34, 225), F(5, 18), F(1, 9), F(17, 10), F(1, 25)),
}

# the level's record, a seeded run's: classes 0 to 5, the split zone,
# the ties, flips, flips won by a root, sd(D-hat) measured
LEVEL_PINS = {
    ("W(12,3)", 50): ((830, 102, 29, 32, 1, 6), 1, 9, 440, 271, 0.0902),
    ("W(12,3)", 200): ((951, 32, 4, 12, 1, 0), 1, 0, 275, 252, 0.0465),
    ("W(12,3)", 1000): ((1000, 0, 0, 0, 0, 0), 0, 0, 60, 60, 0.0198),
    ("W(2,8)", 50): ((743, 151, 1, 97, 8, 0), 0, 0, 322, 318, 0.0726),
    ("W(2,8)", 200): ((906, 51, 0, 41, 2, 0), 0, 0, 132, 132, 0.0362),
    ("W(2,8)", 1000): ((999, 0, 0, 1, 0, 0), 0, 0, 3, 3, 0.0154),
}
# ten further seeds: replicates, scored, in the zone, on a tie
FAR_PINS = (60000, 59866, 47, 91)
D_LAW_PINS = {"W(12,3)": (0.368, 0.247, 0.063),
              "W(2,8)": (0.294, 0.137, 0.007)}

# the band's record: counts of R_BAND and means, at n = 50, 200, 1000
BAND_PINS = {
    "DIAL(1/5,0)": dict(fit=(174, 177, 168), up=(200, 200, 200),
                        ups=(0.794, 0.747, 0.648), lo=(200, 200, 186),
                        los=(0.194, 0.146, 0.047)),
    "DIAL(1/5,2)": dict(up=(192, 174, 182), ups=(0.558, 0.181, 0.047)),
    "DIAL(4/5,0)": dict(fit=(175, 178, 166), up=(200, 200, 185),
                        ups=(0.197, 0.145, 0.045), lo=(200, 200, 200),
                        los=(0.797, 0.748, 0.645)),
    "W(12,3)": dict(fit=(145, 138, 142), width=(0.712, 0.610, 0.367),
                    fit3=(189, 183, 174), lo=(196, 183, 166)),
    "W(2,8)": dict(fit=(154, 152, 156), fit3=(189, 177, 177),
                   up=(180, 172, 175)),
}


def check(name, ok, detail=""):
    CHECKS.append(bool(ok))
    tag = "PASS" if ok else "FAIL"
    print(f"  {tag}  {name}" + (f"  ({detail})" if detail else ""))


def section(title):
    print()
    print(title)


def phi(x):
    return 0.5 * (1.0 + erf(x / sqrt(2.0)))


# -------------------------------------------------------------- worlds

def hg_moments(M, K, w=3):
    """Mean, variance, fourth and third central moments of HG(M, K, w)."""
    p = [F(comb(K, c) * comb(M - K, w - c), comb(M, w))
         for c in range(w + 1)]
    mu = sum(c * q for c, q in enumerate(p))
    var = sum((c - mu) ** 2 * q for c, q in enumerate(p))
    m4 = sum((c - mu) ** 4 * q for c, q in enumerate(p))
    m3 = sum((c - mu) ** 3 * q for c, q in enumerate(p))
    return mu, var, m4, m3


def var_s2(mom, n):
    """Exact variance of a sample variance (ddof 1) over n draws."""
    return mom[2] / n - mom[1] ** 2 * F(n - 3, n * (n - 1))


class Depth:
    """The depth cell (a, b): exact class moments and the three samplers."""

    def __init__(self, a, b):
        self.a, self.b, self.T = a, b, a + b
        self.name = f"W({a},{b})"
        self.pi = F(b, self.T)
        self.m = hg_moments(self.T - 1, a - 1)
        self.n = hg_moments(self.T - 1, a)
        self.u = hg_moments(self.T, a)
        self.laws = (self.m[:2], self.n[:2], self.u[:2])
        d = self.n[0] - self.m[0]
        self.B = d * d
        self.A = self.u[1] - self.m[1]
        self.G = self.n[1] - self.m[1] + self.B
        self.D = self.A - (self.G / 2 - self.B / 4)

    def var_A(self, n):
        """Exact variance of A-hat = s_u^2 - s_m^2."""
        return var_s2(self.u, n) + var_s2(self.m, n)

    def var_D(self, n):
        """Delta-method variance of D-hat = s_u^2 - s_m^2/2 - s_n^2/2 -
        dhat^2/4 from the exact moments: cov(s^2, xbar) = mu3/n within
        a sample."""
        d = self.n[0] - self.m[0]
        return (var_s2(self.u, n) + var_s2(self.m, n) / 4
                + var_s2(self.n, n) / 4
                + d * d / 4 * (self.m[1] + self.n[1]) / n
                + d / 2 * (self.n[3] - self.m[3]) / n)

    def sd_A(self, n):
        return sqrt(float(self.var_A(n)))

    def sd_D(self, n):
        return sqrt(float(self.var_D(n)))

    def draw(self, rng, n, size=None):
        shape = (n,) if size is None else (size, n)
        T, a = self.T, self.a
        xm = rng.hypergeometric(a - 1, T - a, 3, shape).astype(float)
        xn = rng.hypergeometric(a, T - 1 - a, 3, shape).astype(float)
        xu = rng.hypergeometric(a, T - a, 3, shape).astype(float)
        return xm, xn, xu


class Dial:
    """F_in = N(0, 1), F_out = N(2, 1 + gamma), the audited set a
    kappa-mixture."""

    def __init__(self, pi, gamma):
        self.pi, self.gamma = F(pi), F(gamma)
        self.name = f"DIAL({self.pi},{self.gamma})"
        self.B = F(4)
        self.G = self.gamma + 4
        self.A = self.pi * self.gamma + 4 * self.pi * (1 - self.pi)
        self.laws = ((F(0), F(1)), (F(2), 1 + self.gamma),
                     (2 * self.pi, 1 + self.A))

    def draw(self, rng, n, size=None):
        shape = (n,) if size is None else (size, n)
        sn = sqrt(1.0 + float(self.gamma))
        xm = rng.normal(0.0, 1.0, shape)
        xn = rng.normal(2.0, sn, shape)
        pick = rng.random(shape) < float(self.pi)
        xu = np.where(pick, rng.normal(2.0, sn, shape),
                      rng.normal(0.0, 1.0, shape))
        return xm, xn, xu


def coefficients(xm, xn, xu):
    """A, G, B from the three samples (last axis), ddof 1."""
    d = xn.mean(-1) - xm.mean(-1)
    B = d * d
    vm = xm.var(-1, ddof=1)
    A = xu.var(-1, ddof=1) - vm
    G = xn.var(-1, ddof=1) - vm + B
    return A, G, B


def resampled_levels(xm, xu, idx):
    """A-hat on each resample idx of the audited sample, var_in held at
    the member sample's: what the tool's band resamples."""
    return xu[idx].var(1, ddof=1) - xm.var(ddof=1)


# ----------------------------------------------------------- estimator

def candidates(A, G, B):
    """The source's candidate set, in its order, nan where absent.

    The critical points of (A - pG + p^2 B)^2 are the roots of
    (B p^2 - G p + A)(2 B p - G), the source's cubic: the vertex and the
    level's two roots, root+ the larger; at B = 0 the one root A/G,
    tagged root+."""
    A, G, B = np.broadcast_arrays(*map(np.asarray, (A, G, B)))
    A, G, B = A.astype(float), G.astype(float), B.astype(float)
    nan = np.full(A.shape, np.nan)
    pos = B > 0
    with np.errstate(divide="ignore", invalid="ignore"):
        v = np.where(pos, G / (2 * B), nan)
        disc = G * G - 4 * A * B
        sq = np.sqrt(np.where(disc >= 0, disc, nan))
        rp = np.where(pos, (G + sq) / (2 * B), nan)
        rm = np.where(pos, (G - sq) / (2 * B), nan)
        lin = (~pos) & (G != 0)
        rp = np.where(lin, A / G, rp)

    def box(x):
        return np.where((x >= 0) & (x <= 1), x, nan)
    return np.stack([np.zeros(A.shape), np.ones(A.shape), box(v),
                     box(rp), box(rm)]), A, G, B


def estimate(A, G, B):
    """Estimate, winning candidate (0 end0, 1 end1, 2 vertex, 3 root+,
    4 root-), the in-box root count, and the candidate stack."""
    C, A, G, B = candidates(A, G, B)
    f = (A - C * G + C * C * B) ** 2
    best = f[0].copy()
    tag = np.zeros(A.shape, dtype=int)
    for k in range(1, 5):
        better = f[k] < best          # an absent candidate is nan: never
        best = np.where(better, f[k], best)
        tag = np.where(better, k, tag)
    est = np.take_along_axis(C, tag[None], 0)[0]
    nroots = (~np.isnan(C[3])).astype(int) + (~np.isnan(C[4])).astype(int)
    return est, tag, nroots, C


def root_span(C):
    """Smallest and largest in-box root per entry, nan where none."""
    R = C[3:5]
    none = np.isnan(R).all(0)
    lo = np.where(none, np.nan, np.where(np.isnan(R), np.inf, R).min(0))
    hi = np.where(none, np.nan, np.where(np.isnan(R), -np.inf, R).max(0))
    return lo, hi


def bounds(C):
    """UPPER, the 95% quantile of the largest in-box root (none: the box
    top), and LOWER, the 5% quantile of the smallest (none: 0)."""
    lo, hi = root_span(C)
    return (float(np.quantile(np.where(np.isnan(hi), 1.0, hi), 0.95)),
            float(np.quantile(np.where(np.isnan(lo), 0.0, lo), 0.05)))


def side_read(A, G, B):
    """Per entry: the estimate with its winner, its class (0 off the
    box, 1 the vertex wins, 2 an endpoint, 3 a lone root, 4 a root of
    two, 5 degenerate, B-hat and G-hat zero to 1e-12), whether it sits
    in the split zone or on a tie, D-hat, the side (B) derives and the
    side the estimate takes, each as a sign; whether the vertex or an
    endpoint below both ends' levels won off a tie (fixed: the class
    samples alone give the side) or on one (sym), or an endpoint won
    with A-hat on an end's level."""
    est, tag, nroots, _ = estimate(A, G, B)
    A, G, B = (np.asarray(x, dtype=float) for x in (A, G, B))
    h = G / 2 - B / 4
    with np.errstate(divide="ignore", invalid="ignore"):
        v = G / (2 * B)               # infinite or nan at B = 0: off
        inbox = (v >= 0) & (v <= 1)
    winner = np.select([tag == 2, tag < 2, nroots == 1], [1, 2, 3], 4)
    flat = (np.abs(B) <= TOL) & (np.abs(G) <= TOL)
    case = np.where(inbox, winner, np.where(flat, 5, 0))
    tie = (np.abs(A - h) <= TOL) | (np.abs(G - B) <= TOL)
    alone = (case == 1) | ((case == 2) & (A < np.minimum(0, G - B) - TOL))
    return dict(est=est, tag=tag, nroots=nroots, case=case, D=A - h,
                split=inbox & (A >= np.maximum(0, G - B) - TOL)
                & (A <= h + TOL), tie=tie,
                law=np.sign((A - h) * (G - B)), side=np.sign(est - 0.5),
                fixed=alone & ~tie, sym=alone & tie,
                on_level=(case == 2)
                & (np.isclose(A, 0, rtol=0, atol=TOL)
                   | np.isclose(A, G - B, rtol=0, atol=TOL)))


def hand_sides(rows):
    """The hand rows through side_read: agreements a field, and the
    counts the sweeps leave small."""
    A, G, B = (np.array([r[k] for r in rows], dtype=float) for k in range(3))
    s = side_read(A, G, B)
    scored = np.array([r[7] is not None for r in rows])
    want = np.array([1 if r[7] else -1 for r in rows])
    return dict(
        est=sum(float(x) == r[3] for x, r in zip(s["est"], rows)),
        tag=sum(int(x) == r[4] for x, r in zip(s["tag"], rows)),
        nroots=sum(int(x) == r[5] for x, r in zip(s["nroots"], rows)),
        case=sum(int(x) == r[6] for x, r in zip(s["case"], rows)),
        scored=int((scored == ~(s["split"] | s["tie"])).sum()),
        law=int((scored & (s["law"] == want)).sum()),
        side=int((scored & (s["law"] == s["side"])).sum()),
        split=int(s["split"].sum()), tie=int(s["tie"].sum()),
        fixed=int(s["fixed"].sum()), sym=int(s["sym"].sum()),
        on_level=int(s["on_level"].sum()))


def rng_for(cell_index, n, seed=SEED):
    return np.random.default_rng([seed, cell_index, n])


# -------------------------------------------------------- the controls

W2, W3 = Depth(12, 3), Depth(2, 8)


def moment_hits(w):
    """Agreements of the cell's 12 moments with the hand ones, and of
    A, G, B, D, the objective at kappa and at the hand second root."""
    hand, cell = HAND_MOMENTS[w.name], HAND_CELLS[w.name]
    moments = sum(x == y for got, want in zip((w.m, w.n, w.u), hand)
                  for x, y in zip(got, want))
    coeff = sum(x == y for x, y in zip((w.A, w.G, w.B, w.D), cell[:3]
                                       + cell[4:]))
    roots = sum(w.A - p * w.G + p * p * w.B == 0 for p in (w.pi, cell[3]))
    return moments, coeff, roots + (w.G / w.B - w.pi == cell[3])


def dial_roots(gamma):
    """The engine's in-box roots on the dial at kappa = 1/5, sorted."""
    dl = Dial(F(1, 5), gamma)
    C = candidates(float(dl.A), float(dl.G), float(dl.B))[0]
    return sorted(float(x) for x in C[3:5] if not np.isnan(x))


def dial_hits(inside, outside):
    """Gammas whose in-box roots are kappa and 1 - kappa + gamma/4, and
    gammas whose in-box root is kappa alone."""
    two = sum(len(r) == 2 and abs(r[0] - 0.2) < TOL
              and abs(r[1] - 0.8 - float(g) / 4) < TOL
              for g in inside for r in [dial_roots(g)])
    one = sum(len(r) == 1 and abs(r[0] - 0.2) < TOL
              for g in outside for r in [dial_roots(g)])
    return two, one


def sampler_gaps(worlds, n=100000):
    """Over each world's three samplers: the gap of the sample mean from
    the exact mean, and of the sample variance from the exact one as a
    share of it. Returns the reads inside 0.03 and the worst of each."""
    gm, gv = [], []
    for k, w in enumerate(worlds):
        for x, (mu, var) in zip(w.draw(rng_for(k, n), n), w.laws):
            gm.append(abs(float(x.mean()) - float(mu)))
            gv.append(abs(float(x.var(ddof=1)) / float(var) - 1))
    return sum(g < 0.03 for g in gm + gv), max(gm), max(gv)


def kappa_hits(cells):
    """Cells where the estimator at the population's coefficients
    returns kappa, and the worst gap."""
    gaps = [abs(float(estimate(float(w.A), float(w.G), float(w.B))[0])
                - float(w.pi)) for w in cells]
    return sum(g < TOL for g in gaps), max(gaps)


def tangency_sweep(grid):
    """Over class rates and weights on the grid: points where (D)'s
    identity holds; points with d != 0; of those, the balanced, the
    ones whose two roots meet, and the ones where the two agree."""
    rec = dict(points=0, identity=0, live=0, balanced=0, meet=0, iff=0)
    for qm in grid:
        for qn in grid:
            for pi in grid:
                d = qn - qm
                qu = pi * qn + (1 - pi) * qm
                A = qu * (1 - qu) - qm * (1 - qm)
                B = d * d
                G = qn * (1 - qn) - qm * (1 - qm) + B
                rec["points"] += 1
                rec["identity"] += A - B * pi * pi == pi * d * (1 - 2 * qu)
                if d != 0:
                    balanced, meet = 2 * qu == 1, G * G == 4 * A * B
                    rec["live"] += 1
                    rec["balanced"] += balanced
                    rec["meet"] += meet
                    rec["iff"] += balanced == meet
    return rec


# ---------------------------------------------------------- the sweeps

def flip_law(w, n):
    """The D-law: Phi(-D/sd(D-hat))."""
    return phi(-float(w.D) / w.sd_D(n))


def flip_gap(w, n, flips):
    """The flip rate less the D-law, in the law's standard errors over
    R_LEVEL replicates."""
    law = flip_law(w, n)
    return (flips / R_LEVEL - law) / sqrt(law * (1 - law) / R_LEVEL)


def frozen_law(w, n):
    """P3 as frozen: G and B at the population, the spread of A-hat."""
    return phi(-float(w.D) / w.sd_A(n))


def level_row(w, ci, n, seed=SEED):
    """One (cell, n): R_LEVEL replicates read by side_read. A replicate
    is scored outside the split zone and off the ties, and hits when
    the law's side is the estimate's."""
    xm, xn, xu = w.draw(rng_for(ci, n, seed), n, R_LEVEL)
    s = side_read(*coefficients(xm, xn, xu))
    pi = float(w.pi)
    flip = s["side"] * (pi - 0.5) < 0
    scored = ~(s["split"] | s["tie"])
    hit = scored & (s["law"] == s["side"])
    box = s["case"] > 0               # class 5 is a tie: never scored
    return dict(
        cases=tuple(int((s["case"] == c).sum()) for c in range(6)),
        split=int(s["split"].sum()), tie=int(s["tie"].sum()),
        scored_off=int((scored & (s["case"] == 0)).sum()),
        scored_box=int((scored & box).sum()),
        hit_off=int((hit & (s["case"] == 0)).sum()),
        hit_box=int((hit & box).sum()),
        flips=int(flip.sum()),
        root_flips=int((flip & (s["tag"] > 2)).sum()),
        fixed=int(s["fixed"].sum()), sym=int(s["sym"].sum()),
        on_level=int(s["on_level"].sum()),
        sd=float(np.std(s["D"], ddof=1)))


def level_sweep(cells, seed=SEED):
    return {(w.name, n): level_row(w, ci, n, seed)
            for ci, w in enumerate(cells, start=1) for n in NS}


def law_sweep(cells, seeds):
    """The side law alone over further seeds: replicates, those in the
    split zone, on a tie, scored, and the scored that hit."""
    t = dict(rep=0, split=0, tie=0, scored=0, hits=0)
    for seed in seeds:
        for r in level_sweep(cells, seed).values():
            t["rep"] += sum(r["cases"])
            t["split"] += r["split"]
            t["tie"] += r["tie"]
            t["scored"] += r["scored_off"] + r["scored_box"]
            t["hits"] += r["hit_off"] + r["hit_box"]
    return t


def level_totals(rec):
    """Replicates off the box, in it, in its first three classes and
    its first two; of those two, side-fixed, symmetric, on an
    endpoint's level; the law's agreements and the replicates it
    scores."""
    t = dict(off=0, box=0, three=0, two=0, fixed=0, sym=0, on_level=0,
             hits=0, scored=0)
    for r in rec.values():
        c = r["cases"]
        t["off"] += c[0]
        t["box"] += sum(c[1:5])
        t["three"] += sum(c[1:4])
        t["two"] += c[1] + c[2]
        t["fixed"] += r["fixed"]
        t["sym"] += r["sym"]
        t["on_level"] += r["on_level"]
        t["hits"] += r["hit_off"] + r["hit_box"]
        t["scored"] += r["scored_off"] + r["scored_box"]
    return t


def band_row(w, ci, n):
    """One (cell, n): R_BAND replicates, each with BOOT resamples.
    Counts of trials covering kappa a arm, and the mean width of the
    tool's band and slack of each bound."""
    rng = rng_for(ci, n)
    pi = float(w.pi)
    rows = []
    for _ in range(R_BAND):
        xm, xn, xu = w.draw(rng, n)
        A, G, B = coefficients(xm, xn, xu)
        idx = rng.integers(0, n, (BOOT, n))
        est, _, _, C = estimate(resampled_levels(xm, xu, idx), G, B)
        q5, q95 = np.quantile(est, (0.05, 0.95))
        U, L = bounds(C)
        im = rng.integers(0, n, (BOOT, n))
        i_n = rng.integers(0, n, (BOOT, n))
        est3 = estimate(*coefficients(xm[im], xn[i_n], xu[idx]))[0]
        r5, r95 = np.quantile(est3, (0.05, 0.95))
        rows.append((q5 <= pi <= q95, pi <= U, L <= pi, r5 <= pi <= r95,
                     q95 - q5, U - pi, pi - L))
    a = np.array(rows, dtype=float)
    return dict(fit=int(a[:, 0].sum()), up=int(a[:, 1].sum()),
                lo=int(a[:, 2].sum()), fit3=int(a[:, 3].sum()),
                width=float(a[:, 4].mean()), ups=float(a[:, 5].mean()),
                los=float(a[:, 6].mean()))


def band_sweep(cells):
    return {(w.name, n): band_row(w, ci, n)
            for ci, w in enumerate(cells, start=10) for n in NS}


def band_hits(rec, pins):
    """The pinned values a record meets, a count equal or a mean to its
    three places, and the ones it misses."""
    hits, bad = 0, []
    for name, fields in pins.items():
        for key, want in fields.items():
            for n, x in zip(NS, want):
                got = rec[name, n][key]
                if (got == x) if isinstance(x, int) else \
                        (abs(got - x) < 0.0005):
                    hits += 1
                else:
                    bad.append(f"{name} {key} n={n}: {got}")
    return hits, bad


def excess_above(rec, w):
    """How far UPPER's mean sits above the far root 1 - kappa."""
    k = float(w.pi)
    return [k + rec[w.name, n]["ups"] - (1 - k) for n in NS]


# ------------------------------------------------------------ sections

def section_controls():
    section("CONTROLS")
    for w in (W2, W3):
        print(f"  {w.name}: kappa = {w.pi}, A = {w.A}, G = {w.G}, "
              f"B = {w.B}, second root {w.G / w.B - w.pi}, D = {w.D}")
    hits = [moment_hits(w) for w in (W2, W3)]
    check("the six laws' moments as by hand",
          [h[0] for h in hits] == [12, 12])
    check("A, G, B and D at both cells as by hand",
          [h[1] for h in hits] == [4, 4])
    check("kappa and the hand second root zero the objective, the "
          "second root G/B - kappa", [h[2] for h in hits] == [3, 3])
    hand = [F(92153, 202500) / n
            - F(153521, 810000) * F(n - 3, n * (n - 1)) for n in NS]
    hand_a = [F(6794, 16875) / n
              - F(9556, 50625) * F(n - 3, n * (n - 1)) for n in NS]
    check("Var(D-hat) and Var(A-hat) at (2, 8) as by hand at each n",
          sum(W3.var_D(n) == x for n, x in zip(NS, hand)) == 3
          and sum(W3.var_A(n) == x for n, x in zip(NS, hand_a)) == 3)
    check("phi at 0 and at 1",
          phi(0.0) == 0.5 and abs(phi(1.0) - 0.8413447460685429) < TOL)
    A, G, B = coefficients(np.array([0., 1., 2.]), np.array([2., 5., 8.]),
                           np.array([0., 0., 3.]))
    check("coefficients() on the hand samples", (A, G, B) == (2, 24, 16),
          f"{A}, {G}, {B}")
    lev = resampled_levels(np.array([0., 1., 2.]), np.array([0., 0., 3.]),
                           np.array([[0, 1, 2], [0, 0, 1]]))
    check("a resample's A-hat on the hand samples",
          lev.tolist() == [2, -1])
    hs = hand_sides(HAND_ROWS)
    n = len(HAND_ROWS)
    check("the estimator's hand rows: estimate, winner, root count, class",
          (hs["est"], hs["tag"], hs["nroots"], hs["case"]) == (n, n, n, n),
          f"{hs['est']}, {hs['tag']}, {hs['nroots']}, {hs['case']} of {n}")
    check("the hand rows' side: scored as by hand, the law's side and "
          "the estimate's on each, the zone and the ties",
          (hs["scored"], hs["law"], hs["side"], hs["split"], hs["tie"])
          == (n, 21, 21, 3, 5),
          f"{hs['law']} and {hs['side']} of 21, {hs['split']} in the zone, "
          f"{hs['tie']} ties")
    check("the hand rows' side-fixed, symmetric and on-level counts",
          (hs["fixed"], hs["sym"], hs["on_level"]) == (5, 2, 2))
    stack = np.full((5, 5), np.nan)
    stack[3] = [0.2, np.nan, 0.6, np.nan, 0.8]
    stack[4] = [np.nan, np.nan, 0.1, 0.4, 0.3]
    U, L = bounds(stack)
    check("the bounds on the hand stack",
          abs(U - 0.96) < TOL and abs(L - 0.02) < TOL, f"{U:.4f}, {L:.4f}")
    two, one = dial_hits((F(0), F(1, 4), F(1, 2), F(4, 5)), (F(1), F(2)))
    check("the engine's in-box dial roots: kappa and 1 - kappa + gamma/4 "
          "in the box, kappa alone past it", (two, one) == (4, 2),
          f"{two} of 4, {one} of 2")
    hit, err = kappa_hits((W2, W3))
    check("the estimator at population coefficients returns kappa at "
          "both cells", hit == 2, f"{err:.1e}")
    hit, gm, gv = sampler_gaps((W2, W3, Dial(F(1, 5), 0), Dial(F(1, 5), 2),
                                Dial(F(4, 5), 0)))
    check("the 15 samplers' means within 0.03 and variances within 3% "
          "of the exact ones", hit == 30, f"worst {gm:.4f}, {gv:.4f}")
    return all(CHECKS)


def section_level():
    section("THE SIDE AND THE FLIP")
    rec = level_sweep((W2, W3))
    print("  cell          n   off  won by v/end/root/root of 2  degenerate"
          "  split  ties  flip  D-law  root|flip  sd(D-hat) by the delta "
          "method, measured")
    for (name, n), r in rec.items():
        w = W2 if name == W2.name else W3
        c = r["cases"]
        print(f"  {name:9s} {n:5d}  {c[0]:4d}  {c[1]}/{c[2]}/{c[3]}/{c[4]}"
              f"  {c[5]}  {r['split']}  {r['tie']}"
              f"  {r['flips'] / R_LEVEL:.3f}  {flip_law(w, n):.3f}"
              f"  {r['root_flips'] / max(r['flips'], 1):.3f}"
              f"  {w.sd_D(n):.4f}, {r['sd']:.4f}")
    t = level_totals(rec)
    print(f"  LEVEL the side is the sign of D-hat (G-hat - B-hat): "
          f"{t['hits']} of {t['scored']} scored")
    check("LEVEL off the box the side is the sign of "
          "D-hat (G-hat - B-hat) at every scored replicate",
          sum(r["hit_off"] == r["scored_off"] for r in rec.values()) == 6,
          f"{sum(r['hit_off'] for r in rec.values())} of "
          f"{sum(r['scored_off'] for r in rec.values())}")
    check("LEVEL in the box the same",
          sum(r["hit_box"] == r["scored_box"] for r in rec.values()) == 6,
          f"{sum(r['hit_box'] for r in rec.values())} of "
          f"{sum(r['scored_box'] for r in rec.values())}")
    check("LEVEL the classes, the zone, the ties, the flips and the "
          "root flips as recorded",
          sum((r["cases"], r["split"], r["tie"], r["flips"],
               r["root_flips"]) == LEVEL_PINS[k][:5]
              for k, r in rec.items()) == 6)
    check("LEVEL sd(D-hat) measured as recorded",
          sum(abs(r["sd"] - LEVEL_PINS[k][5]) < 0.00005
              for k, r in rec.items()) == 6)
    far = law_sweep((W2, W3), range(SEED + 1, SEED + 11))
    print(f"  at ten further seeds: {far['hits']} of {far['scored']} "
          f"scored of {far['rep']}, {far['split']} in the zone, "
          f"{far['tie']} ties")
    check("LEVEL the same at ten further seeds, every scored replicate",
          far["hits"] == far["scored"])
    check("LEVEL the ten further seeds' replicates, scored, zone and "
          "ties as recorded",
          (far["rep"], far["scored"], far["split"], far["tie"])
          == FAR_PINS)
    check("LEVEL the totals: off the box, in it, its first three "
          "classes, its first two; of those, side-fixed, symmetric, on "
          "a level; the law's hits and its scored",
          (t["off"], t["box"], t["three"], t["two"], t["fixed"],
           t["sym"], t["on_level"], t["hits"], t["scored"])
          == (5429, 565, 553, 370, 363, 3, 4, 5989, 5989),
          f"{t['off']}, {t['box']}, {t['three']}, {t['two']}, "
          f"{t['fixed']}, {t['sym']}, {t['on_level']}")
    gaps = [flip_gap(W2 if name == W2.name else W3, n, r["flips"])
            for (name, n), r in rec.items() if n >= 200]
    check("LEVEL the flip rate within 4 standard errors of the D-law at "
          "each row with n >= 200",
          sum(abs(g) <= 4 for g in gaps) == 4,
          "in standard errors " + ", ".join(f"{g:+.2f}" for g in gaps))
    check("LEVEL the D-law as by hand at n = 1000 and as recorded",
          abs(flip_law(W2, 1000) - 0.0631) < 0.00005
          and abs(flip_law(W3, 1000) - 0.0071) < 0.00005
          and sum(abs(flip_law(w, n) - x) < 0.0005 for w in (W2, W3)
                  for n, x in zip(NS, D_LAW_PINS[w.name])) == 6)
    fz = frozen_law(W2, 1000)
    z = (fz - rec[W2.name, 1000]["flips"] / R_LEVEL) \
        / sqrt(fz * (1 - fz) / R_LEVEL)
    check("LEVEL P3 as frozen at (12, 3), n = 1000: its rate and its "
          "distance from the measured in its standard errors",
          abs(fz - 0.09954) < 0.00005 and abs(z - 4.176) < 0.005,
          f"{fz:.4f}, {z:.2f}")


def section_tangency():
    section("THE TANGENCY: a balanced binary feature")
    t = tangency_sweep([F(k, 10) for k in range(1, 10)])
    check("the identity A - B kappa^2 = kappa d (1 - 2 mu_u) at every "
          "grid point", (t["points"], t["identity"]) == (729, 729))
    check("the two roots meet exactly at the balanced points with d != 0",
          (t["live"], t["balanced"], t["meet"], t["iff"])
          == (648, 16, 16, 648),
          f"{t['meet']} of {t['live']}")


def section_band():
    section("THE BAND AND THE IDENTIFIED SET")
    cells = (Dial(F(1, 5), 0), Dial(F(1, 5), 2), Dial(F(4, 5), 0), W2, W3)
    rec = band_sweep(cells)
    names = dict(fit="FIT", up="UPPER", lo="LOWER", fit3="FIT3",
                 width="width", ups="UPPER slack", los="LOWER slack")
    for name, fields in BAND_PINS.items():
        print(f"  {name}: " + "; ".join(
            names[key] + " " + ", ".join(
                (f"{rec[name, n][key] / R_BAND:.3f}"
                 if isinstance(want[0], int)
                 else f"{rec[name, n][key]:.3f}") for n in NS)
            for key, want in fields.items()))
    hits, bad = band_hits(rec, BAND_PINS)
    check("BAND the 57 quoted counts and means as recorded", hits == 57,
          "; ".join(bad))
    ex = excess_above(rec, cells[0])
    print(f"  {cells[0].name}'s UPPER in the mean above 4/5: "
          + ", ".join(f"{x:.3f}" for x in ex))
    check("BAND the pair's excess above the far root as recorded",
          sum(abs(x - y) < 0.0005
              for x, y in zip(ex, (0.194, 0.147, 0.048))) == 3)


def main():
    t0 = time.time()
    if not section_controls():
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    if sys.argv[1:2] == ["--seeds"]:
        first, count = int(sys.argv[2]), int(sys.argv[3])
        t = law_sweep((W2, W3), range(first, first + count))
        print(f"seeds {first} to {first + count - 1}: {t['hits']} of "
              f"{t['scored']} scored of {t['rep']}, {t['split']} in the "
              f"zone, {t['tie']} ties, {time.time() - t0:.1f} s")
        sys.exit(0 if t["hits"] == t["scored"] else 1)
    section_level()
    section_tangency()
    section_band()
    print()
    print(f"{sum(CHECKS)} of {len(CHECKS)} checks, "
          f"{time.time() - t0:.1f} s")
    sys.exit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()