estimators.py

Checks: RULER: The knife: a consistent point inside an inconsistent interval property; known; theorem; rule; RULER: More data, a worse held-out interval property; observation; RULER: One bound at two statistics theorem; RULER: The spanning tree is not identified property; known.

Cited on: RULER.

To run it: save estimators.py; standard library only.

"""estimators.py -- standard Bayes-error estimators scored against an
exact Bayes error, on the threshold family of ceiling.py.

QUESTION. ceiling.py derives the Bayes error of [x >= t] read through
x mod M as a Fraction. That makes the family a RULER: any estimator of
the Bayes error can be scored on its BIAS against the truth and on the
COVERAGE of the 95% interval it states for itself, the fraction of
trials whose interval contains the truth. Where do the textbook
estimators fail, is the failure the ring's or the estimator's, and
what do the distribution-free brackets actually certify?

THE ESTIMATORS. A sample is n pairs (bin r, label y).
  RESUBSTITUTION  (1/n) sum_r min(n_r0, n_r1).
  HELD-OUT        fit the majority label per bin on a fair-coin half
                  (an empty or tied bin guesses 1), score its 0-1
                  error on the other half.
  1-NN            the nearest-neighbour error R_NN; on a categorical
                  channel with every training bin populated, a test
                  point's neighbours are its own bin, so R_NN is the
                  rate at which a random same-bin training label
                  disagrees.
  COVER-HART      the bracket [(1 - sqrt(1 - 2 R_NN))/2, R_NN].
  DIVERGENCE      the Friedman-Rafsky count W of cross-label edges of a
                  minimum spanning tree of the pooled sample, u =
                  1 - 2W/n, and the bracket [(1 - sqrt u)/2, (1 - u)/2]
                  of Berisha, Wisler, Hero and Spanias (IEEE Trans.
                  Signal Process. 2016, Theorem 2, whose D~_p is u).
Resubstitution and held-out state the binomial bar
1.96 sqrt(p(1 - p)/m) on the m points the rate is computed from; they
are sampled. The two brackets are read at their population values, in
exact rationals, and the tree's count on samples.

THE ARGUMENT.
  (A) THE RING IS A MIXTURE OF BERNOULLIS (property). Drawing x
      uniform on Z/N and reading (x mod M, [x >= t]) draws r uniform
      and y ~ Bernoulli(eta_r), eta_r the share of fiber r at or above
      t. So whatever an estimator does on the ring it does on bare
      Bernoulli bins with those eta_r; the ring supplies the placement,
      eta_r = 1/2 exactly at a knife slice (c = N/M even, t = N/2),
      with the truth in exact rational arithmetic.
  (B) THE KNIFE'S DEFICIT IS EXACT. min(B, m - B) = m/2 - |B - m/2|,
      and for B ~ Bin(m, 1/2) the mean absolute deviation is
      MAD(m) = nu C(m, nu)/2^m at nu = floor(m/2) + 1 (de Moivre; P.
      Diaconis and S. Zabell, Statist. Sci. 6 (1991) 284-302). A bin's
      count is m ~ Bin(n, 1/M), so at eta_r = 1/2 on every bin
          E[resubstitution] = 1/2 - (M/n) E[MAD(m)]
      at every n and M. MAD(m) is sqrt(m/(2 pi)) (1 -+ 1/(4m)), the
      sign by m's parity, and E sqrt(m) ~ sqrt(mu) (1 - (1 - 1/M)/(8 mu))
      at mu = n/M, so the deficit over the half-bar at 1/2,
      1.96/(2 sqrt n), is
          sqrt(2M/pi)/1.96 (1 - (M - 1)/(8n) + ...):
      free of n in the limit (1.5766 at M = 15) and already within
      0.4% of it at n = 500. Both are 1/sqrt n: the point estimate
      is consistent, its interval's bias a fixed share of its bar.
      The variance of one sample's minority labels sum_r min is
      n/4 - M E[MAD(m)^2] + Var(sum_r MAD(n_r)); MAD is nondecreasing
      (MAD(2k - 1) = MAD(2k) < MAD(2k + 1)) and multinomial counts are
      negatively associated (K. Joag-Dev and F. Proschan, Ann. Statist.
      11 (1983) 286-295), so the last term lies in [0, M Var(MAD(m))]
      and the variance in [n/4 - M E[MAD(m)^2], n/4 - M (E MAD(m))^2],
      whose width tends to (M - 1)/(8 pi), 0.56 at M = 15, under a
      variance near n (1 - 2/pi)/4. A distance below uses the upper
      end, so it is no larger in size than the true one.
  (C) THE TRANSIENT'S BIAS IS EXACT. Held-out scores a fitted RULE.
      Given the training half and a test half that is not empty (an
      empty one, probability 2^-n, has no estimate), each test point is
      a fresh draw, so the
      estimate's mean is the rule's risk, R* + sum_r P(r) |2 eta_r - 1|
      [bin r flipped]. At eta = 6/11 on every bin a bin is flipped when
      its training labels hold strictly more zeros, its training
      points K ~ Bin(n, 1/(2M)) and its ones Bin(K, 6/11):
          E[held-out] - R* = P(flip)/11,
          P(flip) = sum_K Bin(n, 1/(2M))(K) P(Bin(K, 6/11) < K/2),
      the flip's probability given a test half, which this sum gives to
      within 2^-n.
      At |eta - 1/2| = delta that decays like exp(-delta^2 n_r) only
      once n_r passes 1/delta^2, while the bar decays as 1/sqrt n from
      the start. So coverage FALLS with n until n_r ~ 1/delta^2 and
      recovers after: at M = 105, eta = 6/11, 1/delta^2 = 484 per bin,
      n ~ 50,000. The flipped bins of a sample are an integer; their
      spread is read as M independent bins' (a normal reading: the
      bins' counts are multinomial, and where the law expects under
      one flip the distance says only whether one occurred). Given its
      rule the estimate is a binomial rate on the test half, so a
      row's bias less its flipped bins' share is the test half's
      noise, read in units of sqrt(risk (1 - risk)/(n/2)/40).
  (D) ONE BOUND AT TWO STATISTICS. (2 eta - 1)^2 = 1 - 4 eta (1 - eta)
      bin by bin, so with u = E[(2 eta - 1)^2] the upper end (1 - u)/2
      is E[2 eta (1 - eta)] identically. R_NN has that mean at every n:
      given the training half's size in each bin, every one
      populated, and a test half that is not empty, a test point lies
      in each bin at 1/M and in
      bin r errs at (1 - eta_r) tb/tr + eta_r ta/tr (ta zeros and tb
      ones of tr = ta + tb training points), and E[tb/tr] = eta_r. And
      W/n under a tree blind to the labels tends to the same quantity
      (F). So the Cover-Hart and divergence brackets are one bound read
      through two statistics. R* = 1/2 - E|2 eta - 1|/2, so the lower
      end's gap is (sqrt E(2 eta - 1)^2 - E|2 eta - 1|)/2: zero iff
      |2 eta_r - 1| is constant over r, iff M | t or (c odd and
      floor(t/M) = (c - 1)/2), the odd-c middle range of ceiling.py.
  (E) THE RANGE LAW. On the range, c = 2m + 1 and M not dividing t,
      every fiber holds m or m + 1 ones, so |2 eta_r - 1| = 1/c: the
      lower end is R* = m/c, the upper (1 - 1/c^2)/2 = 1/2 - 1/(2c^2).
      The no-evidence value min(t, N - t)/N is above R* there (t and
      N - t both exceed M m), and above the upper end iff
      |2t - N| c < M (never with equality, c being prime to M): the
      exact bracket certifies a lift at about M/c of the range's M - 1
      thresholds, none where M < c and N is odd. At N = 105, M = 15
      the range is
      t = 46..59, the bracket [3/7, 24/49], and the no-evidence value
      lies outside only at t = 52, 53.
  (F) THE MST IS NOT IDENTIFIED. Two points of one bin sit at distance
      0, so any spanning tree of a bin's clique is part of a minimum
      spanning tree, every one genuine, and the source's estimator
      assumes a unique tree. A class-ordered chain puts one cross edge
      in each two-label bin, so W <= M within bins and the bracket
      collapses to [0, 0]; a spanning tree of the bipartite graph
      between a bin's
      two label classes makes all n_r - 1 edges cross, W = n - M where
      every bin holds both labels, u -> -1, the bracket at [1/2, 1/2]
      after clipping. A tree whose shape ignores the labels has the
      labels exchangeable on its n_r - 1 edges, expected cross count
      2 n_r0 n_r1 / n_r, the population quantity: label-blindness is
      the repair, randomness buys nothing beyond it. For the chain in
      draw order the labels along a bin are independent, so with every
      bin holding two points or more its crossings have mean
      (n - M) 2pq and variance (n - M) 2pq (1 - 2pq) +
      2 (n - 2M) pq (1 - 4pq) at pq = eta (1 - eta) on every bin: a
      crossing at one edge and at the next is the pattern aba,
      probability pq. The edges between bins, at most M - 1, are not
      counted; they move W/n by at most M/n.

BY HAND (before any engine ran; the sums over a binomial evaluated
outside this file).
  slices  (30, 6, 8): c = 5, ones per fiber 3, 3, 4, 4, 4, 4; R* =
          4/15, E[2 eta (1 - eta)] = 28/75, u = 19/75; (1 - 2R*)^2 =
          49/225 against 57/225, not tight. ODD: eta = 4/7, 3/7, 24/49,
          1/49. WIDE: 6/11, 5/11, 60/121, 1/121. KNIFE: 1/2 at each, 0.
          Tight: (105, 15, 45) (M | t), (105, 15, 52) and (30, 6, 14)
          (the range); not (210, 15, 100), where c = 14 is even and
          floor(t/M) = c/2 - 1.
  counts  resubstitution on [[3, 1], [2, 2], [0, 4]]: 3 of 12, bar
          1.96 sqrt((3/16)/12) = 0.245. Training counts [[2, 1],
          [1, 1], [0, 0], [1, 3]] guess 0, 1, 1, 1; on the test counts
          [[3, 1], [2, 2], [1, 4], [0, 5]] wrong 1 + 2 + 1 + 0 = 4 of
          18, bar 1.96 sqrt((2/9)(7/9)/18) = 0.192062. 1-NN at training
          [[1, 3], [4, 1]], test [[2, 1], [1, 3]]:
          (2 (3/4) + 1/4) + (1/5 + 3 (4/5)) = 87/20 over 7 points.
          bar(1/2, 2401) = 0.02, bar(1/10, 3600) = 0.0098.
  (B)     MAD(0..6) = 0, 1/2, 1/2, 3/4, 3/4, 15/16, 15/16. Deficit at
          (n, M) = (2, 1): 1/4. (2, 2): bins (2, 0) or (0, 2) at 1/4
          each give E min = 1/2 and (1, 1) gives 0, so E = 1/8 and the
          deficit 3/8. (4, 2): E[MAD] over Bin(4, 1/2) is (0 + 4/2 +
          6/2 + 3 + 3/4)/16 = 35/64, the deficit 35/128. The ratio's
          expansion at M = 15: 1.57111, 1.57525, 1.57628, 1.57654 at
          n = 500, 2000, 8000, 32,000.
  (C)     P(flip) at (n, M) = (1, 1): K = 1 at 1/2, a zero at 5/11:
          5/22. (2, 1): 5/22 + (1/4)(25/121) = 135/484 (K = 2 with one
          label of each is a tie and guesses 1).
  (E)     the family: 15 products of two primes of 2..13 (sum 652), 18
          of three within 500 (sum 3,386), and 210, 330, 390, 462,
          with 2, 6 and 14 moduli each: 194 cells and 2 (652 - 15) +
          6 (3386 - 18) + 14 (1392 - 4) = 40,914 slices. Tight per
          cell: the c - 1 multiples of M, and at c odd the range's
          M - 1: 7,296. Odd-c cells 131, range slices 2,697, of which
          |2t - N| c < M at 583.
  (F)     chain crossings: [0, 0, 1, 1] 1, [0, 1, 0, 1] 3, [1] 0, [] 0.
          Cells [[0, 1, 1, 0], [1, 1], [0], [], [1, 1, 1], [0, 1]]:
          two two-label bins; the class-ordered chains cross twice, the
          bipartite trees 4 times, the draw-order chains 3. One bin
          of 3 points at 4/7: mean 2 (24/49) = 48/49, variance
          2 (24/49)(25/49) + 2 (12/49)(1/49) = 1224/2401; two such
          bins, twice each. At ODD, n = 8000, 533 points a
          bin at 4/7: every bin holds both labels, W = 15 a sample in
          class order and 7,985 bipartite, 600 and 319,400 over 40.
  control two bins at (1/5, 9/10): while no bin flips each point is a
          minority label at (1/5 + 1/10)/2 = 3/20, so the minority
          labels of n = 8000 are Bin(8000, 3/20), mean 1,200 and
          variance 1,020.

DESIGN. Slices of the threshold family (ceiling.py's notation):
  KNIFE   N = 210,  M = 15,  t = 105, R* = 1/2
  ODD     N = 105,  M = 15,  t = 45,  R* = 3/7
  WIDE    N = 1155, M = 105, t = 525, R* = 5/11
n in {500, 2000, 8000, 32000}, 40 trials, fixed seeds. Ring arms draw
x uniform; bare arms draw per-bin binomial counts. The transient's
bare arm runs on to n = 512,000. The exact legs are over the family's
cells within 500 (N a product of two to four of the primes 2..13, M a
divisor of N other than 1 and N) and every 0 < t < N.
A row is one function of its arguments (knife_row, dial_row,
transient_row, tight_row, range_row, tree_counts) and a sweep collects
or sums rows. CONTROLS, before any sweep and stopping the run if one
fails: each estimator and each exact read on hand rows; property (A)
counted over every x of Z/N through the point map the ring sampler
draws with; the knife's and the flip law on hand rows, against every
split sample of a small world enumerated through the estimators
themselves (split_samples), and against their float forms at
n = 500; held-out's mean and the 1-NN error's over the same samples;
the chain's law against every label string; a positive control of
the coverage count on two benign bins. The samplers and the trial
loop have no hand row: the pinned records hold them and the laws'
distances read them. Each seeded row is then pinned as recorded, an
integer
count a row beside its hits; a row of the knife or of the transient
also with its distance from the exact law in the law's standard
errors, held inside 4 (the dial's rows are records alone; the
control's and the tree's distances are pinned, under no bar); and the
two laws are read again at ten further seeds on the bare arms, at
n = 500 and at 2000 apart (runs at two n from one seed share a
stream);
`--seeds FIRST COUNT` reads them at any others, behind the controls.

PREDICTIONS (fixed before the first engine).
  P0 positive control, two equiprobable bins at eta = (0.2, 0.9),
     R* = 3/20, n = 8000: resubstitution and held-out cover in at
     least 34 of 40 trials with |bias| < 0.01; the Cover-Hart bracket
     excludes the no-evidence 0.45 in at least 34 of 40.
  P1 (B) resubstitution at KNIFE, ring and bare: coverage <= 0.10 at
     every n, the mean deficit over the mean half-bar in
     [-2.0, -1.2] at every n.
  P2 (C) held-out at WIDE, ring and bare: coverage >= 0.70 at n = 500,
     <= 0.35 at n = 32000; the bare arm >= 0.85 at n = 512,000.
  P3 (D) exact: (1 - u)/2 = E[2 eta (1 - eta)] on every slice; the
     lower end equals R* iff s = 0 or t in the odd-c middle range.
     Sampled: |R_NN - E[2 eta (1 - eta)]| < 0.005 at n = 32000 on
     KNIFE, ODD, WIDE.
  P4 (E) the exact bracket contains the no-evidence value at 12 of
     the 14 thresholds in the range, excluding t = 52, 53.
  P5 (F) at n = 8000 on ODD: the class-ordered chain gives
     2W/n < 4M/n, the bipartite trees 2W/n > 1.9, a chain in draw
     order within 0.02 of 24/49 over 40 trials.
PREDICTIONS (fixed before the laws' checks, the draws as they were).
  F1 every rate, bias, half-bar and ratio of the first record
     reprints at its seed.
  F2 each of the knife's eight totals within 3 of the law's standard
     errors; the eight ratios average above the exact 1.571 to 1.577
     in size, the half-bar being read at the estimate, below 1/2.
  F3 the flipped bins of each of the transient's ten rows within 3
     standard errors of 4,200 P(flip); none at n = 512,000.
  F4 tight iff the rule on 40,914 of 40,914 slices, 7,296 tight; the
     range law on 2,697 of 2,697, 583 outside.
  F5 600 two-label bins of 600, W = 600 and 319,400; the draw-order
     total within 3 standard errors of 156,440.8.
  F6 the 1-NN error's exact mean over every split sample with the
     training bins populated is E[2 eta (1 - eta)].
  F7 at ten further seeds the knife's pooled total and the pooled
     flipped bins within 3 standard errors of their laws.

KILL. A hand control off: nothing is read. A row of the knife or of
the transient past 4 of its law's standard errors, or a further read
past 3: the law is read in exact
terms before it is restated. Only the printed value decides.

FINDINGS. No kill fired. P0 to P4 held; P5's draw-order clause was
frozen on 2W/n, where it is W/n that tends to E[2 eta (1 - eta)]
under a label-blind tree: the first run printed 2W/n = 0.9769 and
failed it, and read as W/n it held. The first argument's (C) had the
flip probability decaying like exp(-2 delta^2 n_r), where the rule is
fit on n_r/2 points. F4 to F7 hold as checks, F7 at each n apart (the
two n pooled would count as independent the knife's two totals, which
one seed's stream ties together); F1 to F3 are read off
the record: every rate, bias and ratio reprinted, the knife's eight
ratios average 1.597 in size, and the largest distances are 2.37 at
the knife, 1.27 among the flipped bins and 2.56 among the test halves.
  controls   every hand row; 141 of 141 fibers at the four slices; the
             knife's and the flip law on their hand rows, through
             every split sample of a small world and in floats at
             n = 500; held-out's mean and the 1-NN error's through the
             same samples; the chain's law through every label string
             of 3 and of 5. On the two benign bins resubstitution
             covers 38 of 40 at bias +0.0010
             (48,320 minority labels, +1.58 standard errors of
             Bin(320000, 3/20)) and held-out 37 of 40 at -0.0006, no
             bin flipped.
  knife      the exact ratio 1.57108, 1.57525, 1.57628, 1.57654 under
             the limit 1.5766. Printed, bias over mean half-bar:
             -1.605, -1.606, -1.623, -1.612 on the ring and -1.682,
             -1.644, -1.462, -1.544 bare; coverage 1, 1, 0, 0 and 0,
             1, 1, 1 of 40; the minority labels 8,607, 37,191,
             154,313, 628,698 and 8,542, 37,126, 154,877, 629,178 sit
             -0.37, -0.56, -0.94, -0.72 and -1.89, -1.32, +2.37, +0.68
             standard errors from the exact law.
  dial       resubstitution at M = 15, n = 8000 covers 1, 36, 39, 37
             of 40 at delta = 0, 1/64, 1/32, 1/8; in units of a bin's
             standard deviation 1/64 is 2 delta sqrt(n/M) = 0.72.
  transient  held-out at WIDE covers 29, 24, 5, 12 of 40 on the ring
             and 35, 23, 7, 7, 38, 36 bare (to n = 512,000). P(flip)
             is 0.309616, 0.327729, 0.260045, 0.122212, 0.011694,
             0.000003, so the exact bias is 0.0281, 0.0298, 0.0236,
             0.0111, 0.0011, 0.0000 (printed +0.0405, +0.0270,
             +0.0235, +0.0112 and +0.0244, +0.0304, +0.0248, +0.0116,
             +0.0009, +0.0000); the flipped bins of 4,200 are 1282,
             1415, 1058, 524 and 1292, 1410, 1107, 518, 41, 0, at
             -0.61, +1.27, -1.20, +0.50 and -0.28, +1.10, +0.52,
             +0.22, -1.16, -0.12 standard errors (at n = 512,000 the
             law expects 0.014 flips, and the distance says only that
             none occurred); the test half sits +2.56, -1.44, +0.51,
             -0.30 and -0.71, -0.07, +0.70, +0.68, -0.06, +0.08
             standard errors from the rules' risk. P(flip) RISES from
             n = 500 to 2000: at two or three training points a bin
             over a quarter of the bins are empty or tied, and those
             guess the right side.
  bound      tight iff the rule on 40,914 of 40,914 slices, 7,296
             tight; the range law on each of the 2,697 range slices of
             the odd-c cells, the no-evidence value outside at
             583; at (105, 15) outside only at t = 52, 53.
  tree       600 of 600 bins hold both labels; class order W = 600
             (2W/n = 0.00375), bipartite 319,400 (1.99625), draw order
             156,310 (W/n = 0.4885), -0.45 standard errors from the
             chain's law at 0.4889, 24/49 being 0.4898. By hand from W:
             [0.0009, 0.0019], [1/2, 1/2] and [0.4241, 0.4885] beside
             the exact [0.4286, 0.4898].
  further    at ten further seeds on bare bins: the minority labels
             86,311 at n = 500 and 372,555 at 2000, +0.61 and +0.63
             standard errors of the knife's law; the flipped bins
             12,902 and 13,542, -1.08 and -2.31 of the flip law. Read
             once more at 100 seeds from 5000 and 100 from 7000, held
             by no check: -1.16, +0.27 and +0.34, +1.47 for the knife,
             +0.40, -0.21 and -0.22, +2.00 for the flips.
Coverage over 40 trials reads to about a tenth; a pinned count, ratio
or distance is the record of its seed on this generator. The hand
rows, the exact legs and the bars of 4 and of 3 standard errors do not
depend on it.
No longer run: the identity's sweep ((D) makes it algebra); the
sampled 1-NN leg of P3, whose gap read noise about an exact mean, and
the sampled Cover-Hart bracket of P0; the ring sampler's frequency
bands, property (A) being counted; every band the pins imply.

RUN RECORD. python estimators.py (Python 3.12, for
random.binomialvariate): 35 of 35 checks, about 5 s, peak commit about
11 MB. The hits, the ratios and the biases reprint the first record's
rates; the minority labels, the flipped bins, the draw-order crossings,
the distances and the further seeds' record were entered from a print
of this file; the HAND constants were derived before any print.
Read by breaks: of 392 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) 371 fail a check and one never ends (the tail's
stop made never to stop); twenty pass and move no line. Three are a
symmetry of the labels (a second label of another name in
chain_moments, the dial mirrored about 1/2, the tree's labels
exchanged); two read eta at another bin of a world with one eta; nine
are bounds never met with equality (a pin's last place, an estimate
exactly a bar from the truth, a coin of exactly 1/2 three times, the
range law's three, c being prime to M, and a product of exactly 500);
one admits a product of seven primes where six exist; one doubles
every weight of a normalized mean; one changes 2g - 1 where only its
sign is read; three move the laws' window by terms of no mass, the
term at 0 being zero in both laws. Of 41 edits by hand, the controls'
stop lifted, 37 fail a check named before the run and four pass as
predicted (the window at 9 standard deviations and from 0, the family
cut to four primes, the 2,000-point tail's own check read at 20).
Every run's seed moved by one fails the five seeded records and no
bar; the tree's seed, its record alone. The further seeds' bar notices
the knife's deficit or P(flip) moved by 5%, not the deficit by 1%.
"""

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

import random
import sys
import time
from fractions import Fraction
from itertools import combinations, product
from math import comb, exp, lgamma, log, pi, prod, sqrt

Z = 1.96
TRIALS = 40
NS = (500, 2000, 8000, 32000)
LONG = NS + (128000, 512000)
KNIFE, ODD, WIDE = (210, 15, 105), (105, 15, 45), (1155, 105, 525)
HAND = (30, 6, 8)
TREE_N = 8000
FAR = tuple(range(1000, 1010))
TOL = 1e-12
CHECKS = []

# by hand, before any engine ran (BY HAND)
HAND_ONES = ((KNIFE, [7] * 15), (ODD, [4] * 15), (WIDE, [6] * 105),
             (HAND, [3, 3, 4, 4, 4, 4]))
# R*, E[2 eta (1 - eta)], u
HAND_MOMENTS = ((KNIFE, ("1/2", "1/2", "0")), (ODD, ("3/7", "24/49", "1/49")),
                (WIDE, ("5/11", "60/121", "1/121")),
                (HAND, ("4/15", "28/75", "19/75")))
# a slice and whether its lower end is R*
HAND_TIGHT = (((30, 6, 8), False), ((105, 15, 45), True),
              ((105, 15, 52), True), ((30, 6, 14), True),
              ((210, 15, 100), False))
HAND_MAD = ("0", "1/2", "1/2", "3/4", "3/4", "15/16", "15/16")
HAND_DEFICIT = (((2, 1), "1/4"), ((2, 2), "3/8"), ((4, 2), "35/128"))
HAND_FLIP = (((1, 1), "5/22"), ((2, 1), "135/484"))
HAND_RATIO = (1.57111, 1.57525, 1.57628, 1.57654)
HAND_CHAINS = (([0, 0, 1, 1], 1), ([0, 1, 0, 1], 3), ([1], 0), ([], 0))
HAND_CELLS = [[0, 1, 1, 0], [1, 1], [0], [], [1, 1, 1], [0, 1]]

# the recorded seeds' rows, entered from a print (RUN RECORD)
# (ring or bare, n): hits, minority labels, ratio, the law's distance
KNIFE_PINS = {
    ("ring", 500): (1, 8607, -1.605, -0.37),
    ("ring", 2000): (1, 37191, -1.606, -0.56),
    ("ring", 8000): (0, 154313, -1.623, -0.94),
    ("ring", 32000): (0, 628698, -1.612, -0.72),
    ("bare", 500): (0, 8542, -1.682, -1.89),
    ("bare", 2000): (1, 37126, -1.644, -1.32),
    ("bare", 8000): (1, 154877, -1.462, 2.37),
    ("bare", 32000): (1, 629178, -1.544, 0.68)}
# delta: hits, minority labels
DIAL_PINS = {"0": (1, 154465), "1/64": (36, 153174),
             "1/32": (39, 149796), "1/8": (37, 120384)}
# (ring or bare, n): hits, flipped bins, bias, the law's distance, the
# test half's
TRANSIENT_PINS = {
    ("ring", 500): (29, 1282, 0.0405, -0.61, 2.56),
    ("ring", 2000): (24, 1415, 0.0270, 1.27, -1.44),
    ("ring", 8000): (5, 1058, 0.0235, -1.20, 0.51),
    ("ring", 32000): (12, 524, 0.0112, 0.50, -0.30),
    ("bare", 500): (35, 1292, 0.0244, -0.28, -0.71),
    ("bare", 2000): (23, 1410, 0.0304, 1.10, -0.07),
    ("bare", 8000): (7, 1107, 0.0248, 0.52, 0.70),
    ("bare", 32000): (7, 518, 0.0116, 0.22, 0.68),
    ("bare", 128000): (38, 41, 0.0009, -1.16, -0.06),
    ("bare", 512000): (36, 0, 0.0000, -0.12, 0.08)}
# resubstitution: hits, minority labels, the law's distance;
# held-out: hits, flipped bins, bias
CONTROL_PINS = ((38, 48320, 1.58), (37, 0, -0.0006))
# the draw-order chain's crossings and their distance
TREE_PINS = (156310, -0.45)
# ten further seeds, by n: minority labels, flipped bins, the two
# distances
FAR_PINS = {500: (86311, 12902, 0.61, -1.08),
            2000: (372555, 13542, 0.63, -2.31)}


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)


# ------------------------------------------------------------ the ring

def ring_point(x, M, t):
    """The bin and the label of x."""
    return x % M, int(x >= t)


def ring_ones(N, M, t):
    """Per fiber r, its points at or above t, counted along the fiber."""
    c = N // M
    return [sum(1 for j in range(c) if r + j * M >= t) for r in range(M)]


def ring_etas(N, M, t):
    """eta_r = P(x >= t | x mod M = r), exact."""
    c = N // M
    return [Fraction(a, c) for a in ring_ones(N, M, t)]


def fiber_hits(N, M, t):
    """Fibers whose labels, tallied over every x of Z/N through
    ring_point, are ring_ones' count of ones and the rest zeros."""
    tally = [[0, 0] for _ in range(M)]
    for x in range(N):
        r, y = ring_point(x, M, t)
        tally[r][y] += 1
    c = N // M
    return sum(tally[r] == [c - a, a]
               for r, a in enumerate(ring_ones(N, M, t)))


def ring_sample(rng, N, M, t, n):
    """Per-bin label counts [n_r0, n_r1] from n uniform draws of x."""
    counts = [[0, 0] for _ in range(M)]
    for _ in range(n):
        r, y = ring_point(rng.randrange(N), M, t)
        counts[r][y] += 1
    return counts


def bare_sample(rng, etas, n):
    """Per-bin label counts: a multinomial over equiprobable bins, then
    a binomial label count in each."""
    M = len(etas)
    counts = []
    left = n
    for r in range(M):
        nr = rng.binomialvariate(left, 1 / (M - r))
        left -= nr
        n1 = rng.binomialvariate(nr, float(etas[r])) if nr else 0
        counts.append([nr - n1, n1])
    return counts


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


def nn_limit(etas):
    return sum(2 * e * (1 - e) for e in etas) / len(etas)


def u_of(etas):
    return sum((2 * e - 1) ** 2 for e in etas) / len(etas)


# ---------------------------------------------------------- estimators

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


def resub(counts, n):
    """The estimate, its stated half-bar, and the minority labels."""
    low = sum(min(a, b) for a, b in counts)
    est = low / n
    return est, bar(est, n), low


def majority(train):
    """Per bin, the label guessed: 1 unless zeros are strictly more."""
    return [int(tb >= ta) for ta, tb in train]


def flipped(train, etas):
    """Bins whose guess is on the other side of 1/2 from eta."""
    return sum(1 for g, e in zip(majority(train), etas)
               if (2 * g - 1) * (2 * e - 1) < 0)


def held_out(train, test):
    m = sum(a + b for a, b in test)
    wrong = sum(a if g else b for g, (a, b) in zip(majority(train), test))
    est = wrong / m
    return est, bar(est, m), wrong, m


def one_nn(train, test):
    """The error of 'a random training label of the test point's bin',
    exact, every training bin populated."""
    m = sum(a + b for a, b in test)
    return sum(Fraction(a * tb + b * ta, ta + tb)
               for (ta, tb), (a, b) in zip(train, test)) / m


def split(rng, counts):
    """Split per-bin counts into two halves, each point a fair coin."""
    train, test = [], []
    for a, b in counts:
        a1 = sum(1 for _ in range(a) if rng.random() < 0.5)
        b1 = sum(1 for _ in range(b) if rng.random() < 0.5)
        train.append([a1, b1])
        test.append([a - a1, b - b1])
    return train, test


def est_resub(rng, counts, n, etas):
    return resub(counts, n)


def est_held(rng, counts, n, etas):
    train, test = split(rng, counts)
    return held_out(train, test)[:2] + (flipped(train, etas),)


def run(etas, n, seed, estimator, cell=None):
    """TRIALS samples at one seed, on the ring slice `cell` or on bare
    bins: the trials whose stated interval holds the truth, the
    estimator's integer summed (resubstitution's minority labels,
    held-out's flipped bins), the mean estimate less the truth and the
    mean half-bar."""
    rng = random.Random(seed)
    truth = float(bayes(etas))
    est_sum = bar_sum = 0.0
    hits = count = 0
    for _ in range(TRIALS):
        counts = (ring_sample(rng, *cell, n) if cell
                  else bare_sample(rng, etas, n))
        est, b, k = estimator(rng, counts, n, etas)
        est_sum += est
        bar_sum += b
        hits += abs(est - truth) <= b
        count += k
    return dict(hits=hits, count=count, bias=est_sum / TRIALS - truth,
                hb=bar_sum / TRIALS)


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

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


def binom_pmf(n, k, p):
    return exp(lgamma(n + 1) - lgamma(k + 1) - lgamma(n - k + 1)
               + k * log(p) + (n - k) * log(1 - p))


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


def mad_fair(m):
    """E|B - m/2| for B ~ Bin(m, 1/2): nu C(m, nu)/2^m at
    nu = floor(m/2) + 1 (de Moivre)."""
    nu = m // 2 + 1
    return Fraction(nu * comb(m, nu), 2 ** m)


def knife_deficit(n, M):
    """1/2 less the mean of resubstitution on n points over M bins at
    eta = 1/2, exact."""
    return Fraction(M, n) * sum(
        Fraction(comb(n, m) * (M - 1) ** (n - m), M ** n) * mad_fair(m)
        for m in range(n + 1))


def knife_law(n, M):
    """One sample's minority labels at the knife: the mean, and the
    upper end of the variance."""
    e1 = sum(binom_pmf(n, m, 1 / M) * float(mad_fair(m))
             for m in window(n, 1 / M))
    return n / 2 - M * e1, n / 4 - M * e1 * e1


def knife_ratio(n, M):
    """The exact deficit over the half-bar at 1/2, Z/(2 sqrt n)."""
    return (n / 2 - knife_law(n, M)[0]) / n * 2 * sqrt(n) / Z


def below_half(K, eta):
    """d^K P(Bin(K, eta) < K/2) at eta = a/d, an integer."""
    a, d = eta.numerator, eta.denominator
    return sum(comb(K, j) * a ** j * (d - a) ** (K - j)
               for j in range((K + 1) // 2))


def flip_exact(n, M, eta):
    """P(a bin's training labels hold strictly more zeros), exact: the
    bin's training points K ~ Bin(n, 1/(2M)), its ones Bin(K, eta)."""
    d = eta.denominator
    return Fraction(
        sum(comb(n, K) * ((2 * M - 1) * d) ** (n - K) * below_half(K, eta)
            for K in range(n + 1)), (2 * M * d) ** n)


def flip_given(K, eta):
    """P(Bin(K, eta) < K/2), summed down from the largest j below K/2
    until a term no longer moves the sum (the term after j = 0 is
    0)."""
    if K == 0:
        return 0.0
    j = (K - 1) // 2
    term = binom_pmf(K, j, eta)
    tot = 0.0
    while tot + term > tot:
        tot += term
        term *= j / (K - j + 1) * (1 - eta) / eta
        j -= 1
    return tot


def flip_law(n, M, eta):
    """One sample's flipped bins: the mean M P, and the variance of M
    independent bins."""
    p = 1 / (2 * M)
    P = sum(binom_pmf(n, K, p) * flip_given(K, eta) for K in window(n, p))
    return M * P, M * P * (1 - P)


def chain_law(n, M, eta):
    """Crossings of the draw-order chain over M bins of two points or
    more, n points in all: the mean and the variance, exact."""
    pq = eta * (1 - eta)
    return ((n - M) * 2 * pq,
            (n - M) * 2 * pq * (1 - 2 * pq)
            + 2 * (n - 2 * M) * pq * (1 - 4 * pq))


def chain_cross(labels):
    return sum(1 for a, b in zip(labels, labels[1:]) if a != b)


def chain_moments(L, eta):
    """The mean and the variance of a chain's crossings over every
    label string of length L."""
    m1 = m2 = Fraction(0)
    for s in product((0, 1), repeat=L):
        w = prod(eta if y else 1 - eta for y in s)
        k = chain_cross(s)
        m1 += w * k
        m2 += w * k * k
    return m1, m2 - m1 * m1


def split_samples(etas, n):
    """Every assignment of n points to a bin, a label and a half, with
    its weight, the product of each point's eta or 1 - eta (bins and
    halves are uniform): (4M)^n of them."""
    M = len(etas)
    for s in product(range(4 * M), repeat=n):
        w = Fraction(1)
        train = [[0, 0] for _ in range(M)]
        test = [[0, 0] for _ in range(M)]
        for v in s:
            r, y, h = v // 4, v // 2 % 2, v % 2
            w *= etas[r] if y else 1 - etas[r]
            (test if h else train)[r][y] += 1
        yield w, train, test


def enumerated(etas, n):
    """Exact means over split_samples: the minority labels of the whole
    sample; the flipped bins; the 1-NN error over the samples whose
    training bins are all populated and whose test half is not empty;
    and, over the samples whose test half is not empty, the held-out
    estimate and the flipped bins."""
    tw = low = flips = nnw = nn = hw = ho = hf = Fraction(0)
    for w, train, test in split_samples(etas, n):
        whole = [[a + c, b + d] for (a, b), (c, d) in zip(train, test)]
        tw += w
        low += w * resub(whole, n)[2]
        flips += w * flipped(train, etas)
        if any(a + b for a, b in test):
            hw += w
            ho += w * Fraction(*held_out(train, test)[2:])
            hf += w * flipped(train, etas)
            if all(a + b for a, b in train):
                nnw += w
                nn += w * one_nn(train, test)
    return low / tw, flips / tw, nn / nnw, ho / hw, hf / hw


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

def knife_row(n, seed, cell=None):
    """Resubstitution at the knife: run's record, the ratio of bias to
    half-bar, and the total's distance from the exact law."""
    etas = ring_etas(*KNIFE)
    rec = run(etas, n, seed, est_resub, cell)
    mean, var = knife_law(n, len(etas))
    rec["ratio"] = rec["bias"] / rec["hb"]
    rec["z"] = z_of(rec["count"], TRIALS * mean, TRIALS * var)
    return rec


def knife_sweep():
    return {(name, n): knife_row(n, 100 + i, cell)
            for name, cell in (("ring", KNIFE), ("bare", None))
            for i, n in enumerate(NS)}


def dial_row(d):
    """Resubstitution on 15 bare bins at eta = 1/2 + d, n = 8000."""
    return run([Fraction(1, 2) + d] * 15, 8000, 300, est_resub)


def transient_row(n, seed, cell=None):
    """Held-out at WIDE: run's record, the flipped bins' distance from
    the exact law, and the test half's: the bias less the flipped
    bins' share, the estimate read as a rate on n/2 points about the
    rules' mean risk."""
    etas = ring_etas(*WIDE)
    eta = float(etas[0])
    rec = run(etas, n, seed, est_held, cell)
    mean, var = flip_law(n, len(etas), eta)
    rec["z"] = z_of(rec["count"], TRIALS * mean, TRIALS * var)
    share = rec["count"] / (TRIALS * len(etas)) * (2 * eta - 1)
    risk = float(bayes(etas)) + share
    rec["t"] = z_of(rec["bias"], share, risk * (1 - risk) / (n / 2) / TRIALS)
    return rec


def transient_sweep():
    return {(name, n): transient_row(n, 200 + i, cell)
            for name, cell, ns in (("ring", WIDE, NS), ("bare", None, LONG))
            for i, n in enumerate(ns)}


def benign_rows():
    """Two equiprobable bins at eta = (1/5, 9/10), n = 8000: both
    estimators; resubstitution's minority labels are Bin(n, 3/20) a
    sample while no bin flips."""
    etas = [Fraction(1, 5), Fraction(9, 10)]
    a = run(etas, 8000, 11, est_resub)
    b = run(etas, 8000, 12, est_held)
    a["z"] = z_of(a["count"], TRIALS * 1200, TRIALS * 1020)
    return a, b


def far_row(n, seeds):
    """Over further seeds, on bare bins at one n: the knife's minority
    labels and the transient's flipped bins, each total with its
    distance from its law. One n a read: runs at two n from one seed
    share a stream, and the knife's totals correlate."""
    km, kv = knife_law(n, KNIFE[1])
    pm, pv = flip_law(n, WIDE[1], 6 / 11)
    low = sum(knife_row(n, seed)["count"] for seed in seeds)
    flips = sum(transient_row(n, seed)["count"] for seed in seeds)
    k = TRIALS * len(seeds)
    return low, flips, z_of(low, k * km, k * kv), z_of(flips, k * pm, k * pv)


def far_sweep(seeds):
    return {n: far_row(n, seeds) for n in NS[:2]}


def threshold_family(cap):
    PR = (2, 3, 5, 7, 11, 13)
    out = []
    for k in range(2, 7):
        for ps in combinations(PR, k):
            N = prod(ps)
            if N > cap:
                continue
            for m in range(1, k):
                for S in combinations(ps, m):
                    out.append((N, prod(S)))
    return out


def tight_row(N, M, t):
    """Whether the bracket's lower end is R*, in integers ((sum |d_r|)^2
    = M sum d_r^2 at d_r = 2 ones_r - c, which is (1 - 2R*)^2 = u), and
    whether M | t or t is in the odd-c middle range."""
    c = N // M
    d = [2 * a - c for a in ring_ones(N, M, t)]
    Q, s = divmod(t, M)
    return (sum(abs(x) for x in d) ** 2 == M * sum(x * x for x in d),
            s == 0 or (c % 2 == 1 and Q == (c - 1) // 2))


def tight_fraction(N, M, t):
    etas = ring_etas(N, M, t)
    return (1 - 2 * bayes(etas)) ** 2 == u_of(etas)


def tight_sweep(cells):
    """Slices 0 < t < N, the tight ones, and those where the two reads
    of tight_row agree."""
    slices = tight = agree = 0
    for N, M in cells:
        for t in range(1, N):
            a, b = tight_row(N, M, t)
            slices += 1
            tight += a
            agree += a == b
    return slices, tight, agree


def range_ts(N, M):
    """The odd-c middle range: t // M = (c - 1)/2, M not dividing t."""
    c = N // M
    return list(range(M * (c - 1) // 2 + 1, M * (c + 1) // 2))


def range_row(N, M, t):
    """At a slice of the range: R* is (c - 1)/(2c); the lower end is
    R*; the upper end is 1/2 - 1/(2c^2); the no-evidence value is
    above R*; it is above the upper end; and that is so iff
    |2t - N| c < M."""
    c = N // M
    etas = ring_etas(N, M, t)
    u = u_of(etas)
    naive = Fraction(min(t, N - t), N)
    out = naive > (1 - u) / 2
    return (bayes(etas) == Fraction(c - 1, 2 * c),
            (1 - 2 * bayes(etas)) ** 2 == u,
            (1 - u) / 2 == Fraction(1, 2) - Fraction(1, 2 * c * c),
            naive > bayes(etas), out, out == (abs(2 * t - N) * c < M))


def range_sweep(cells):
    """Over the ranges of the odd-c cells: slices, and those passing
    each field of range_row."""
    tot = [0] * 7
    for N, M in cells:
        if N // M % 2 == 1:
            for t in range_ts(N, M):
                tot = [x + y for x, y in zip(tot, (1,) + range_row(N, M, t),
                                             strict=True)]
    return tuple(tot)


def tree_counts(cells):
    """Within-bin cross edges of three spanning trees of the bins'
    label lists: the chain in class order, the bipartite trees, the
    chain in draw order; and the bins holding both labels."""
    g = b = d = two = 0
    for lab in cells:
        g += chain_cross(sorted(lab))
        d += chain_cross(lab)
        if 0 < sum(lab) < len(lab):
            two += 1
            b += len(lab) - 1
    return g, b, d, two


def tree_sweep(seed):
    """TRIALS samples of TREE_N points at ODD: tree_counts summed,
    and the draw-order crossings' distance from the chain's law."""
    etas = ring_etas(*ODD)
    rng = random.Random(seed)
    tot = [0] * 4
    for _ in range(TRIALS):
        cells = [[] for _ in range(len(etas))]
        for _ in range(TREE_N):
            r = rng.randrange(len(etas))
            cells[r].append(int(rng.random() < etas[r]))
        tot = [x + y for x, y in zip(tot, tree_counts(cells), strict=True)]
    mean, var = chain_law(TREE_N, len(etas), etas[0])
    return tuple(tot) + (z_of(tot[2], TRIALS * mean, TRIALS * var),)


# ------------------------------------------------------------ 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("the ring's ones per fiber on four hand slices",
          sum(ring_ones(*s) == ones for s, ones in HAND_ONES) == 4)
    hits = [fiber_hits(*s) for s, _ in HAND_ONES]
    check("every x of Z/N through the point map gives each fiber its "
          "ones and zeros, at the four slices",
          hits == [15, 15, 105, 6], f"{sum(hits)} fibers")
    check("R*, E[2 eta (1 - eta)] and u on the four hand slices",
          sum(f(ring_etas(*s)) == Fraction(h) for s, hand in HAND_MOMENTS
              for f, h in zip((bayes, nn_limit, u_of), hand)) == 12)
    est, b, low = resub([[3, 1], [2, 2], [0, 4]], 12)
    check("resubstitution on hand counts: 3 minority labels of 12, bar "
          "0.245", (low, est) == (3, 0.25) and abs(b - 0.245) <= TOL)
    train = [[2, 1], [1, 1], [0, 0], [1, 3]]
    est, b, wrong, m = held_out(train, [[3, 1], [2, 2], [1, 4], [0, 5]])
    check("the majority on hand counts, a tie and an empty bin guessing "
          "1; held-out wrong on 4 of 18, bar 0.192062; one bin flipped "
          "at eta above 1/2, three below it",
          majority(train) == [0, 1, 1, 1] and (wrong, m) == (4, 18)
          and abs(est - 4 / 18) <= TOL and abs(b - 0.192062) < 5e-7
          and flipped(train, [Fraction(6, 11)] * 4) == 1
          and flipped(train, [Fraction(5, 11)] * 4) == 3
          and flipped(train, [Fraction(1, 2)] * 4) == 0)
    check("the bar on two hand rows",
          abs(bar(0.5, 2401) - 0.02) <= TOL
          and abs(bar(0.1, 3600) - 0.0098) <= TOL)
    check("1-NN on hand counts",
          one_nn([[1, 3], [4, 1]], [[2, 1], [1, 3]]) == Fraction(87, 140))
    check("a fair binomial's mean absolute deviation at m = 0..6",
          [mad_fair(m) for m in range(7)] == [Fraction(h) for h in HAND_MAD])
    half = enumerated([Fraction(1, 2)] * 2, 4)
    check("the knife's deficit at three hand rows, and every split "
          "sample of 4 points on 2 bins through resubstitution",
          sum(knife_deficit(*a) == Fraction(h) for a, h in HAND_DEFICIT) == 3
          and half[0] == 4 * (Fraction(1, 2) - knife_deficit(4, 2))
          and half[1] == 0)
    exact = 500 * (Fraction(1, 2) - knife_deficit(500, 15))
    check("the knife's law in floats is the exact one at n = 500",
          abs(knife_law(500, 15)[0] - float(exact)) <= 1e-9)
    e = Fraction(6, 11)
    one, two = enumerated([e], 2), enumerated([e] * 2, 3)
    check("P(flip) at two hand rows, and every split sample of 2 points "
          "on one bin and of 3 on two through the majority",
          sum(flip_exact(*a, e) == Fraction(h) for a, h in HAND_FLIP) == 2
          and one[1] == Fraction(135, 484)
          and two[1] == 2 * flip_exact(3, 2, e))
    check("the flip law in floats is the exact one at n = 500, M = 105, "
          "and a bin's flip at 2,000 training points the exact tail to "
          "1e-9 of it",
          abs(flip_law(500, 105, 6 / 11)[0]
              - 105 * float(flip_exact(500, 105, e))) <= 1e-9
          and abs(flip_given(2000, 6 / 11)
                  / float(Fraction(below_half(2000, e), 11 ** 2000)) - 1)
          <= 1e-9)
    check("held-out's mean less R* is the flipped bins' share, over "
          "every split sample with a test half, at the two worlds",
          one[3] - Fraction(5, 11) == one[4] / 11
          and two[3] - Fraction(5, 11) == two[4] / 2 / 11
          and one[4] > 0 and two[4] > 0)
    far = enumerated([Fraction(1, 5), Fraction(9, 10)], 4)
    check("the 1-NN error's mean over every split sample with the "
          "training bins populated is E[2 eta (1 - eta)], at three worlds",
          (half[2], two[2], far[2])
          == (Fraction(1, 2), Fraction(60, 121), Fraction(1, 4)))
    check("chain crossings on four hand rows; the three trees on hand "
          "cells",
          sum(chain_cross(lab) == k for lab, k in HAND_CHAINS) == 4
          and tree_counts(HAND_CELLS) == (2, 4, 3, 2))
    e = Fraction(4, 7)
    check("the chain's law at one bin of 3 points and at two by hand, "
          "and at 3 and at 5 over every label string",
          chain_law(3, 1, e) == (Fraction(48, 49), Fraction(1224, 2401))
          and chain_law(6, 2, e) == (Fraction(96, 49), Fraction(2448, 2401))
          and sum(chain_moments(L, e) == chain_law(L, 1, e)
                  for L in (3, 5)) == 2)
    check("the tight read on five hand slices, in integers, by the "
          "rule and in Fractions",
          sum(tight_row(*s) == (h, h) and tight_fraction(*s) == h
              for s, h in HAND_TIGHT) == 5)
    cells = threshold_family(500)
    check("the family holds 194 cells",
          (len(cells), len(set(cells))) == (194, 194))
    check("the range of (105, 15) is t = 46..59, and of (30, 6) t = 13..17",
          range_ts(105, 15) == list(range(46, 60))
          and range_ts(30, 6) == [13, 14, 15, 16, 17])
    check("a distance in standard errors on two hand rows",
          abs(z_of(110, 100, 25) - 2) <= TOL
          and abs(z_of(90, 100, 400) + 0.5) <= TOL)
    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.236), (4, 1.23))]
          == [True, True, False, False])
    a, b = benign_rows()
    print(f"  two bins at eta = (1/5, 9/10), n = 8000: resubstitution "
          f"bias {a['bias']:+.4f}, covers {a['hits']} of 40, minority "
          f"labels {a['count']} ({a['z']:+.2f} se of Bin(320000, 3/20)); "
          f"held-out bias {b['bias']:+.4f}, covers {b['hits']} of 40, "
          f"{b['count']} bins flipped")
    check("on two benign bins both estimators cover as recorded, no bin "
          "flipped",
          near((a["hits"], a["count"], a["z"]), CONTROL_PINS[0],
                   (0, 0, 2))
          and near((b["hits"], b["count"], b["bias"]), CONTROL_PINS[1],
                   (0, 0, 4)))
    return all(CHECKS)


def section_knife():
    section("THE KNIFE: a consistent point inside an inconsistent interval")
    limit = sqrt(2 * 15 / pi) / Z
    ratios = [knife_ratio(n, 15) for n in NS]
    print(f"  sqrt(2M/pi)/Z = {limit:.4f}; the exact deficit over "
          f"Z/(2 sqrt n): " + ", ".join(f"{r:.5f}" for r in ratios))
    check("the exact ratio within 0.00005 of the hand expansion at the "
          "four n, each under the limit",
          sum(abs(r - h) < 0.00005 and r < limit
              for r, h in zip(ratios, HAND_RATIO)) == 4
          and abs(limit - 1.5766) < 0.00005)
    rec = knife_sweep()
    for (name, n), r in rec.items():
        print(f"  {name} n = {n:5d}: bias {r['bias']:+.4f}, half-bar "
              f"{r['hb']:.4f}, ratio {r['ratio']:+.3f}, coverage "
              f"{r['hits'] / TRIALS:.2f} ({r['hits']} of 40); minority "
              f"labels {r['count']}, {r['z']:+.2f} se of the law")
    check("KNIFE the eight rows' hits, minority labels, ratios and "
          "distances as recorded",
          len(rec) == 8
          and sum(near((r["hits"], r["count"], r["ratio"], r["z"]),
                       KNIFE_PINS[key], (0, 0, 3, 2))
                  for key, r in rec.items()) == 8)
    check("KNIFE each row's minority labels inside 4 standard errors of "
          "the exact law", sum(abs(r["z"]) < 4 for r in rec.values()) == 8)
    dial = {d: dial_row(Fraction(d)) for d in ("0", "1/64", "1/32", "1/8")}
    for d, r in dial.items():
        print(f"  knife dial delta = {d:5s}: coverage "
              f"{r['hits'] / TRIALS:.2f} ({r['hits']} of 40), minority "
              f"labels {r['count']}")
    check("DIAL the four rows' hits and minority labels as recorded",
          sum((r["hits"], r["count"]) == DIAL_PINS[d]
                  for d, r in dial.items()) == 4)


def section_transient():
    section("THE TRANSIENT: more data, a worse held-out interval, then not")
    rec = transient_sweep()
    for (name, n), r in rec.items():
        law = flip_law(n, 105, 6 / 11)[0] / 105
        print(f"  {name} n = {n:6d}: bias {r['bias']:+.4f}, coverage "
              f"{r['hits'] / TRIALS:.2f} ({r['hits']} of 40); flipped "
              f"{r['count']} of 4200, {r['z']:+.2f} se of the law "
              f"{law:.6f}, bias {law / 11:.4f}; the test half "
              f"{r['t']:+.2f} se")
    check("TRANSIENT the ten rows' hits, flipped bins, bias and the two "
          "distances as recorded",
          len(rec) == 10
          and sum(near((r["hits"], r["count"], r["bias"], r["z"], r["t"]),
                       TRANSIENT_PINS[key], (0, 0, 4, 2, 2))
                  for key, r in rec.items()) == 10)
    check("TRANSIENT each row's flipped bins and its test half inside 4 "
          "standard errors",
          sum(abs(r["z"]) < 4 and abs(r["t"]) < 4 for r in rec.values())
          == 10)


def section_bound():
    section("ONE BOUND AT TWO STATISTICS")
    cells = threshold_family(500)
    slices, tight, agree = tight_sweep(cells)
    check("the lower end is R* iff M | t or the odd-c middle range, at "
          "every slice of the family; 40,914 slices, 7,296 tight",
          (slices, tight, agree) == (40914, 7296, 40914),
          f"{agree} of {slices}, {tight} tight")
    r = range_sweep(cells)
    check("on the 2,697 range slices of the odd-c cells: R* is "
          "(c - 1)/(2c), the lower end R*, the upper 1/2 - 1/(2c^2), the "
          "no-evidence value above R*, and above the upper end iff "
          "|2t - N| c < M, at 583",
          r == (2697, 2697, 2697, 2697, 2697, 583, 2697),
          f"{r[1]}, {r[2]}, {r[3]}, {r[4]} and {r[6]} of {r[0]}; {r[5]} "
          f"outside")
    rows = [range_row(105, 15, t) for t in range_ts(105, 15)]
    out = [t for t, row in zip(range_ts(105, 15), rows) if row[4]]
    check("at (105, 15), c = 7, the bracket is [3/7, 24/49] at each of "
          "the 14 thresholds and the no-evidence value lies outside at "
          "t = 52, 53 alone",
          out == [52, 53]
          and sum(r[0] and r[1] and r[2] for r in rows) == 14,
          f"outside at {out}")


def section_mst():
    section("THE SPANNING TREE IS NOT IDENTIFIED")
    g, b, d, two, z = tree_sweep(500)
    law = chain_law(TREE_N, 15, Fraction(4, 7))[0] / TREE_N
    points = TRIALS * TREE_N
    print(f"  40 samples of n = 8000 at (105, 15, 45): {two} of 600 bins "
          f"hold both labels")
    print(f"  class-ordered chain: W = {g}, 2W/n = {2 * g / points:.5f}")
    print(f"  bipartite trees: W = {b}, 2W/n = {2 * b / points:.5f}")
    print(f"  chain in draw order: W = {d}, W/n = {d / points:.4f}, "
          f"{z:+.2f} se of the law {float(law):.4f}; "
          f"24/49 = {24 / 49:.4f}")
    check("TREE every bin holds both labels in every trial, so W is 15 "
          "a trial in class order and n - 15 bipartite",
          (two, g, b) == (600, 600, 319400))
    check("TREE the draw-order crossings and their distance from the "
          "chain's law as recorded",
          near((d, z), TREE_PINS, (0, 2)))


def section_far():
    section("FURTHER SEEDS")
    far = far_sweep(FAR)
    for n, r in far.items():
        print(f"  ten further seeds, bare bins at n = {n}: minority labels "
              f"{r[0]}, {r[2]:+.2f} se of the knife's law; flipped bins "
              f"{r[1]}, {r[3]:+.2f} se of the flip law")
    check("FAR the knife's total and the flipped bins inside 3 standard "
          "errors of their laws at ten further seeds, at each n",
          sum(abs(r[2]) < 3 and abs(r[3]) < 3 for r in far.values()) == 2)
    check("FAR the ten further seeds' record",
          sum(near(r, FAR_PINS[n], (0, 0, 2, 2)) for n, r in far.items())
          == 2)


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])
        far = far_sweep(range(first, first + count))
        for n, r in far.items():
            print(f"seeds {first} to {first + count - 1}, n = {n}: minority "
                  f"labels {r[0]}, {r[2]:+.2f} se of the knife's law; "
                  f"flipped bins {r[1]}, {r[3]:+.2f} se of the flip law")
        return 0 if all(abs(r[2]) < 3 and abs(r[3]) < 3
                        for r in far.values()) else 1
    section_knife()
    section_transient()
    section_bound()
    section_mst()
    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())