lira.py

Checks: RULER: The per-example audit states its Gaussian limit property; observation.

Cited on: RULER.

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

"""lira.py -- a published per-example membership audit scored against
the exact posterior: the probability it states converges to its
Gaussian limit rather than to the truth, whether its membership call
survives is a side criterion read cell by cell, and its accuracy, its
calibration error and the probability it states have exact means at a
finite shadow count.

QUESTION. U-LiRA (Hayes, Shumailov, Triantafillou, Khalifa and
Papernot, "Inexact Unlearning Needs More Careful Evaluations to Avoid
a False Sense of Privacy", arXiv:2403.01218, Algorithm 1 and Sec. 4.3,
read at source) audits one example: it collects the example's score
under N shadow models that saw and then unlearned it (in) and N that
never saw it (out), fits a Gaussian to each, and for the audited
model's score o states
    p_member = N(o; mu1, s1^2) / (N(o; mu1, s1^2) + N(o; mu0, s0^2)),
calling a member iff p_member > 1/2. Its stated outputs are the
balanced accuracy of that call and the per-example p_member itself
("an optimal unlearning algorithm would result in a predicted
membership probability of 1/2"); it states no interval. The source
names the Gaussian fit as a risk to the attack's ACCURACY on
non-Gaussian shadow distributions (its Sec. 7, bimodal and skewed
examples). Where the truth is known exactly, what do the call and the
probability each converge to, and what are they at a finite N?

THE WORLD. The depth cell (a, b) of audit.py: the audited datum is the
first move of a uniform arrangement of a twos and b threes, member =
first move 2, and the score is the number of 2-moves in the three
positions after the first, so
    P_in(c) = HG(T - 1, a - 1, 3),  P_out(c) = HG(T - 1, a, 3),  T = a + b.
p_member is the posterior at prior 1/2 under the fits, so its estimand
is the EQUAL-PRIOR posterior tau(c) = P_in(c)/(P_in(c) + P_out(c)), an
exact Fraction; the balanced accuracy's ceiling is
(1/2) sum_c max(P_in(c), P_out(c)). The audited mass of score c is
P_u(c) = (a/T) P_in(c) + (b/T) P_out(c). Cells W1 = (5, 5), W2 = (12, 3),
W3 = (2, 8) and (5, 12); S, off the depth column: support points
{0, 3}, member mass (9/10, 1/10), non-member mirrored; FAR, a far
support point: member masses 0.45, 0.1, 0.45 at 0, 1, 10, non-member
0.2, 0.8 at 1, 5.

THE ARGUMENT.
  (A) THE LIMIT (property). The fitted means and variances converge to
      the class moments, so p_member(c) converges to the GAUSSIAN-LIMIT
      posterior p_lim(c), the formula at the exact moments, and every
      calibration error converges to its value at p_lim:
      ECE_lim = sum_c P_u(c) |p_lim(c) - tau(c)| is a property of the
      model class, not of the shadow count. It is a limit and not a
      lower bound: (L) puts the error under it at finite N. The error
      is continuous in p; the call and OVER are not, and converge only
      where p_lim is off 1/2 and off tau. A class of zero variance has
      no Gaussian limit: (D), and among the census's cells (2, 2) alone
      (a cell with one move of a kind has such a class).
  (B) THE SIDE CRITERION (property). The balanced accuracy is
      (1/2) sum over scores of the class mass the call picks, maximized
      exactly by picking the larger of P_in(c), P_out(c), i.e. by tau's
      side of 1/2. So the limit call reaches the ceiling iff the call
      p_lim(c) > 1/2 takes tau's side at every score with mass and
      tau != 1/2, and each exception costs |P_in(c) - P_out(c)|/2.
      Whether the call survives is a cell-by-cell fact, and a census
      decides whether it ever fails on the depth column.
  (C) TAU IN CLOSED FORM, AND THE MIRROR (proved). On a depth cell,
      at a score with mass, P_in(c)/P_out(c) = (a - c) b / (a (b - 3 +
      c)), so
          tau(c) = b (a - c) / (b (a - c) + a (b - 3 + c)),
      above 1/2 iff c < 3a/T and equal to it iff c T = 3a. Exchanging
      2 and 3 sends the cell (a, b) to (b, a), the score c to 3 - c
      and swaps the classes; a Gaussian fit follows its sample, so tau
      and p_lim both go to one minus themselves and, where p_lim is
      off 1/2 (the call is strict), every exception goes to an
      exception of the same cost. On the diagonal a = b > 2 the two
      variances are equal, the Gaussian boundary is the midpoint 3/2
      of the means, and so is tau's: no exception; (2, 2) is (f)'s.
  (D) DEGENERATE FITS. A class whose N shadow scores coincide fits a
      zero variance, a point mass, of density infinite on its point
      and 0 off it: the stated probability is 1/2 where two point
      masses both sit on the score or both miss it, and otherwise 1 or
      0 for the class that can hold the score. The chance of such a
      fit is
          1 - prod over the two classes of (1 - sum_c P(c)^N).
  (L) THE LAW (proved). A class's N scores enter its fit only through
      their sum and the sum of their squares, a function of the counts
      at each support point, which are multinomial; the two classes
      are drawn apart. So every column of the table below is a function
      of two independent multinomials, and its mean and variance at
      any N are a finite double sum over the pairs of fits, the ATOMS,
      taken through the same fit(), logpdf(), combine() and score()
      that read a drawn replicate. It is computed for ACC, ECE, OVER,
      FLAT and the stated p, in floats, and two exact ties are where
      floats matter. Two unequal fits can state exactly 1/2 (equal
      variances, the score midway between the means), and the floats
      give exactly 1/2 there only at N
      a power of two, as every N here is, the means being dyadic; at
      another N rounding can decide the call: at (5, 5), N = 3, the
      code gives an accuracy of 0.525880 where the tie decided in
      rationals gives 0.526785 (a scratch read; equal at N = 4). And a
      stated p can sit exactly at tau: where the two quadratic terms
      cancel, p = 1/(1 + sqrt(v1/v0)), rational when the ratio is a
      square. At (5, 5) the fits (9/8, 47/64) and (43/32, 423/1024),
      both met at N = 32, state 3/7 = tau at score 2 (each quadratic
      term 49/94), and the floats put that p 1.1e-16 under tau. So
      extreme() reads a p within 1e-12 of tau as at
      tau, not past it; OVER's mean is the same with that tolerance at
      1e-13 and at 1e-9 at every row (a scratch read), and with none it
      is 4e-7 higher at (5, 5) and at (12, 3), N = 32, and under 1e-8
      higher at every other row. On S
      a class has N + 1 atoms; on a depth
      cell a class has of the order of N^2, and the pairs that carry
      the mass grow about as N^2 (2 * 10^7 at (5, 5), N = 128), so the
      law is read there to N = 128, the source's own count, and N =
      512 is a seeded record. Atoms are kept heaviest first until what
      is left weighs under 1e-10 a class, and the law is the mean
      given the kept atoms: every column lies in [0, 1], so it is off
      the exact mean by at most the two classes' dropped mass.

BY HAND.
  (a) (12, 3): tau = (1, 11/15, 5/9, 3/7), ceiling 419/728; moments
      (33/14, 0.427394) and (18/7, 0.310832); logits 3.977137,
      1.658266, 0.216806, -0.347243, so p_lim = (0.9816, 0.8400,
      0.5540, 0.4141): the certain score stated short of certainty,
      the scores at 11/15 and 3/7 past theirs.
  (b) (5, 5): tau = (5 - c)/7; both variances 5/9, logit 0.9 - 0.6 c,
      p_lim = (0.710950, 0.574443, 0.425557, 0.289050); P_u = (1, 5,
      5, 1)/12; ECE_lim = 0.003068, over-confident mass 5/6, least gap
      0.003014, ceiling 25/42.
  (c) (5, 12): P_in = (220, 264, 72, 4)/560, P_out = (165, 275, 110,
      10)/560, P_u(1) = 33/68; tau(1) = 24/49 against p_lim(1) =
      0.501865 (logit 0.007460 at moments (3/4, 0.4875), (15/16,
      0.558594)): an exception costing 11/1120, the limit call's
      accuracy 151/280 under the ceiling 123/224. Least gap 0.002408;
      over-confident at scores 2 and 3, mass 3/17 + 1/68 = 13/68.
  (d) S: means 3/10 and 27/10, both variances 81/100, logit
      p_lim(0) = 40/9, p_lim(0) = 0.988393 against tau = 9/10;
      ECE_lim = 0.088393, every score over-confident. The stated p is
      unmoved by an affine map of the score, so any two support points
      give these numbers.
  (e) FAR: moments (4.6, 23.94) and (4.2, 2.56); at score 1 the logit
      is 0.611552, p_lim = 0.6483 against tau = 1/3, cost 1/20.
  (f) (2, 2): three positions hold all three other moves, so the member
      scores 1 and the non-member 2, both point masses; the sides
      agree. (2, 4): P_in = (4, 6, 0)/10, P_out = (1, 6, 3)/10 on
      scores 0 to 2, none at 3; tau = (4/5, 1/2, 0), P_u = (1, 3,
      1)/5.
  (g) The Gaussian pair N(0, 1), N(3, 4): the posterior at 0 is
      1/(1 + e^(-9/8)/2) = 0.860344 and at 3 it is
      1/(1 + e^(9/2)/2) = 0.021735.
  (h) THE LAW on S at N = 2. With k the scores at 3, the member's k is
      0, 1, 2 at weights (81, 18, 1)/100 and the non-member's at
      (1, 18, 81)/100; k = 1 fits N(3/2, 9/4), the others a point
      mass. Over the nine pairs p(0) is 1 at weight 9477, 1/2 at 486
      and 0 at 37 of 10^4, and p(3) mirrors it: mean p = (0.972,
      0.028); the accuracy is 0.9, 0.5, 0.1 at those weights, mean
      0.8776 and variance 0.00964224; ECE 0.11754; OVER 0.9477; a
      degenerate fit at 1 - 0.18^2 = 0.9676, variance 0.9676 * 0.0324
      = 0.03135024; the stated p's variance is 0.95985 - 0.972^2 =
      0.015066 at score 0 and the same at 3.
  (i) (D) at (2, 8), N = 8: 1 - (6304/6561)(427911454/429981696) =
      0.043797; on S, N = 8: 1 - (1 - 0.9^8 - 0.1^8)^2 = 0.675632.
  (j) A class on four support points at N = 4 has 35 count vectors and
      34 atoms: (1, 0, 3, 0) and (0, 3, 0, 1) share sum 6 and squares
      12. On (5, 5)'s member class, (10, 40, 30, 4)/84, that atom
      weighs (1080000 + 1024000)/84^4.
  (k) The census's sizes: 29^2 = 841 cells; live scores max(0, 3 - b)
      <= c <= min(3, a), 784 * 4 + 56 * 3 + 2 = 3306; ties by (C),
      c = 1 with b = 2a and c = 2 with a = 2b, 14 + 14 = 28; 406 pairs
      a < b and 29 diagonal cells.

ARMS.
  THE CENSUS  every depth cell with 2 <= a, b <= 30, a row a cell:
              tau in Fraction, p_lim in float, the scores at a tie set
              aside, the exceptions and their cost.
  THE LAW     (L) at S for N = 8, 32, 128, 512 and at W1, W2, W3 and
              (5, 12) for N = 8, 32, 128: the mean and variance of
                ACC   the call's balanced accuracy,
                ECE   sum_c P_u(c) |p(c) - tau(c)|,
                OVER  sum of P_u(c) where p(c) is more extreme than
                      tau(c) on tau's side of 1/2,
                FLAT  a degenerate fit in either class,
              and of the stated p at each score.
  THE TOOL    R = 400 replicates of N member and N non-member shadow
              scores at each of the five cells and N = 8, 32, 128,
              512, one seeded stream a (cell, N); fits by mean and
              maximum-likelihood variance; each replicate scored
              exactly over the support. TOP counts the replicates whose
              call reaches the ceiling. Where a row has a law, each of
              its means is read in the law's own standard errors
              (sqrt(variance/n), n the replicates read, a variance
              under 1e-18 read as 1e-18:
              a column the law holds fixed), behind a bar of 4.
  FURTHER SEEDS  the law's rows at ten more seeds pooled, 4000
              replicates a row, read the same way; --seeds BASE COUNT
              reads any others.

CONTROLS, read first; a failure stops the run. The end values of (a)
to (j), and the moments. stated() at a Gaussian pair's own moments, at
point masses and at (L)'s pair, which extreme() must read as at tau
(a check of its own: the pair's mirror above 1/2 is exact in floats,
so that side's tolerance is read at S alone, on made-up values);
score() and the limits on hand probabilities, among
them a probability exactly at tau, one exactly at 1/2 ((5, 5) stated
(0.8, 0.5, 0.3, 0.2) calls a member at score 0 alone: ACC 15/28, ECE
41/420, OVER 7/12) and a cell with a score at tau = 1/2 and one of no
mass ((2, 4) stated (0.9, 0.9, 0.1, 0.7): ACC 13/20, ECE 7/25, OVER
1/5; with 0.2 at score 1, ECE 11/50 and the rest unmoved); the atoms
of a class against (j); the law against (h)
and (i); and every pair of samples of 4 scores a class, 20,736 on
(12, 3) and 256 on S, pushed through the fit and the scoring with
their weights exact and the sums in floats, against the law's means
and variances with no atom left out.

WHAT THE BARS NOTICE. The bar of 4 reads that the seeded columns are
draws from the law, not that the law is right: that is the controls'.
With every mean of the law scaled up by 1% (5%, 10%), 21 (48, 69) of
the 117 reads leave the bar on the recorded seed and 43 (86, 101) on
the further seeds; scaled down, 17 (52, 67) and 43 (91, 99). A column
at a time, scaled up, over the 16 rows on the further
seeds: ACC leaves at all 16 at 1%; ECE at 2, 14 and 16; OVER at 3, 11
and 16; FLAT at none, none and 1, so (D)'s closed form is what reads
it. With the limit's values in place of the law's, 56 reads leave on
the recorded seed and 87 on the further seeds: the bars tell the law
at a finite N from (A)'s limit.

PREDICTIONS. The first engine's, fixed before it: a Gaussian control
within 0.02 of its ceiling; (a) and (d); at N = 512 the mean stated p
within 0.02 of p_lim at every score of mass above 0.01, ECE within
0.015 of ECE_lim, and ECE_lim above 0.01, at S, W1, W2 and W3; OVER
within 0.05 of the limit's over-confident mass at all four; the
accuracy within 0.01 of the ceiling wherever the census finds the
sides agree, and under it by the limit loss, within 0.01, at the
census's worst cell. This engine's, fixed before it with (a) to (k):
every integer behind the first engine's printed rates and every float
of its table reprint; the census's sizes are (k)'s, with 90 cells
holding an exception and the largest loss at (5, 12) and (12, 5)
alone; the law meets the enumeration to 1e-12; every seeded mean with
a law sits inside 4 of the law's standard errors, 117 reads, on the
recorded seed and on ten further seeds pooled; at S the law's ECE is
above its limit at N = 8 and below it at 32, 128 and 512. KILL: the
enumeration
off, or a read outside 4, on the recorded seed or the further seeds
pooled, at a column the law gives no rare far value.

FINDINGS. The first run stopped in the controls, at two faults of
their own (the RUN RECORD): the enumeration, the control the kill
names, read the law with its lightest atoms left out, 1e-11 off, and
holds to 1e-12 with none left out; and a hand value was wrong in its
sixth place. The next run was the first to reach the tables, and every
prediction of this engine held on it. Later reads moved one printed
place: OVER's law at W1,
N = 32, printed 0.549923 until a p exactly at tau was read as at tau.
Of the first engine's, three
clauses were wrong or empty. "ECE_lim above 0.01 at all four" was
never computed at W1,
whose limit is 0.0031 by (b). OVER, an indicator, was read as if it
converged by N = 512 everywhere: where p_lim sits within the fit's
noise of tau it counts about half the replicates, and the law now says
so with no seed, 0.561848, 0.549922, 0.553813 at W1 for N = 8, 32,
128 against a limit of 5/6. And the worst cell's loss, 0.0098, was
given a band of 0.01.
  census    90 of 841 cells have an exception; 28 of 3306 live scores
            sit at a tie; the largest loss is 11/1120 = 0.0098, at
            (5, 12), score 1 (tau 24/49 = 0.4898, p_lim 0.5019) and at
            its mirror (12, 5), score 2 (25/49 = 0.5102, 0.4981); the
            406 mirror pairs lose the same and no diagonal cell loses;
            the least |p_lim - 1/2| off a tie is 6.46e-05, so every
            side is decided in floats. An exception needs tau near
            1/2, where the class masses nearly tie, so on the depth
            column it is common and costs little; FAR puts one at
            tau = 1/3, costing 1/20.
  the law   At S the mean ECE is 0.091666, 0.079896, 0.084711,
            0.087370 at N = 8, 32, 128, 512 against ECE_lim =
            0.088393: above the limit at 8, under it at 32, 128 and
            512, rising. At the source's own N = 128 the mean ECE is
            0.026947 at W1 (limit 0.003068), 0.031502 at W2
            (0.016182), 0.040545 at W3 (0.034770) and 0.029235 at
            (5, 12) (0.011909): at W1 almost nine tenths of the error
            is the fit's noise and not the model class. The mean
            accuracy at N = 128 is under the ceiling by 0.0005 at W1 and
            0.0006 at W2, and at it to six places at W3. At
            (5, 12) it is 0.541604, ABOVE the limit call's 151/280 =
            0.539286: p_lim(1) clears 1/2 by 0.0019, the fits' noise
            splits the call at score 1, and the split is right more
            often than the limit. By (A) the accuracy tends to the
            limit call's, so somewhere past 128 more shadow models
            lower it; no row here shows it (0.5437 at 512, seeded).
            The mean stated p is slowest at the
            scores of least mass: 0.950358 at W2's certain score at
            N = 128 against p_lim 0.9816.
  the tool  At N = 512 the call is at the ceiling in all 400
            replicates at S, W1, W2 and W3, and in 179 at (5, 12)
            (102, 141, 173 at N = 8, 32, 128), its mean accuracy
            0.5437. ECE at N = 512 against its limit: S 0.0870/0.0884,
            W1 0.0132/0.0031, W2 0.0214/0.0162, W3 0.0358/0.0348. OVER
            reaches its limit where the gaps are wide (S 1.000; W3
            0.925 to 0.933) and not where they are under the noise (W1
            0.591 against 0.833, W2 0.697 against 0.563, 194 of 400
            replicates past tau at W2's score 2, gap 0.0016). A
            degenerate fit: 254 of 400 at S and 22 at W3 at N = 8,
            where (D) gives 0.675632 and 0.043797.
  reads     117 of 117 inside 4 on the recorded seed, the worst 2.34
            (W3, N = 8); 117 of 117 on the further seeds, the worst
            3.23.
Rates over R = 400 read to about 0.025 at their largest; the law, the
census and the side criterion are the finding, the seeded table their
instance.

RUN RECORD.
python lira.py: 29 of 29 checks, 4.6 s, peak commit 128.3 MB.
  The replicates at the ceiling, each row's worst distance and the
further seeds' worst read were entered from the first run of this
engine to reach the tables; every other seeded pin was fixed before it
from the first
engine's print, and reprinted. The law's pins were printed before the
predictions were fixed, by a probe of the same sums on the first
engine's functions. Two controls failed on the first run and were
the controls' own: the enumeration was first set against the law with
its lightest atoms left out, off by 1e-11 at (12, 3), whose rarest
sample weighs 364^-4, and now reads the law with none left out; and
(c)'s least gap, first worked to 0.002410, is 0.002408 with its
logarithms carried a place further, as are three logits of (a) and
(c), wrong in their sixth place when the predictions were fixed. The
prediction on S's ECE has no check of its own: the law's pins and (d)
imply it.
  `--seeds 7000 40` read 117 of 117 inside 4, the worst 2.28, and
`--seeds 9000 160`, 64,000 replicates a row, the worst 2.36: records no
check holds. A seed at a time, the bar is left mostly where the law
gives a column a rare far value: of the 46,800 reads of seeds 1 to
400, each alone, 14 left it, 10 of them ACC at S, N = 8 (one replicate
of 400 off the ceiling), 2 OVER at S, N = 128, one ACC at W1, N = 128,
and one the mean stated p at W1, N = 8, a column with no far value:
an ordinary tail, of which a normal read expects about 3 in 46,800.
Seed 20260931 alone leaves it at OVER on
S, N = 128, three replicates of 400 off 1 where the law expects 0.31,
at -4.68; pooled with nine more that read is the further seeds' worst,
3.23.
  Read by breaks: of 290 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) 275 fail a check; 15 pass and move no line.
Seven are bounds never met with equality (a tail of exactly the drop,
a difference of exactly half a last place, an accuracy exactly 1e-12
under the ceiling, a p exactly 1e-12 from tau on either side, p_lim
exactly 1/2, and tau exactly 1/2, which the census sets aside before
the call). One changes the Gaussian's constant, which cancels between
the classes. Two enlarge the base of an atom's
key, any base above the largest sum of squares grouping alike; one
lets a count of N + 1 through to the filter on the sum; one doubles
the least slab, never reached; two move FAR's prior, which enters no
value read; one reads only a cell's first exception, and no cell of
the census has two. Of 42 edits by hand, the controls' stop lifted,
each with the checks it should fail named first, 41 fail (three by a
strict zip's crash) and one passes as predicted (the mean stated p
left unnormalised, a factor within 2e-10 of 1); some fail further
lines their labels named neither way. The recorded seed moved by seven
fails every record and no bar. Four labels were wrong in a line they
did name: the limits never read
the side criterion; two seed breaks failed a bar beside the records,
both through seed 20260931's read above; and a clause on the mass left
out passed at a drop of 1e-6, being forced by the rule that keeps the
atoms, and is cut.
"""

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

import sys
import time
from fractions import Fraction as F
from functools import lru_cache
from itertools import product
from math import comb, exp, lgamma, pi, prod, sqrt

import numpy as np

NS = (8, 32, 128, 512)
LAW_NS = (8, 32, 128)
R = 400
SEED = 20260930
FAR_SEEDS = tuple(range(SEED + 1, SEED + 11))
DROP = 1e-10
SLAB = 200_000
TOL = 1e-12
LOGFACT = np.array([lgamma(i + 1) for i in range(max(NS) + 1)])
CHECKS = []

# Each cell at N = 8, 32, 128, 512: ACC, ECE, OVER, the replicates with a
# degenerate fit, the replicates at the ceiling, and (a row with a law)
# the worst of its distances from the law.
TABLE_PINS = {
    "S": [(0.9000, 0.0897, 0.881, 254, 400, 1.87),
          (0.9000, 0.0803, 0.969, 25, 400, 1.53),
          (0.9000, 0.0852, 1.000, 0, 400, 0.81),
          (0.9000, 0.0870, 1.000, 0, 400, 1.34)],
    "W(5,5)": [(0.5508, 0.1309, 0.576, 0, 214, 1.53),
               (0.5795, 0.0547, 0.536, 0, 316, 2.12),
               (0.5947, 0.0266, 0.546, 0, 396, 1.75),
               (0.5952, 0.0132, 0.591, 0, 400, None)],
    "W(12,3)": [(0.5386, 0.1399, 0.565, 12, 249, 1.55),
                (0.5625, 0.0609, 0.571, 0, 331, 1.74),
                (0.5750, 0.0311, 0.589, 0, 396, 1.41),
                (0.5755, 0.0214, 0.697, 0, 400, None)],
    "W(2,8)": [(0.5860, 0.1408, 0.544, 22, 297, 2.34),
               (0.6232, 0.0628, 0.672, 0, 395, 0.99),
               (0.6250, 0.0389, 0.807, 0, 400, 1.36),
               (0.6250, 0.0358, 0.925, 0, 400, None)],
    "W(5,12)": [(0.5157, 0.1292, 0.481, 5, 102, 1.52),
                (0.5299, 0.0573, 0.471, 0, 141, 1.13),
                (0.5424, 0.0288, 0.410, 0, 173, 1.50),
                (0.5437, 0.0182, 0.336, 0, 179, None)],
}
# At N = 512, a live score at a time: the mean stated p, and the
# replicates stating p more extreme than tau.
SCORE_PINS = {
    "S": ((0.9871, 0.0131), (400, 400)),
    "W(5,5)": ((0.7106, 0.5753, 0.4255, 0.2891), (186, 258, 236, 183)),
    "W(12,3)": ((0.9761, 0.8392, 0.5555, 0.4131), (0, 392, 194, 338)),
    "W(2,8)": ((0.6468, 0.3584, 0.0251), (398, 395, 0)),
    "W(5,12)": ((0.5700, 0.5018, 0.3703, 0.2160), (188, 32, 301, 333)),
}
# ECE_lim, the over-confident mass and the least gap |p_lim - tau|.
LIMIT_PINS = {"S": (0.0884, 1.000, 0.0884), "W(5,5)": (0.0031, 0.833, 0.0030),
              "W(12,3)": (0.0162, 0.563, 0.0016),
              "W(2,8)": (0.0348, 0.933, 0.0245),
              "W(5,12)": (0.0119, 0.191, 0.0024)}
# The law's ACC, ECE, OVER and FLAT, a row an N.
LAW_PINS = {
    "S": [(0.899973, 0.091666, 0.893548, 0.675632),
          (0.900000, 0.079896, 0.962337, 0.067495),
          (0.900000, 0.084711, 0.999607, 0.000003),
          (0.900000, 0.087370, 1.000000, 0.000000)],
    "W(5,5)": [(0.549185, 0.131492, 0.561848, 0.005809),
               (0.580670, 0.056082, 0.549922, 0.000000),
               (0.594727, 0.026947, 0.553813, 0.000000)],
    "W(12,3)": [(0.536282, 0.137869, 0.565158, 0.021606),
                (0.561511, 0.059640, 0.572969, 0.000000),
                (0.574928, 0.031502, 0.614959, 0.000000)],
    "W(2,8)": [(0.592954, 0.137177, 0.593267, 0.043797),
               (0.623087, 0.063534, 0.674347, 0.000002),
               (0.625000, 0.040545, 0.815109, 0.000000)],
    "W(5,12)": [(0.516046, 0.130380, 0.502177, 0.006438),
                (0.529469, 0.056895, 0.462568, 0.000000),
                (0.541604, 0.029235, 0.404581, 0.000000)],
}
# The law's mean stated p at a cell's largest N with a law.
MEAN_PINS = {"S": (0.987370, 0.012630),
             "W(5,5)": (0.709095, 0.575971, 0.424029, 0.290905),
             "W(12,3)": (0.950358, 0.826237, 0.556906, 0.413266),
             "W(2,8)": (0.646982, 0.356508, 0.029859),
             "W(5,12)": (0.569883, 0.501261, 0.370860, 0.237259)}
# The further seeds' worst read.
FAR_PIN = 3.23


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)


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

def hg(M, K, w=3):
    return [F(comb(K, c) * comb(M - K, w - c), comb(M, w))
            for c in range(w + 1)]


class Cell:
    """A two-class score world on a finite integer support, exact
    throughout."""

    def __init__(self, name, pts, Pm, Pn, wm):
        self.name, self.pts = name, tuple(pts)
        self.xs = np.array(self.pts, dtype=float)
        self.Pm, self.Pn, self.wm = Pm, Pn, F(wm)
        self.Pu = [self.wm * m + (1 - self.wm) * n for m, n in zip(Pm, Pn)]
        self.tau = [m / (m + n) if m + n else None for m, n in zip(Pm, Pn)]
        self.ceiling = sum(max(m, n) for m, n in zip(Pm, Pn)) / 2

        def mom(P):
            mu = sum(x * p for x, p in zip(self.pts, P))
            return float(mu), float(sum((x - mu) ** 2 * p
                                        for x, p in zip(self.pts, P)))
        self.mom_m, self.mom_n = mom(Pm), mom(Pn)
        self.plim = stated(*self.mom_m, *self.mom_n, self.xs)

    def live(self):
        """Support indices with audited mass."""
        return [i for i, p in enumerate(self.Pu) if p > 0]


def depth(a, b):
    T = a + b
    return Cell(f"W({a},{b})", range(4), hg(T - 1, a - 1), hg(T - 1, a),
                F(a, T))


def two_point():
    return Cell("S", (0, 3), [F(9, 10), F(1, 10)], [F(1, 10), F(9, 10)],
                F(1, 2))


def far_point():
    return Cell("FAR", (0, 1, 5, 10),
                [F(45, 100), F(1, 10), F(0), F(45, 100)],
                [F(0), F(2, 10), F(8, 10), F(0)], F(1, 2))


def cells():
    """The table's five, in the order of their streams."""
    return (two_point(), depth(5, 5), depth(12, 3), depth(2, 8),
            depth(5, 12))


# ------------------------------------------------------------ the tool

def fit(s1, s2, N):
    """The fitted mean and maximum-likelihood variance, from the sum of
    N scores and the sum of their squares."""
    return s1 / N, (N * s2 - s1 * s1) / (N * N)


def logpdf(o, mu, var):
    """Gaussian log density; a zero variance is the point mass."""
    with np.errstate(divide="ignore", invalid="ignore"):
        g = -(o - mu) ** 2 / (2 * var) - 0.5 * np.log(2 * pi * var)
    at = np.isclose(o, mu)
    return np.where(var > 0, g, np.where(at, np.inf, -np.inf))


def combine(l1, l0):
    """1/(1 + e^(l0 - l1)); two point masses both on the score, or both
    off it, state 1/2."""
    tie = (l1 == l0) & np.isinf(l1)
    with np.errstate(invalid="ignore", over="ignore"):
        p = 1.0 / (1.0 + np.exp(l0 - l1))
    return np.where(tie, 0.5, p)


def stated(mu1, v1, mu0, v0, o):
    """U-LiRA's p_member at scores o (broadcast over leading axes)."""
    mu1, v1, mu0, v0 = (np.asarray(t, dtype=float)[..., None]
                        for t in (mu1, v1, mu0, v0))
    return combine(logpdf(o, mu1, v1), logpdf(o, mu0, v0))


def extreme(cell, p):
    """Where p is past tau on tau's side of 1/2, a score at a time; never
    at a score with no mass or with tau = 1/2, and a p within TOL of
    tau is at tau."""
    out = np.zeros(np.shape(p), dtype=bool)
    for i in cell.live():
        tau = float(cell.tau[i])
        if tau > 0.5:
            out[..., i] = p[..., i] > tau + TOL
        elif tau < 0.5:
            out[..., i] = p[..., i] < tau - TOL
    return out


def score(cell, p):
    """ACC, ECE and OVER of stated probabilities p over the support."""
    acc, ece, over = 0.0, 0.0, 0.0
    more = extreme(cell, p)
    for i in cell.live():
        pm, pn, pu, tau = (float(cell.Pm[i]), float(cell.Pn[i]),
                           float(cell.Pu[i]), float(cell.tau[i]))
        acc = acc + np.where(p[..., i] > 0.5, pm, pn) / 2
        ece = ece + pu * np.abs(p[..., i] - tau)
        over = over + pu * more[..., i]
    return acc, ece, over


def limits(cell):
    """At p_lim: ECE, the over-confident mass, the least |p_lim - tau|
    over the live scores, and the call's accuracy."""
    acc, ece, over = score(cell, cell.plim)
    gap = min(abs(float(cell.plim[i]) - float(cell.tau[i]))
              for i in cell.live())
    return float(ece), float(over), gap, float(acc)


def off_side(cell, i):
    """Whether the limit call at score i leaves tau's side."""
    return bool(cell.plim[i] > 0.5) != (cell.tau[i] > F(1, 2))


def cost(cell, i):
    return abs(cell.Pm[i] - cell.Pn[i]) / 2


def flat_form(cell, N):
    """(D): the chance that either class's N scores coincide."""
    return 1 - prod(1 - sum(p ** N for p in P) for P in (cell.Pm, cell.Pn))


# ---------------------------------------------------------- the census

def census_cell(a, b):
    """One depth cell: its limit loss, its scores at a tie, its live
    scores, the least |p_lim - 1/2| off a tie, and the scores where the
    limit call leaves tau's side."""
    c = depth(a, b)
    loss, ties, margin, off = F(0), 0, 1.0, []
    for i in c.live():
        if c.tau[i] == F(1, 2):
            ties += 1
            continue
        margin = min(margin, abs(float(c.plim[i]) - 0.5))
        if off_side(c, i):
            loss += cost(c, i)
            off.append(i)
    return dict(loss=loss, ties=ties, live=len(c.live()), margin=margin,
                off=off)


def census(lo, hi):
    """Every cell lo <= a, b <= hi: the cells, the live scores, the ties,
    the cells with an exception, the largest loss and the cells it sits
    at, the least margin, the pairs a < b whose two cells lose the
    same at mirrored scores, those pairs, and the diagonal cells with
    no exception."""
    rows = {(a, b): census_cell(a, b)
            for a in range(lo, hi + 1) for b in range(lo, hi + 1)}
    worst = max(r["loss"] for r in rows.values())
    pairs = [k for k in rows if k[0] < k[1]]
    return dict(cells=len(rows), live=sum(r["live"] for r in rows.values()),
                ties=sum(r["ties"] for r in rows.values()),
                bad=[k for k, r in rows.items() if r["loss"]],
                worst=worst,
                at=[k for k, r in rows.items() if r["loss"] == worst],
                margin=min(r["margin"] for r in rows.values()),
                mirror=sum((rows[b, a]["loss"], rows[b, a]["off"])
                           == (rows[a, b]["loss"],
                               sorted(3 - i for i in rows[a, b]["off"]))
                           for a, b in pairs),
                pairs=len(pairs),
                diagonal=sum(not rows[a, a]["loss"]
                             for a in range(lo, hi + 1)))


# ------------------------------------------------------------- the law

@lru_cache(maxsize=None)
def compositions(N, k):
    """Every way to write N as k >= 2 counts in order, a row each."""
    grids = np.meshgrid(*[np.arange(N + 1, dtype=np.int16)] * (k - 1),
                        indexing="ij")
    rest = np.stack([g.ravel() for g in grids], axis=1)
    rest = rest[rest.sum(1, dtype=np.int64) <= N].astype(np.int64)
    return np.column_stack([N - rest.sum(1), rest])


def atoms(pts, P, N, drop):
    """The fits a class's N scores can give: the mean, the variance and
    the weight of each (sum, sum of squares), heaviest first, the
    lightest left out while they weigh under drop together; and what
    was left out."""
    held = [(x, float(p)) for x, p in zip(pts, P) if p > 0]
    x = np.array([x for x, _ in held])
    n = compositions(N, len(held))
    logw = (LOGFACT[N] - LOGFACT[n].sum(1)
            + n @ np.log([p for _, p in held]))
    side = N * int(x.max()) ** 2 + 1
    key, inv = np.unique((n @ x) * side + n @ (x * x), return_inverse=True)
    w = np.bincount(inv, weights=np.exp(logw))
    order = np.argsort(-w, kind="stable")
    key, w = key[order], w[order]
    tail = np.cumsum(w[::-1])[::-1]
    keep = tail >= drop
    mean, var = fit(key[keep] // side, key[keep] % side, N)
    return mean, var, w[keep], float(w[~keep].sum())


def law(cell, N, drop=DROP):
    """(L): over the pairs of kept atoms, the mean and variance of ACC,
    ECE, OVER and FLAT, the mean and variance of the stated p at each
    score, the mass left out a class, and each class's whole weight."""
    m1, v1, w1, d1 = atoms(cell.pts, cell.Pm, N, drop)
    m0, v0, w0, d0 = atoms(cell.pts, cell.Pn, N, drop)
    l1 = logpdf(cell.xs, m1[:, None], v1[:, None])
    l0 = logpdf(cell.xs, m0[:, None], v0[:, None])
    ref = score(cell, cell.plim)
    tot, sq = np.zeros(3), np.zeros(3)
    pm, pq = np.zeros(len(cell.pts)), np.zeros(len(cell.pts))
    step = max(1, SLAB // len(w0))
    for s in range(0, len(w1), step):
        p = combine(l1[s:s + step, None, :], l0[None, :, :])
        ww = w1[s:s + step, None] * w0[None, :]
        for j, col in enumerate(score(cell, p)):
            tot[j] += (ww * col).sum()
            sq[j] += (ww * (col - ref[j]) ** 2).sum()
        pm += np.tensordot(ww, p, 2)
        pq += np.tensordot(ww, (p - cell.plim) ** 2, 2)
    mass = float(w1.sum() * w0.sum())
    mean = tot / mass
    var = sq / mass - (mean - np.array(ref, dtype=float)) ** 2
    pmean = pm / mass
    flat = 1 - float(w1[v1 > 0].sum() * w0[v0 > 0].sum()) / mass
    out = {k: (float(m), float(v))
           for k, m, v in zip(("acc", "ece", "over"), mean, var)}
    out.update(flat=(flat, flat * (1 - flat)),
               p=(pmean, pq / mass - (pmean - cell.plim) ** 2),
               dropped=(d1, d0),
               whole=(float(w1.sum()) + d1, float(w0.sum()) + d0))
    return out


def samples(pts, P, N):
    """Every string of N scores a class can give, with its weight."""
    held = [(x, p) for x, p in zip(pts, P) if p > 0]
    seqs = list(product(range(len(held)), repeat=N))
    return (np.array([[held[i][0] for i in s] for s in seqs], dtype=float),
            [prod(held[i][1] for i in s) for s in seqs])


def enumerated(cell, N):
    """Every pair of samples of N scores a class through fit(), stated()
    and score(): the means and the variances of ACC, ECE and OVER, the
    chance of a degenerate fit (a Fraction), the mean and the variance
    of the stated p, and the pairs."""
    (sm, wm), (sn, wn) = (samples(cell.pts, P, N) for P in (cell.Pm, cell.Pn))
    (m1, v1), (m0, v0) = (fit(s.sum(1), (s * s).sum(1), N) for s in (sm, sn))
    p = stated(m1[:, None], v1[:, None], m0[None, :], v0[None, :], cell.xs)
    ww = (np.array([float(w) for w in wm])[:, None]
          * np.array([float(w) for w in wn])[None, :])
    cols = score(cell, p)
    means = [float((ww * c).sum()) for c in cols]
    spread = [float((ww * (c - m) ** 2).sum()) for c, m in zip(cols, means)]
    flat = 1 - (sum(w for w, v in zip(wm, v1) if v > 0)
                * sum(w for w, v in zip(wn, v0) if v > 0))
    pmean = np.tensordot(ww, p, 2)
    return (means, spread, flat, pmean, np.tensordot(ww, (p - pmean) ** 2, 2),
            ww.size)


# ------------------------------------------------------------ the rows

def draw(cell, ci, N, seed):
    """R replicates of N member and N non-member shadow scores."""
    rng = np.random.default_rng([seed, ci, N])
    pm = np.array([float(x) for x in cell.Pm])
    pn = np.array([float(x) for x in cell.Pn])
    sm = rng.choice(cell.xs, size=(R, N), p=pm / pm.sum())
    sn = rng.choice(cell.xs, size=(R, N), p=pn / pn.sum())
    return sm, sn


def row(cell, ci, N, seeds):
    """One (cell, N) over the seeds given: the replicates; the means of
    ACC, ECE and OVER; the replicates with a degenerate fit and those
    at the ceiling; the mean stated p and the replicates stating p
    more extreme than tau, a score at a time."""
    sm, sn = (np.concatenate(t)
              for t in zip(*[draw(cell, ci, N, s) for s in seeds]))
    (m1, v1), (m0, v0) = (fit(s.sum(1), (s * s).sum(1), N) for s in (sm, sn))
    p = stated(m1, v1, m0, v0, cell.xs)
    acc, ece, over = score(cell, p)
    return dict(n=len(p), acc=float(acc.mean()), ece=float(ece.mean()),
                over=float(over.mean()),
                flat=int(((v1 == 0) | (v0 == 0)).sum()),
                top=int((acc >= float(cell.ceiling) - TOL).sum()),
                p=p.mean(0), more=extreme(cell, p).sum(0))


def z_of(x, mean, var, n):
    """A mean of n draws against a law, in the law's standard errors, a
    variance under 1e-18 read as 1e-18."""
    return (x - mean) / sqrt(max(var, 1e-18) / n)


def distances(cell, rec, lw):
    """A row's reads of its law: ACC, ECE, OVER, FLAT, and the mean
    stated p at each live score."""
    n = rec["n"]
    zs = [z_of(rec[k], *lw[k], n) for k in ("acc", "ece", "over")]
    zs.append(z_of(rec["flat"] / n, *lw["flat"], n))
    zs.extend(z_of(rec["p"][i], lw["p"][0][i], lw["p"][1][i], n)
              for i in cell.live())
    return zs


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


def law_sweep(world):
    """The law at every (cell, N) that has one: S at each N, a depth
    cell to N = 128."""
    return {(ci, N): law(c, N) for ci, c in enumerate(world, start=1)
            for N in (NS if ci == 1 else LAW_NS)}


def tool_sweep(world, seeds):
    return {(ci, N): row(c, ci, N, seeds)
            for ci, c in enumerate(world, start=1) for N in NS}


def far_sweep(world, laws, seeds):
    """The law's rows at further seeds pooled: the reads, those inside
    4, and the worst."""
    zs = [z for (ci, N), lw in laws.items()
          for z in distances(world[ci - 1],
                             row(world[ci - 1], ci, N, seeds), lw)]
    return len(zs), within(zs), max(abs(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(world):
    section("CONTROLS")
    S, W1, W2, W3, W5 = world
    print(f"  W(12,3): tau = {[str(x) for x in W2.tau]}, ceiling "
          f"{W2.ceiling}, p_lim = {np.round(W2.plim, 4).tolist()}")
    print(f"  S: tau(0) = {S.tau[0]}, p_lim(0) = {float(S.plim[0]):.6f}")
    check("(12, 3) by hand: tau, the ceiling, the moments and p_lim",
          W2.tau == [F(1), F(11, 15), F(5, 9), F(3, 7)]
          and W2.ceiling == F(419, 728)
          and near(W2.mom_m + W2.mom_n,
                   (33 / 14, 0.427394, 18 / 7, 0.310832), (9, 6, 9, 6))
          and near(W2.plim, (0.9816, 0.8400, 0.5540, 0.4141), (4,) * 4))
    check("(5, 5) by hand: tau, the audited mass, the ceiling and p_lim",
          W1.tau == [F(5 - c, 7) for c in range(4)]
          and W1.Pu == [F(1, 12), F(5, 12), F(5, 12), F(1, 12)]
          and W1.ceiling == F(25, 42)
          and near(W1.plim, (0.710950, 0.574443, 0.425557, 0.289050),
                   (6,) * 4))
    check("(5, 12) by hand: the class masses, tau, the audited mass and "
          "p_lim at score 1, an exception costing 11/1120",
          W5.Pm == [F(x, 560) for x in (220, 264, 72, 4)]
          and W5.Pn == [F(x, 560) for x in (165, 275, 110, 10)]
          and (W5.tau[1], W5.Pu[1], W5.ceiling)
          == (F(24, 49), F(33, 68), F(123, 224))
          and near(W5.mom_m + W5.mom_n, (0.75, 0.4875, 0.9375, 0.558594),
                   (9, 9, 9, 6))
          and near((float(W5.plim[1]),), (0.501865,), (6,))
          and off_side(W5, 1) and cost(W5, 1) == F(11, 1120)
          and [off_side(W5, i) for i in (0, 2, 3)] == [False] * 3)
    check("S and the far point by hand: p_lim(0) = 1/(1 + e^(-40/9)) "
          "against 9/10; tau(1) = 1/3 against p_lim(1) = 0.6483, an "
          "exception costing 1/20",
          abs(float(S.plim[0]) - 1 / (1 + exp(-40 / 9))) <= TOL
          and S.tau == [F(9, 10), F(1, 10)]
          and near(S.mom_m + S.mom_n, (0.3, 0.81, 2.7, 0.81), (9,) * 4)
          and far_row() == (F(1, 3), True, F(1, 20))
          and near(far_point().mom_m + far_point().mom_n,
                   (4.6, 23.94, 4.2, 2.56), (9,) * 4)
          and near((float(far_point().plim[1]),), (0.6483,), (4,)))
    g = stated(0.0, 1.0, 3.0, 4.0, np.array([0.0, 3.0]))
    check("stated() at a Gaussian pair's own moments is its posterior on "
          "two hand points; point masses state 1, 0 and 1/2",
          near(g, (0.860344, 0.021735), (6, 6))
          and stated(0.0, 0.0, 3.0, 0.0, np.array([0.0, 3.0, 1.0])).tolist()
          == [1.0, 0.0, 0.5]
          and stated(3.0, 0.0, 3.0, 0.0, np.array([3.0, 0.0])).tolist()
          == [0.5, 0.5]
          and stated(1.5, 2.25, 0.0, 0.0, np.array([0.0, 3.0])).tolist()
          == [0.0, 1.0]
          and stated(1.5, 2.25, 1.5, 2.25, np.array([0.0])).tolist() == [0.5])
    check("the fit from two sums on three hand samples",
          fit(3, 9, 2) == (1.5, 2.25) and fit(6, 18, 2) == (3.0, 0.0)
          and fit(4, 6, 4) == (1.0, 0.5))
    hand = (((1.0, 0.0), (0.9, 0.1, 1.0)), ((0.5, 0.5), (0.5, 0.4, 0.0)),
            ((0.95, 0.2), (0.9, 0.075, 0.5)), ((0.9, 0.1), (0.9, 0.0, 0.0)),
            ((0.4, 0.6), (0.1, 0.5, 0.0)))
    half = [float(v) for v in score(W1, np.array([0.8, 0.5, 0.3, 0.2]))]
    W24 = depth(2, 4)
    tied = [float(v) for p in ((0.9, 0.9, 0.1, 0.7), (0.9, 0.2, 0.1, 0.7))
            for v in score(W24, np.array(p))]
    check("score() on five hand rows at S, one exactly at tau; at (5, 5) "
          "with a score stated exactly 1/2; at (2, 4), by hand, with a "
          "score at tau = 1/2, stated above 1/2 and below, and one of "
          "no mass: ACC, ECE and OVER",
          sum(near([float(v) for v in score(S, np.array(p))], want, (9,) * 3)
              for p, want in hand) == 5
          and near(half, (15 / 28, 41 / 420, 7 / 12), (9,) * 3)
          and W24.tau == [F(4, 5), F(1, 2), F(0), None]
          and W24.Pu == [F(1, 5), F(3, 5), F(1, 5), F(0)]
          and near(tied, (13 / 20, 7 / 25, 1 / 5, 13 / 20, 11 / 50, 1 / 5),
                   (9,) * 6))
    at_tau = stated(9 / 8, 47 / 64, 43 / 32, 423 / 1024, W1.xs)
    edge = [extreme(S, np.array(p)).tolist() for p in
            ((0.9 + 1e-13, 0.1 - 1e-13), (0.9 + 1e-9, 0.1 - 1e-9))]
    check("a stated p exactly at tau is not past it: at (5, 5) the fits "
          "(9/8, 47/64) and (43/32, 423/1024) state 3/7 at score 2, by "
          "hand",
          abs(float(at_tau[2]) - 3 / 7) <= TOL
          and not extreme(W1, at_tau)[2])
    check("at S a p within 1e-13 of tau is at it and one 1e-9 past it is "
          "past, on each side of 1/2",
          edge == [[False, False], [True, True]])
    check("the limits by hand: ECE_lim, the over-confident mass, the "
          "least gap and the call's accuracy at (5, 5) and S; the last "
          "three at (5, 12)",
          near(limits(W1), (0.003068, 5 / 6, 0.003014, 25 / 42),
               (6, 9, 6, 9))
          and near(limits(S), (0.088393, 1.0, 0.088393, 0.9), (6, 9, 6, 9))
          and near(limits(W5)[1:], (13 / 68, 0.002408, 151 / 280),
                   (9, 6, 9)))
    mean, var, w, left = atoms(range(4), W1.Pm, 4, DROP)
    at = [i for i in range(len(w)) if (mean[i], var[i]) == (1.5, 0.75)]
    s_atoms = atoms((0, 3), S.Pm, 2, DROP)
    check("the atoms of a class: 34 from 35 count vectors at N = 4, the "
          "shared one's weight, nothing left out; and S's three at N = 2",
          (len(compositions(4, 4)), len(w), len(at), left)
          == (35, 34, 1, 0.0)
          and abs(w[at[0]] - 2104000 / 84 ** 4) <= TOL
          and abs(w.sum() - 1) <= TOL
          and [t.tolist() for t in s_atoms[:2]]
          == [[0.0, 1.5, 3.0], [0.0, 2.25, 0.0]]
          and near(s_atoms[2], (0.81, 0.18, 0.01), (11,) * 3))
    lw = law(S, 2)
    check("the law at S, N = 2, by hand: ACC 0.8776 with variance "
          "0.00964224, ECE 0.11754, OVER 0.9477, FLAT 0.9676 with "
          "variance 0.03135024, mean p (0.972, 0.028) with variance "
          "0.015066 at each",
          near((lw["acc"][0], lw["acc"][1], lw["ece"][0], lw["over"][0],
                *lw["flat"], *lw["p"][0], *lw["p"][1]),
               (0.8776, 0.00964224, 0.11754, 0.9477, 0.9676, 0.03135024,
                0.972, 0.028, 0.015066, 0.015066), (11,) * 10))
    check("a degenerate fit's chance in closed form by hand at (2, 8) "
          "and S, N = 8, and the law's FLAT there",
          flat_form(W3, 8) == 1 - F(6304, 6561) * F(427911454, 429981696)
          and flat_form(S, 8) == 1 - (1 - F(9, 10) ** 8 - F(1, 10) ** 8) ** 2
          and near((float(flat_form(W3, 8)), float(flat_form(S, 8))),
                   (0.043797, 0.675632), (6, 6))
          and abs(law(W3, 8)["flat"][0] - float(flat_form(W3, 8))) <= TOL
          and abs(law(S, 8)["flat"][0] - float(flat_form(S, 8))) <= TOL)
    agree, sizes = 0, []
    for c in (W2, S):
        means, spread, flat, pmean, pvar, size = enumerated(c, 4)
        lw = law(c, 4, 0.0)
        sizes.append(size)
        agree += (all(abs(lw[k][0] - m) <= TOL and abs(lw[k][1] - v) <= TOL
                      for k, m, v in zip(("acc", "ece", "over"), means,
                                         spread, strict=True))
                  and flat == flat_form(c, 4)
                  and abs(lw["flat"][0] - float(flat)) <= TOL
                  and float(np.abs(lw["p"][0] - pmean).max()) <= TOL
                  and float(np.abs(lw["p"][1] - pvar).max()) <= TOL
                  and lw["dropped"] == (0.0, 0.0))
    check("every pair of samples of 4 scores a class through the fit, "
          "stated() and score(), 20,736 pairs on (12, 3) and 256 on S: "
          "the law's means and variances, and FLAT's closed form",
          agree == 2 and sizes == [20736, 256])
    check("a distance in the law's standard errors on three hand rows, "
          "two of a column held fixed; of four distances two are inside 4",
          abs(z_of(0.51, 0.5, 0.04, 400) - 1) <= 1e-9
          and z_of(0.9, 0.9, 0.0, 400) == 0
          and abs(z_of(0.9 + 1e-6, 0.9, 0.0, 400) - 2e4) <= 1e-3
          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])
    rows = [census_cell(*k) for k in ((5, 12), (2, 2), (2, 4), (12, 3))]
    check("a census row by hand at (5, 12), (2, 2), (2, 4) and (12, 3): "
          "the loss, the ties, the live scores and the exceptions",
          [(r["loss"], r["ties"], r["live"], r["off"]) for r in rows]
          == [(F(11, 1120), 0, 4, [1]), (F(0), 0, 2, []), (F(0), 1, 3, []),
              (F(0), 0, 4, [])])
    return all(CHECKS)


def far_row():
    """The far point at score 1: tau, whether the limit call leaves its
    side, and the cost."""
    c = far_point()
    return c.tau[1], off_side(c, 1), cost(c, 1)


def section_census():
    section("THE CENSUS: does the limit call keep tau's side? "
            "2 <= a, b <= 30")
    r = census(2, 30)
    print(f"  {len(r['bad'])} of {r['cells']} cells have an exception; "
          f"{r['ties']} of {r['live']} live scores at a tie tau = 1/2 set "
          f"aside; least |p_lim - 1/2| off a tie {r['margin']:.2e}")
    for a, b in r["at"]:
        c = depth(a, b)
        for i in census_cell(a, b)["off"]:
            print(f"  the largest limit loss {r['worst']} = "
                  f"{float(r['worst']):.4f}: W({a},{b}) at score {i}, tau "
                  f"{c.tau[i]} = {float(c.tau[i]):.4f}, p_lim "
                  f"{float(c.plim[i]):.4f}")
    print("  cells with an exception: " + ", ".join(
        f"({a},{b})" for a, b in r["bad"][:40])
        + (" ..." if len(r["bad"]) > 40 else ""))
    check("the census's sizes by hand: 841 cells, 3306 live scores, 28 "
          "at a tie", (r["cells"], r["live"], r["ties"]) == (841, 3306, 28))
    check("90 cells with an exception, as the first engine printed",
          len(r["bad"]) == 90)
    check("the largest loss is 11/1120, at (5, 12) and (12, 5) alone",
          r["worst"] == F(11, 1120) and r["at"] == [(5, 12), (12, 5)])
    check("the mirror: equal losses at mirrored scores at the 406 pairs "
          "a < b, and no exception on the 29 diagonal cells",
          (r["mirror"], r["pairs"], r["diagonal"]) == (406, 406, 29))
    check("the least |p_lim - 1/2| off a tie as recorded, 6.46e-05",
          abs(r["margin"] - 6.46e-05) < 0.005e-05)
    tau1, _, c1 = far_row()
    print(f"  off the depth column, a far support point: tau(1) = {tau1}, "
          f"p_lim(1) = {float(far_point().plim[1]):.4f}, exception cost {c1}")


def section_law(world, laws):
    section("THE LAW: each column's exact mean over every pair of fits")
    rows = 0
    for ci, c in enumerate(world, start=1):
        ns = [N for (cj, N) in laws if cj == ci]
        print(f"  == {c.name}: ECE_lim {limits(c)[0]:.6f}")
        print("       N       ACC       ECE      OVER      FLAT")
        for N, pin in zip(ns, LAW_PINS[c.name], strict=True):
            lw = laws[ci, N]
            rec = tuple(lw[k][0] for k in ("acc", "ece", "over", "flat"))
            rows += near(rec, pin, (6,) * 4)
            print(f"     {N:4d}  " + "  ".join(f"{x:.6f}" for x in rec))
        top = laws[ci, ns[-1]]["p"][0]
        rows += near([top[i] for i in c.live()], MEAN_PINS[c.name],
                     (6,) * len(c.live()))
        print(f"     mean p at N = {ns[-1]}: "
              + "  ".join(f"{top[i]:.6f}" for i in c.live())
              + "  against p_lim "
              + "  ".join(f"{float(c.plim[i]):.4f}" for i in c.live()))
    check("the law's 16 rows and its five cells' mean stated p as "
          "recorded", rows == 21 and len(laws) == 16)
    check("each class's atoms weigh 1 to 1e-12 before any is left out, "
          "at each of the 16 rows",
          sum(max(abs(x - 1) for x in lw["whole"]) <= TOL
              for lw in laws.values()) == 16)


def section_tool(world, laws, recs):
    section(f"THE TOOL: R = {R} replicates per shadow count, scored "
            f"exactly; seed {SEED}")
    rows, scores, zs = 0, 0, []
    for ci, c in enumerate(world, start=1):
        lim = limits(c)
        rows += near(lim[:3], LIMIT_PINS[c.name], (4, 3, 4))
        print(f"  == {c.name}: ceiling {c.ceiling} = {float(c.ceiling):.4f}, "
              f"ECE_lim {lim[0]:.4f}, over-confident mass {lim[1]:.3f}, "
              f"least gap {lim[2]:.4f}")
        print("       N      ACC      ECE   OVER  FLAT  TOP  worst distance")
        for N, pin in zip(NS, TABLE_PINS[c.name], strict=True):
            r = recs[ci, N]
            z = distances(c, r, laws[ci, N]) if (ci, N) in laws else []
            zs.extend(z)
            worst = max(abs(x) for x in z) if z else None
            rec = (r["acc"], r["ece"], r["over"], r["flat"], r["top"])
            rows += (near(rec, pin[:5], (4, 4, 3, 0, 0))
                     and (worst is None) == (pin[5] is None)
                     and (worst is None or near((worst,), pin[5:], (2,))))
            print(f"     {N:4d}   {r['acc']:.4f}   {r['ece']:.4f}  "
                  f"{r['over']:.3f}   {r['flat']:3d}  {r['top']:3d}  "
                  + ("" if worst is None else f"{worst:.2f}"))
        r = recs[ci, NS[-1]]
        live = c.live()
        scores += (near([r["p"][i] for i in live], SCORE_PINS[c.name][0],
                        (4,) * len(live))
                   and [int(r["more"][i]) for i in live]
                   == list(SCORE_PINS[c.name][1]))
        print(f"     score  P_u     tau     p_lim   mean p at N = {NS[-1]}, "
              f"replicates more extreme than tau")
        for i in live:
            print(f"       {c.xs[i]:.0f}   {float(c.Pu[i]):.3f}  "
                  f"{float(c.tau[i]):.4f}  {float(c.plim[i]):.4f}  "
                  f"{r['p'][i]:.4f}  {int(r['more'][i]):3d}")
    check("the limits and the table's 20 rows as recorded", rows == 25)
    check("the mean stated p and the replicates more extreme than tau at "
          "N = 512 as recorded, at the five cells", scores == 5)
    check("each seeded mean with a law inside 4 of the law's standard "
          "errors: 117 reads", (len(zs), within(zs)) == (117, 117))


def section_far(world, laws, seeds):
    section(f"FURTHER SEEDS: {len(seeds)} from {seeds[0]}, pooled, the "
            f"law's rows")
    reads, inside, worst = far_sweep(world, laws, seeds)
    print(f"  {inside} of {reads} reads inside 4, the worst {worst:.2f}")
    check("at further seeds each mean with a law inside 4 of its "
          "standard errors: 117 reads", (reads, inside) == (117, 117))
    if seeds == FAR_SEEDS:
        check("the further seeds' worst read as recorded",
              near((worst,), (FAR_PIN,), (2,)))


def main():
    t0 = time.time()
    seeds = FAR_SEEDS
    if "--seeds" in sys.argv:
        i = sys.argv.index("--seeds")
        base, count = int(sys.argv[i + 1]), int(sys.argv[i + 2])
        seeds = tuple(range(base, base + count))
    world = cells()
    if not section_controls(world):
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    section_census()
    laws = law_sweep(world)
    section_law(world, laws)
    section_tool(world, laws, tool_sweep(world, (SEED,)))
    section_far(world, laws, seeds)
    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()