erring_lower.py

Checks: SIZE: Growing widths property; observation; SIZE: The rate of the least error theorem; property; observation.

Cited on: SIZE.

To run it: save erring_lower.py, with erring_label.py, erring_widths.py, erring_zones.py beside it; needs numpy.

"""
erring_lower.py -- the lower side of kappa_m: a width bound under the
continuum error, and the exponential widths that meet it up to a
constant.

QUESTION. Fill [0, c) with m intervals below one overflow label
[c, 2c - 1), e_m(c) the least error as in erring_label.py, kappa_m the
limsup over c of e_m(c)/c^2. Is kappa_m bounded below by a multiple of
1/log m, and above by one?

PROOF. P is 0 = c_0 < ... < c_m = 1, widths w_i, labels I_1..I_m and
overflow [1, 2), E(P) its continuum error (erring_zones.py's
cont_error: each cell's area less its largest label area).
  (1) kappa_m = inf_P E(P). Rounding cP to integers moves each count by
      O(c), so e_m(c) <= c^2 E(P) + O(m^2 c). Conversely a cut set at c
      scaled by 1/c is a P; in a cell, for each integer x the y-count of
      a label is an integer interval counted exactly, and its length is
      1-Lipschitz in x, so each label count is within the cell's x-width
      of c^2 times its area while the cell's count is exact: e >= c^2
      E(P) - O(m^2 c). So e_m(c)/c^2 converges to inf_P E(P).
  (2) E(P) >= LB(P) = (1/8) sum w_a^2 + (1/4) sum_{a<j} w_a min(w_a, w_j).
      A cell I_a x I_b errs at least the integral over y in I_b of
      e_a(y), I_a's measure off its largest label once shifted by y.
      A label boundary beta strictly inside I_a + y leaves every label
      class on one side, so e_a(y) >= w_a/2 - |beta - t|, t the shifted
      midpoint. Integrating t over a later label [c_{j-1}, c_j), both
      ends boundaries, gives at least w_a min(w_a, w_j)/4; the boundary
      1 gives w_a^2/8 on [1, 1 + w_a/2).
  (3) Each pair term w_a min(w_a, w_j) is at least min(w_a, w_j)^2, and
      the pairs' squared minima depend on the widths only as a
      multiset: with v sorted increasing and S_j = sum_{i<=j} v_i^2
      they sum to sum_i v_i^2 (m - i) = sum_{j<m} S_j. So LB >= G =
      S_m/8 + (1/4) sum_{j<m} S_j = R/4 - S_m/8 >= R/8, where
      R = S_1 + ... + S_m >= S_m.
  (4) R >= F(delta) = min(delta(2 - delta)/4,
      (1 - delta)^2/log(4m/delta^2)) at every mass delta in (0, 1):
      j0 the last index with v_1 + ... + v_j0 <= delta, A that sum
      (j0 < m as the widths sum to 1). A < delta/2 puts every later
      width above delta - A > delta/2, their sum 1 - A > 1 - delta/2, so
      R >= S_m > delta(2 - delta)/4. Else S_j0 >= A^2/j0 >=
      delta^2/(4m), and with D_j = log(S_j/S_{j-1}), v_j^2 <= S_j D_j
      (log(1 + x) >= x/(1 + x)); Cauchy-Schwarz:
      (1 - delta)^2 <= (sum_{j>j0} v_j)^2 <= R log(S_m/S_j0)
      <= R log(4m/delta^2), S_m <= 1. delta = 1/2 gives
      R >= 1/(4 log 16m), as 3/16 > 1/(4 log 16), so E(P) >= LB(P) >=
      R/8 >= 1/(32 log 16m) at every P, and kappa_m = inf_P E(P) >=
      1/(32 log 16m) at every m.
  (5) G >= F2(delta, eta) = min(delta(2 - delta)/32, eta^2/8,
      (1 - delta - eta)^2/(4 log(4m/delta^2))) for delta, eta > 0,
      delta + eta < 1, with j0 and A as in (4). A < delta/2: G >= S_m/8
      > delta(2 - delta)/32. Else S_j0 >= delta^2/(4m); if v_m >= eta,
      G >= S_m/8 >= eta^2/8; if not, the widths strictly between j0
      and m sum past 1 - delta - eta > 0, and Cauchy-Schwarz over them
      alone gives (1 - delta - eta)^2 <= log(S_{m-1}/S_j0)
      sum_{j<m} S_j. At delta = 8/log m, eta = (log m)^(-1/3) the three
      terms are (1 - o(1))/(2 log m), (log m)^(-2/3)/8 and
      (1 - o(1))/(4 log m), so kappa_m >= (1 - o(1))/(4 log m).
  (6) The upper side, by the zone construction ([0, t0) one interval,
      [t0, 1) in zones of width D, zone k a grid of width eps f(z_k) at
      an independent uniform phase; erring_zones.py's zones builds it
      with f(t) = t^p only), whose phases can be chosen to err at most
      the integral of (w(x) + w(y))/(4 w(x + y)) over x, y >= t0,
      x + y < 1, plus 2 t0 + 6(1/D + 2) eps f(1), at
      m* = 1 + sum_k (ceil(D/w_k) + 2) intervals; and kappa_m is
      nonincreasing in m: once c > m some interval [u, v) has
      v - u >= 2; split at v - 1, a split cell errs no more than the
      whole and only the sums equal to v - 1 change label, at most c
      pairs, so e_{m+1}(c) <= e_m(c) + c. f(t) = exp(K(t - 1)): the
      integrand is at most (e^{K(D - y)} + e^{K(D - x)})/4, integral at
      most 1/(2K) at t0 = D; t0 = D = K^-1.5, eps = K^-3 give
      (1/2 + O(K^-0.5))/K, K B <= 1/2 + 8/sqrt(K) + 12/K^2, at
      m* = K^2 e^K (1 + o(1)) intervals. Given m, some K with
      m*(K) <= m has K = log m - O(log(log m)), and monotonicity carries
      the bound to m: kappa_m <= (1/2 + o(1))/log m.
  So kappa_m >= 1/(32 log 16m) at every m, and
  1/4 <= liminf kappa_m log m <= limsup kappa_m log m <= 1/2.

DESIGN. One sweep. population yields 1196 cut sets under nine keys: five
width laws at m = 2..60, four reads each (Dirichlet; log-uniform over six
decades; many tiny widths then one wide; alternating wide and tiny;
sorted increasing; the third and fourth draw nothing, so their four
sets at each m are one set read four times, counted four times), the
growing-width profiles (p = 1 at m = 162 and
400, p = 2 at m = 400), rounding at m = 18, 66 and 162, and ten
deterministic exponential cut sets t -> t + eps e^{K(t - 1)} from 0
(K = 3..7, eps = 1/K and 1/K^2, m up to 7673). read_one takes a cut set
to its readings: m, E (cont_error, not computed at m = 7673), LB, G, R,
F(delta) at delta in {1/2, 1/4, 0.1} and F2 at the pairs of grid(m),
those delta with eta in {1/4, 1/8, (log m)^(-1/3)}, delta + eta < 1.
read_set folds the readings into a row a key: its sizes, four counts of
agreements (LB <= E, G <= LB, F <= R, F2 <= G, each to a factor
1 + 1e-9), E/LB's ends and the largest F/R, F(1/2)/R and F2/G. A kill is
a count of agreements short of its population, each population's size
counted by hand in SIZES. Two steps of the chain have no count of their
own: the floor 1/(32 log 16m) is F(1/2)/8, since 3/16 > 1/(4 log 16m) at
every m, so its step is K3 at delta = 1/2; and LB >= R/8 is K4 with
G - R/8 = (R - S_m)/8. The limit's delta = 8/log m enters no triple
below m = e^(64/7), about 9,348 (delta + 1/8 >= 1 until then), past
every m run, so F2 log m at the limit's choice is read from f2, which
takes log m, at m = 10^8 to 10^1024. The discrete arm scales a P to c
and reads erring_label's error against c^2 E(P).

CONTROLS. Before any sweep: cont_error at its known least (C1) and at
one interval, where E = 1/2 is four times LB (C0); sums, LB and G by
hand at the widths (1), (3, 1, 2)/6 and (1, 4, 2, 3)/10, with the
constants the plants use (H1); F and F2 at seven points by hand, each
term of each binding, F's log term and F2's first at two delta, since
at delta = 1/2 alone delta^2 is delta/2 (H2); the grid's lengths at
seven m, each
side of the three m where a pair joins (H3); exp_cuts at K = 0 and at
K = log 2 (H4); read_set on five readings written by hand, each
agreement failing once, the tolerance held between 5e-10 and 1e-8 and
read on its edge (H5).
After the sweep and before any kill is read, four plants go through
read_set with one field of every reading replaced, each owed failures
at some and not all of its population: C2 to C5 below.

Pinned as first printed, with no hand value: the plants' four counts,
the rows' E/LB ends, the three largest ratios, the nine (m, E) of the
exponential sets, four of the five F2 log m at the limit's choice, and
K2's least slack. The three random laws' rows and K2 are numpy's streams
at seeds 1567 and 7.

PREDICTIONS AND KILLS (written before the first run; restated where a
repair changed what a check reads, RUN RECORD says how).
  C1 min over a of E([0, a, 1]) is 3/14 at a = 2/7.
  C2 a planted break, LB with its pair constant doubled, fails LB <= E
     at some sets and not at all (the kill can fire, and not on the
     counter alone).
  K1 LB <= E at every set with an E, to a factor 1 + 1e-9; a set short
     kills step (2).
  K2 the discrete error at c = 200 and 400 at least c^2 E(P) - m^2 c.
  P3 E/LB bounded, 2 to 6, on the smooth profiles.
  P4 (a probe) the exponential cuts print E log m flat or falling in K
     (the cut set past m = 3000 has no E).
  C3 a planted break, F(delta) with its 1/log factor dropped,
     min(delta(2 - delta)/4, (1 - delta)^2), fails F <= R at some pairs
     and not at all.
  K3 F(delta) <= R at every set and delta in {1/2, 1/4, 0.1}; a pair
     short kills step (4), at delta = 1/2 the floor 1/(32 log 16m).
  C4 a planted break, R/4 in place of G (gain with its S_m coefficient
     1/4), fails G <= LB at some sets and not at all.
  C5 a planted break, G's S_m term dropped, the term that pays for the
     cases A < delta/2 and the wide last width, fails F2 <= G at some
     triples and not at all.
  K4 G <= LB at every set; a set short kills step (3).
  K5 F2 <= G at every (set, delta, eta); a triple short kills step (5).
  P6 the best F2 on the grid times log m under 0.1 at every m run.

FINDINGS (from the printed run; the controls passed first, C1 0.2142857
at a = 0.2857, and the plants before any kill was read: C2 fails at 27
of 1195 sets, C3 at 6 of 3588 pairs, C4 at 890 of 1196 sets, C5 at 2097
of 9349 triples).
  K1 silent: LB <= E at 1195 of 1195. E/LB runs from 1.20 (rounding) to
     4.00 (log-uniform, tiny then wide), its value at one interval.
  K2 held at 24 of 24: the least (e - c^2 E)/(m^2 c) is -0.0969.
  P3 failed as stated: E/LB 1.85 to 1.86 (p = 1) and 2.15 (p = 2) on
     the profiles, p = 1 under the predicted 2.
  P4 failed as stated: E log m reads 0.373, 0.396, 0.394, 0.435, 0.419
     at eps = 1/K, K = 3..7, and rises 0.401, 0.448, 0.464, 0.479 at
     eps = 1/K^2, K = 3..6, falling in neither arm, where the proof's
     o(1) is about 8/sqrt(K): no rate is read off it. The exponential
     cuts beat the growing-width profiles at nearby m: E 0.07247 at
     m = 406 against p = 2's 0.0800 at m = 400, and 0.05978 at m = 1100
     against 0.0738 at m = 1000 (the profiles' limits, erring_widths.py's
     print), so kappa_1100 < 0.0598 (E bounds kappa_m above by step 1).
  K3 silent at 3588 of 3588 pairs: the largest F/R is 0.3806, and
     0.1886 at delta = 1/2, both at exponential sets, so the floor
     1/(32 log 16m) is loose by 5 or more against R/8 at these m.
  K4 silent at 1196 of 1196 sets, K5 at 9349 of 9349 triples: the
     largest F2/G is 0.1924, at an exponential set.
  P6 held: the best F2 log m over the 69 values of m is 0.0531, at the
     largest, m = 7673. At the limit's choice it reads 0.0075, 0.0519,
     0.1364, 0.1849 and 0.2111 at m = 10^8, 10^16, 10^64, 10^256 and
     10^1024, against its limit 1/4: the 1/4 is asymptotic, and no run
     reaches it.

RUN RECORD. First runs, 11/11: K1 read the largest of three ratios
(LB/E, (R/8)/LB, floor/(R/8)) over the 1186 sets without the exponential
ones, K3 to K5 the largest ratios in a second pass over all 1196, and
the rows, P4's table and the sizes were compared with nothing. After a
code read, 22/22: one sweep, each kill a count of agreements set against
a size counted by hand, the plants through the same counter. C2's
constants were (1, 1), which every set fails; C4's bar was a largest
ratio above 1 where the unbroken G already prints 1.0000; C5 dropped
F2's eta term too. Cut, each for the reason DESIGN gives or as an
identity: the (R/8)/LB and floor/(R/8) ratios (the second read 0.1618
without the exponential sets), G/(R/8) by key (it is 2 - S_m/R) and its
prediction, the best F2 log m by key (a function of m alone), the
grid's delta = 8/log m, a second copy of F2 in closed form, the print
of step (6)'s 1/2 + 8/sqrt(K) + 12/K^2 at K = 7 (3.77, arithmetic on
three literals), and
exp_cuts' snap of a last cut within 1e-9 of 1, which never fired: every
cut set, here and in the scripts that import exp_cuts, is unchanged.
"""

import math
import os
from collections import namedtuple
from fractions import Fraction as Fr

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import numpy as np  # noqa: E402

from erring_label import error, rounding  # noqa: E402
from erring_widths import profile_at  # noqa: E402
from erring_zones import cont_error  # noqa: E402

CHECKS = []
TOL = 1 + 1e-9
DELTAS = (0.5, 0.25, 0.1)
ETAS = (0.25, 0.125)
Reading = namedtuple("Reading", "m E LB G R F F2")

# Counted by hand from the sets' m, the exponential sets' m being EXP's
# below. key: (n, with E, largest m, triples). A law is 59 values of m
# by 4 reads (two laws draw nothing: one set read four times), its
# triples 4 * (6 * 59 + 57 + 50): six pairs of the grid
# at every m, eta = (log m)^(-1/3) beside delta = 0.1 from m = 4 and
# beside 1/4 from m = 11. Every other set has m >= 11 and 8 triples, the
# one at m = 7673 > e^8 a ninth; that set alone has no E.
SIZES = {
    "dirichlet": (236, 236, 60, 1844),
    "log-uniform": (236, 236, 60, 1844),
    "tiny then wide": (236, 236, 60, 1844),
    "alternating": (236, 236, 60, 1844),
    "sorted": (236, 236, 60, 1844),
    "profile p = 1": (2, 2, 400, 16),
    "profile p = 2": (1, 1, 400, 8),
    "rounding": (3, 3, 162, 24),
    "exponential": (10, 9, 7673, 81),
}
# As first printed, no hand value. key: E/LB's least and largest.
ENDS = {
    "dirichlet": "1.78..2.94",
    "log-uniform": "1.65..4.00",
    "tiny then wide": "3.95..4.00",
    "alternating": "2.06..3.99",
    "sorted": "1.70..3.96",
    "profile p = 1": "1.85..1.86",
    "profile p = 2": "2.15..2.15",
    "rounding": "1.20..1.41",
    "exponential": "1.63..1.90",
}
# As first printed: (K, 1/eps, m, E) of the exponential sets, in order.
EXP = [(3, 3, 21, "0.12259"), (3, 9, 59, "0.09840"), (4, 4, 56, "0.09833"),
       (4, 16, 217, "0.08324"), (5, 5, 150, "0.07873"),
       (5, 25, 740, "0.07016"), (6, 6, 406, "0.07247"),
       (6, 36, 2418, "0.06150"), (7, 7, 1100, "0.05978"),
       (7, 49, 7673, "none")]
# F2 log m at delta = 8/log m, eta = (log m)^(-1/3), m = 10^ex: 0.2111 by
# hand (L = 2357.85, the log term 0.84912/(4 * 2370.61)), the rest as
# first printed.
LIMIT = [(8, "0.0075"), (16, "0.0519"), (64, "0.1364"), (256, "0.1849"),
         (1024, "0.2111")]


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


def lb(cuts, k4=1 / 4):
    """LB(P) of a cut set, step (2)."""
    w = np.diff(np.asarray(cuts, dtype=float))
    pair = sum(w[a] * np.minimum(w[a], w[a + 1:]).sum()
               for a in range(len(w)))
    return (w * w).sum() / 8 + k4 * pair


def cuts_of(w):
    w = np.asarray(w, dtype=float)
    return np.concatenate([[0.0], np.cumsum(w / w.sum())])


def laws(m, rng):
    yield "dirichlet", rng.dirichlet(np.ones(m))
    yield "log-uniform", 10.0 ** rng.uniform(-6, 0, m)
    yield "tiny then wide", np.append(np.full(m - 1, 1e-4), 1.0)
    yield "alternating", np.where(np.arange(m) % 2 == 0, 1.0, 1e-3)
    yield "sorted", np.sort(rng.exponential(1.0, m) ** 3)


def partitions(rng):
    for m in range(2, 61):
        for _ in range(4):
            for name, w in laws(m, rng):
                yield name, cuts_of(w)
    for c, p, m, u in [(4000, 1, 162, 0.8), (4000, 1, 400, 0.8),
                       (4000, 2, 400, 0.8)]:
        yield f"profile p = {p}, m = {m}", np.array(profile_at(c, p, m, u)) / c
    for m, u in [(18, 0.8), (66, 0.8), (162, 0.8)]:
        cu = rounding(4000, u * 4000 / (m - 2), u)
        yield f"rounding m = {len(cu) - 1}", np.array(cu) / 4000


def exp_cuts(K, eps):
    cuts, t = [0.0], 0.0
    while t < 1:
        t = min(t + eps * math.exp(K * (t - 1)), 1.0)
        cuts.append(t)
    return cuts


def population():
    """(key, cuts): partitions' 1186, then ten exponential cut sets."""
    for name, cu in partitions(np.random.default_rng(1567)):
        yield name.split(",")[0].split(" m")[0], cu
    for K in (3, 4, 5, 6, 7):
        for eps in (1 / K, 1 / K ** 2):
            yield "exponential", exp_cuts(K, eps)


def floor_delta(m, delta):
    """F(delta): step (4) at a free mass delta, a lower bound on R."""
    return min(delta * (2 - delta) / 4,
               (1 - delta) ** 2 / math.log(4 * m / delta ** 2))


def sums(cu):
    """S_m, sum_{j<m} S_j and R of a cut set's sorted widths."""
    S = np.cumsum(np.sort(np.diff(np.asarray(cu, dtype=float))) ** 2)
    return S[-1], S[:-1].sum(), S.sum()


def gain(Sm, pair, k8=1 / 8):
    """G = S_m/8 + (1/4) sum_{j<m} S_j, step (3)'s bound under LB."""
    return k8 * Sm + pair / 4


def grid(m):
    """The (delta, eta) of the run at m: those with delta + eta < 1."""
    es = ETAS + (math.log(m) ** (-1 / 3),)
    return [(d, e) for d in DELTAS for e in es if d + e < 1]


def f2(L, d, e):
    """F2(delta, eta) at log m = L, step (5)'s floor under G."""
    return min(d * (2 - d) / 32, e * e / 8,
               (1 - d - e) ** 2 / (4 * (math.log(4) + L - 2 * math.log(d))))


def read_one(cu, E=None):
    """A cut set's readings: m, E as handed in, LB, G, R, F at each delta
    and F2 at each pair of the grid."""
    m = len(cu) - 1
    Sm, pair, R = sums(cu)
    return Reading(m, E, lb(cu), gain(Sm, pair), R,
                   [floor_delta(m, d) for d in DELTAS],
                   [f2(math.log(m), d, e) for d, e in grid(m)])


def read_set(readings):
    """A row a key, from (key, reading) pairs: the sizes (n, those with an
    E, the largest m, the triples), the agreements LB <= E, G <= LB,
    F <= R and F2 <= G, each at the factor TOL, E/LB's least and largest,
    and the largest F/R, F(1/2)/R and F2/G."""
    rows = {}
    for key, r in readings:
        row = rows.setdefault(key, dict(
            n=0, nE=0, m=0, triples=0, okE=0, okG=0, okF=0, okT=0,
            lo=math.inf, hi=0.0, F=0.0, Fhalf=0.0, T=0.0))
        row["n"] += 1
        row["m"] = max(row["m"], r.m)
        row["triples"] += len(r.F2)
        if r.E is not None:
            row["nE"] += 1
            row["okE"] += r.LB <= r.E * TOL
            row["lo"] = min(row["lo"], r.E / r.LB)
            row["hi"] = max(row["hi"], r.E / r.LB)
        row["okG"] += r.G <= r.LB * TOL
        row["okF"] += sum(f <= r.R * TOL for f in r.F)
        row["okT"] += sum(v <= r.G * TOL for v in r.F2)
        row["F"] = max(row["F"], max(r.F) / r.R)
        row["Fhalf"] = max(row["Fhalf"], r.F[0] / r.R)
        row["T"] = max(row["T"], max(r.F2) / r.G)
    return rows


def sweep():
    """[(key, cuts, reading)] over the population, E by cont_error where
    m <= 3000 (its cells at m = 7673 are past a run's memory)."""
    out = []
    for key, cu in population():
        E = cont_error(cu) if len(cu) <= 3001 else None
        out.append((key, cu, read_one(cu, E)))
    return out


def total(rows, field):
    return sum(row[field] for row in rows.values())


def control_plant(pop, count, field, f):
    """The agreements `count` over the population once every reading has
    `field` replaced by f(cuts, reading)."""
    rows = read_set((k, r._replace(**{field: f(cu, r)})) for k, cu, r in pop)
    return total(rows, count)


def section_controls():
    print("controls, before any sweep")
    a = min(np.linspace(0.2, 0.36, 1601), key=lambda t: cont_error([0, t, 1]))
    e = cont_error([0, a, 1])
    check("C1: min E([0, a, 1]) is 3/14 near a = 2/7",
          abs(e - 3 / 14) < 1e-6 and abs(a - 2 / 7) < 1e-3,
          f"{e:.7f} at a = {a:.4f}, 3/14 = {3 / 14:.7f}")
    one = cont_error([0, 1])
    check("C0: E of one interval is 1/2, four times its LB",
          abs(one - 0.5) < 1e-12 and abs(one / lb([0, 1]) - 4) < 1e-12,
          f"E {one:.6f}, E/LB {one / lb([0, 1]):.6f}")
    hand = [((1,), (1, 0, 1), Fr(1, 8), Fr(1, 8)),
            ((3, 1, 2), (Fr(7, 18), Fr(1, 6), Fr(5, 9)), Fr(17, 144),
             Fr(13, 144)),
            ((1, 4, 2, 3), (Fr(3, 10), Fr(1, 5), Fr(1, 2)), Fr(21, 200),
             Fr(7, 80))]
    got, want = [], []
    for w, s, lo, g in hand:
        cu = cuts_of(w)
        Sm, pair, R = sums(cu)
        got += [Sm, pair, R, lb(cu), gain(Sm, pair)]
        want += [*s, lo, g]
    cu = cuts_of((3, 1, 2))
    Sm, pair, R = sums(cu)
    got += [lb(cu, 1 / 2), gain(Sm, pair, 1 / 4), gain(Sm, pair, 0),
            gain(Sm, pair) - (R / 4 - Sm / 8)]
    want += [Fr(3, 16), Fr(5, 36), Fr(1, 24), 0]
    ok = sum(abs(x - float(y)) < 1e-14 for x, y in zip(got, want))
    check("H1: sums, LB and G by hand at the widths (1), (3, 1, 2)/6 and "
          "(1, 4, 2, 3)/10, the plants' constants at the second",
          (ok, len(got)) == (19, 19), f"{ok} of {len(got)}")
    L2 = math.log(2)
    got = [floor_delta(2, 0.1), floor_delta(4, 0.5), floor_delta(4, 0.25),
           f2(L2, 0.1, 0.25), f2(L2, 0.05, 0.25), f2(L2, 0.5, 0.125),
           f2(L2, 0.5, 0.25)]
    want = [19 / 400, 1 / (4 * math.log(64)), 9 / (16 * math.log(256)),
            19 / 3200, 39 / 12800, 1 / 512, 1 / (64 * math.log(32))]
    ok = sum(abs(x - y) < 1e-15 for x, y in zip(got, want))
    check("H2: F and F2 by hand, each term binding, F's log term and F2's "
          "first at two delta", (ok, len(got)) == (7, 7),
          f"{ok} of {len(got)}: " + ", ".join(f"{x:.6f}" for x in got))
    lens = [len(grid(m)) for m in (2, 3, 4, 10, 11, 2980, 2981)]
    six = [(d, e) for d in (0.5, 0.25, 0.1) for e in (0.25, 0.125)]
    check("H3: the grid's lengths at m = 2, 3, 4, 10, 11, 2980, 2981, and "
          "its six pairs at m = 2",
          lens == [6, 6, 7, 7, 8, 8, 9] and grid(2) == six, f"{lens}")
    flat = np.diff(exp_cuts(0, 0.3))
    two = exp_cuts(math.log(2), 0.5)
    ok = (len(flat) == 4 and np.abs(flat - [0.3, 0.3, 0.3, 0.1]).max() < 1e-12
          and len(two) == 5
          and np.abs(np.array(two) - [0, 0.25, 0.5473, 0.9126, 1]).max() < 5e-5
          and two[-1] == 1.0)
    check("H4: exp_cuts by hand at K = 0, eps = 0.3 and at K = log 2, "
          "eps = 1/2", ok,
          "widths " + ", ".join(f"{x:.4f}" for x in flat) + "; cuts "
          + ", ".join(f"{x:.4f}" for x in two))
    x = [Reading(3, 0.2, 0.1, 0.05, 1.0, [0.5, 0.25, 0.125], [0.01, 0.02]),
         Reading(5, None, 0.1, 0.2, 0.2, [0.1, 0.3, 0.15], [0.3, 0.1, 0.1]),
         Reading(4, 0.1 * (1 - 1e-8), 0.1, 0.1, 1.0, [0.25, 0.5, 0.125],
                 [0.1])]
    y = Reading(2, 1.0, TOL, TOL * TOL, 1.0, [TOL] * 3, [TOL * TOL * TOL])
    u = 1 + 5e-10
    z = Reading(2, 1.0, u, u * u, 1.0, [u] * 3, [u * u * u])
    rows = read_set([("x", r) for r in x] + [("y", y), ("z", z)])
    rx = rows["x"]
    held = [[rows[k][f] for f in ("okE", "okG", "okF", "okT")]
            for k in ("y", "z")]
    counts = [rx[f] for f in ("n", "nE", "m", "triples", "okE", "okG", "okF",
                              "okT")]
    ends = [rx[f] for f in ("lo", "hi", "F", "Fhalf", "T")]
    ok = (counts == [3, 2, 5, 6, 1, 2, 8, 5]
          and np.abs(np.array(ends) - [1 - 1e-8, 2, 1.5, 0.5, 1.5]).max()
          < 1e-12
          and held == [[1, 1, 3, 1], [1, 1, 3, 1]]
          and list(rows) == ["x", "y", "z"])
    check("H5: read_set on five readings by hand: each agreement failing "
          "once, LB <= E by a factor 1e-8, and each holding at 5e-10 "
          "and on the tolerance's edge", ok,
          f"{counts}, {', '.join(f'{v:.6f}' for v in ends)}, {held}")


def section_discrete():
    """K2: the discrete error at c against c^2 E(P) - m^2 c."""
    print("K2: step (1)'s lower count, discrete against continuum")
    rng = np.random.default_rng(7)
    worst, n, ok = math.inf, 0, 0
    for m in (2, 3, 5, 8):
        for _ in range(3):
            P = np.sort(rng.choice(np.arange(1, 40), m - 1, replace=False))
            P = np.concatenate([[0], P, [40]]) / 40
            E = cont_error(P)
            for c in (200, 400):
                cu = tuple(int(round(x * c)) for x in P)
                d = error(cu + (2 * c - 1,), 2 * c - 1)
                slack = (d - c * c * E) / (m * m * c)
                n += 1
                ok += slack >= -1
                worst = min(worst, slack)
    check("K2: e >= c^2 E(P) - m^2 c at the 24 runs", (ok, n) == (24, 24),
          f"{ok} of {n}")
    check("K2: the least (e - c^2 E)/(m^2 c) as first printed",
          f"{worst:+.4f}" == "-0.0969", f"{worst:+.4f}")


def section_sweep():
    """C2 to C5, the sizes, K1 and K3 to K5, the pins, P4 and P6."""
    print("the sweep: E >= LB >= G, R >= F(delta), G >= F2")
    pop = sweep()
    rows = read_set((k, r) for k, _, r in pop)
    plants = [
        ("C2: LB's pair constant doubled fails LB <= E at some sets, not "
         "all", "okE", "nE", "LB", lambda cu, r: lb(cu, 1 / 2)),
        ("C3: F without its 1/log fails F <= R at some pairs, not all",
         "okF", None, "F",
         lambda cu, r: [min(d * (2 - d) / 4, (1 - d) ** 2) for d in DELTAS]),
        ("C4: G with S_m's coefficient 1/4 fails G <= LB at some sets, not "
         "all", "okG", "n", "G",
         lambda cu, r: gain(*sums(cu)[:2], 1 / 4)),
        ("C5: G with its S_m term dropped fails F2 <= G at some triples, "
         "not all", "okT", "triples", "G",
         lambda cu, r: gain(*sums(cu)[:2], 0)),
    ]
    planted = []
    for name, count, size, field, f in plants:
        of = total(rows, size) if size else 3 * total(rows, "n")
        planted.append(int(of - control_plant(pop, count, field, f)))
        check(name, 0 < planted[-1] < of, f"{planted[-1]} of {of}")
    if not all(CHECKS):
        print("    CONTROL FAILED: the sweep is not read.")
        return
    for key, r in rows.items():
        print(f"    {key:16s} n = {r['n']:3d} ({r['nE']:3d} with E), m <= "
              f"{r['m']:4d}, {r['triples']:4d} triples: E/LB "
              f"{r['lo']:.2f}..{r['hi']:.2f}")
    sizes = {k: (r["n"], r["nE"], r["m"], r["triples"])
             for k, r in rows.items()}
    n, nE, tr = (total(rows, f) for f in ("n", "nE", "triples"))
    check("the sizes by key are the hand counts: sets, sets with E, the "
          "largest m, triples",
          sizes == SIZES and (n, nE, tr) == (1196, 1195, 9349),
          f"{n} sets, {nE} with E, {3 * n} pairs, {tr} triples")
    check("K1: LB <= E at the 1195 sets with E",
          total(rows, "okE") == 1195, f"{total(rows, 'okE')} of {nE}")
    check("K4: G <= LB at the 1196 sets", total(rows, "okG") == 1196,
          f"{total(rows, 'okG')} of {n}")
    check("K3: F(delta) <= R at the 3588 pairs", total(rows, "okF") == 3588,
          f"{total(rows, 'okF')} of {3 * n}")
    check("K5: F2 <= G at the 9349 triples", total(rows, "okT") == 9349,
          f"{total(rows, 'okT')} of {tr}")
    ends = {k: f"{r['lo']:.2f}..{r['hi']:.2f}" for k, r in rows.items()}
    tops = [max((r[f], k) for k, r in rows.items())
            for f in ("F", "Fhalf", "T")]
    shown = ", ".join(f"{name} {v:.4f} ({k})" for name, (v, k) in
                      zip(("F/R", "F(1/2)/R", "F2/G"), tops))
    check("the plants' counts, the rows' E/LB ends and the largest F/R, "
          "F(1/2)/R and F2/G as first printed",
          planted == [27, 6, 890, 2097] and ends == ENDS
          and [f"{v:.4f}" for v, _ in tops]
          == ["0.3806", "0.1886", "0.1924"], f"{planted}, {shown}")
    print("P4: exponential cuts t -> t + eps e^(K (t - 1))")
    ok, logs = 0, []
    for (K, inv, m, pin), (_, _, r) in zip(EXP, pop[-10:]):
        E = "none" if r.E is None else f"{r.E:.5f}"
        ok += (r.m, E) == (m, pin)
        tail = ""
        if r.E is not None:
            logs.append(r.E * math.log(r.m))
            tail = f", E log m {logs[-1]:.3f}"
        print(f"    K = {K}  eps = 1/{inv}: m = {r.m:4d}, E {E}{tail}")
    span = f"{min(logs):.3f}..{max(logs):.3f}"
    check("P4: the ten sets' m and E as first printed, E log m from 0.373 "
          "to 0.479", ok == 10 and span == "0.373..0.479",
          f"{ok} of {len(EXP)}, E log m {span}")
    ms = sorted({r.m for _, _, r in pop})
    best = {m: max(f2(math.log(m), d, e) for d, e in grid(m)) * math.log(m)
            for m in ms}
    top = max(ms, key=best.get)
    check("P6: the best F2 log m of the run is at m = 7673, where it is "
          "(19/3200) log 7673",
          top == 7673 and len(ms) == 69
          and abs(best[top] - 19 / 3200 * math.log(7673)) < 1e-15,
          f"{best[top]:.4f} at m = {top}, over {len(ms)} values of m")
    print("    the limit's choice delta = 8/log m, eta = (log m)^(-1/3):")
    ok = 0
    for ex, pin in LIMIT:
        L = ex * math.log(10)
        d, e = 8 / L, L ** (-1 / 3)
        v = f"{f2(L, d, e) * L:.4f}"
        ok += v == pin and d + e < 1
        print(f"    m = 10^{ex:<5d} F2 log m {v}")
    check("F2 log m at the limit's choice, m = 10^8 to 10^1024: 0.2111 at "
          "the last by hand, the rest as first printed", ok == 5,
          f"{ok} of {len(LIMIT)}")


def main():
    section_controls()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        raise SystemExit(1)
    section_discrete()
    section_sweep()
    print(f"{sum(CHECKS)}/{len(CHECKS)} checks passed")
    raise SystemExit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()