statements.py

Checks: RULER: The sign law of a stated interval property; observation; RULER: Coverage is a function of two ratios property; observation; RULER: The kernel of the inside instruments property; observation.

Cited on: RULER.

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

"""statements.py -- a stated uncertainty read as a law: the sign of what
it omits, the two ratios its coverage is a function of, what an auditor
can see of the omission from inside, and the exact mean under each
seeded column.

QUESTION. estimators.py found intervals that fail without warning: a
resubstitution bar at a knife slice that almost never covers, a held-out
bar whose coverage falls as data grows. Those are failures of particular
estimators. This script reads the object they share, the UNCERTAINTY
STATEMENT "estimate +- h", and asks three things of it. Which way can
it fail? What decides whether more data cures it? And can the failure
be seen by someone holding one sample and no truth?

THE WORLDS. M = 15 equiprobable bins (WIDE: 105), bin r labelled 1 with
rate eta_r, a Fraction; the target is the Bayes error R* = (1/M) sum_r
min(eta_r, 1 - eta_r), exact. Drawing x uniform from a threshold slice
of ceiling.py and reading (x mod M, [x >= t]) is such a draw
(estimators.py, property A), so the ring's bins enter as their eta.
  CLEAR  three groups of five, no rate nearer 1/2 than 1/10, every group
         straddling 1/2: 1/10 3/10 2/5 3/5 4/5 | 1/5 1/4 7/10 3/4 9/10
         | 1/10 2/5 3/5 7/10 9/10.   R* = 19/75.
  KNIFE  every eta_r = 1/2: the ring slice N = 210, M = 15, t = 105.
  MILD   per group four bins well off 1/2 and one just past it:
         3/10 x4, 13/25 | 1/4 x4, 27/50 | 2/5 x4, 51/100.  R* = 523/1500.
  SAME   every rate below 1/2, heterogeneous within each group:
         1/10 1/5 3/10 2/5 9/20 | 1/20 3/20 1/4 7/20 9/20 | 1/10 3/20
         1/5 3/10 2/5.   R* = 77/300.
  WIDE   105 bins at eta = 6/11: the ring slice N = 1155, M = 105,
         t = 525, R* = 5/11.

THE STATEMENTS. From per-bin counts (zeros, ones) of n draws:
  PER-BIN   the minority labels over n: sum_r min(zeros_r, ones_r)/n.
  POOLED    the same with the bins merged into the three groups: a
            model class that cannot hold CLEAR's or MILD's truth. Its
            limit misses R* by the POOLING GAP, exact: 29/150 on CLEAR,
            7/750 on MILD, 0 on SAME.
  SHRUNK    every bin's rate pulled toward 1/2 with weight lam = n^(-1/4)
            before the min.
  HELD-OUT  the per-bin majority fitted on an exact half of the sample,
            a tie or an empty bin guessing 1, its 0-1 error scored on
            the other half.
Each FIT states the two-sided bar h = z sqrt(E(1 - E)/m) about its
estimate E, z = 1.96, m the points the rate is read from. The BOUND is
the held-out error with the one-sided upper bar at the same z.

THE ARGUMENT.
  (A) THE SIGN LAW (proved, with no normal approximation). A rule fitted
      on one half is fixed before the other half is read, and the
      halves of an exact split are independent samples (L2), so its
      test errors are binomial on m points about the rule's own risk
      rho, and every rule has rho >= R*. The upper bound at x errors,
      f(x) = x/m + z sqrt(x (m - x)/m^3), is concave on [0, m] with
      f(m) = 1, so for any level c <= 1 the counts whose bound holds c
      are every count from a least one x*(m, c) up. A binomial's upper
      tail rises with its rate. So, in every world and for every way of
      choosing the rule from the training half,
          P(err + h >= R*) >= P(Bin(m, R*) >= x*(m, R*)),
      with equality where every rule has risk R*. The right side is the
      chance that the same bar, stated about a coin of rate R*, holds
      that rate: the omitted term rho - R* has a known sign and only
      adds to it. The floor is that chance and not 0.975: at R* = 1/2
      the edge is x* = ceil(m/2 - (z/2) m / sqrt(m + z^2)), the Wilson
      edge, and the chance runs under 0.975 at three of the four m here.
      A fit has no such law: its bias has the sign its class gives it
      (PER-BIN's mean deviation is <= 0 in every world, min being
      concave; a pooled fit adds its gap against that) and its bar can
      be too wide or too narrow. Nor is a bound empty for being
      conservative: on CLEAR it stays below 1/2.
  (B) THE PLANE. Write b for the estimate's mean deviation from R*, sd
      for its standard deviation, h for the mean stated bar. If the
      estimate is near normal and the bar near its mean, a two-sided
      fit covers at
      Phi((h - b)/sd) - Phi((-h - b)/sd) and the bound at
      Phi((b + h)/sd): coverage is a function of (b/sd, h/sd) alone.
      Whether data cures a failure is the trajectory of b/h: to 0
      (cured), constant (sample size irrelevant), to infinity (more
      data is worse).
  (C) THE KNIFE ON THE PLANE. On KNIFE a bin's rate estimate is about
      N(1/2, 1/(4 n_r)), so b is about -sqrt(M/(2 pi n)) and h about
      z/(2 sqrt n): |b|/h tends to sqrt(2M/pi)/z = 1.5766. The
      half-normal gives sd = sqrt((1 - 2/pi)/(4n)), h/sd = 3.25: the
      bar is too WIDE, and the coverage, about Phi(8.4) - Phi(1.87) =
      0.03 on the plane, is lost to b alone.
  (D) THE THIRD REGIME. POOLED on MILD has b -> 7/750 while h falls as
      1/sqrt n; with the estimate near 0.358, h = 0.940/sqrt n, so
      |b|/h runs 0.22, 0.44, 0.89, 1.78 over the four n and grows
      without bound.
  (E) THE CORNER. min(x, 1 - x) is linear on each side of 1/2 and a
      pull toward 1/2 never crosses it, so SHRUNK = (1 - lam) PER-BIN
      + lam/2 at every sample, and b = (1 - lam) b_plug + lam (1/2 -
      R*): on CLEAR b decays as n^(-1/4), b/h grows as n^(1/4).
  (F) TWO INSIDE INSTRUMENTS. The BOOTSTRAP term, the mean over
      resamples of the estimate less the estimate at the same n,
      estimates the bias against the estimator's OWN estimand; the
      DRIFT, the estimate on the sample less the estimate on an exact
      half of it, reads b(n) - b(n/2). At the knife a resampled bin
      rate carries twice the fitted one's variance, so the bootstrap
      term is about sqrt 2 - 1 = 0.4142 of b.
  (G) THE KERNEL (property). The bootstrap's estimand is the class's
      own functional, so the gap between the class's limit and R* is
      invisible to it; the drift differences a settled term away. A
      term that has stopped moving is in the kernel of both. On SHRUNK
      the lam/2 parts cancel at equal n, so the bootstrap term is
      (1 - lam) times PER-BIN's on the same resamples.
  (H) THE READABLE COORDINATE. sd is estimable by resampling with no
      truth, so h/sd is visible from inside; b/sd decides, and it is
      the one hidden.
  (I) THE NESTED REPAIR. Where a richer class is at hand, read the two
      fits' difference in the functional: Dhat = POOLED - PER-BIN >= 0
      (min is concave), its limit the pooling gap. A goodness-of-fit
      statistic reads the MODEL instead, and on SAME, wrong about 14
      bins of 15 and exact about R*, it fires hardest.

THE LAWS, each exact, with no simulation.
  (L1) A bin of weight q and rate eta holds K ~ Bin(n, q) points, its
       ones Bin(K, eta). With e = min(eta, 1 - eta) and X ~ Bin(K, e),
       E min(zeros, ones) = n q e - E (2X - K)^+. PER-BIN's mean is the
       sum over the bins at q = 1/M, over n. A draw's label within a
       group is Bernoulli at the group's mean rate, so POOLED's mean is
       the same law on three bins of weight 1/3; SHRUNK's follows by
       (E). So b is exact at every fit setting.
  (L2) An exact half of n independent points is n/2 independent points,
       so the drift's mean is the law at n less the law at n/2.
  (L3) A bin's part of the h = n/2 training points is Bin(h, 1/M), and
       its majority is not the better guess when X > K/2 (eta > 1/2) or
       X >= K/2 (eta < 1/2, a tie or an empty bin guessing 1). Held-out's
       mean less R* is (1/M) sum_r P(that) |2 eta_r - 1|.
  (L4) Given the rules, the hits of TRIALS trials are independent
       indicators, a trial's rate P(Bin(m, rho) in the cover set). At
       the knife every rho is 1/2 and the hits are Bin(400, the floor).

BY HAND.
  Targets and gaps: CLEAR's minima sum to 3.8, MILD's to 5.23, SAME's to
    3.85, over 15: 19/75, 523/1500, 77/300. The group rates are (0.44,
    0.56, 0.54), (0.344, 0.308, 0.422), (0.29, 0.25, 0.23): pooled
    limits 67/150, 179/500, 77/300, gaps 29/150, 7/750, 0. SAME's 1/4
    is its group's rate: 14 bins of 15 are off theirs.
  Estimators, zeros (3, 0, 2, 4, 1, 0), ones (1, 2, 2, 0, 0, 1), n = 16:
    minima 1, 0, 2, 0, 0, 0 a bin, 3; groups (3, 3), (6, 2), (1, 1), 6.
    lam = 1/2: rates 1/4, 1, 1/2, 0, 0, 1 pulled to 3/8, 3/4, 1/2, 1/4,
    1/4, 3/4, minima 3/8, 1/4, 1/2, 1/4, 1/4, 1/4 at weights 4, 2, 4,
    4, 1, 1 over 16: 11/32 = (1/2)(3/16) + 1/4. Pearson: 3 + 8/3 + 2
    = 23/3 on 3 degrees of freedom, (23/3 - 3)/sqrt 6.
  Held-out, the same counts as the training half: guesses 0, 1, 1 (a
    tie), 0, 0, 1; test zeros (2, 1, 0, 3, 1, 4) and ones (5, 0, 2, 1,
    6, 1): wrong 5 + 1 + 0 + 1 + 6 + 4 = 17. At rates (0.6, 0.4, 0.5,
    0.7, 0.2, 0.3) the majority is not the better guess at bins 1, 2,
    4 and 6.
  Moments, deviations (-0.02, 0.03, 0.05, -0.04), bars (0.03, 0.03,
    0.04, 0.03): 2 hold two-sided (the second a tie), 3 one-sided; b
    0.005, h 0.0325, sd sqrt(0.0053/3) = 0.042032; the plane
    Phi(0.6543) - Phi(-0.8922) = 0.5574 and Phi(0.8922) = 0.8139.
  X at e = 2/5: P(X > K/2), P(X >= K/2), E(2X - K)^+ are 0, 1, 0 at
    K = 0; 2/5 each at 1; 4/25, 16/25, 8/25 at 2; 44/125, 44/125,
    12/25 at 3.
  (L1): two points, q = 1/2, eta = 1/2: 1/8. Two points, q = 1/3,
    eta = 3/10: (1/9) 2 (21/100) = 7/150. Three points: 3 q^2 eta (1 -
    eta)(2 - q), 2/15 at q = 1/3 and eta = 2/5 or 3/5.
  (L3), eta = 6/11: one training point on one bin 5/11; two on two
    bins 5/22 + 25/484 = 135/484. eta = 5/11, two on two: 1/4 + 5/22 +
    85/484 = 79/121. eta = 2/5: 1/4 + 1/5 + 4/25 = 61/100.
  (A) at the knife: m/2 - (z/2) m / sqrt(m + z^2) is 109.62, 469.07,
    1938.05, 7876.05 at m = 250, 1000, 4000, 16000: x* = 110, 470,
    1939, 7877. At m = 3 and R* = 47/110 the bound holds R* from one
    error up; at m = 4 and 1/2 the two-sided bar holds 1/2 at 1, 2 or
    3 errors, 7/8 of a fair coin and 87/128 of one at 1/4.

DESIGN. n in {500, 2000, 8000, 32000}, each even, 400 trials, 150
bootstrap resamples of the 2M (bin, label) categories, the half-sample exact
(hypergeometric within categories); one seed per setting, the draws in
one order, so a recorded rate reprints. Fit arms: FIT-CLEAR, FIT-KNIFE,
FIT-MILD, FIT-SAME (per-bin); POOL-CLEAR, POOL-MILD, POOL-SAME;
SHRUNK-CLEAR. Held-out arms: BOUND-CLEAR, BOUND-KNIFE (one-sided),
HELD-WIDE (two-sided). 44 settings.
  Each fit row is read three ways. Its mean deviation b against (L1)
and its mean drift against (L2), each in the row's own standard errors,
behind a bar of 4. Its integers and printed ratios against the recorded
run, which holds the stream: a generator whose draws differ fails every
record and no bar. Each held row likewise: b against (L3), its hits
against (L4) in the standard deviations (L4) gives, and its record.
  A setting is GOOD at 360 hits or more and BAD below 320. A detector is
a single-sample rule on a statistic whose threshold holds alarms <=
0.10 over the GOOD settings' trials (not all false: POOL-MILD at
n = 500 is GOOD with a gap): |bootstrap term|/h over the fit settings,
Dhat/h over the pooled ones, so POOL-SAME's alarms are in sample (its
1,600 trials are 4/5 of that pool, its mean alarm rate held to 0.125
by construction). The
Pearson statistic is the within-group chi-square of the per-bin rates
against the group's rate, standardized as (X2 - 12)/sqrt 24.
  The controls run first and stop the run: every hand row above; the
float laws against the exact ones at 500 points and at 4, and their
reach against whole sums at K = 2,134 and 10,667; every sample of 4
points on 6 bins (rates 1/10, 3/5 | 2/5, 1/2 | 3/10, 9/10) through the
three estimators against (L1) in rationals; every sample of 6 points, 3
a half, on 2 bins (6/11, 2/5) through held-out against (L3) and (A),
and on two bins at 1/2 for (A)'s equality.
  FURTHER SEEDS. (L1), (L3) and (L4) are read again at ten further
seeds, 4,000 trials a setting, on draws made a batch at a time and
halves drawn as two samples: 56 reads behind the same bar, their worst
and the sum of their squares recorded. `python statements.py --seeds
FIRST COUNT` reads any others and exits 0 iff every read is within 4.
  WHAT THE BARS NOTICE (each law moved, the recorded draws read
again; records no check holds). With (L1)'s second term scaled up, the
recorded seeds leave the bar at 5% (3 of 32 reads at 4 or more) and
not at 2%; the further seeds leave it at 1% (3 of their 32 reads of
(L1), the worst 5.02). With (L3) scaled up, the recorded seeds leave
it at 10% (2 of 12) and not at 5%; the further seeds at 5% (3 of their
12 reads of (L3)) and not at 1%. (L2)'s only
read is the recorded seeds': the drift's law 10% low leaves the bar (2
of 32) and 10% high does not (the worst 3.77), and at 16 of the 32
settings the law is under 1.5 of its standard errors. (L1) with every
bin held at its mean size, no binomial over K, passes every bar here
(the worst 2.96): that the laws are exact is read by the rationals,
the bars reading that the seeded columns are draws from them. Where no
trial's excess is positive (POOL-SAME at n = 32000) Dhat's distance is
its law, 1.08e-9, over the floor 1e-9.
  A float law's weights come from a table of log-factorials, each
weight good to about 1e-10 of itself at 32,000 points; a binomial is
summed to 10 standard deviations past its mean, and a law's mean
deviation that rounds to 0 prints as +0.00000. A tail that starts
further out than that reach is cut short, by up to 4e-4 of a sum near
1e-20 at e = 2/5 and K = 2,134: an error no check reads.

PREDICTIONS (fixed before the first engine, which had no laws: bands on
the seeded rates). S0 FIT-CLEAR covers near 0.95, FIT-KNIFE's |b|/h is
near 1.5766. S1 both bounds cover at 0.975 less noise; BOUND-CLEAR
excludes 1/2; FIT-KNIFE's h/sd in [2.9, 3.6]. S2 every setting within
0.05 of the plane. S3 FIT-CLEAR's |b|/h falls; FIT-KNIFE covers <= 0.07;
POOL-MILD's coverage falls from >= 0.80 to <= 0.12 as |b|/h rises. S4
SHRUNK's |b|/h rises past 3. S5 HELD-WIDE falls by >= 0.40 from n = 500
to 8000. K1 the knife's bhat/b in [0.35, 0.48]. K2 SHRUNK's bootstrap
identity; its drift negative, near -0.189 |b|. K3 at the converged
settings mean |bhat|/h and mean |drift|/h below 0.25. K4 the bootstrap
detector catches the knife and not POOL-CLEAR; the drift detector's
rate on SHRUNK rises. K5 h/sdhat cannot tell POOL-MILD from FIT-MILD.
K6 Dhat catches POOL-CLEAR and POOL-MILD at 32000, not POOL-SAME, while
Pearson fires on SAME. KILL: S0 off (the engine is broken and nothing
else is read), S1's coverage off (the sign law is false),
S2 off (not a two-ratio phenomenon), K3 off (the kernel is not the
class's), K6's false alarms off (the repair reads the model).
  Fixed before the laws were first run whole: every read of (L1) to
(L4) within 4; the cover set an upper set at the 8 one-sided settings,
x* at the knife the four hand values, the floor between 0.970 and
0.976; every hit count of the earlier run reprinted; the two
enumerations exact; the further seeds within 4; a seed moved by one
failing the records and no bar. Of these the rows' distances, the
upper sets, the edges and the floors had been seen in a probe before
they were fixed, and the hit counts were the earlier run's own; the
enumerations, the further seeds and the moved seeds had not (and the
moved seeds were read apart from the plane's bar only once its check
was split from its record). The enumerations were fixed at 3 points
on 6 bins and at 4 points on 2, and run at 4 and at 6.

FINDINGS. Every prediction fixed before the laws held on the first
run, those unseen among them (the floor's range is no longer a check).
Of the first engine's, three did not stand. K3, a kill, FAILED as
frozen: it read the MEAN ABSOLUTE drift, whose floor is noise (a
drift's sd is about the estimate's own, 1.29 to 1.31 of it at the
knife), so the miss was the statistic's and no other kill fired; the
drift's mean, the quantity (F) argues about, now has
(L2), and all 32 means sit within 2.40 standard errors of it. (A)'s
first form said a fit's omitted bias can have either sign: PER-BIN's
is <= 0 in every world. And S3's FIT-CLEAR clause, then its
replacement "|b|/h within noise of 0", were read off one seed: by (L1)
b is -0.00287 at n = 500 and -0.00008 at 2000; the recorded seed drew
-0.00181.
  laws       fit: b within 2.06 standard errors of (L1) at all 32
             settings, the drift within 2.40 of (L2). Held-out: b
             within 2.21 of (L3) at all 12, the hits within 1.59
             standard deviations of (L4). Ten further seeds: 56 of 56
             reads within 4, the worst 2.88, their squares summing
             to 64.0.
  sign       the cover set is an upper set at all 8 settings. A
             binomial at R* reaches its edge at 0.97128, 0.97091,
             0.97314, 0.97418 on CLEAR (edges 51, 228, 961, 3947) and
             0.97515, 0.97316, 0.97411, 0.97457 at the knife: the
             guarantee is under 0.975 at seven of the eight. BOUND-CLEAR
             covers 395, 393, 390, 391 of 400 and is below 1/2 in every
             trial; BOUND-KNIFE covers 395, 390, 394, 388 (there
             a miss and a bound below 1/2 are one event). FIT-KNIFE's
             h/sd is 3.10,
             3.24, 3.09, 3.26: its bar is too wide.
  plane      44 settings, worst |coverage - plane| 0.0337 (SHRUNK at
             n = 500), mean 0.0058.
  regimes    FIT-CLEAR |b|/h 0.048, 0.045, 0.030, 0.038, covering 385,
             387, 378, 375; FIT-KNIFE 1.581, 1.572, 1.601, 1.565,
             covering 13, 9, 10, 12, its exact b -0.06886, -0.03452,
             -0.01727, -0.00864; POOL-MILD |b|/h 0.222, 0.416, 0.914,
             1.813, covering 377, 357, 232, 23, its exact b 0.00913 at
             n = 500 and on the gap 0.00933 from 2000.
  corner     SHRUNK |b|/h 1.239, 1.858, 2.664, 3.794, covering 94, 3,
             0, 0.
  held-out   HELD-WIDE covers 355, 203, 71, 95 of 400, each within
             0.027 of the plane; its exact b is 0.02816, 0.02979,
             0.02364, 0.01111, rising before it falls.
  kernel     knife bhat/b 0.4141, 0.4189, 0.4021, 0.4197 against
             sqrt 2 - 1, sdhat/sd 1.182 to 1.243, sd(drift)/sd 1.291
             to 1.311. SHRUNK's identity to 1.9e-16; its drift/h
             -0.149, -0.287, -0.511, -0.714 against (L2) over the mean
             bar, -0.143, -0.326, -0.502, -0.716, where -0.189 |b|/h
             gives -0.234, -0.351, -0.504, -0.717: the plug-in's part
             is not small at n = 500. MILD h/sdhat POOL 2.033, 1.980,
             1.960, 1.968 against FIT 2.230, 2.097, 2.045, 2.007 while
             coverage parts to 23 against 386.
  detector   threshold 0.208 over 17 GOOD settings, 14 BAD. Alarms of
             400: FIT-KNIFE all at every n; POOL-CLEAR 109, 5, 0, 0 as
             |b|/h grows 4.4 to 35.
  repair     Dhat/h threshold 0.514 over POOL-MILD at 500 and POOL-SAME
             at every n. Alarms of 400: POOL-CLEAR all; POOL-MILD 176,
             216, 360, 399; POOL-SAME 24, 0, 0, 0 while its Pearson
             mean runs 8.3, 34.0, 137.2, 548.0. Dhat is never negative
             and its mean sits within 1.79 standard errors of the two
             laws' difference.
Held and no longer run, the laws or the record holding more: the bands
of S0 to S5, K1, K2 and K5; K3's signed means (under 0.25 at the
converged settings); K4's drift detector (0.020 to 0.410 on
SHRUNK, rising); K6's bands. Coverage over 400 trials reads to about
0.011 at nominal; the laws, the plane's fit and the directions are the
finding, the rates their instance.

RUN RECORD.
python statements.py: 36 of 36 checks, 5.8 s, peak commit 33.2 MB.
  The seeded integers, and the further seeds' two numbers, were entered
from the first run of this engine; every hit count of 400 was fixed
before it from the earlier engine's printed rates, and reprinted.
`--seeds 7000 40` read 56 of 56 within 4, the worst 3.29 (BOUND-CLEAR's
hits at n = 32000), and `--seeds 9000 160`, 64,000 trials a setting, the
worst 2.67, the squares summing to 47.0: records no check holds.
  Read by breaks: of 341 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) 316 fail a check; 25 pass and move no line. Eight
are bounds never met with equality (a bar exactly at the truth, twice;
a setting at exactly 360 or 320 hits; a gap of exactly 1e-12; a bound
of exactly 1/2; a pin's last place; a plane gap of exactly 0.05).
Three read a rate of exactly 1/2, where a wrong majority costs 0. Four
drop the fold e = min(eta, 1 - eta) from (L1), which holds at any rate
(min(o, K - o) = o - (2o - K)^+); the fold only shortens the sum. One
names the inferred dimension -2; one labels the ones 2. Six widen a
sum's window, or move its last column, and two stop the whole sum a
term early or late: terms of no mass. Of 44 edits by hand, the
controls' stop lifted, each with checks it should fail named first, 37
fail a named check, some failing further lines no label named, and 7
pass as predicted (the two cover sets strict, the sums cut at 8
standard deviations twice, GOOD strictly above 360, and two that
differ only at odd n). Three first predictions were wrong, their
labels rewritten before the last run: a SAME whose second group
is all 1/4 keeps R* and the gap, and fails the 14-of-15 control alone
among the controls; the pooled class cut into five groups of three
fails the deviation's bar and not the drift's, a settled term being in
the drift's kernel; SHRUNK pulled toward 1/3 also passes the drift's
bar, its term moving as n^(-1/4), too slowly for these trials to
read. Each sweep's seed moved by one fails the records that read its
draws and no bar.
"""

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

import sys
import time
from collections import Counter
from fractions import Fraction as F
from functools import lru_cache
from itertools import product
from math import comb, erf, lgamma, log, prod, sqrt

import numpy as np

Z = 1.96
TRIALS = 400
BOOT = 150
NS = (500, 2000, 8000, 32000)
GROUPS = 3
FAR = tuple(range(3000, 3010))
TOL = 1e-12
LOGFACT = np.array([lgamma(k + 1) for k in range(NS[-1] + 1)])
CHECKS = []

WORLDS = {
    "CLEAR": [F(1, 10), F(3, 10), F(2, 5), F(3, 5), F(4, 5),
              F(1, 5), F(1, 4), F(7, 10), F(3, 4), F(9, 10),
              F(1, 10), F(2, 5), F(3, 5), F(7, 10), F(9, 10)],
    "KNIFE": [F(1, 2)] * 15,
    "MILD": [F(3, 10)] * 4 + [F(13, 25)] + [F(1, 4)] * 4 + [F(27, 50)]
            + [F(2, 5)] * 4 + [F(51, 100)],
    "SAME": [F(1, 10), F(1, 5), F(3, 10), F(2, 5), F(9, 20),
             F(1, 20), F(3, 20), F(1, 4), F(7, 20), F(9, 20),
             F(1, 10), F(3, 20), F(1, 5), F(3, 10), F(2, 5)],
    "WIDE": [F(6, 11)] * 105,
}
ARMS = [("FIT", "CLEAR"), ("FIT", "KNIFE"), ("FIT", "MILD"),
        ("FIT", "SAME"), ("POOL", "CLEAR"), ("POOL", "MILD"),
        ("POOL", "SAME"), ("SHRUNK", "CLEAR")]
HELD = [("CLEAR", "one"), ("KNIFE", "one"), ("WIDE", "two")]
SMALL = [F(1, 10), F(3, 5), F(2, 5), F(1, 2), F(3, 10), F(9, 10)]
PAIR = [F(6, 11), F(2, 5)]

HAND_TARGETS = ("19/75", "1/2", "523/1500", "77/300", "5/11")
HAND_GAPS = ("29/150", "7/750", "0")
HAND_Z = [3, 0, 2, 4, 1, 0]
HAND_O = [1, 2, 2, 0, 0, 1]
HAND_UPPER = (("0", "1", "0"), ("2/5", "2/5", "2/5"),
              ("4/25", "16/25", "8/25"), ("44/125", "44/125", "12/25"))
HAND_LOW = (((2, F(1, 2), F(1, 2)), "1/8"), ((2, F(1, 3), F(3, 10)), "7/150"),
            ((3, F(1, 3), F(2, 5)), "2/15"), ((3, F(1, 3), F(3, 5)), "2/15"))
HAND_FLIP = (((1, F(1), F(6, 11)), "5/11"),
             ((2, F(1, 2), F(6, 11)), "135/484"),
             ((2, F(1, 2), F(5, 11)), "79/121"),
             ((2, F(1, 2), F(2, 5)), "61/100"))
HAND_EDGE = (110, 470, 1939, 7877)

# Each row at n = 500, 2000, 8000, 32000: hits of 400, minority labels,
# |b|/h, h/sd, the plane, and the distances of b and of the drift.
FIT_PINS = {
    ("FIT", "CLEAR"): [(385, 50305, 0.048, 2.09, 0.962, 1.16, 1.87),
        (387, 201979, 0.045, 2.10, 0.964, -1.73, -0.49),
        (378, 811589, 0.030, 1.95, 0.948, 1.18, -1.29),
        (375, 3244965, 0.038, 1.93, 0.946, 1.45, -1.64)],
    ("FIT", "KNIFE"): [(13, 86277, 1.581, 3.10, 0.036, 0.34, 1.48),
        (9, 372516, 1.572, 3.24, 0.032, 0.49, 0.53),
        (10, 1543899, 1.601, 3.09, 0.032, -1.47, -0.65),
        (12, 6290263, 1.565, 3.26, 0.033, 0.76, 2.32)],
    ("FIT", "MILD"): [(370, 67328, 0.291, 2.14, 0.932, 0.64, 2.16),
        (382, 276110, 0.169, 2.15, 0.957, 0.01, 0.06),
        (386, 1113578, 0.065, 2.02, 0.955, 0.95, -1.09),
        (386, 4460131, 0.042, 2.08, 0.962, -0.49, -1.22)],
    ("FIT", "SAME"): [(373, 50173, 0.153, 1.96, 0.940, -0.18, 2.40),
        (380, 204519, 0.053, 2.03, 0.956, -0.58, -0.72),
        (392, 821758, 0.014, 2.16, 0.969, 0.69, -0.17),
        (378, 3283767, 0.026, 1.93, 0.947, -0.99, -0.30)],
    ("POOL", "CLEAR"): [(0, 88658, 4.365, 2.39, 0.000, -0.04, -1.45),
        (0, 357637, 8.892, 2.04, 0.000, 0.89, 0.63),
        (0, 1428204, 17.717, 1.94, 0.000, -1.25, -0.13),
        (0, 5716465, 35.481, 1.92, 0.000, -0.48, -1.56)],
    ("POOL", "MILD"): [(377, 71600, 0.222, 1.99, 0.931, 0.19, -0.56),
        (357, 285929, 0.416, 2.05, 0.883, -1.15, 0.43),
        (232, 1146458, 0.914, 1.98, 0.568, 1.01, -1.05),
        (23, 4584868, 1.813, 1.92, 0.059, 1.41, 1.85)],
    ("POOL", "SAME"): [(381, 51628, 0.038, 2.00, 0.954, 1.54, -0.22),
        (383, 204568, 0.050, 2.06, 0.959, -2.06, -0.53),
        (385, 821130, 0.007, 2.03, 0.957, -0.27, 0.07),
        (378, 3284920, 0.007, 1.96, 0.950, -0.26, 0.71)],
    ("SHRUNK", "CLEAR"): [(94, 50086, 1.239, 2.58, 0.269, -0.04, -0.30),
        (3, 202736, 1.858, 2.55, 0.014, 0.36, 2.06),
        (0, 811094, 2.664, 2.11, 0.000, 0.51, -0.41),
        (0, 3243396, 3.794, 2.17, 0.000, 0.47, 0.07)],
}
# Each row as above: hits, test errors, wrong bins, bounds below 1/2,
# the plane, and the distances of b and of the hits.
HELD_PINS = {
    "CLEAR": [(395, 26608, 375, 400, 0.983, -2.21, 0.27),
        (393, 102488, 77, 400, 0.978, 0.21, 0.89),
        (390, 404978, 1, 400, 0.976, -0.74, 0.22),
        (391, 1620626, 0, 400, 0.974, -0.65, 0.42)],
    "KNIFE": [(395, 50055, 0, 5, 0.986, 0.39, 1.59),
        (390, 199343, 0, 10, 0.966, -2.04, 0.23),
        (394, 800989, 0, 6, 0.985, 1.66, 1.37),
        (388, 3200327, 0, 12, 0.971, 0.25, -0.58)],
    "WIDE": [(355, 48200, 12933, 30, 0.861, -0.45, 1.36),
        (203, 194304, 13860, 66, 0.494, 1.70, -0.65),
        (71, 764976, 10876, 312, 0.187, -0.17, -0.36),
        (95, 2980234, 5093, 400, 0.233, 0.03, -0.91)],
}
FLOOR_PINS = {
    "CLEAR": [(51, 0.97128), (228, 0.97091), (961, 0.97314), (3947, 0.97418)],
    "KNIFE": [(110, 0.97515), (470, 0.97316), (1939, 0.97411),
              (7877, 0.97457)],
}
# The knife's bhat/b, sdhat/sd and sd(drift)/sd.
KNIFE_PINS = ((0.4141, 1.182, 1.291), (0.4189, 1.236, 1.294),
              (0.4021, 1.189, 1.311), (0.4197, 1.243, 1.307))
MILD_PINS = {"POOL": (2.033, 1.980, 1.960, 1.968),
             "FIT": (2.230, 2.097, 2.045, 2.007)}
# SHRUNK's mean drift over h, and the drift's law over the mean bar.
SHRUNK_PINS = ((-0.149, -0.143), (-0.287, -0.326), (-0.511, -0.502),
               (-0.714, -0.716))
# The bootstrap detector's threshold, its GOOD and BAD settings, and the
# alarms of 400 in ARMS' order.
BOOT_PINS = (0.208, 17, 14,
             ((89, 1, 0, 0), (400, 400, 400, 400), (298, 85, 11, 0),
              (160, 28, 0, 0), (109, 5, 0, 0), (8, 0, 0, 0), (0, 0, 0, 0),
              (23, 0, 0, 0)))
# The repair's threshold, its GOOD pooled settings, and each pooled
# setting's alarms, Pearson mean and the distance of its mean excess.
REPAIR_PINS = (0.514,
               [("MILD", 500), ("SAME", 500), ("SAME", 2000), ("SAME", 8000),
                ("SAME", 32000)],
               ((400, 28.5, -0.12), (400, 116.8, 1.79), (400, 466.6, -0.59),
                (400, 1871.3, 0.83), (176, 3.4, -0.90), (216, 14.2, -1.18),
                (360, 57.3, 0.04), (399, 228.5, 0.31), (24, 8.3, -0.09),
                (0, 34.0, -1.26), (0, 137.2, 0.14), (0, 548.0, -1.08)))
# The further seeds' worst read and the sum of the reads' squares.
FAR_PINS = (2.88, 64.0)


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 ring_etas(N, M, t):
    """eta_r = P(x >= t | x mod M = r) on the ring Z/N, exact."""
    c = N // M
    return [F(sum(1 for j in range(c) if r + j * M >= t), c)
            for r in range(M)]


def bayes(etas):
    return sum(min(e, 1 - e) for e in etas) / len(etas)


def pooled(etas):
    """The three groups' mean rates."""
    size = len(etas) // GROUPS
    return [sum(etas[g * size:(g + 1) * size]) / size for g in range(GROUPS)]


# ----------------------------------------------------------- estimators
# A sample is two count vectors z (label 0) and o (label 1) over the
# bins; every estimator accepts a leading batch axis.

def low_cell(z, o):
    return np.minimum(z, o).sum(axis=-1)


def low_pool(z, o):
    sh = z.shape[:-1] + (GROUPS, -1)
    return np.minimum(z.reshape(sh).sum(-1),
                      o.reshape(sh).sum(-1)).sum(axis=-1)


def est_cell(z, o, n):
    return low_cell(z, o) / n


def est_pool(z, o, n):
    return low_pool(z, o) / n


def lam(n):
    return n ** -0.25


def est_shrunk(z, o, n):
    """Every bin's rate pulled toward 1/2 at weight lam before the min;
    an empty bin has weight 0."""
    nr = z + o
    es = (1 - lam(n)) * (o / np.maximum(nr, 1)) + lam(n) / 2
    return (nr / n * np.minimum(es, 1 - es)).sum(axis=-1)


def bar(p, m):
    return Z * np.sqrt(p * (1 - p) / m)


def pearson(z, o):
    """Within-group chi-square of the per-bin rates against the group
    rate, standardized at bins - groups degrees of freedom."""
    nr = z + o
    size = z.shape[-1] // GROUPS
    x2 = 0.0
    for g in range(GROUPS):
        sl = slice(g * size, (g + 1) * size)
        eg = o[sl].sum() / nr[sl].sum()
        er = o[sl] / np.maximum(nr[sl], 1)
        x2 += float((nr[sl] * (er - eg) ** 2).sum() / (eg * (1 - eg)))
    df = z.shape[-1] - GROUPS
    return (x2 - df) / sqrt(2 * df)


def held_err(tz, to, sz, so):
    """Test labels the training half's majority gets wrong, a tie or an
    empty bin guessing 1."""
    return np.where(to >= tz, sz, so).sum(axis=-1)


def wrong_bins(tz, to, eta):
    """The bins whose majority is not the better guess, where one is."""
    return ((to >= tz) != (eta > 0.5)) & (eta != 0.5)


FITS = {"FIT": est_cell, "POOL": est_pool, "SHRUNK": est_shrunk}
LOWS = {"FIT": low_cell, "POOL": low_pool, "SHRUNK": low_cell}


# ---------------------------------------------------------------- draws

def draw(rng, eta, n):
    counts = rng.multinomial(n, np.full(len(eta), 1 / len(eta)))
    o = rng.binomial(counts, eta)
    return counts - o, o


def split(rng, z, o):
    cat = np.concatenate([z, o])
    tr = rng.multivariate_hypergeometric(cat, int(cat.sum()) // 2)
    te = cat - tr
    M = len(z)
    return tr[:M], tr[M:], te[:M], te[M:]


def batch(rng, eta, n):
    """TRIALS samples of n points at once."""
    counts = rng.multinomial(n, np.full(len(eta), 1 / len(eta)), size=TRIALS)
    o = rng.binomial(counts, eta)
    return counts - o, o


def fit_trials(kind, world, n, seed):
    """TRIALS samples of one fit setting, the draws in the recorded
    order: the sample, BOOT resamples of its 2M (bin, label) categories,
    an exact half. A trial's deviation and bar, its bootstrap term and
    dispersion, its drift; for SHRUNK the bootstrap term's distance from
    (1 - lam) times PER-BIN's on the same resamples; for POOL the
    excess over PER-BIN and the Pearson statistic; and the minority
    labels summed."""
    etas = WORLDS[world]
    truth = float(bayes(etas))
    eta = np.array([float(e) for e in etas])
    est, M = FITS[kind], len(etas)
    rng = np.random.default_rng(seed)
    t = {k: np.full(TRIALS, np.nan) for k in
         ("dev", "h", "boot", "sdhat", "drift", "dhat", "pear", "ident")}
    low = 0
    for i in range(TRIALS):
        z, o = draw(rng, eta, n)
        e = float(est(z, o, n))
        cat = np.concatenate([z, o])
        rs = rng.multinomial(n, cat / n, size=BOOT)
        bz, bo = rs[:, :M], rs[:, M:]
        eb = est(bz, bo, n)
        half = rng.multivariate_hypergeometric(cat, n // 2)
        low += int(LOWS[kind](z, o))
        t["dev"][i] = e - truth
        t["h"][i] = float(bar(e, n))
        t["boot"][i] = eb.mean() - e
        t["sdhat"][i] = eb.std(ddof=1)
        t["drift"][i] = e - float(est(half[:M], half[M:], n // 2))
        if kind == "SHRUNK":
            pc = est_cell(bz, bo, n).mean() - float(est_cell(z, o, n))
            t["ident"][i] = abs(t["boot"][i] - (1 - lam(n)) * pc)
        if kind == "POOL":
            t["dhat"][i] = e - float(est_cell(z, o, n))
            t["pear"][i] = pearson(z, o)
    return t, low


def held_trials(world, n, seed):
    """TRIALS samples split in exact halves: the test labels the
    training half's majority gets wrong, and the bins it has wrong."""
    eta = np.array([float(e) for e in WORLDS[world]])
    rng = np.random.default_rng(seed)
    wrong = np.zeros(TRIALS, dtype=int)
    bins = np.zeros((TRIALS, len(eta)), dtype=bool)
    for i in range(TRIALS):
        z, o = draw(rng, eta, n)
        tz, to, sz, so = split(rng, z, o)
        wrong[i] = held_err(tz, to, sz, so)
        bins[i] = wrong_bins(tz, to, eta)
    return wrong, bins


# ----------------------------------------------------------------- laws

def pmf(n, ks, p):
    return np.exp(LOGFACT[n] - LOGFACT[ks] - LOGFACT[n - ks]
                  + ks * log(p) + (n - ks) * log(1 - p))


def window(n, p):
    """The k of Bin(n, p) within 10 standard deviations of its mean, and
    10 more."""
    mu = n * p
    w = 10 * sqrt(mu * (1 - p)) + 10
    return np.arange(max(0, int(mu - w)), min(n, int(mu + w)) + 1)


def upper(ks, e):
    """For X ~ Bin(K, e), e <= 1/2, at each K of ks: P(X > K/2),
    P(X >= K/2) and E(2X - K)^+, summed from K/2 up to 10 standard
    deviations past the mean, and 12 more."""
    reach = ks * (e - 0.5) + 10 * np.sqrt(ks * e * (1 - e)) + 12
    first = (ks + 1) // 2
    js = first[:, None] + np.arange(int(reach.max()) + 1)[None, :]
    inside = js <= ks[:, None]
    js = np.minimum(js, ks[:, None])
    p = np.where(inside, pmf(ks[:, None], js, e), 0.0)
    over = 2 * js - ks[:, None]
    return (p * (over > 0)).sum(1), p.sum(1), (p * over).sum(1)


def upper_whole(K, e):
    """upper's three sums at one K, over every j from K/2 to K."""
    js = np.arange((K + 1) // 2, K + 1)
    p, over = pmf(K, js, e), 2 * js - K
    return (float((p * (over > 0)).sum()), float(p.sum()),
            float((p * over).sum()))


@lru_cache(maxsize=None)
def low_mean(n, q, eta):
    """E min(zeros, ones) in a bin of weight q and rate eta, n points."""
    e = min(eta, 1 - eta)
    ks = window(n, q)
    return n * q * e - float((pmf(n, ks, q) * upper(ks, e)[2]).sum())


@lru_cache(maxsize=None)
def flip_prob(h, q, eta):
    """P(the majority of a bin's part of h training points is not the
    better guess), eta off 1/2."""
    ks = window(h, q)
    strict, weak, _ = upper(ks, min(eta, 1 - eta))
    return float((pmf(h, ks, q) * (strict if eta > 0.5 else weak)).sum())


def upper_exact(K, e):
    a, d = e.numerator, e.denominator
    strict = weak = excess = 0
    for j in range((K + 1) // 2, K + 1):
        term = comb(K, j) * a ** j * (d - a) ** (K - j)
        weak += term
        if 2 * j > K:
            strict += term
            excess += term * (2 * j - K)
    return F(strict, d ** K), F(weak, d ** K), F(excess, d ** K)


def mix_exact(n, q, g):
    """E g(K), K ~ Bin(n, q)."""
    return sum(comb(n, K) * q ** K * (1 - q) ** (n - K) * g(K)
               for K in range(n + 1))


def low_exact(n, q, eta):
    e = min(eta, 1 - eta)
    return n * q * e - mix_exact(n, q, lambda K: upper_exact(K, e)[2])


def flip_exact(h, q, eta):
    e = min(eta, 1 - eta)
    return mix_exact(h, q, lambda K: upper_exact(K, e)[2 * eta < 1])


def class_bins(kind, etas):
    """The bins a fit's class reads, as (weight, rate, how many)."""
    rates = pooled(etas) if kind == "POOL" else etas
    return [(F(1, len(rates)), e, c) for e, c in Counter(rates).items()]


@lru_cache(maxsize=None)
def fit_law(kind, world, n):
    """The mean of a fit's estimate on n points, exact up to the float
    sums."""
    e = sum(c * low_mean(n, float(q), float(r))
            for q, r, c in class_bins(kind, WORLDS[world])) / n
    return (1 - lam(n)) * e + lam(n) / 2 if kind == "SHRUNK" else e


def low_law(kind, etas, n):
    """The mean minority labels of a fit's class, in rationals."""
    return sum(c * low_exact(n, q, r) for q, r, c in class_bins(kind, etas))


def held_law(etas, h):
    """Held-out's mean less R*: the wrong bins' cost, h training points
    (a bin at 1/2 costs 0 either way)."""
    M = len(etas)
    return sum(c * flip_prob(h, 1 / M, float(e)) * abs(2 * float(e) - 1)
               for e, c in Counter(etas).items()) / M


def held_exact(etas, h):
    M = len(etas)
    return sum(flip_exact(h, F(1, M), e) * abs(2 * e - 1) for e in etas) / M


def cover_set(m, truth, sided):
    """The test-error counts x of m whose stated interval holds the
    truth, by the arithmetic a trial uses."""
    err = np.arange(m + 1) / m
    dev, h = err - truth, bar(err, m)
    return np.abs(dev) <= h if sided == "two" else dev >= -h


def upper_set(cover):
    """The least count a cover set holds, and whether it holds every
    count above it."""
    edge = int(np.flatnonzero(cover)[0])
    return edge, bool(cover[edge:].all())


def cover_prob(m, rho, cover):
    """P(Bin(m, rho) in the cover set)."""
    xs = window(m, rho)
    return float(pmf(m, xs, rho)[cover[xs]].sum())


def cover_exact(m, rho, cover):
    return sum(comb(m, x) * rho ** x * (1 - rho) ** (m - x)
               for x in range(m + 1) if cover[x])


def cond_law(m, risks, cover):
    """Given each trial's rule, the hits are independent indicators: the
    sum of their rates and of rate (1 - rate)."""
    rates, counts = np.unique(risks, return_counts=True)
    p = np.array([cover_prob(m, r, cover) for r in rates])
    return float((counts * p).sum()), float((counts * p * (1 - p)).sum())


def z_of(count, mean, var):
    return (count - mean) / sqrt(var)


def z_mean(x, law):
    """A sample mean's distance from a law in its own standard errors, a
    standard error below 1e-9 read as 1e-9 (a sample that does not
    vary)."""
    se = float(x.std(ddof=1)) / sqrt(len(x))
    return (float(x.mean()) - law) / max(se, 1e-9)


def within(zs):
    """How many of the distances are inside 4."""
    return sum(abs(z) < 4 for z in zs)


def moments(dev, h, sided):
    """The trials whose interval holds the truth, the mean deviation b,
    the mean bar, the deviation's sd, and the plane's coverage at
    those three."""
    b, hm, sd = float(dev.mean()), float(h.mean()), float(dev.std(ddof=1))
    if sided == "two":
        hits = int((np.abs(dev) <= h).sum())
        pred = phi((hm - b) / sd) - phi((-hm - b) / sd)
    else:
        hits = int((dev >= -h).sum())
        pred = phi((b + hm) / sd)
    return dict(hits=hits, b=b, h=hm, sd=sd, pred=pred,
                ratio=abs(b) / hm, hsd=hm / sd)


# --------------------------------------------------------- enumerations

def sequences(etas, n):
    """Every string of n points over the 2M (bin, label) categories,
    with its weight."""
    M = len(etas)
    p = [(e if y else 1 - e) / M for e in etas for y in (0, 1)]
    seqs = list(product(range(2 * M), repeat=n))
    return np.array(seqs), [prod(p[c] for c in s) for s in seqs]


def counts(seqs, M):
    c = (seqs[:, :, None] == np.arange(2 * M)).sum(axis=1)
    return c[:, 0::2], c[:, 1::2]


def enum_fit(etas, n):
    """Over every sample of n points: the mean minority labels of the
    per-bin and the pooled class, the samples where SHRUNK is (1 - lam)
    PER-BIN + lam/2, the samples where the pooled count is below the
    per-bin one, and the samples."""
    seqs, w = sequences(etas, n)
    z, o = counts(seqs, len(etas))
    cell, pool = low_cell(z, o), low_pool(z, o)
    gap = np.abs(est_shrunk(z, o, n) - ((1 - lam(n)) * cell / n + lam(n) / 2))
    return (sum(a * int(c) for a, c in zip(w, cell)),
            sum(a * int(c) for a, c in zip(w, pool)),
            int((gap <= TOL).sum()), int((pool < cell).sum()), len(w))


def enum_held(etas, n):
    """Over every sample of n points, the first n // 2 its training
    half: held-out's mean less R*, the mean cost of the wrong bins, and
    the chance its upper bound holds R*."""
    M, h = len(etas), n // 2
    truth = bayes(etas)
    seqs, w = sequences(etas, n)
    tz, to = counts(seqs[:, :h], M)
    sz, so = counts(seqs[:, h:], M)
    wrong = held_err(tz, to, sz, so)
    bins = wrong_bins(tz, to, np.array([float(e) for e in etas]))
    cost = [abs(2 * e - 1) / M for e in etas]
    cover = cover_set(n - h, float(truth), "one")
    return (sum(a * int(x) for a, x in zip(w, wrong)) / (n - h) - truth,
            sum(a * sum(c for c, f in zip(cost, row) if f)
                for a, row in zip(w, bins)),
            sum(a for a, x in zip(w, wrong) if cover[x]))


# ----------------------------------------------------------------- rows

def fit_row(kind, world, n, seed):
    """One fit setting: moments' record, the minority labels, and the
    mean deviation's and the mean drift's distances from their laws."""
    t, low = fit_trials(kind, world, n, seed)
    law = fit_law(kind, world, n)
    b_law = law - float(bayes(WORLDS[world]))
    rec = moments(t["dev"], t["h"], "two")
    rec.update(t=t, low=low, law=b_law, zb=z_mean(t["dev"], b_law),
               zd=z_mean(t["drift"], law - fit_law(kind, world, n // 2)))
    return rec


def fit_sweep():
    return {(kind, world, n): fit_row(kind, world, n, 1000 + 10 * a + j)
            for a, (kind, world) in enumerate(ARMS)
            for j, n in enumerate(NS)}


def held_row(world, n, seed, sided):
    """One held-out setting: moments' record; the test errors, the wrong
    bins and the trials whose upper bound is below 1/2, summed; the
    least count the cover set holds, whether it holds every count above
    it, and its chance at risk R*; and the distances of the mean
    deviation from its law and of the hits from the law given the
    rules."""
    etas = WORLDS[world]
    truth, m = float(bayes(etas)), n - n // 2
    wrong, bins = held_trials(world, n, seed)
    err = wrong / m
    rec = moments(err - truth, bar(err, m), sided)
    cover = cover_set(m, truth, sided)
    edge, whole = upper_set(cover)
    cost = np.abs(2 * np.array([float(e) for e in etas]) - 1) / len(etas)
    law = held_law(etas, n // 2)
    rec.update(wrong=int(wrong.sum()), flips=int(bins.sum()),
               below=int((err + bar(err, m) < 0.5).sum()),
               edge=edge, upper=whole,
               floor=cover_prob(m, truth, cover), law=law,
               zb=z_mean(err - truth, law),
               zc=z_of(rec["hits"],
                       *cond_law(m, truth + (bins * cost).sum(axis=1), cover)))
    return rec


def held_sweep():
    return {(world, n): held_row(world, n, 2000 + 100 * w + j, sided)
            for w, (world, sided) in enumerate(HELD)
            for j, n in enumerate(NS)}


def plane(recs):
    """Over the settings: those within 0.05 of the plane, the worst
    gap and its setting, and the mean gap."""
    gaps = {k: abs(r["hits"] / TRIALS - r["pred"]) for k, r in recs.items()}
    worst = max(gaps, key=gaps.get)
    return (sum(g <= 0.05 for g in gaps.values()), gaps[worst], worst,
            sum(gaps.values()) / len(gaps))


def threshold(values):
    """The least threshold holding alarms <= 0.10 over values."""
    v = np.sort(np.concatenate(values))
    return float(v[int(np.ceil(0.9 * len(v))) - 1])


def detector(recs, key):
    """A single-sample rule on |key|/h at the threshold of the settings
    covering at 0.90 or more: the threshold, those settings, the
    settings covering below 0.80, and each setting's alarms."""
    stat = {k: np.abs(r["t"][key]) / r["t"]["h"] for k, r in recs.items()}
    good = [k for k, r in recs.items() if r["hits"] >= 0.90 * TRIALS]
    bad = [k for k, r in recs.items() if r["hits"] < 0.80 * TRIALS]
    thr = threshold([stat[k] for k in good])
    return thr, good, bad, {k: int((s > thr).sum()) for k, s in stat.items()}


def knife_kernel(r):
    """The bootstrap term over b, the mean resampled sd over sd, and the
    drift's sd over sd."""
    t = r["t"]
    return (float(t["boot"].mean()) / r["b"],
            float(t["sdhat"].mean()) / r["sd"],
            float(t["drift"].std(ddof=1)) / r["sd"])


def readable(r):
    """The mean of h over the resampled sd, a trial at a time."""
    return float(np.mean(r["t"]["h"] / r["t"]["sdhat"]))


def shrunk_drift(r, n):
    """SHRUNK's mean drift over h, a trial at a time, and the drift's
    law over the mean bar."""
    law = fit_law("SHRUNK", "CLEAR", n) - fit_law("SHRUNK", "CLEAR", n // 2)
    return float(np.mean(r["t"]["drift"] / r["t"]["h"])), law / r["h"]


def repair_row(recs, world, n):
    """A pooled setting's excess over PER-BIN: the trials where it is
    negative, its mean's distance from the two laws' difference, and
    the mean Pearson statistic."""
    t = recs["POOL", world, n]["t"]
    law = fit_law("POOL", world, n) - fit_law("FIT", world, n)
    return (int((t["dhat"] < 0).sum()), z_mean(t["dhat"], law),
            float(t["pear"].mean()))


def far_fit(kind, world, n, seeds):
    """At further seeds, on batches: the mean deviation's distance from
    its law."""
    etas = WORLDS[world]
    eta = np.array([float(e) for e in etas])
    a = ARMS.index((kind, world))
    est = np.concatenate([
        FITS[kind](*batch(np.random.default_rng((s, a, n)), eta, n), n)
        for s in seeds])
    return z_mean(est, fit_law(kind, world, n))


def far_held(world, n, seeds, sided):
    """At further seeds, the halves drawn as two samples: the mean
    deviation's distance from its law, and the hits' from the law given
    the rules."""
    etas = WORLDS[world]
    eta = np.array([float(e) for e in etas])
    truth, m = float(bayes(etas)), n - n // 2
    cost = np.abs(2 * eta - 1) / len(etas)
    w = len(ARMS) + HELD.index((world, sided))
    wrong, risks = [], []
    for s in seeds:
        rng = np.random.default_rng((s, w, n))
        tz, to = batch(rng, eta, n // 2)
        wrong.append(held_err(tz, to, *batch(rng, eta, m)))
        risks.append(truth + (wrong_bins(tz, to, eta) * cost).sum(axis=1))
    wrong, cover = np.concatenate(wrong), cover_set(m, truth, sided)
    return (z_mean(wrong / m - truth, held_law(etas, n // 2)),
            z_of(int(cover[wrong].sum()),
                 *cond_law(m, np.concatenate(risks), cover)))


def far_sweep(seeds):
    """Every read of a law at further seeds: how many, how many within
    4, the worst, and the sum of their squares."""
    zs = [far_fit(kind, world, n, seeds) for kind, world in ARMS for n in NS]
    for world, sided in HELD:
        for n in NS:
            zs.extend(far_held(world, n, seeds, sided))
    return (len(zs), within(zs), max(abs(z) for z in zs),
            sum(z * z for z in zs))


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

def near(rec, pin, places):
    """An integer field equal, a float field to its printed places."""
    return all(a == b if isinstance(b, int)
               else abs(a - b) < 0.5 * 10 ** -p
               for a, b, p in zip(rec, pin, places, strict=True))


def section_controls():
    section("CONTROLS")
    check("KNIFE and WIDE are the ring slices (210, 15, 105) and "
          "(1155, 105, 525)",
          ring_etas(210, 15, 105) == WORLDS["KNIFE"]
          and ring_etas(1155, 105, 525) == WORLDS["WIDE"])
    gaps = {w: bayes(pooled(WORLDS[w])) - bayes(WORLDS[w])
            for w in ("CLEAR", "MILD", "SAME")}
    print("  exact targets: " + ", ".join(
        f"{w} {bayes(e)}" for w, e in WORLDS.items()))
    print("  pooling gaps: " + ", ".join(f"{w} {g}" for w, g in gaps.items()))
    check("the five targets and the three pooling gaps by hand",
          [bayes(e) for e in WORLDS.values()] == [F(h) for h in HAND_TARGETS]
          and list(gaps.values()) == [F(h) for h in HAND_GAPS])
    s = WORLDS["SAME"]
    off = sum(e != g for g, i in zip(pooled(s), range(0, 15, 5))
              for e in s[i:i + 5])
    check("SAME's bins off their group's rate: 14 of 15", off == 14)
    z, o = np.array(HAND_Z), np.array(HAND_O)
    check("the estimators on hand counts: 3 minority labels of 16 a bin "
          "and 6 a group, SHRUNK 11/32, Pearson 14/(3 sqrt 6)",
          (int(low_cell(z, o)), int(low_pool(z, o))) == (3, 6)
          and abs(est_cell(z, o, 16) - 3 / 16) <= TOL
          and abs(est_pool(z, o, 16) - 6 / 16) <= TOL
          and abs(est_shrunk(z, o, 16) - 11 / 32) <= TOL
          and abs(pearson(z, o) - 14 / (3 * sqrt(6))) <= TOL)
    w = held_err(z, o, np.array([2, 1, 0, 3, 1, 4]),
                 np.array([5, 0, 2, 1, 6, 1]))
    bins = wrong_bins(z, o, np.array([0.6, 0.4, 0.5, 0.7, 0.2, 0.3]))
    check("held-out on hand counts, a tie guessing 1: 17 test labels wrong, "
          "four bins' majorities",
          int(w) == 17 and bins.tolist() == [1, 1, 0, 1, 0, 1])
    check("the bar on two hand rows, and phi at 0 and 1.96",
          abs(bar(0.5, 2401) - 0.02) <= TOL
          and abs(bar(0.1, 3600) - 0.0098) <= TOL
          and phi(0) == 0.5 and abs(phi(1.96) - 0.9750021) < 5e-8)
    dev = np.array([-0.02, 0.03, 0.05, -0.04])
    h = np.array([0.03, 0.03, 0.04, 0.03])
    two, one = moments(dev, h, "two"), moments(dev, h, "one")
    check("moments on four hand trials, a tie among them: 2 hold "
          "two-sided and 3 one-sided, b 0.005, h 0.0325, sd 0.042032, "
          "the plane 0.5574 and 0.8139; and a one-sided tie holds",
          (two["hits"], one["hits"]) == (2, 3)
          and moments(np.array([-0.03, 0.01]), np.array([0.03, 0.03]),
                      "one")["hits"] == 2
          and near((two["b"], two["h"], two["sd"], two["pred"], one["pred"],
                    two["ratio"], two["hsd"]),
                   (0.005, 0.0325, 0.042032, 0.5574, 0.8139, 0.1538, 0.7732),
                   (9, 9, 6, 4, 4, 4, 4)))
    check("the threshold on 1..20 is 18, and on 1..10 is 9",
          threshold([np.arange(1.0, 21.0)]) == 18
          and threshold([np.arange(6.0, 11.0), np.arange(1.0, 6.0)]) == 9)
    check("a binomial's weights at n = 4, and its window at (32000, 1/15) "
          "holds all but 1e-9",
          np.abs(pmf(4, np.arange(5), 0.5) * 16 - [1, 4, 6, 4, 1]).max() <= TOL
          and abs(pmf(32000, window(32000, 1 / 15), 1 / 15).sum() - 1) <= 1e-9)
    fl = np.array(upper(np.arange(4), 0.4)).T
    check("P(X > K/2), P(X >= K/2) and E(2X - K)^+ at e = 2/5, K = 0..3, "
          "in rationals and in floats",
          sum(upper_exact(K, F(2, 5)) == tuple(F(x) for x in hand)
              and np.abs(fl[K] - [float(F(x)) for x in hand]).max() <= TOL
              for K, hand in enumerate(HAND_UPPER)) == 4)
    big = np.array([2134, 10667])
    pairs = [(a, b) for e in (0.45, 0.49, 0.5)
             for row, K in zip(np.array(upper(big, e)).T, big)
             for a, b in zip(row, upper_whole(int(K), e))]
    check("the three sums as far as they reach, at K = 2134 and 10667 and "
          "e = 9/20, 49/100 and 1/2, against the sums over every j: 15 to "
          "1e-9 of each, and 3 with both under 1e-15",
          sum(b > 1e-15 and abs(a - b) <= 1e-9 * b for a, b in pairs) == 15
          and sum(b <= 1e-15 and a <= 1e-15 for a, b in pairs) == 3)
    check("a bin's mean minority labels on four hand rows, and the "
          "chance its majority is wrong on four",
          sum(low_exact(*a) == F(h) for a, h in HAND_LOW) == 4
          and sum(flip_exact(*a) == F(h) for a, h in HAND_FLIP) == 4)
    rows = ((500, F(1, 15), F(2, 5)), (500, F(1, 3), F(211, 500)),
            (500, F(1, 15), F(1, 2)), (500, F(1, 15), F(9, 10)),
            (4, F(1, 2), F(2, 5)), (4, F(1, 2), F(3, 5)))
    check("the two laws in floats are the exact ones at 500 points and "
          "at 4, to 1e-9 of each, at six bins and at five",
          sum(abs(low_mean(n, float(q), float(e)) / float(low_exact(n, q, e))
                  - 1) <= 1e-9 for n, q, e in rows) == 6
          and sum(abs(flip_prob(n, float(q), float(e))
                      / float(flip_exact(n, q, e)) - 1) <= 1e-9
                  for n, q, e in rows if 2 * e != 1) == 5)
    cell, pool, ident, below, size = enum_fit(SMALL, 4)
    check("every sample of 4 points on 6 bins through the estimators: "
          "the mean minority labels are the law's a bin and a group, "
          "SHRUNK is (1 - lam) PER-BIN + lam/2 at each, the pooled count "
          "never below the per-bin one",
          (cell, pool) == (low_law("FIT", SMALL, 4), low_law("POOL", SMALL, 4))
          and (ident, below, size) == (20736, 0, 20736) and pool > cell)
    dev, risk, cov = enum_held(PAIR, 6)
    kdev, krisk, kcov = enum_held([F(1, 2)] * 2, 6)
    cover = cover_set(3, 47 / 110, "one")
    floor = cover_exact(3, F(47, 110), cover)
    check("every sample of 6 points, 3 a half, on 2 bins through "
          "held-out: its mean less R* is the wrong bins' cost and the "
          "law's; its bound holds R* more often than a binomial at R* "
          "does, and as often on a world of rate 1/2",
          dev == risk == held_exact(PAIR, 3) and dev > 0 and cov > floor
          and (kdev, krisk) == (0, 0)
          and kcov == cover_exact(3, F(1, 2), cover_set(3, 0.5, "one")),
          f"{float(cov):.4f} against {float(floor):.4f}")
    check("the cover set, an upper set and one that is not, and its "
          "chance, on hand rows",
          cover.tolist() == [0, 1, 1, 1]
          and cover_set(4, 0.5, "two").tolist() == [0, 1, 1, 1, 0]
          and upper_set(cover) == (1, True)
          and upper_set(cover_set(4, 0.5, "two")) == (1, False)
          and abs(cover_prob(4, 0.5, cover_set(4, 0.5, "two")) - 7 / 8) <= TOL
          and cover_exact(3, F(1, 2), cover) == F(7, 8)
          and near(cond_law(4, np.array([0.5, 0.5, 0.25]),
                            cover_set(4, 0.5, "two")),
                   (2 * 7 / 8 + 87 / 128, 2 * 7 / 64 + 87 * 41 / 128 ** 2),
                   (9, 9)))
    check("a distance in standard errors on four hand rows, one of a "
          "sample that does not vary; of four distances two are inside 4",
          abs(z_of(110, 100, 25) - 2) <= TOL
          and abs(z_of(90, 100, 400) + 0.5) <= TOL
          and abs(z_mean(np.array([1.0, 2.0, 3.0, 6.0]), 2.0)
                  - 1 / sqrt(14 / 3 / 4)) <= TOL
          and abs(z_mean(np.zeros(4), 1e-10) + 0.1) <= TOL
          and within([0.5, -3.99, 4.0, -5.0]) == 2)
    check("a record against its pin on four hand rows: equal, a float "
          "inside its last place, outside it, an integer off by one",
          [near(r, (3, 1.23), (0, 2)) for r in
           ((3, 1.23), (3, 1.2349), (3, 1.2351), (4, 1.23))]
          == [True, True, False, False])
    return all(CHECKS)


def show(name, n, r):
    print(f"  {name:12s} n = {n:5d}: coverage {r['hits'] / TRIALS:.3f} "
          f"({r['hits']} of {TRIALS}; plane {r['pred']:.3f}), b "
          f"{r['b']:+.5f} ({r['zb']:+.2f} se of the law "
          f"{round(r['law'], 5) + 0.0:+.5f}), "
          f"|b|/h {r['ratio']:.3f}, h/sd {r['hsd']:.2f}", end="")


def section_fits(fits):
    section("THE FITS: 32 settings against the exact mean")
    for (kind, world, n), r in fits.items():
        show(f"{kind}-{world}", n, r)
        print(f"; minority labels {r['low']}, the drift {r['zd']:+.2f} se "
              f"of its law")
    check("FIT the 32 settings' hits, minority labels, |b|/h, h/sd, plane "
          "and the two distances as recorded",
          len(fits) == 32
          and sum(near((r["hits"], r["low"], r["ratio"], r["hsd"], r["pred"],
                        r["zb"], r["zd"]), FIT_PINS[k[:2]][NS.index(k[2])],
                       (0, 0, 3, 2, 3, 2, 2))
                  for k, r in fits.items()) == 32)
    check("FIT each mean deviation inside 4 standard errors of the "
          "exact law", within(r["zb"] for r in fits.values()) == 32)
    check("FIT each mean drift inside 4 standard errors of the law at n "
          "less the law at n/2",
          within(r["zd"] for r in fits.values()) == 32)


def show_held(world, n, r):
    show(f"{'HELD' if world == 'WIDE' else 'BOUND'}-{world}", n, r)
    print(f"; test errors {r['wrong']}, wrong bins {r['flips']}, below 1/2 "
          f"in {r['below']}, hits {r['zc']:+.2f} sd of the law given the "
          f"rules")


def section_sign(held):
    section("THE SIGN LAW: the bound against the binomial at R*")
    one = {k: r for k, r in held.items() if k[0] != "WIDE"}
    for (world, n), r in one.items():
        show_held(world, n, r)
        print(f"{'':28s}the cover set starts at {r['edge']} of "
              f"{n - n // 2}; a binomial at R* reaches it at "
              f"{r['floor']:.5f}")
    check("SIGN the cover set is every count from its least up, at the 8 "
          "settings, and at the knife its least is Wilson's 110, 470, "
          "1939, 7877",
          sum(r["upper"] for r in one.values()) == 8
          and tuple(one["KNIFE", n]["edge"] for n in NS) == HAND_EDGE)
    check("SIGN the edge and the binomial's chance of reaching it as "
          "recorded",
          sum(near((r["edge"], r["floor"]),
                   FLOOR_PINS[k[0]][NS.index(k[1])], (0, 5))
              for k, r in one.items()) == 8)


def section_held(held):
    section("HELD-OUT: 12 settings against the exact laws")
    for n in NS:
        show_held("WIDE", n, held["WIDE", n])
    check("HELD the 12 settings' hits, test errors, wrong bins, bounds "
          "below 1/2, plane and the two distances as recorded",
          len(held) == 12
          and sum(near((r["hits"], r["wrong"], r["flips"], r["below"],
                        r["pred"], r["zb"], r["zc"]),
                       HELD_PINS[k[0]][NS.index(k[1])],
                       (0, 0, 0, 0, 3, 2, 2))
                  for k, r in held.items()) == 12)
    check("HELD each mean deviation inside 4 standard errors of the "
          "wrong bins' cost, and each setting's hits inside 4 standard "
          "deviations of the law given its rules",
          within(z for r in held.values() for z in (r["zb"], r["zc"]))
          == 24)


def section_plane(fits, held):
    section("THE PLANE: coverage against (b/sd, h/sd)")
    recs = {**fits, **{("HELD",) + k: r for k, r in held.items()}}
    within, worst, key, mean = plane(recs)
    check("PLANE each of the 44 settings within 0.05 of the plane",
          (len(recs), within) == (44, 44))
    check("PLANE the worst gap 0.0337, SHRUNK-CLEAR at n = 500, and the "
          "mean 0.0058, as recorded",
          key == ("SHRUNK", "CLEAR", 500)
          and near((worst, mean), (0.0337, 0.0058), (4, 4)),
          f"worst {worst:.4f} at {key}, mean {mean:.4f}")


def section_kernel(fits):
    section("THE KERNEL: what a sample shows of its own uncounted term")
    knife = [knife_kernel(fits["FIT", "KNIFE", n]) for n in NS]
    for n, k in zip(NS, knife):
        print(f"  FIT-KNIFE    n = {n:5d}: bhat/b {k[0]:.4f}, sdhat/sd "
              f"{k[1]:.3f}, sd(drift)/sd {k[2]:.3f}")
    check("KERNEL the knife's bhat/b, sdhat/sd and sd(drift)/sd as "
          "recorded",
          sum(near(k, p, (4, 3, 3))
              for k, p in zip(knife, KNIFE_PINS, strict=True)) == 4)
    ident = max(float(np.max(fits["SHRUNK", "CLEAR", n]["t"]["ident"]))
                for n in NS)
    check("KERNEL SHRUNK's bootstrap term is (1 - lam) times PER-BIN's "
          "on the same resamples, to 1e-12 at every trial",
          ident <= TOL, f"largest gap {ident:.1e}")
    drift = [shrunk_drift(fits["SHRUNK", "CLEAR", n], n) for n in NS]
    for n, (d, law) in zip(NS, drift):
        ratio = fits["SHRUNK", "CLEAR", n]["ratio"]
        print(f"  SHRUNK-CLEAR n = {n:5d}: drift/h {d:+.3f}; the law over "
              f"the mean bar {law:+.3f}; -0.189 |b|/h = {-0.189 * ratio:+.3f}")
    check("KERNEL SHRUNK's mean drift over h, and its law over the mean "
          "bar, as recorded",
          sum(near(d, pin, (3, 3))
              for d, pin in zip(drift, SHRUNK_PINS, strict=True)) == 4)
    hs = {kind: [readable(fits[kind, "MILD", n]) for n in NS]
          for kind in ("POOL", "FIT")}
    for kind, row in hs.items():
        print(f"  {kind}-MILD h/sdhat " + ", ".join(f"{x:.3f}" for x in row))
    check("KERNEL h/sdhat on MILD, pooled and per-bin, as recorded",
          sum(near(row, MILD_PINS[kind], (3,) * 4)
              for kind, row in hs.items()) == 2)
    thr, good, bad, alarms = detector(fits, "boot")
    print(f"  bootstrap threshold {thr:.3f} over {len(good)} GOOD settings, "
          f"{len(bad)} BAD")
    for kind, world in ARMS:
        print(f"  {kind + '-' + world:12s} bootstrap alarms " + ", ".join(
            str(alarms[kind, world, n]) for n in NS))
    check("KERNEL the bootstrap detector's threshold, its GOOD and BAD "
          "settings and the 32 settings' alarms as recorded",
          near((thr, len(good), len(bad)), BOOT_PINS[:3], (3, 0, 0))
          and sum(tuple(alarms[kind, world, n] for n in NS) == pin
                  for (kind, world), pin in zip(ARMS, BOOT_PINS[3],
                                                strict=True)) == 8)


def section_repair(fits):
    section("THE NESTED REPAIR: the two fits' difference in the functional")
    pools = {k[1:]: {"t": {"dhat": r["t"]["dhat"], "h": r["t"]["h"]},
                     "hits": r["hits"]}
             for k, r in fits.items() if k[0] == "POOL"}
    thr, good, _, alarms = detector(pools, "dhat")
    print(f"  Dhat/h threshold {thr:.3f} over the GOOD pooled settings "
          f"{good}")
    rows = {k: repair_row(fits, *k) for k in pools}
    for w in ("CLEAR", "MILD", "SAME"):
        print(f"  POOL-{w:5s} Dhat alarms " + ", ".join(
            str(alarms[w, n]) for n in NS) + "; Pearson " + ", ".join(
            f"{rows[w, n][2]:.1f}" for n in NS) + "; mean Dhat " + ", ".join(
            f"{rows[w, n][1]:+.2f}" for n in NS) + " se of its law")
    check("REPAIR the threshold, the GOOD pooled settings, and each "
          "setting's alarms, Pearson mean and distance as recorded",
          near((thr,), REPAIR_PINS[:1], (3,)) and good == REPAIR_PINS[1]
          and sum(near((alarms[k], rows[k][2], rows[k][1]), pin, (0, 1, 2))
                  for k, pin in zip(pools, REPAIR_PINS[2], strict=True)) == 12)
    check("REPAIR the pooled estimate is never below the per-bin one, "
          "at the 4,800 trials, and its mean excess is inside 4 standard "
          "errors of the two laws' difference at the 12 settings",
          sum(TRIALS - r[0] for r in rows.values()) == 4800
          and within(r[1] for r in rows.values()) == 12)


def section_far():
    section("FURTHER SEEDS")
    reads, within, worst, squares = far_sweep(FAR)
    print(f"  ten further seeds, 4,000 trials a setting: {within} of {reads} "
          f"reads within 4, the worst {worst:.2f}, their squares sum to "
          f"{squares:.1f}")
    check("FAR each read of (L1), (L3) and (L4) inside 4 at ten further "
          "seeds",
          (reads, within) == (56, 56))
    check("FAR the ten further seeds' record",
          near((worst, squares), FAR_PINS, (2, 1)))


def main():
    t0 = time.time()
    if not section_controls():
        print("\nCONTROL FAILED: nothing below is read.")
        return 1
    if sys.argv[1:2] == ["--seeds"]:
        first, count = int(sys.argv[2]), int(sys.argv[3])
        reads, within, worst, squares = far_sweep(range(first, first + count))
        print(f"seeds {first} to {first + count - 1}: {within} of {reads} "
              f"reads within 4, the worst {worst:.2f}, their squares sum "
              f"to {squares:.1f}")
        return 0 if within == reads else 1
    fits, held = fit_sweep(), held_sweep()
    section_fits(fits)
    section_sign(held)
    section_held(held)
    section_plane(fits, held)
    section_kernel(fits)
    section_repair(fits)
    section_far()
    print()
    n, ok = len(CHECKS), sum(CHECKS)
    print(f"{ok} of {n} checks pass, {time.time() - t0:.1f} s")
    return 0 if ok == n else 1


if __name__ == "__main__":
    sys.exit(main())