ceiling.py

"""ceiling.py -- evaluations whose Bayes-optimal score is derived, not
estimated: an integer read through a proper set of its residue channels
and asked one question about its size or its order.

QUESTION. Take x in Z/N, N = Mc, and let the evidence be the residue
r = x mod M, read through the channels whose product is M; the FIBER
over r is the c integers r + jM, j = 0..c-1, and c is the COFACTOR. An
EVAL is a task with a prior, this evidence and a score. Its CEILING is
the Bayes-optimal expected score, its FLOOR the best score with the
evidence severed, and a cell (N, M) is DEAD when the two coincide. For
which tasks is the ceiling a closed form in (N, M), which cells are
dead, what does a solver that attains the ceiling cost, and what
happens to all of it when the uniform prior is tilted to theta^x?

THE TASKS.
  SIGN       [2x >= N], one size bit.
  THRESHOLD  [x >= t] at every t, written t = QM + s, 0 <= s < M.
  ORIENTATION  the cyclic orientation of a uniform ordered triple of
             distinct points, all three read mod M; positive iff
             (y - x) mod N < (z - x) mod N.
  COMPARISON [x < y] on a uniform ordered pair of distinct points,
             both read mod M.
  MAGNITUDE  the class Y = floor(kx/N) out of k, the sign bit at k = 2.
Scores: 0-1 accuracy, and log-loss (conditional entropy in nats).
The tilted prior puts weight theta^x on x; q = theta^M is the ratio
between neighbours within a fiber, and theta = 1 is uniform.

THE ARGUMENT (written before the engine).
  (A) SIGN. The below-count of fiber r is #{j : 2(r + jM) < N} =
      ceil(c/2 - r/M). At even c it is c/2 on every fiber, so the
      posterior is the prior. At odd c it is (c+1)/2 for r < M/2 and
      (c-1)/2 otherwise, so every fiber scores (c+1)/2c. Hence the
      ceiling is (c+1)/2c at odd c and 1/2 at even c, the log-loss
      twin H2((c+1)/2c) and log 2. With N squarefree and even, c is
      even iff 2 does not divide M: the dead cells are exactly those.
      At odd N every c is odd and (c+1)/2c > (N+1)/2N whenever M > 1. A lone
      channel p is the same law at M = p. The achiever reconstructs r
      from the channels read (one CRT combination) and compares 2r
      with M.
  (B) THRESHOLD. Fiber r holds Q + [r < s] points below t, so only two
      fiber types exist. At even c no fiber's majority differs from the
      prior's, so the ceiling is the floor max(t, N - t)/N at every t.
      At c = 2m + 1 the ceiling leaves the floor exactly when Q = m and
      s != 0, where every fiber scores (m+1)/c = (c+1)/2c whatever t
      is, and the lift over the floor is the tent min(s, M - s)/N,
      largest at the midpoint: the sign bit is the family's extremal
      member. The log-loss is (s/M) H2((Q+1)/c) + ((M-s)/M) H2(Q/c),
      equal to the prior's entropy iff s = 0; so the log-loss dead set
      is the set {M | t} while the 0-1 dead set is everything
      outside the odd-c middle range. Off that range the posterior
      moves but never crosses 1/2.
  (C) ORIENTATION. Translate x to 0: (a, b) = (y - x, z - x) mod N is
      uniform on ordered distinct nonzero pairs, independent of x, and
      the orientation is [a < b]. With (alpha, beta) = (a, b) mod M,
      a fiber with alpha != beta, both nonzero, is a c-by-c ladder
      grid and holds (c+1)/2c positives when alpha < beta, (c-1)/2c
      otherwise; alpha = beta, or one of them zero, is balanced (the
      zero residue's ladder lacks the point 0, which cancels the
      skew). Weighting: ceiling 1/2 + c(M-1)(M-2)/(2(N-1)(N-2)), floor
      1/2, dead iff M = 2, never 1. A lone channel p is worth a value
      increasing in p, zero at p = 2. The achiever subtracts residues
      channel by channel, CRT-combines the two differences and
      compares them (the code reads the differences mod M, the same
      numbers by CRT; at alpha = beta every guess ties).
  (D) COMPARISON. With (r_x, r_y) = (x, y) mod M, both ladders are
      full: r_x < r_y gives (c+1)/2c, r_x > r_y (c-1)/2c, r_x = r_y
      exactly 1/2. Weighting:
      ceiling 1/2 + (M-1)/(2(N-1)), free of c; floor exactly 1/2; no
      dead cell, M = 2 included. The achiever CRT-combines both
      residues and compares them (read mod M in the code).
  (E) THE SKEW UNIT. In (A)-(D) every interior fiber is a staircase
      count on a c-point ladder and scores (c+1)/2c. Four tasks carry
      three gauge shapes: the RANGE (sign and threshold; at the
      midpoint the range condition is c odd), the INVERTED gauge
      (orientation, dead only at M = 2) and the CONSTANT gauge
      (comparison, never dead).
  (F) THE TILT. Fiber r's weights are theta^r q^j, so the probability
      that a fiber of below-count J lies below t is
      Pb(J) = (1 - q^J)/(1 - q^c), increasing in J. A fiber leans
      below iff Pb(J) > 1/2 iff J > Q*, Q* = log_q((1 + q^c)/2), and
      Q* lies strictly in (0, c) for q != 1. With the two types Q and
      Q + 1, a threshold is live iff s != 0 and Q < Q* < Q + 1:
      THE THRESHOLD-RANGE LAW, one fiber range of M - 1 thresholds at
      floor(Q*), empty iff Q* is an integer J, i.e. iff q is a root of
      f(q) = q^c - 2q^J + 1. At s = 0 every fiber has one type and the
      posterior is the prior at every theta: the seam {M | t} is
      tilt-invariant and is the whole log-loss dead set. The map
      x -> N - 1 - x sends theta to 1/theta and t to N - t, so the
      ceiling at (theta, t) equals the ceiling at (1/theta, N - t).
  (G) THE RESONANCE CRITERION. f is monic with constant term 1, so its
      only rational roots are +-1: no rational q other than 1, hence
      no rational tilt off uniform, is resonant. Its signs +, -, +
      allow two positive roots (Descartes), one of them q = 1, with
      f'(1) = c - 2J; from f(0) = 1 and f -> infinity, at 2J < c the
      other root lies in (0, 1) and at 2J > c in (1, infinity). At
      2J = c q = 1 is a double root and the only one: the uniform
      point is where the whole 2J = c family collapses, which is the
      even-c deadness of (A). q -> 1/q exchanges J and c - J. At
      (J, c) = (1, 3), f = (q - 1)(q^2 + q - 1): the reciprocal golden
      ratio.
  (H) MAGNITUDE. Write c = ak + v, 0 <= v < k. Y is nondecreasing in j,
      so at fixed r the classes are contiguous blocks of fiber indices.
      With f = r/M the block of class y has length
      a + ceil((y+1)v/k - f) - ceil(yv/k - f), which is a or a + 1,
      with exactly v heavy (length a + 1) classes, the heavy set being
      {floor(k(l + f)/v) : l = 0..v-1} and the first heavy class
      y1(r) = floor(kr/(vM)). At uniform every atom's best class
      carries ceil(c/k)/c, so the ceiling is ceil(c/k)/c and the floor
      ceil(N/k)/N; the cell is dead iff M ceil(c/k) = ceil(Mc/k), iff
      v = 0 or M(k - v) < k (SATURATION, class 0 heavy at every atom,
      possible only at k > M). At k = 2 this is (A). Guessing y1(r)
      attains the ceiling. Under the tilt a block starting at lo of
      length w carries mass q^lo (1 - q^w): q's powers are monotone, so
      among blocks of equal length the first wins at q < 1, and a heavy
      block beats every later light one. So off uniform an atom's best
      class is 0 or y1(r) at q < 1, and by the same count from the top
      the last heavy class or k - 1 at q > 1: at most four classes are
      ever optimal at an atom off uniform. At q < 1 the floor's guess
      is class 0, and an atom with y1 >= 1 overrules it iff
      g(q) = 1 - q^a - q^L + q^(L+a+1) < 0, L = a y1(r); g has signs
      +, -, -, +, a root at 1 with g'(1) = 1, and g(0) = 1 at a >= 1,
      so one root in (0, 1), and the atom overrules above it. At a = 0
      an atom with y1 >= 1 has an empty class 0 and overrules at every
      q < 1. The partition Y = floor(kx/N) is NOT symmetric under
      x -> N - 1 - x, so the q > 1 side is read on its own: an atom
      whose top class is light prefers ylast to k - 1 on
      (1, 1/root of g) at L = a(k - 1 - ylast), and at a = 0 an empty
      top class at every q > 1; the top class is light at r = 0 when k
      does not divide c, and if it is light at every atom, r = 0 and
      r = M - 1 differ in ylast, so the cell is alive there. So every
      cell is alive on one open arc (q_lo, q_up) of q and dead off it:
      at v = 0 the arc is empty; q_lo = 1 at saturation; q_up is
      infinite at a = 0. When M > k, a >= 1 and k does not divide c
      some atom has y1 = 1, so L = a and the lower
      edge is the root of q^(2a+1) - 2q^a + 1 in (0, 1), the resonance
      root rho_a of (G) at (J, c) = (a, 2a + 1), a function of
      floor(c/k) alone; the upper edge is 1/rho_a. The sign bit is the
      k = 2 row: at odd c = 2m + 1 it is alive exactly for q in
      (rho_m, 1/rho_m).

DESIGN. Every probability is an exact integer count or Fraction; a tilt
theta = num/den is carried as the integer weight num^x den^(N-1-x), so
tilted ceilings are exact. Entropies are floats checked to 1e-12. The
rings are the squarefree N built from two or more of 2, 3, 5, 7, 11, 13,
each read through every proper nonempty channel subset.
  sign        every ring (57 rings, N to 30030), every subset; the
              achiever run from the channel residues at N <= 2310.
  threshold   every ring N <= 500, every subset, every t, by an
              incremental sweep of the per-fiber below-counts; the
              achiever at N <= 210.
  orientation every ring N <= 210, every subset, over all difference
              pairs; the full-triple control at N = 30.
  comparison  every ring N <= 210, every subset, over all pairs.
  tilt        every ring N <= 105, every subset, theta on {1/10, 1/3,
              1/2, 2/3, 1, 3/2, 2, 3, 10}, every t.
  resonance   every q = num/den with num, den <= 40 coprime and
              num != den, every c <= 12, every 0 < J < c, in
              integers; each (J, c) pair's roots located by bisection
              and a sign scan of (0, 2] in steps of 1/400 (f >= 1
              from 2 on), on which at 2J = c f is zero at 1 and
              positive elsewhere.
  magnitude   uniform: M in {2, 3, 6, 15, 35}, c in 2..12, k in 2..9,
              k <= Mc; tilted: M in {2, 3, 6, 15}, c in 2..10, k in
              2..6, k <= Mc, on
              {1/5, 1/2, 4/5, 9/10, 199/200, 201/200, 10/9, 2, 5},
              plus rational tilts 5% of the way to 1 inside and 5% of q
              outside each finite
              arc end; at k | c every exact verdict is read as the
              floor's, and otherwise against the arc and against
              overrules(), alive at the first atom whose g is negative.
Threshold, orientation, comparison and the tilt are each a ROW function
of one cell and a SWEEP that sums rows over the family into a record;
sign, resonance and magnitude sweep in one function each, with no row
of their own. A law is checked as the count of cells,
slices, atoms or probes that agree with it, set against the size of its
population as BY HAND counts it, so a loop that narrows moves a check.
Controls run first and gate the rest: the row functions on C0's hand
cells, on two where a counter that the sweeps leave at zero moves
(orientation at M = N, every class decided; comparison at M = 1, dead
at log 2) and on one where a counter they move stays at zero
(threshold at even c, no interior), the threshold sweep's ceilings
against the definition at one cell, and the sign sweep at cap 30; the
tilt, resonance and magnitude hand cells run inside their sections,
the resonance one where the root count, zero in the census, moves.

PREDICTIONS (fixed before the engine).
  C0 hand cells: sign N = 6, M = 3 gives 2/3 and N = 6, M = 2 gives
     1/2 (WRONG as frozen, the two cells swapped: see FINDINGS);
     threshold N = 30, M = 6, t = 13 gives 3/5; orientation
     N = 6, M = 3 gives 3/5; comparison N = 6 gives 7/10 at M = 3 and
     3/5 at M = 2; at theta = 1/2, N = 6, M = 3 the threshold t = 3 is
     dead at 8/9 and t = 2 scores 19/21 against the floor 16/21;
     magnitude M = 15, c = 7, k = 2 gives 4/7 and M = 2, c = 3, k = 5
     is dead at 1/3.
  P1 (A) at every sign cell: ceiling, dead set, log twin; the
     achiever at N <= 2310.
  P2 (B) at every threshold slice: ceiling, the tent, the two floor
     sets; the achiever at N <= 210.
  P3 (C) at every orientation cell, the determined fraction 0, and the
     full-triple control equal to the difference-pair ceiling.
  P4 (D) at every comparison cell.
  P5 (F) at every tilted slice: posterior = prior iff M | t; the
     live set exactly one range of M - 1 thresholds at the J the
     exact test Pb(J) < 1/2 < Pb(J + 1) names, empty at theta = 1 for
     even c; every even-c cell alive at every theta != 1; reflection.
  P6 (G): no rational root; one root per 2B != c pair on the side
     sign(2B - c) names; the double root alone at 2B = c; reflection
     of the roots; the golden control.
  P7 (H): block lengths and heavy set, uniform ceiling and floor, the
     dead-cell equivalence, the achiever, the four-class set off
     uniform, the arc law at every v >= 1 tilted cell, the band
     (rho_a, 1/rho_a) at M > k, and the sign-bit row.

BY HAND, the families of cells() at its caps, counted without the
engine. The squarefree N from two or more of the six primes are
2^6 - 1 - 6 = 57 rings; a ring of n primes has 2^n - 2 cells, so
15*2 + 20*6 + 15*14 + 6*30 + 62 = 602 cells. The sign bit's dead cells
are the even N read without channel 2, 2^(n-1) - 1 of them in a ring of n
primes holding 2: 5*1 + 10*3 + 10*7 + 5*15 + 31 = 211, and 391 live.
At N <= 500: the 15 rings of two primes, 18 of three (ten with 2, and
105, 165, 195, 231, 273, 385, 429, 455) and 210, 330, 390, 462, so 37
rings and 30 + 108 + 56 = 194 cells; N - 1 summed over each kind is
637, 3368 and 1388, so 2*637 + 6*3368 + 14*1388 = 40,914 slices. At
N <= 210: 15 + 12 + 1 = 28 rings and 30 + 72 + 14 = 116 cells, of
which the 15 even rings read at {2} are orientation's dead cells. At
N <= 105: 14 + 6 = 20 rings and 28 + 36 = 64 cells. At cap 30: the
rings 6, 10, 14, 15, 21, 22, 26, 30 and 20 cells, 5 + 3 = 8 dead.
  sign       N <= 2310 keeps every ring of two or three primes, 13 of
     four and 2310: 30 + 120 + 182 + 30 = 362 cells. A ring of n primes
     has n lone channels: 30 + 60 + 60 + 30 + 6 = 186.
  threshold  A cell's seam is t = M, .., (c - 1)M, so a ring gives
     sigma(N) - N - 1 - (2^n - 2): 175 over two primes, 2,384 - 108 =
     2,276 over three, 351 + 519 + 603 + 675 = 2,148 over four, 4,599.
     A cell with c odd has M - 1 interior slices: every cell of an odd
     ring (136 over two primes, 1,274 over three), and at an even ring
     M = 2M' with M' a proper divisor of N/2, 2(sigma(N/2) - N/2) -
     (2^(n-1) - 1): 5, 302 and 167 + 239 + 275 + 299 = 980; 2,697 in
     all, and 40,914 - 2,697 = 38,217 off it. At N <= 210 the slices
     are 2*637 + 6*1,315 + 14*209 = 12,090.
  orientation  Adjacent lone channels: 15 + 2*12 + 3 = 42 in the 28
     rings.
  tilt       N - 1 slices a cell: 2*495 + 6*385 = 3,300 a tilt, 29,700
     over nine. The even-c cells: 6, 10, 14, 22, 26 read at the odd
     prime, and 30, 42, 66, 70, 78 at a nonempty set of the two odd
     primes: 20.
  resonance  Coprime ordered pairs to 40: 2*490 - 1 = 979, less (1, 1);
     the (J, c): 1 + .. + 11 = 66; 978*66 = 64,548. Six even c: 6
     double roots, 60 pairs.
  magnitude  Uniform: k <= Mc cuts only M = 2 (79 cells) and M = 3
     (85): 79 + 85 + 3*88 = 428. k | c at 20 (c, k) per M, 100;
     saturated, v > k(M - 1)/M, 27 at M = 2, 14 at M = 3, 3 at M = 6:
     44, so 144 dead. Atoms, M a cell: 158 + 255 + 528 + 1,320 + 3,080
     = 5,341, of them 59*2 + 65*3 + 68*56 = 4,121 at k not dividing c.
     Tilted: 43 + 3*45 = 178 cells, 1,166 atoms, 10,494 by nine tilts.
     k | c at 13 (c, k) per M: 52 cells, 468 reads. The other 126 give
     nine probes each and two more at each finite arc end, q_up at the
     88 cells with a >= 1 and q_lo at the 80 of them unsaturated: 1,134
     + 176 + 160 = 1,470. The band's cells: 4 + 18 + 22 = 44.

KILL. Any printed ceiling, floor, entropy, count or root off its
predicted value, at any cell. Only the printed value decides.

FINDINGS. No kill fired; every law (A)-(H) held at every cell. One
frozen control was wrong: C0 swapped the sign-bit hand cells. At
N = 6, M = 3 the cofactor is 2, even, so the cell is dead at 1/2; at
M = 2 it is 3, odd, and scores 2/3. The engine printed the law's
values, and the control was rewritten to them. Two other first-run
FAILs were errors in the checks, not the law: the lone-channel check
read the smallest prime present as channel 2, and a literal carried
c = 7 for c = 14. Four statements have no check of their own, each
being a ceiling check and a line of algebra: the tent (B), dead iff
M = 2 (C), f = (q^J - 1)^2 at 2J = c (G), and M ceil(c/k) =
ceil(Mc/k) (H).
  sign        602 cells over 57 rings: 211 dead, exactly the cells
              with N even and M odd, 391 live; the achiever exact
              on 362 cells; N = 2310 read at {2, 3, 5} scores 39/77,
              its best lone channel 578/1155, a price of 1/165.
  threshold   194 cells, 40,914 slices: 2,697 interior, exactly the
              odd-c middle ranges; the log-loss dead set 4,599, exactly
              {M | t}, against the 0-1 dead set's 38,217; the rule
              below iff Q + [r < s] > c/2, scored on the brute counts,
              exact on 12,090 slices.
  orientation 116 cells, 15 dead, exactly M = 2; no fiber decides; a
              fixed guess at alpha = beta loses nothing; the brute
              lone-channel ceilings rise with the modulus at all 42
              adjacent pairs; N = 210 read at {3, 5} scores 885/1672
              against the better of its two lone channels, 5497/10868.
  comparison  116 cells, none dead, each below log 2.
  tilt        64 cells x 9 tilts: one range of M - 1 at every tilt
              off uniform; every even-c cell alive at every theta != 1
              (20 of 20 at each), none at theta = 1.
  resonance   64,548 rational tuples, no root; 60 pairs with one root
              each on the predicted side, 6 double roots at 2J = c
              (P6 writes B for J).
  magnitude   428 uniform cells, 144 dead, 44 of them saturated; the
              floor's verdict at the k | c cells' 468 reads and the
              arc law at 1,470 exact probes; the band (rho_a, 1/rho_a)
              at all 44 cells with M > k, a >= 1 and k not dividing c,
              rho_1..rho_6 =
              0.618034, 0.848375, 0.920568, 0.951425, 0.967305,
              0.976518. The sign bit M = 15, c = 3 is alive at
              theta = 199/200 (q = 0.928) and dead at 24/25 (q = 0.542),
              either side of rho_1.

RUN RECORD. python ceiling.py: 55 of 55 checks, 1.7 s.
"""

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

import sys
import time
from fractions import Fraction
from itertools import combinations
from math import ceil, log, prod, gcd

from crt import Ring, decode_from

PRIMES = (2, 3, 5, 7, 11, 13)
TOL = 1e-12
THETAS = [Fraction(1, 10), Fraction(1, 3), Fraction(1, 2), Fraction(2, 3),
          Fraction(1), Fraction(3, 2), Fraction(2), Fraction(3),
          Fraction(10)]
MAG_TILTS = [Fraction(1, 5), Fraction(1, 2), Fraction(4, 5),
             Fraction(9, 10), Fraction(199, 200), Fraction(201, 200),
             Fraction(10, 9), Fraction(2), Fraction(5)]
HALF = Fraction(1, 2)
CHECKS = []


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


def section(title):
    print()
    print(title)


def H2(p):
    p = float(p)
    if p <= 0.0 or p >= 1.0:
        return 0.0
    return -p * log(p) - (1 - p) * log(1 - p)


def cells(cap):
    """Every (N, S): N squarefree from >= 2 of PRIMES, N <= cap, S a
    proper nonempty subset of N's primes (the channels read)."""
    out = []
    for n in range(2, len(PRIMES) + 1):
        for ps in combinations(PRIMES, n):
            N = prod(ps)
            if N > cap:
                continue
            for m in range(1, n):
                for S in combinations(ps, m):
                    out.append((N, ps, S))
    return out


def total(rows, start):
    """The rows' records summed field by field onto start."""
    tot = dict(start)
    for rec in rows:
        for key, v in rec.items():
            tot[key] = tot.get(key, 0) + int(v)
    return tot


# ------------------------------------------------------------ sign bit

def sign_brute(N, M):
    """Exact 0-1 ceiling and conditional entropy of [2x >= N] from x mod M."""
    c = N // M
    right, ent = 0, 0.0
    for r in range(M):
        below = sum(1 for j in range(c) if 2 * (r + j * M) < N)
        right += max(below, c - below)
        ent += H2(Fraction(below, c)) / M
    return Fraction(right, N), ent


def sign_achiever(N, ps, S):
    """Reconstruct r from the channels read, guess 'below' iff 2r < M."""
    ring = Ring(ps)
    idx = [ps.index(p) for p in S]
    M = prod(S)
    right = 0
    for x in range(N):
        res = tuple(x % p for p in ps)
        r = decode_from(res, ring, idx)
        right += (2 * r < M) == (2 * x < N)
    return Fraction(right, N)


def sign_sweep(cap):
    """The parity law over cells(cap): each law a count of the cells
    that agree with it."""
    fam = cells(cap)
    rec = dict(cells=len(fam), rings=len({N for N, _, _ in fam}),
               ceiling=0, dead=0, live=0, dead_law=0, log=0)
    for N, ps, S in fam:
        M = prod(S)
        c = N // M
        ceil_, ent = sign_brute(N, M)
        floor_ = Fraction((N + 1) // 2, N)
        want = Fraction(c + 1, 2 * c) if c % 2 else HALF
        rec["ceiling"] += ceil_ == want
        is_dead = ceil_ == floor_
        rec["dead"] += is_dead
        rec["live"] += floor_ < ceil_
        rec["dead_law"] += is_dead == (2 in ps and 2 not in S)
        want_log = H2(want) if c % 2 else log(2)
        rec["log"] += abs(ent - want_log) <= TOL
    return rec


def sign_achieved(cap):
    """(cells of cells(cap) where the achiever scores the ceiling, cells)."""
    fam = cells(cap)
    return sum(sign_achiever(N, ps, S) == sign_brute(N, prod(S))[0]
               for N, ps, S in fam), len(fam)


def sign_lone(cap):
    """(lone channels (N, p) on the law, lone channels) over the rings
    of cells(cap)."""
    ok = n = 0
    for N in sorted({N for N, _, _ in cells(cap)}):
        for p in PRIMES:
            if N % p:
                continue
            if N % 2 == 0:
                want = HALF + Fraction(1, N) if p == 2 else HALF
            else:
                want = HALF + Fraction(p, 2 * N)
            n += 1
            ok += sign_brute(N, p)[0] == want
    return ok, n


def section_sign():
    section("THE SIGN BIT: the parity law")
    rec = sign_sweep(30030)
    print(f"  {rec['cells']} cells over {rec['rings']} rings")
    check("the family: 602 cells over 57 rings",
          (rec["cells"], rec["rings"]) == (602, 57))
    check("ceiling (c+1)/2c at odd c, 1/2 at even c, at all 602",
          rec["ceiling"] == 602, f"{rec['ceiling']} agree")
    check("dead iff N is even and M odd, at all 602: 211 dead, 391 live",
          (rec["dead_law"], rec["dead"], rec["live"]) == (602, 211, 391),
          f"{rec['dead']} dead, {rec['live']} live")
    check("log-loss H2((c+1)/2c) and log 2, at all 602", rec["log"] == 602)
    got = sign_achieved(2310)
    check("one CRT combination and one comparison attain the ceiling at "
          "all 362 cells with N <= 2310", got == (362, 362),
          f"{got[0]} of {got[1]}")
    N = 2310
    joint = sign_brute(N, 30)[0]
    single = max(sign_brute(N, p)[0] for p in (2, 3, 5))
    check("N = 2310 read at {2, 3, 5}: 39/77 against the best lone "
          "channel 578/1155, price 1/165",
          (joint, single, joint - single)
          == (Fraction(39, 77), Fraction(578, 1155), Fraction(1, 165)))
    got = sign_lone(30030)
    check("a lone channel: only 2 earns at even squarefree N (1/2 + 1/N); "
          "every p earns 1/2 + p/2N at odd N, at all 186 pairs",
          got == (186, 186), f"{got[0]} of {got[1]}")


# ----------------------------------------------------------- threshold

def threshold_row(N, M, achieve):
    """One cell over t = 1..N-1 by an incremental sweep of the per-fiber
    below-counts: (record, the brute ceilings by t). With achieve, the
    rule 'below iff Q + [r < s] > c/2' is scored on the brute counts."""
    c = N // M
    m = (c - 1) // 2
    below = [0] * M
    right = M * c                 # t = 0: every fiber all above
    hist = {0: M}
    rec = dict(slices=0, ceiling=0, interior=0, inside=0, floor01=0, log=0,
               seam=0, seam_law=0, achiever=0)
    ceilings = []
    for t in range(1, N):
        r = (t - 1) % M
        old = below[r]
        right -= max(old, c - old)
        below[r] = old + 1
        right += max(old + 1, c - old - 1)
        hist[old] -= 1
        hist[old + 1] = hist.get(old + 1, 0) + 1
        rec["slices"] += 1
        Q, s = divmod(t, M)
        ceil_ = Fraction(right, N)
        floor_ = Fraction(max(t, N - t), N)
        inside = c % 2 == 1 and Q == m and s != 0
        want = Fraction(c + 1, 2 * c) if inside else floor_
        rec["ceiling"] += ceil_ == want
        rec["interior"] += ceil_ > floor_
        rec["floor01"] += ceil_ == floor_
        rec["inside"] += inside
        ent = sum(n * H2(Fraction(b, c)) for b, n in hist.items()
                  if n) / M
        want_log = (s / M) * H2(Fraction(Q + 1, c)) \
            + ((M - s) / M) * H2(Fraction(Q, c))
        rec["log"] += abs(ent - want_log) <= TOL
        core = all(b * N == c * t for b in below)
        rec["seam"] += core
        rec["seam_law"] += core == (s == 0)
        if achieve:
            got = sum(below[rr] if 2 * (Q + (rr < s)) > c
                      else c - below[rr] for rr in range(M))
            rec["achiever"] += got == right
        ceilings.append(ceil_)
    return rec, ceilings


def threshold_sweep(cap, ach_cap):
    """threshold_row summed over cells(cap), the achiever at N <= ach_cap."""
    fam = cells(cap)
    return total((threshold_row(N, prod(S), N <= ach_cap)[0]
                  for N, _, S in fam), dict(cells=len(fam)))


def section_threshold():
    section("THE THRESHOLD FAMILY: one threshold range, one tent")
    rec = threshold_sweep(500, 210)
    print(f"  {rec['cells']} cells, {rec['slices']} (cell, t) slices")
    check("the family: 194 cells, 40,914 slices",
          (rec["cells"], rec["slices"]) == (194, 40914))
    check("ceiling = floor off the odd-c middle range, (c+1)/2c inside, at "
          "all 40,914: 2,697 interior",
          (rec["ceiling"], rec["interior"], rec["inside"])
          == (40914, 2697, 2697), f"{rec['interior']} interior slices")
    check("log-loss two-point form at all 40,914", rec["log"] == 40914)
    check("posterior = prior iff M | t at all 40,914: the log-loss floor "
          "4,599 slices, the 0-1 floor 38,217",
          (rec["seam_law"], rec["seam"], rec["floor01"])
          == (40914, 4599, 38217),
          f"log floor {rec['seam']} slices, 0-1 floor {rec['floor01']}")
    check("guessing below iff Q + [r < s] > c/2 attains the ceiling at all "
          "12,090 slices with N <= 210", rec["achiever"] == 12090,
          f"{rec['achiever']} slices")


# ------------------------------------------- orientation and comparison

def orientation_counts(N, M):
    pos, neg = {}, {}
    for a in range(1, N):
        for b in range(1, N):
            if a == b:
                continue
            key = (a % M, b % M)
            if a < b:
                pos[key] = pos.get(key, 0) + 1
            else:
                neg[key] = neg.get(key, 0) + 1
    return pos, neg


def orientation_row(N, M):
    """One cell over all difference pairs: (brute ceiling, record). The
    achiever guesses positive iff alpha <= beta, a fixed guess at a tie."""
    c = N // M
    pos, neg = orientation_counts(N, M)
    keys = set(pos) | set(neg)
    right = sum(max(pos.get(k, 0), neg.get(k, 0)) for k in keys)
    pairs = (N - 1) * (N - 2)
    ceil_ = Fraction(right, pairs)
    want = HALF + Fraction(c * (M - 1) * (M - 2), 2 * (N - 1) * (N - 2))
    decided = sum(pos.get(k, 0) == 0 or neg.get(k, 0) == 0 for k in keys)
    ent = sum((pos.get(k, 0) + neg.get(k, 0))
              * H2(Fraction(pos.get(k, 0), pos.get(k, 0) + neg.get(k, 0)))
              for k in keys) / pairs
    mixed = (M - 1) * (M - 2) * c * c
    want_log = (mixed * H2(Fraction(c + 1, 2 * c))
                + (pairs - mixed) * log(2)) / pairs
    ach = sum(pos.get(k, 0) if k[0] <= k[1] else neg.get(k, 0)
              for k in keys)
    return ceil_, dict(ceiling=ceil_ == want, decided=decided,
                       dead=ceil_ == HALF, log=abs(ent - want_log) <= TOL,
                       achiever=ach == right)


def orientation_sweep(cap):
    """(orientation_row summed over cells(cap), the brute ceilings by
    (N, S))."""
    fam = cells(cap)
    brute, rows = {}, []
    for N, _, S in fam:
        brute[N, S], rec = orientation_row(N, prod(S))
        rows.append(rec)
    return total(rows, dict(cells=len(fam))), brute


def orientation_lone(brute):
    """Over the rings of brute, read on the brute lone-channel ceilings:
    (adjacent channels p < p' with the larger worth strictly more, adjacent
    channels, even rings whose channel 2 scores 1/2, even rings)."""
    rises = adjacent = twos = evens = 0
    for N in sorted({N for N, _ in brute}):
        vals = [brute[N, (p,)] for p in PRIMES if N % p == 0]
        adjacent += len(vals) - 1
        rises += sum(u < v for u, v in zip(vals, vals[1:]))
        if N % 2 == 0:
            evens += 1
            twos += vals[0] == HALF
    return rises, adjacent, twos, evens


def triple_ceiling(N, M):
    """The orientation ceiling from the raw evidence (x, y, z) mod M."""
    pos, neg = {}, {}
    for x in range(N):
        for y in range(N):
            for z in range(N):
                if x == y or y == z or x == z:
                    continue
                key = (x % M, y % M, z % M)
                d = pos if (y - x) % N < (z - x) % N else neg
                d[key] = d.get(key, 0) + 1
    keys = set(pos) | set(neg)
    right = sum(max(pos.get(k, 0), neg.get(k, 0)) for k in keys)
    return Fraction(right, N * (N - 1) * (N - 2))


def comparison_row(N, M):
    """One cell over all ordered pairs: (brute ceiling, record). The
    achiever guesses x < y iff r_x <= r_y, a fixed guess at a tie."""
    c = N // M
    lt, gt = {}, {}
    for x in range(N):
        for y in range(N):
            if x == y:
                continue
            key = (x % M, y % M)
            d = lt if x < y else gt
            d[key] = d.get(key, 0) + 1
    keys = set(lt) | set(gt)
    pairs = N * (N - 1)
    right = sum(max(lt.get(k, 0), gt.get(k, 0)) for k in keys)
    ach = sum(lt.get(k, 0) if k[0] <= k[1] else gt.get(k, 0) for k in keys)
    ceil_ = Fraction(right, pairs)
    want = HALF + Fraction(M - 1, 2 * (N - 1))
    ent = sum((lt.get(k, 0) + gt.get(k, 0))
              * H2(Fraction(lt.get(k, 0), lt.get(k, 0) + gt.get(k, 0)))
              for k in keys) / pairs
    want_log = (M * (M - 1) * c * c * H2(Fraction(c + 1, 2 * c))
                + M * c * (c - 1) * log(2)) / pairs
    return ceil_, dict(ceiling=ceil_ == want, achiever=ach == right,
                       dead=ceil_ == HALF, log=abs(ent - want_log) <= TOL,
                       below_log2=ent < log(2) - TOL)


def comparison_sweep(cap):
    """comparison_row summed over cells(cap)."""
    fam = cells(cap)
    return total((comparison_row(N, prod(S))[1] for N, _, S in fam),
                 dict(cells=len(fam)))


def section_orientation():
    section("ORIENTATION INVERTS THE GAUGE; COMPARISON HAS NONE")
    rec, brute = orientation_sweep(210)
    check("orientation ceiling 1/2 + c(M-1)(M-2)/(2(N-1)(N-2)) at all 116 "
          "cells", (rec["cells"], rec["ceiling"]) == (116, 116),
          f"{rec['cells']} cells")
    check("no fiber's posterior reaches 0 or 1", rec["decided"] == 0,
          f"{rec['decided']} decided")
    check("15 cells dead", rec["dead"] == 15,
          f"{rec['dead']} dead")
    check("orientation log-loss at all 116", rec["log"] == 116)
    check("guessing by the residues' order, positive at a tie, attains it "
          "at all 116", rec["achiever"] == 116)
    thirty = [S for N, S in brute if N == 30]
    same = sum(triple_ceiling(30, prod(S)) == brute[30, S] for S in thirty)
    check("full triples at N = 30 give the difference-pair ceiling at all "
          "6 cells", (same, len(thirty)) == (6, 6))
    got = orientation_lone(brute)
    check("a lone channel is worth more the larger its modulus, at all 42 "
          "adjacent pairs, and channel 2 nothing at all 15 even rings",
          got == (42, 42, 15, 15))
    joint = brute[210, (3, 5)]
    single = max(brute[210, (3,)], brute[210, (5,)])
    check("N = 210 read at {3, 5}: 885/1672 against 5497/10868",
          (joint, single) == (Fraction(885, 1672), Fraction(5497, 10868)))
    rec = comparison_sweep(210)
    check("comparison ceiling 1/2 + (M-1)/(2(N-1)) at all 116 cells, "
          "attained by comparing the residues",
          (rec["cells"], rec["ceiling"], rec["achiever"]) == (116, 116, 116),
          f"{rec['cells']} cells")
    check("no comparison cell is dead", rec["dead"] == 0,
          f"{rec['dead']} dead")
    check("comparison log-loss at all 116, below log 2 at each",
          (rec["log"], rec["below_log2"]) == (116, 116))


# ------------------------------------------------------------ the tilt

def weights(N, theta):
    u, v = theta.numerator, theta.denominator
    return [u ** x * v ** (N - 1 - x) for x in range(N)]


def lean(q, J, c):
    """The sign of Pb(J) - 1/2 at q = theta^M, exact."""
    d = (Fraction(2 * J - c) if q == 1 else
         2 * (1 - q ** J) / (1 - q ** c) - 1)
    return (d > 0) - (d < 0)


def tilt_ceilings(N, M, theta):
    """(ceiling, floor, seam) at every t = 1..N-1, exact."""
    w = weights(N, theta)
    tot = [sum(w[r + j * M] for j in range(N // M)) for r in range(M)]
    W = sum(tot)
    below = [0] * M
    Wb = 0
    right = sum(tot)
    out = []
    for t in range(1, N):
        r = (t - 1) % M
        right -= max(below[r], tot[r] - below[r])
        below[r] += w[t - 1]
        right += max(below[r], tot[r] - below[r])
        Wb += w[t - 1]
        core = all(below[i] * W == tot[i] * Wb for i in range(M))
        out.append((Fraction(right, W), Fraction(max(Wb, W - Wb), W), core))
    return out


def tilt_row(N, M, theta):
    """One cell at one tilt over t = 1..N-1: the record, and its live
    thresholds."""
    c = N // M
    q = theta ** M
    rows = tilt_ceilings(N, M, theta)
    live = [t for t, (ce, fl, _) in enumerate(rows, 1) if ce > fl]
    seam_law = sum(core == (t % M == 0)
                   for t, (_, _, core) in enumerate(rows, 1))
    Js = [J for J in range(c) if lean(q, J, c) < 0 < lean(q, J + 1, c)]
    want = [J * M + s for J in Js for s in range(1, M)]
    if theta == 1:
        one = (len(live) == M - 1) == (c % 2 == 1)
    else:
        one = len(live) == M - 1
    back = tilt_ceilings(N, M, 1 / theta)
    refl = sum(rows[t - 1][0] == back[N - t - 1][0] for t in range(1, N))
    return dict(slices=len(rows), seam_law=seam_law,
                range=live == want and one, reflection=refl), live


def tilt_sweep(cap, thetas):
    """(tilt_row summed over cells(cap) x thetas, the even-c cells
    [alive, read] by tilt)."""
    fam = cells(cap)
    rows = []
    even = {th: [0, 0] for th in thetas}
    for N, _, S in fam:
        M = prod(S)
        for theta in thetas:
            rec, live = tilt_row(N, M, theta)
            rows.append(rec)
            if (N // M) % 2 == 0:
                even[theta][0] += bool(live)
                even[theta][1] += 1
    return total(rows, dict(cells=len(fam), sweeps=len(rows))), even


def section_tilt():
    section("THE TILT: the threshold-range law")
    rows = tilt_ceilings(6, 3, HALF)
    check("hand cell theta = 1/2, N = 6, M = 3: t = 3 dead at 8/9, t = 2 "
          "19/21 against 16/21",
          rows[2][:2] == (Fraction(8, 9), Fraction(8, 9))
          and rows[1][:2] == (Fraction(19, 21), Fraction(16, 21)))
    got = tilt_row(6, 3, HALF)
    check("hand row theta = 1/2, N = 6, M = 3: live at t = 1, 2 alone, the "
          "seam t = 3",
          got == (dict(slices=5, seam_law=5, range=True, reflection=5),
                  [1, 2]))
    rec, even = tilt_sweep(105, THETAS)
    print(f"  {rec['cells']} cells x {len(THETAS)} tilts, "
          f"{rec['sweeps']} sweeps, {rec['slices']} slices")
    check("the family: 64 cells x 9 tilts, 576 sweeps, 29,700 slices",
          (rec["cells"], rec["sweeps"], rec["slices"]) == (64, 576, 29700))
    check("posterior = prior iff M | t, at every tilt, at all 29,700",
          rec["seam_law"] == 29700)
    check("the live set is one range of M - 1 at the J the exact "
          "test names; at theta = 1 empty iff c even, at all 576",
          rec["range"] == 576)
    print("  even-c cells alive, by theta: " + ", ".join(
        f"{th}: {a}/{n}" for th, (a, n) in even.items()))
    check("every even-c cell alive at every theta != 1, none at 1: 20 of "
          "20, 0 of 20",
          even == {th: [0 if th == 1 else 20, 20] for th in THETAS})
    check("reflection: ceiling(theta, t) = ceiling(1/theta, N - t) at all "
          "29,700", rec["reflection"] == 29700)


def f_res(q, J, c):
    return q ** c - 2 * q ** J + 1


def bisect(fn, lo, hi, iters=200):
    flo = fn(lo)
    for _ in range(iters):
        mid = (lo + hi) / 2
        fm = fn(mid)
        if (fm > 0) == (flo > 0):
            lo, flo = mid, fm
        else:
            hi = mid
    return (lo + hi) / 2


def resonance_root(J, c):
    """The positive root of q^c - 2q^J + 1 other than 1 (2J != c)."""
    fn = lambda q: f_res(q, J, c)
    if 2 * J < c:
        return bisect(fn, 1e-12, 1 - 1e-12)
    hi = 2.0
    while fn(hi) < 0:
        hi *= 2
    return bisect(fn, 1 + 1e-12, hi)


def is_root(u, v, J, c):
    """Whether q = u/v is a root of q^c - 2q^J + 1, in integers."""
    return u ** c + v ** c == 2 * u ** J * v ** (c - J)


def coprime_pairs(umax):
    """Every (u, v), u != v, both <= umax, coprime: the q = u/v != 1."""
    return [(u, v) for u in range(1, umax + 1) for v in range(1, umax + 1)
            if u != v and gcd(u, v) == 1]


def rational_census(pairs, cmax):
    """(tuples tried, roots) over the pairs (u, v) and 0 < J < c <= cmax."""
    tried = hits = 0
    for u, v in pairs:
        for c in range(2, cmax + 1):
            for J in range(1, c):
                tried += 1
                hits += is_root(u, v, J, c)
    return tried, hits


def root_census(cmax):
    """Every 0 < J < c <= cmax on the grid (0, 2] of step 1/400, where
    f(1.0) is 0.0 exactly and past which f >= 1: at 2J = c, f vanishes
    at 1 alone and is positive elsewhere; otherwise f changes sign twice,
    the bisected root is a zero of f a grid step or more from 1, the
    count of changes below 1 names its side, and q -> 1/q reflects it."""
    rec = dict(pairs=0, doubles=0, located=0, side=0, reflection=0,
               double_law=0)
    grid = [i / 400 for i in range(1, 801)]
    for c in range(2, cmax + 1):
        for J in range(1, c):
            if 2 * J == c:
                rec["doubles"] += 1
                rec["double_law"] += [x for x in grid
                                      if f_res(x, J, c) <= 0] == [1.0]
                continue
            rec["pairs"] += 1
            root = resonance_root(J, c)
            flips = [b for a, b in zip(grid, grid[1:])
                     if (f_res(a, J, c) > 0) != (f_res(b, J, c) > 0)]
            rec["located"] += len(flips) == 2 \
                and abs(f_res(root, J, c)) <= 1e-9 \
                and abs(root - 1) > 1 / 400
            rec["side"] += sum(b < 1 for b in flips) == (2 * J < c)
            other = resonance_root(c - J, c)
            rec["reflection"] += abs(root * other - 1) <= 1e-9
    return rec


def section_resonance():
    section("THE RESONANCE CRITERION")
    check("hand tuples: 1/1 and 2/2 roots at every (J, c), c <= 3, 1/2 at "
          "none: 6 roots in 9",
          rational_census([(1, 1), (2, 2), (1, 2)], 3) == (9, 6))
    pairs = coprime_pairs(40)
    got = rational_census(pairs, 12)
    check("no rational q = u/v != 1, u, v <= 40, c <= 12, is a root, at "
          "all 64,548 tuples of the 978 pairs",
          (len(pairs), got) == (978, (64548, 0)),
          f"{got[0]} (u, v, J, c) tuples, {got[1]} roots")
    rec = root_census(12)
    check("one root other than 1 per 2J != c pair, on the side 2J - c "
          "names, at all 60",
          (rec["pairs"], rec["located"], rec["side"]) == (60, 60, 60),
          f"{rec['pairs']} pairs")
    check("at 2J = c, f is zero at q = 1 and positive at every other "
          "grid point, at all 6", (rec["doubles"], rec["double_law"]) == (6, 6),
          f"{rec['doubles']} pairs")
    check("q -> 1/q exchanges J and c - J, at all 60",
          rec["reflection"] == 60)
    phi = (5 ** 0.5 - 1) / 2
    Qstar = log((1 + phi ** 3) / 2) / log(phi)
    check("golden control: q^3 - 2q + 1 = (q - 1)(q^2 + q - 1), "
          "Q* = 1 there",
          all(f_res(x, 1, 3) == (x - 1) * (x * x + x - 1)
              for x in range(-5, 6)) and abs(Qstar - 1) < TOL)


# ----------------------------------------------------------- magnitude

def blocks(M, c, k, r):
    """lo[0..k] of the class blocks at atom r, by definition."""
    N = c * M
    lo = [0] * (k + 1)
    counts = [0] * k
    for j in range(c):
        counts[k * (r + j * M) // N] += 1
    for y in range(k):
        lo[y + 1] = lo[y] + counts[y]
    return lo


def block_formula(M, c, k, r):
    a, b = divmod(c, k)
    f = Fraction(r, M)
    return [a + ceil((y + 1) * Fraction(b, k) - f)
            - ceil(y * Fraction(b, k) - f) for y in range(k)]


def g_poly(q, a, L):
    return 1 - q ** a - q ** L + q ** (L + a + 1)


def g_root(a, L):
    return bisect(lambda q: g_poly(q, a, L), 1e-12, 1 - 1e-12)


def magnitude_exact(M, c, k, theta):
    """(ceiling numerator, floor numerator, argmax sets) at an exact tilt."""
    N = M * c
    w = weights(N, theta)
    right = 0
    tops = []
    for r in range(M):
        mass = [0] * k
        for j in range(c):
            x = r + j * M
            mass[k * x // N] += w[x]
        best = max(mass)
        right += best
        tops.append({y for y in range(k) if mass[y] == best})
    cls = [0] * k
    for x in range(N):
        cls[k * x // N] += w[x]
    return right, max(cls), tops


def arc(M, c, k):
    """(q_lo, q_up) of the live arc, from the per-atom roots."""
    a, b = divmod(c, k)
    lows, ups = [], []
    for r in range(M):
        lo = blocks(M, c, k, r)
        n = [lo[y + 1] - lo[y] for y in range(k)]
        heavy = [y for y in range(k) if n[y] == a + 1]
        y1, ylast = heavy[0], heavy[-1]
        if y1 >= 1:
            lows.append(0.0 if a == 0 else g_root(a, a * y1))
        if n[k - 1] == a:
            ups.append(float("inf") if a == 0
                       else 1 / g_root(a, a * (k - 1 - ylast)))
    q_lo = min(lows) if lows else 1.0
    q_up = max(ups) if ups else 1.0
    return q_lo, q_up


def overrules(M, c, k, q):
    """The exact prediction of (H), read off g's sign: at q < 1 some
    atom's best class is not class 0; at q > 1 some atom with a light
    top class prefers another class to k - 1, at 1/q. g is negative
    only inside (0, 1), where at a = 0 it is q - 1, so neither side nor
    a = 0 is cased."""
    a, b = divmod(c, k)
    for r in range(M):
        lo = blocks(M, c, k, r)
        n = [lo[y + 1] - lo[y] for y in range(k)]
        heavy = [y for y in range(k) if n[y] == a + 1]
        if heavy[0] >= 1 and g_poly(q, a, a * heavy[0]) < 0:
            return True
        if n[k - 1] == a and g_poly(1 / q, a, a * (k - 1 - heavy[-1])) < 0:
            return True
    return False


def rational_near(x, den=10 ** 6):
    return Fraction(round(x * den), den)


def mag_grid(Ms, cmax, kmax):
    return [(M, c, k) for M in Ms for c in range(2, cmax + 1)
            for k in range(2, kmax + 1) if k <= M * c]


def magnitude_uniform(grid):
    """The uniform laws over a grid of (M, c, k): the block lengths and
    heavy set and the achiever's class by atom, the ceiling, floor and
    dead-cell equivalence by cell."""
    rec = dict(cells=len(grid), atoms=0, blocks=0, heavy_atoms=0, achiever=0,
               ceiling=0, dead=0, saturated=0, dead_law=0)
    for M, c, k in grid:
        a, b = divmod(c, k)
        N = M * c
        for r in range(M):
            lo = blocks(M, c, k, r)
            n = [lo[y + 1] - lo[y] for y in range(k)]
            heavy = {y for y in range(k) if n[y] == a + 1}
            want_heavy = {k * (m * M + r) // (b * M) for m in range(b)}
            rec["atoms"] += 1
            rec["blocks"] += n == block_formula(M, c, k, r) \
                and set(n) <= {a, a + 1} \
                and len(heavy) == b and heavy == want_heavy
            if b:
                rec["heavy_atoms"] += 1
                rec["achiever"] += (k * r) // (b * M) == min(heavy)
        right, fl, _ = magnitude_exact(M, c, k, Fraction(1))
        rec["ceiling"] += Fraction(right, N) == Fraction(-(-c // k), c) \
            and Fraction(fl, N) == Fraction(-(-N // k), N)
        is_dead = right == fl
        saturated = M * (k - b) < k
        rec["dead"] += is_dead
        rec["saturated"] += saturated
        rec["dead_law"] += is_dead == (b == 0 or saturated)
    return rec


def magnitude_four(grid, tilts):
    """(atoms, by tilt, whose best classes lie in the allowed pair, atoms
    by tilt)."""
    ok = n = 0
    for M, c, k in grid:
        a, b = divmod(c, k)
        for theta in tilts:
            _, _, tops = magnitude_exact(M, c, k, theta)
            for r in range(M):
                lo = blocks(M, c, k, r)
                cnt = [lo[y + 1] - lo[y] for y in range(k)]
                heavy = [y for y in range(k) if cnt[y] == a + 1]
                allowed = {0, *heavy[:1]} if theta < 1 else \
                    {*heavy[-1:], k - 1}
                n += 1
                ok += 0 < len(tops[r]) and tops[r] <= allowed
    return ok, n


def magnitude_arc(grid, tilts):
    """The tilted verdicts over a grid: at k | c each read as the
    floor's; otherwise each exact probe against the arc and against
    overrules(), and the band at M > k, a >= 1."""
    rec = dict(floor_reads=0, floor_law=0, probes=0, arc_law=0, g_law=0,
               banded=0, band_law=0)
    for M, c, k in grid:
        a, b = divmod(c, k)
        if b == 0:
            for theta in tilts:
                right, fl, _ = magnitude_exact(M, c, k, theta)
                rec["floor_reads"] += 1
                rec["floor_law"] += right == fl
            continue
        q_lo, q_up = arc(M, c, k)
        qs = []
        if 0 < q_lo < 1:
            qs += [q_lo * 0.95, q_lo + (1 - q_lo) * 0.05]
        if 1 < q_up < float("inf"):
            qs += [q_up * 1.05, q_up - (q_up - 1) * 0.05]
        probes = list(tilts) + [rational_near(x ** (1 / M)) for x in qs]
        for th in probes:
            q = float(th) ** M
            right, fl, _ = magnitude_exact(M, c, k, th)
            alive = right > fl
            rec["probes"] += 1
            rec["arc_law"] += alive == (q_lo < q < q_up)
            rec["g_law"] += alive == overrules(M, c, k, th ** M)
        if M > k and a >= 1:
            rec["banded"] += 1
            rho = resonance_root(a, 2 * a + 1)
            rec["band_law"] += abs(q_lo - rho) <= 1e-9 \
                and abs(q_up - 1 / rho) <= 1e-9
    return rec


def section_magnitude():
    section("THE k-ARY PARENT: the arc replaces the resonance points")
    one = magnitude_exact(15, 7, 2, Fraction(1))
    zero = magnitude_exact(2, 3, 5, Fraction(1))
    check("controls: M = 15, c = 7, k = 2 gives 4/7; M = 2, c = 3, k = 5 "
          "dead at 1/3",
          Fraction(one[0], 105) == Fraction(4, 7)
          and Fraction(zero[0], 6) == Fraction(zero[1], 6)
          == Fraction(1, 3))
    rec = magnitude_uniform(mag_grid((2, 3, 6, 15, 35), 12, 9))
    check("blocks of lengths a and a + 1, exactly v heavy, at the stated "
          "heavy set, at all 5,341 atoms of the 428 cells",
          (rec["cells"], rec["atoms"], rec["blocks"]) == (428, 5341, 5341),
          f"{rec['cells']} cells")
    check("uniform ceiling ceil(c/k)/c, floor ceil(N/k)/N, at all 428",
          rec["ceiling"] == 428)
    check("dead iff k | c or M(k - v) < k, at all 428: 144 dead, 44 "
          "saturated",
          (rec["dead_law"], rec["dead"], rec["saturated"]) == (428, 144, 44),
          f"{rec['dead']} dead, {rec['saturated']} saturated")
    check("the first heavy class is floor(kr/(vM)) at all 4,121 "
          "atoms with k not dividing c",
          (rec["heavy_atoms"], rec["achiever"]) == (4121, 4121))
    tgrid = mag_grid((2, 3, 6, 15), 10, 6)
    got = magnitude_four(tgrid, MAG_TILTS)
    check("off uniform the best class is 0 or the first heavy below, the "
          "last heavy or k - 1 above, at all 10,494 atoms by tilt",
          (len(tgrid), got) == (178, (10494, 10494)),
          f"{len(tgrid)} cells x {len(MAG_TILTS)} tilts")
    rec = magnitude_arc(tgrid, MAG_TILTS)
    check("at k | c the verdict is the floor's at all 468 reads",
          (rec["floor_reads"], rec["floor_law"]) == (468, 468))
    check("the cell is alive exactly where some atom's g < 0, at all "
          "1,470 probes", (rec["probes"], rec["g_law"]) == (1470, 1470))
    check("alive exactly on one open arc (q_lo, q_up), dead off it, at all "
          "1,470", rec["arc_law"] == 1470)
    check("at k not dividing c, M > k, a >= 1 the arc is (rho_a, 1/rho_a), "
          "at all 44", (rec["banded"], rec["band_law"]) == (44, 44),
          f"{rec['banded']} cells")
    rhos = [resonance_root(a, 2 * a + 1) for a in range(1, 7)]
    print("  rho_a, a = 1..6: " + ", ".join(f"{x:.6f}" for x in rhos))
    check("rho_1..rho_6 are roots of q^(2a+1) - 2q^a + 1 in (0, 1), rho_1 "
          "the reciprocal golden ratio",
          sum(0 < x < 1 and abs(f_res(x, a, 2 * a + 1)) <= 1e-9
              for a, x in enumerate(rhos, 1)) == 6
          and abs(rhos[0] - (5 ** 0.5 - 1) / 2) < TOL)
    alive = magnitude_exact(15, 3, 2, Fraction(199, 200))
    dead_ = magnitude_exact(15, 3, 2, Fraction(24, 25))
    check("sign bit M = 15, c = 3: alive at theta = 199/200, dead at 24/25",
          alive[0] > alive[1] and dead_[0] == dead_[1],
          f"q = {float(Fraction(199, 200)) ** 15:.3f} and "
          f"{float(Fraction(24, 25)) ** 15:.3f} against rho_1 = "
          f"{rhos[0]:.3f}")


def section_controls():
    section("CONTROLS")
    check("sign N = 6: 2/3 at M = 2, 1/2 at M = 3",
          sign_brute(6, 2)[0] == Fraction(2, 3)
          and sign_brute(6, 3)[0] == HALF)
    check("sign sweep at cap 30: 20 cells over 8 rings, 8 dead, 12 live",
          sign_sweep(30) == dict(cells=20, rings=8, ceiling=20, dead=8,
                                 live=12, dead_law=20, log=20))
    rec, ceilings = threshold_row(30, 6, True)
    hand = [Fraction(sum(max(b, 5 - b) for b in
                         (sum(1 for j in range(5) if r + 6 * j < t)
                          for r in range(6))), 30) for t in range(1, 30)]
    check("threshold N = 30, M = 6: the sweep's ceilings are the "
          "definition's at t = 1..29, 3/5 at t = 13",
          ceilings == hand and ceilings[12] == Fraction(3, 5))
    check("threshold row (30, 6): 29 slices, 5 interior, seam 4, 0-1 "
          "floor 24",
          rec == dict(slices=29, ceiling=29, interior=5, inside=5,
                      floor01=24, log=29, seam=4, seam_law=29, achiever=29))
    check("threshold row (6, 3): 5 slices, none interior, seam 1",
          threshold_row(6, 3, True)[0]
          == dict(slices=5, ceiling=5, interior=0, inside=0, floor01=5,
                  log=5, seam=1, seam_law=5, achiever=5))
    live = dict(ceiling=True, decided=0, dead=False, log=True,
                achiever=True)
    check("orientation N = 6: 3/5 at M = 3; dead at M = 2; every class "
          "decided at M = 6",
          orientation_row(6, 3) == (Fraction(3, 5), live)
          and orientation_row(6, 2) == (HALF, dict(live, dead=True))
          and orientation_row(6, 6) == (Fraction(1), dict(live, decided=20)))
    live = dict(ceiling=True, achiever=True, dead=False, log=True,
                below_log2=True)
    check("comparison N = 6: 7/10 at M = 3, 3/5 at M = 2; dead at log 2 "
          "with the evidence severed, M = 1",
          comparison_row(6, 3) == (Fraction(7, 10), live)
          and comparison_row(6, 2) == (Fraction(3, 5), live)
          and comparison_row(6, 1)
          == (HALF, dict(live, dead=True, below_log2=False)))


def main():
    t0 = time.time()
    section_controls()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        return 1
    section_sign()
    section_threshold()
    section_orientation()
    section_tilt()
    section_resonance()
    section_magnitude()
    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())