erring_label.py

Checks: SIZE: The erring labelling theorem; SIZE: Rounding's carry at many labels property; SIZE: Doubling cuts against the front rule.

Cited on: SIZE.

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

"""
erring_label.py -- a monotone size label that addition keeps up to an
error: the least error at each reach.

QUESTION. mu nondecreasing from [0, N) onto s labels, the cuts
0 = c_0 < c_1 < ... < c_{s-1} < c_s = N, label a the interval
I_a = [c_a, c_{a+1}). A(a, b) is a plurality value of mu(x + y) over the
ordered pairs (x, y) in I_a x I_b with x + y < N; the ERROR is the number
of such pairs where mu(x + y) differs from A, the REACH the number of
pairs x < y with mu(x) < mu(y). Which cuts trace the front, the least
error at reach at least r, and in what closed form?

THE ARGUMENT (written before this script; T(n) = n(n + 1)/2).
  (D1) Zero error is the additive labelling law's hypothesis, so mu is
       exact on [0, x0) and d-periodic after; monotone forces d = 1 and
       mu(x) = x below x0, so saturation min(x, s - 1) is the only
       zero-error labelling at 1 < s < N.
  (D2) Every pair touching the top interval sums into it, so only the
       cells inside [0, c)^2 err, c = c_{s-1}; once 2c - 1 <= N none of
       their pairs is truncated and the error does not move with N.
  (D3) s = 2: E = C(c, 2), R = c(N - c) for c <= (N + 1)/2. For c > N/2,
       d = N - c, the one erring cell sends d(2c - 1 - d)/2 pairs into
       [c, N), fewer than its T(c) below c, so E = d(2c - 1 - d)/2, which
       exceeds C(d, 2) by d(c - d) > 0: c is beaten by d at equal reach.
       On c = 1..floor(N/2) reach and error both rise strictly, so these
       c are the front.
  (D4) s = 3, alpha = c_1, beta = c - alpha >= alpha, 2c - 1 <= N:
       E = 3 C(alpha, 2) + T(c - 2 alpha): the cell [alpha, c)^2 sends
       T(beta - alpha) <= T(beta - 1) < beta^2/2 of its sums below c,
       the fewer side; continuum optimum alpha = 2c/7, E ~ (3/14) c^2.
       For beta < alpha the cells err C(alpha, 2), T(beta), T(beta) and
       0, so E = C(alpha, 2) + 2 T(beta); its swap alpha' = beta errs at
       most 3 C(beta, 2) + T(alpha - beta), and twice the difference is
       2[alpha(beta - 1) - beta^2 + 3 beta] >= 2(3 beta - 1) > 0. So the
       least error at s = 3 is D4's minimum over alpha <= c/2.
  (D5) At reach r much less than N^2 the front is E ~ kappa_{s-1}
       (r/N)^2, kappa_m the limsup over c of e_m(c)/c^2, e_m(c) the least
       error of m intervals filling [0, c) with sums >= c in the overflow
       label. (At fixed c the limit over m is 0: m = c singletons is
       saturation.)
  NEIGHBOURS. Ratio-2 cuts with the plurality table are the floating-
  point exponent of a sum; the RNS core function and approximate-CRT
  sign detection are size estimates read off the residues, not kept
  from labels alone; rounding to multiples of w is the high digit of
  mixed radix rounded, its error the dropped carry.

PREDICTIONS AND KILLS (written before the run).
  K1 zero-error cut sets are saturation alone, s = 2..6, N = s+1..24.
  K2 the s = 2 front is c <= ceil(N/2), E = C(c, 2), N = 3..60. The
     first run compared the front against every c <= ceil(N/2) and
     printed 29 faults, one per odd N: there c = (N + 1)/2 ties
     c = (N - 1)/2 in reach with more error, so it is off the front.
     The prediction failed there; the check now asks for
     c = 1..floor(N/2).
     D3's c > N/2 count is checked at every such c, N = 3..60.
  K3 the error of a cut set with 2c - 1 <= N is the same at N + 7,
     s = 3, 4, N = 8..30.
  K4 e_2(c) equals D4's minimum over alpha, c = 2..120; D4's beta < alpha
     count and its swap at every alpha > c/2, c = 3..80.
  K5 e_m(c)/c^2 printed: e_2 within 0.01 of 3/14 at c = 120; e_3 below.
  K6 cuts in ratio 2 (t, 2t, 4t, ...) against the front at their reach,
     s = 3, 4. Written as "dies if they are equal", no scale named; the
     engine fails unless the scales that err the front's least at their
     reach are exactly s = 3, t = 1, 2, 3 and 20 (t = 1 is saturation
     there) and s = 4, t = 1.
  K7 (written after K1..K6's prints, the construction read off the
     witnesses of a local search that is not in this script) rounding
     of width w with a top interval [4c/5, c) tends to 1/10: dies if
     w = 10, c = 2000 prints outside [0.0990, 0.105].

FINDINGS (from the printed run; the controls passed first).
  K1 held: saturation is the only zero-error cut set at all 100 cells
     (s, N), s = 2..6, N = s+1..24; D1 proves it at every 1 < s < N.
  K2 held as repaired: the s = 2 front is c = 1..floor(N/2),
     E = C(c, 2), at each of the 58 N = 3..60; D3's count held at all
     870 cut sets with c > N/2.
  K3 held: 4740 cut sets with 2c - 1 <= N err the same at N + 7. One
     cut set past the hypothesis is read, and its error moves: the cuts
     (1, 6) at N = 8, where 2c - 1 = N + 3, err 9, and 10 at N = 15.
  K4 held: e_2(c) equals D4's minimum at every c = 2..120, and all 1560
     cut sets with beta < alpha, c = 3..80, err C(alpha, 2) + 2 T(beta)
     and more than their swap.
  K5 held: e_m(c)/c^2 at the largest c run, 0.4958 (m = 1, c = 120),
     0.2125 (m = 2, c = 120; 3/14 = 0.2143), 0.1738 (m = 3, c = 120),
     0.1572 (m = 4, c = 60), each rising over the c run, m = 1 and 2
     under their limits 1/2 and 3/14. Witnesses (0, 35, 120),
     (0, 22, 69, 120), and (0, 8, 25, 41, 60), the first of two at
     m = 4: the inner cut ratio is 120/35 = 3.4 at m = 2, toward 7/2,
     and the upper intervals of the m = 4 witness (17, 16, 19) are near
     equal, not geometric. The rows at m = 1 and m = 2 are read
     against C(c, 2) and D4's values by hand; those at m = 3 and m = 4
     have no hand value, and their check holds them to this script's
     first printed run.
  K6 held as the engine reads it, mixed as written: ratio-2 cuts err
     the front's least at their reach at s = 3, N = 60 at t = 1, 2, 3
     and 20 (saturation, the two smallest scales, and the uniform cuts,
     which reach the most alone where s divides N) and more than it at
     every other scale run; at s = 4, N = 40 the least at t = 1 only;
     33 of the 38 scales above. Of the five all but s = 3, t = 3 are
     points of the front; that one errs the least at its reach and is
     not a point, so another cut set errs the same at more reach. The
     largest E over the front's is 4.8x (s = 3, t = 29: 516 against
     108; at s = 4, 2.9x, t = 9: 232 against 81). The floating-point
     exponent is not the least-error label past its smallest scales,
     save where its cuts are the uniform ones (s = 3, t = 20).
  K7 the construction: round(x / w) on [0, 4c/5), the wide label
     [4c/5, c) (K7's top interval, below the overflow label),
     c = 2000, prints 0.1301, 0.1149, 0.1077, 0.1028 at w = 100, 50,
     25, 10 (m = 18, 34, 66, 162), toward the continuum
     u^2/8 + (1 - u)^2/2 at u = 4/5, which is 1/10: rounding errs on 1/4
     of the pairs it sees, the carry of a rounded high digit, and the
     wide label's cells err where the sum crosses c. At fixed m the
     construction's e/c^2 holds still in c (w = c/20, m = 18: 0.1299,
     0.1302 at c = 1000, 4000; m = 34: 0.1149, 0.1150; m = 66: 0.1075,
     0.1074); a reading bounds e_m(c)/c^2 at its c alone, no limit in c
     is printed here, and the continuum argument above, a sketch, puts
     the limsup of kappa_m over m at most 1/10. The ten errors have no
     hand value: their check holds them to this script's first printed
     run, and the pair loop reads one of them (c = 1000, w = 50:
     129925). Whether widths growing with position err below 1/10 is
     erring_widths.py's question.

CONTROLS. s = N has error 0 and reach C(N, 2); saturation has error 0
and reach (s - 1)(N - s + 1) + C(s - 1, 2); the closed-form cell counts
agree with a pair-by-pair count on all 561 cut sets at N = 12,
s = 2..5, and on the rounding cut sets at c = 30, w = 8 and c = 1000,
w = 50. By hand: the
(reach, error) of the six cut sets at N = 5, s = 3, which are (7, 0),
(8, 1), (7, 3), (8, 3), (8, 3), (7, 5) at inner cuts (1, 2), (1, 3),
(1, 4), (2, 3), (2, 4), (3, 4), and their front, (1, 2) and (1, 3);
D4's one-interval case, 3 C(36, 2) + T(48) = 3066 at the cuts
(0, 36, 120); rounding's cuts at c = 30, w = 8, at c = 10, w = 4,
u = 0.6, where the half-cut 6 meets the wide label's cut and is not a
cut, and at
w = 25, where they round to even, widths 26 and 24 by turns. The front
is set against its definition, the (reach, error) pairs no other pair
meets in both, over all 253 and 1771 cut sets at N = 24, s = 3 and 4
(20 and 23 points, read against that definition only). Of the other
counts a check prints, these are set against their sizes by hand: 28 and 378
(the first two controls), 100 (K1), 58 and 870 (K2), 4740 (K3: 10 at
N = 8 and 2365 at each parity after), 119 and 1560 (K4),
C(c - 1, m - 1) at K5's twelve keys, 38 (K6: 29 and 9 scales), and
K6's two E by hand, 516 = 406 + 55 + 55 and 232 = 36 +
2 * 36 + 2 * 26 + 2 * 36; the front's 108 and 81 beside them have no
hand value and are this script's first printed run's.
"""

from itertools import combinations
from math import comb

CHECKS = []

# (reach, error) of the six cut sets at N = 5, s = 3, and their front,
# by hand (CONTROLS).
H5 = {(0, 1, 2, 5): (7, 0), (0, 1, 3, 5): (8, 1), (0, 1, 4, 5): (7, 3),
      (0, 2, 3, 5): (8, 3), (0, 2, 4, 5): (8, 3), (0, 3, 4, 5): (7, 5)}
H5_FRONT = [(7, 0, (0, 1, 2, 5)), (8, 1, (0, 1, 3, 5))]

# K5: the c run at each m; e_2(c) and its witnesses by hand; at m = 3, 4
# the first printed run's e, first witness and count of witnesses.
K5_RUNS = {1: (30, 60, 120), 2: (30, 60, 120), 3: (30, 60, 120),
           4: (20, 40, 60)}
K5_HAND = {(2, 30): (186, [(0, 9, 30)]),
           (2, 60): (759, [(0, 17, 60), (0, 18, 60)]),
           (2, 120): (3060, [(0, 35, 120)])}
K5_SEEN = {(3, 30): (152, (0, 6, 17, 30), 1),
           (3, 60): (621, (0, 11, 34, 60), 2),
           (3, 120): (2503, (0, 22, 69, 120), 1),
           (4, 20): (60, (0, 3, 9, 14, 20), 1),
           (4, 40): (248, (0, 6, 17, 28, 40), 1),
           (4, 60): (566, (0, 8, 25, 41, 60), 2)}

# K6: the scales on the front, and at each s the scale of widest gap
# with its (E, front E): the E by hand, the front's the first run's.
K6_ON = [(3, 1), (3, 2), (3, 3), (3, 20), (4, 1)]
K6_POINTS = [(3, 1), (3, 2), (3, 20), (4, 1)]
K6_WIDEST = {3: (29, 516, 108), 4: (9, 232, 81)}

# K7: (c, w) -> (m by hand, e as the first run printed it).
K7_ROWS = {(2000, 100): (18, 520475), (2000, 50): (34, 459625),
           (2000, 25): (66, 430614), (2000, 10): (162, 411395),
           (1000, 50): (18, 129925), (4000, 200): (18, 2083450),
           (1000, 25): (34, 114938), (4000, 100): (34, 1839875),
           (1000, 12.5): (66, 107501), (4000, 50): (66, 1719025)}


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 g(t):
    return t * (t + 1) // 2 if t > 0 else 0


def below(n1, n2, t):
    """#{(i, j) : 0 <= i < n1, 0 <= j < n2, i + j < t}."""
    return g(t) - g(t - n1) - g(t - n2) + g(t - n1 - n2)


def error(cuts, N):
    """Cell by cell (a, b): the pairs with x + y < N, less the most
    that land in one label."""
    s = len(cuts) - 1
    E = 0
    for a in range(s):
        u1, n1 = cuts[a], cuts[a + 1] - cuts[a]
        for b in range(s):
            u2, n2 = cuts[b], cuts[b + 1] - cuts[b]
            base = u1 + u2
            land = [below(n1, n2, min(cuts[c + 1], N) - base)
                    - below(n1, n2, cuts[c] - base) for c in range(s)]
            E += below(n1, n2, N - base) - max(land)
    return E


def reach(cuts):
    L = [cuts[i + 1] - cuts[i] for i in range(len(cuts) - 1)]
    return (sum(L) ** 2 - sum(x * x for x in L)) // 2


def error_brute(cuts, N):
    s = len(cuts) - 1
    mu = [a for a in range(s) for _ in range(cuts[a], cuts[a + 1])]
    cnt = {}
    for x in range(N):
        for y in range(N - x):
            cnt.setdefault((mu[x], mu[y]), [0] * s)[mu[x + y]] += 1
    return sum(sum(v) - max(v) for v in cnt.values())


def cutsets(N, s):
    for inner in combinations(range(1, N), s - 1):
        yield (0,) + inner + (N,)


def points(N, s):
    return [(reach(c), error(c, N), c) for c in cutsets(N, s)]


def front(N, s):
    """Pareto points (R, E, cuts): no other cut set has reach >= R and
    error <= E with one strict; one witness each."""
    pts = sorted(points(N, s), key=lambda p: (-p[0], p[1]))
    out, best = [], None
    for R, E, c in pts:
        if best is None or E < best:
            out.append((R, E, c))
            best = E
    return out[::-1]


def undominated(pts):
    """The front's definition, pair against pair: the (R, E) of pts
    that no other (R, E) of pts meets in both reach and error."""
    pairs = {(R, E) for R, E, _ in pts}
    return sorted(p for p in pairs
                  if not any(q != p and q[0] >= p[0] and q[1] <= p[1]
                             for q in pairs))


def least_at(fr, r):
    return min(E for R, E, _ in fr if R >= r)


def sat(N, s):
    return tuple(range(s)) + (N,)


def inner(m, c):
    """e_m(c), the cut sets attaining it and the count of cut sets
    read: m intervals fill [0, c), the overflow label above,
    N = 2c - 1."""
    N = 2 * c - 1
    best, arg, n = None, [], 0
    for mid in combinations(range(1, c), m - 1):
        cuts = (0,) + mid + (c, N)
        E = error(cuts, N)
        n += 1
        if best is None or E < best:
            best, arg = E, [cuts[:-1]]
        elif E == best:
            arg.append(cuts[:-1])
    return best, arg, n


def d4(c):
    """D4's least error at top cut c, over 1 <= alpha <= c/2."""
    return min(3 * comb(al, 2) + g(c - 2 * al)
               for al in range(1, c // 2 + 1))


def rounding(c, w, u):
    """Cuts at (k + 1/2) w rounded half to even on [0, u c), round(x / w)'s
    but at ties, then one wide label [u c, c)."""
    top = round(u * c)
    mid, k = [], 0
    while round((k + 0.5) * w) < top:
        mid.append(round((k + 0.5) * w))
        k += 1
    return (0,) + tuple(mid) + (top, c)


def section_controls():
    print("controls")
    ok = sum(error(tuple(range(N + 1)), N) == 0
             and reach(tuple(range(N + 1))) == comb(N, 2)
             for N in range(2, 30))
    check("control: s = N errs nowhere and reaches C(N, 2)", ok == 28,
          f"{ok} of 28, N = 2..29")
    ok = sum(error(sat(N, s), N) == 0 and reach(sat(N, s))
             == (s - 1) * (N - s + 1) + comb(s - 1, 2)
             for N in range(3, 30) for s in range(2, N))
    check("control: saturation errs nowhere, reach by hand", ok == 378,
          f"{ok} of 378, N = 3..29, s = 2..N-1")
    ok = n = 0
    for s in range(2, 6):
        for c in cutsets(12, s):
            n += 1
            ok += error(c, 12) == error_brute(c, 12)
    check("control: closed-form cell counts match pair-by-pair counts",
          ok == n == 561, f"{ok} of {n} cut sets at N = 12, s = 2..5")
    got = {c: (R, E) for R, E, c in points(5, 3)}
    ok = sum(got.get(c) == v for c, v in H5.items())
    check("control: reach and error by hand at N = 5, s = 3",
          ok == len(got) == 6, f"{ok} of {len(got)} cut sets")
    check("control: the front and the undominated pairs by hand at N = 5",
          front(5, 3) == H5_FRONT
          and undominated(points(5, 3)) == [p[:2] for p in H5_FRONT],
          f"front {[p[2][1:-1] for p in front(5, 3)]}")
    for s, size in ((3, 253), (4, 1771)):
        pts = points(24, s)
        fr = [p[:2] for p in front(24, s)]
        und = undominated(pts)
        ok = sum(((R, E) in fr) == ((R, E) in und) for R, E, _ in pts)
        check(f"control: the front is the undominated pairs, N = 24, s = {s}",
              fr == und and ok == len(pts) == size,
              f"{ok} of {len(pts)} cut sets, {len(fr)} points")
    e8, e15 = error((0, 1, 6, 8), 8), error((0, 1, 6, 15), 15)
    check("control: a cut set past 2c - 1 <= N whose error moves with N, "
          "by hand",
          (e8, e15) == (9, 10),
          f"cuts (1, 6): {e8} at N = 8, {e15} at N = 15")
    one = rounding(120, 1000, 0.3)
    check("control: one interval below the top is D4's case, by hand",
          one == (0, 36, 120) and error(one + (239,), 239) == 3066,
          f"cuts {one}, e = {error(one + (239,), 239)}")
    cuts = rounding(30, 8, 0.8)
    E = error(cuts + (59,), 59)
    check("control: rounding cuts at (k + 1/2) w; their error matches "
          "the pair loop", cuts == (0, 4, 12, 20, 24, 30)
          and E == error_brute(cuts + (59,), 59), f"cuts {cuts}, e = {E}")
    cuts = rounding(10, 4, 0.6)
    check("control: a half-cut that meets the top is not entered twice",
          cuts == (0, 2, 6, 10), f"cuts {cuts}")
    mid = rounding(2000, 25, 0.8)[1:-2]
    gaps = [b - a for a, b in zip(mid, mid[1:])]
    check("control: at w = 25 the half-cuts round to even, widths 26 and "
          "24 by turns", mid[0] == 12 and gaps == [26, 24] * 31 + [26],
          f"{len(mid)} half-cuts from {mid[0]} to {mid[-1]}")
    cuts = rounding(1000, 50, 0.8) + (1999,)
    E = error(cuts, 1999)
    check("control: the error matches the pair loop at c = 1000, w = 50",
          E == error_brute(cuts, 1999), f"e = {E}")


def section_zero():
    print("K1  zero error")
    ok = n = 0
    for s in range(2, 7):
        for N in range(s + 1, 25):
            zero = [c for c in cutsets(N, s) if error(c, N) == 0]
            n += 1
            ok += zero == [sat(N, s)]
    check("zero-error cut sets: saturation only", ok == n == 100,
          f"{ok} of {n} cells (s, N)")


def section_two():
    print("K2  s = 2")
    ok = 0
    for N in range(3, 61):
        ok += front(N, 2) == [(c * (N - c), comb(c, 2), (0, c, N))
                              for c in range(1, N // 2 + 1)]
    check("s = 2 front: the cuts c = 1..floor(N/2), E = C(c, 2), "
          "R = c(N - c)", ok == 58, f"{ok} of 58, N = 3..60")
    ok = n = 0
    for N in range(3, 61):
        for c in range(N // 2 + 1, N):
            d = N - c
            n += 1
            ok += error((0, c, N), N) == d * (2 * c - 1 - d) // 2
    check("s = 2, c > N/2: E = d(2c - 1 - d)/2, d = N - c", ok == n == 870,
          f"{ok} of {n} cut sets, N = 3..60")


def section_nfree():
    print("K3  N-freeness")
    ok = n = 0
    for s in (3, 4):
        for N in range(8, 31):
            for c in cutsets(N, s):
                if 2 * c[-2] - 1 <= N:
                    n += 1
                    ok += error(c, N) == error(c[:-1] + (N + 7,), N + 7)
    check("N-freeness: error equal at N and N + 7", ok == n == 4740,
          f"{ok} of {n} cut sets")


def section_three():
    print("K4  s = 3 inner closed form")
    ok = sum(inner(2, c)[0] == d4(c) for c in range(2, 121))
    check("s = 3 inner closed form: e_2(c) = D4's min over alpha",
          ok == 119, f"{ok} of 119, c = 2..120")
    form = swap = n = 0
    for c in range(3, 81):
        N = 2 * c - 1
        for al in range(c // 2 + 1, c):
            be = c - al
            n += 1
            E = error((0, al, c, N), N)
            form += E == comb(al, 2) + 2 * g(be)
            swap += E > error((0, be, c, N), N)
    check("s = 3, beta < alpha: E = C(alpha, 2) + 2 T(beta)",
          form == n == 1560, f"{form} of {n} cut sets, c = 3..80")
    check("s = 3, beta < alpha: E above its swap's",
          swap == n == 1560, f"{swap} of {n} cut sets, c = 3..80")


def section_kappa():
    print("K5  e_m(c)/c^2")
    rec = {}
    for m, cs in K5_RUNS.items():
        for c in cs:
            e, arg, n = rec[m, c] = inner(m, c)
            print(f"    m = {m}  c = {c:4d}  e = {e:6d}  e/c^2 = "
                  f"{e / c / c:.4f}  cuts {arg[0]}"
                  + (f" (+{len(arg) - 1} more)" if len(arg) > 1 else ""))
    print(f"    3/14 = {3 / 14:.4f}")
    ok = sum(rec[m, c][2] == comb(c - 1, m - 1) for m, c in rec)
    check("K5 reads every cut set of m intervals on [0, c)",
          ok == len(rec) == 12, f"{ok} of {len(rec)} keys (m, c)")
    ok = sum(rec[1, c][:2] == (comb(c, 2), [(0, c)]) for c in K5_RUNS[1])
    check("m = 1: e_1(c) = C(c, 2), its one witness (0, c)", ok == 3,
          f"{ok} of 3")
    ok = sum(rec[k][:2] == v for k, v in K5_HAND.items())
    check("m = 2: e_2(c) and its witnesses by hand", ok == 3, f"{ok} of 3")
    ok = sum((rec[k][0], rec[k][1][0], len(rec[k][1])) == v
             for k, v in K5_SEEN.items())
    check("m = 3, 4: e, first witness and count as first printed",
          ok == 6, f"{ok} of 6")
    e2, e3 = rec[2, 120][0] / 120 ** 2, rec[3, 120][0] / 120 ** 2
    check("e_2(120)/120^2 within 0.01 of 3/14; e_3(120) below e_2(120)",
          abs(e2 - 3 / 14) < 0.01 and e3 < e2,
          f"e_2 {e2:.4f}, e_3 {e3:.4f}, e_4(60) "
          f"{rec[4, 60][0] / 60 ** 2:.4f}")


def section_geo():
    print("K6  ratio-2 cuts against the front")
    rec = {}
    for s, N in ((3, 60), (4, 40)):
        fr = front(N, s)
        pairs = [p[:2] for p in fr]
        t = 1
        while t * 2 ** (s - 2) < N:
            cuts = (0,) + tuple(t * 2 ** i for i in range(s - 1)) + (N,)
            R, E = reach(cuts), error(cuts, N)
            rec[s, t] = (E, least_at(fr, R), (R, E) in pairs)
            print(f"    s = {s} N = {N} t = {t:2d}  cuts {cuts}  R = {R}"
                  f"  E = {E}  front E = {rec[s, t][1]}")
            t += 1
    on = [k for k, (E, F, _) in rec.items() if E == F]
    above = sum(E > F for E, F, _ in rec.values())
    check("ratio-2 cuts err the front's least at their reach at s = 3, "
          "t = 1, 2, 3, 20 and s = 4, t = 1, more at every other scale",
          on == K6_ON and above == 33 and len(rec) == 38,
          f"{above} of {len(rec)} above, the least at {on}")
    pts = [k for k, (_, _, point) in rec.items() if point]
    check("of those five all but s = 3, t = 3 are points of the front",
          pts == K6_POINTS, f"points at {pts}")
    widest = {s: max((E / F, t, E, F) for (s_, t), (E, F, _) in rec.items()
                     if s_ == s and E > F)[1:] for s in (3, 4)}
    check("the largest E over the front's at each s: its scale, its E by "
          "hand, the front's", widest == K6_WIDEST, ", ".join(
              f"s = {s}, t = {t}: {E} against {F}, {E / F:.1f}x"
              for s, (t, E, F) in widest.items()))


def section_round():
    print("K7  the rounding construction toward 1/10")
    rec = {}
    for c, w in K7_ROWS:
        cuts = rounding(c, w, 0.8)
        rec[c, w] = (len(cuts) - 1, error(cuts + (2 * c - 1,), 2 * c - 1))
    for w in (100, 50, 25, 10):
        m, E = rec[2000, w]
        print(f"    c = 2000  w = {w:3d}  m = {m:3d}  e = {E}  e/c^2 = "
              f"{E / 2000 ** 2:.4f}")
    r = rec[2000, 10][1] / 2000 ** 2
    check("the construction tends to 1/10: w = 10, c = 2000 within "
          "[0.0990, 0.105]", 0.0990 <= r <= 0.105, f"{r:.4f}")
    for k in (20, 40, 80):
        row = [rec[c, c / k] for c in (1000, 2000, 4000)]
        print(f"    w = c/{k}, m in {sorted({m for m, _ in row})}: e/c^2 at "
              f"c = 1000, 2000, 4000: " + ", ".join(
                  f"{E / c / c:.4f}"
                  for (_, E), c in zip(row, (1000, 2000, 4000))))
    ok = sum(rec[k] == v for k, v in K7_ROWS.items())
    check("K7's rows: m by hand, e as first printed", ok == len(rec) == 10,
          f"{ok} of {len(rec)} keys (c, w)")


def main():
    section_controls()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        raise SystemExit(1)
    section_zero()
    section_two()
    section_nfree()
    section_three()
    section_kappa()
    section_geo()
    section_round()
    print(f"{sum(CHECKS)}/{len(CHECKS)} checks passed")
    raise SystemExit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()