poles.py

"""
poles.py -- the pole units read by the many-stream theorem, and the
law that sets their lookahead: the square root, the reciprocal and the
divider, whose lookahead can be negative.

QUESTION. manystream.py reads every C^2 map of signed-digit streams
at the least L with b^L rho >= Lam |I|, Lam the sup over the root box of
the gradient's L1 norm, L = c + o the lookahead plus the LEAD. The
literature's on-line units with a pole -- the square root sqrt(s + x), the
reciprocal 1/(s + x) and the divider x/(s + y) -- are C^2 on the
root box once the pole sits outside it. Three questions. Does the
theorem read them when the lookahead c = L - o is NEGATIVE, the
reader emitting digits before it reads one? What sets the sign of c:
the pole, the dependency structure (a stream multiplied by a function
of the others), or one number of the map? And how do the literature's
published on-line delays sit against the floors the law gives?

THE READER is manystream.py's: streams of the digits D = {-a-, ...,
a+} in radix b, SLACK rho = a- + a+ + 1 - b >= 1, M+- = a+-/(b - 1),
w = M- + M+, |I| = a- + a+; output digits weigh b^(o - t); at
lookahead c the output digit t is committed after n = max(0, t + c)
digits of every stream. The POLE DISTANCE h > 0 places the pole:
s = M- + h, so s + x runs over [h, h + w] on the root box.

THE ARGUMENT (written before this script).
  (1) EVERY L IN Z. For L < o the first o - L output digits are
      committed on the root box alone. The level-t zone has length
      (w - 1) b^(o - t) in absolute units, at least (w - 1) b^L at
      every t <= o - L, and the root box's image is at most Lam w wide,
      so under b^L rho >= Lam |I| no such digit is dead; below the law
      the kill of manystream.py's necessity argument sits at a depth
      n past which nothing changed. And a kill at a coarser level
      implies one at the next: in units of the coarser level a zone
      of length w - 1 holds a whole finer zone of length (w - 1)/b,
      spaced 1/b, whenever
      (w - 1)(b - 1) >= 1, which is rho >= 1. So the theorem holds
      as stated at every L in Z, the lookahead of either sign.
  (2) THE CLOSED FORMS. With Mh = max(M-, M+):
        sqrt(s + x): Lam = 1/(2 sqrt h), range [sqrt h, sqrt(h + w)];
        1/(s + x):   Lam = 1/h^2,        range [1/(h + w), 1/h];
        x/(s + y):   Lam = (h + Mh)/h^2, range [-M-/h, M+/h],
      each partial's modulus largest at the pole corner y = -M-, the
      divider's with |x| = Mh.
  (3) THE LEAD IS THE RANGE'S SCALE. The root tile [-M- b^o, M+ b^o]
      holds [lo, hi] iff b^o >= SIGMA = max(hi/M+, -lo/M-) (a+- >= 1),
      so o = ceil(log_b SIGMA), while L* = ceil(log_b(Lam |I| / rho)).
      Two ceilings differ by less than one more than their arguments,
      so with the RELATIVE GRADIENT Gamma = Lam / SIGMA,
          c* - log_b(Gamma |I| / rho)  lies in (-1, 1):
      THE RELATIVE-GRADIENT LAW. The map enters the lookahead through
      Gamma alone, to within one digit.
  (4) A MULTIPLIED STREAM. For f = x g(y), g > 0 on the root box with
      sup G, the x-partial is g, so Lam >= G, and the range is
      [-M- G, M+ G], so SIGMA = G and Gamma >= 1. At every cell
      |I|/rho = 1 + (b - 1)/rho lies in (1, b], so c* > -1: c* >= 0.
      At slack 1, |I|/rho = b and c* >= 1. The divider has
      Gamma = 1 + Mh/h, so c* < 2 + log_b(1 + Mh/h), and c* <= 2 once
      Mh/h <= b - 1, i.e. h >= Mh/(b - 1): h >= 1/(b - 1) while
      a+- <= b - 1, and no fixed multiple of 1/(b - 1) past the radix,
      where Mh > 1. At (2, 3, 1), h = 1: Lam = 4, 2^L 3 >= 16 at
      L* = 3, o = 0, c* = 3.
  (5) THE POLE UNITS RUN AHEAD. The root has Gamma =
      M+/(2 sqrt(h (h + w))) and the reciprocal Gamma = M+/h, both
      falling to 0 as h grows, so c* falls without bound: the reader
      emits ever more digits before it reads one.
  (6) THE STRUCTURE IS NOT THE VARIABLE. exp(-h y), one stream and no
      product, has Lam = h e^(h M-) and SIGMA = e^(h M-)/M+, so
      Gamma = h M+ RISES with h and c* climbs like log_b h. A stream
      multiplied by a function of the others is one way to hold Gamma
      up, not the only one.

THE DESIGN, frozen before the engine.
  THE PAIRS: the 20 cells b = 2..5, 1 <= a+- <= b - 1, rho >= 1
  (manystream.census), at h = j/(b - 1), j in {1, 2, 4, 8, 32, 128}.
  THE CLOSED FORMS against manystream.Cell's integer loops (law_L,
  lead) at every pair and unit; the root's decided by squaring.
  THE SCANS at L* and L* - 1, L* the LAW'S least L (never raised to
  the lead, unlike manystream.law_of): the reciprocal and the divider
  through manystream.scan with exact images and exact partial
  bounds; the root through a one-stream scan written here, since its
  image is irrational: the box [x0, x1] maps to
  [sqrt(s + x0), sqrt(s + x1)], only boxes with
  4 Lam_law^2 (s + x0) < 1 can kill (the excess region, rational),
  and the zone test asks for an integer strictly inside
  (sqrt(s + x0)/e + M- - 1, sqrt(s + x1)/e - M+), e = b^(L - n),
  decided by an exact floor of sqrt(A)/e plus a rational, by
  squaring. The same one-stream scan is run on the reciprocal as
  its control against manystream.scan.
  THE LAW'S BAND over six families -- sqrt(s + y), 1/(s + y),
  1/(s + y)^2, x/(s + y), exp(-h y), x exp(-h y) -- at the 20 cells
  and h = j/(b - 1), j in {1, 2, 4, 8, 32, 128, 1024, 8192}; the
  exponentials' ceilings in floating point, a pair whose argument sits
  within 1e-9 of an integer printed as a near-tie and not read.
  THE DIVIDER'S DENSE SWEEP: c* at h = j/(b - 1), j = 1..4096, and
  h = q/10, q = 1..1000, at the 20 cells and manystream.over_cells'
  89 cells past the radix, max(a-, a+) >= b, by the closed forms.
  THE LITERATURE'S TABLE: Ercegovac and Lang, Digital Arithmetic (2003),
  Table 9.1, read in the authors' own chapter 9 slides, gives the
  most-significant-first delays addition 2 (r = 2) and 1 (r >= 4),
  multiplication 3 (r = 2) and 2 (r = 4), division 4, square root 4,
  max/min 0; the slide deriving the multiplier's delay lists
  (r, redundancy factor a/(r - 1), delta) = (2, 1, 3), (4, 1, 2),
  (4, 2/3, 3). Their delta counts operand digits past the result
  digit with operands and result in one format, so it is c at o = 0.
  The product x y's c* at the three digit sets (2,1,1), (4,3,3) and
  (4,2,2) is set beside it.

PREDICTIONS.
  PA the controls, read first: the exact floor of sqrt against
     60-digit decimals at 3000 random rationals, perfect squares
     included, with no disagreement; the one-stream scan and
     manystream.scan give the reciprocal the same verdict and the same
     kill depth at every pair at L* - 1 and L*.
  PB the closed forms equal the loops at all 360 (unit, pair); the
     divider's c* is in {0, 1, 2} at every pair; the root's c* is
     negative at 65 of its 120 pairs (a transplant from the root's
     earlier census), the reciprocal's negative at some pair at every
     cell.
  PC at every (unit, pair) the scan at L* finds no kill and the scan
     at L* - 1 finds one, the negative lookaheads included; the
     deepest output depth at most 9.
  PD the band holds at every (family, cell, h).
  PE the divider: (2, 3, 1) at h = 1 reads c* = 3, the hand value
     (the control); c* >= 0 at every dense pair, >= 1 at every slack-1
     cell, <= 2 at every h >= Mh/(b - 1); 0 at some h at every cell of
     slack 2 or more (a transplant: the earlier sweep's zeros lay on
     exactly those ten cells of the 20).
  PF exp(-h y)'s c* at j = 8192 exceeds its j = 1 value at every cell;
     the root's and both reciprocals' sit below theirs at every cell.
  PG the product's c* is 2, 1 and 2 at (2,1,1), (4,3,3) and (4,2,2),
     one below the literature's delta at each.

KILLS, as what the script prints.
  K1 a PA line off: the comparator or the one-stream scan is wrong;
     nothing below is read.
  K2 a closed form off a loop: (2) or (3) is wrong.
  K3 a kill at L*, or a pair alive at L* - 1 whose scan ran out of
     region: the first is (1)'s sufficiency, the second necessity
     unread there.
  K4 the band broken at any read pair: (3) is wrong.
  K5 a divider c* below 0 anywhere, below 1 at slack 1 or above 2
     at h >= Mh/(b - 1): (4) is wrong.
  K6 exp(-h y) not rising at some cell: (6) is wrong.

POSITIVE CONTROL: PA, read before any verdict line.

THE ESTIMATE, a second question put after the record run: is the
literature's one extra multiplier digit (PG) the price of selecting the
output digit from an ESTIMATE of the residual rather than from the
residual itself?

  THE LITERATURE'S CONDITION (Ercegovac and Lang, chapter 9 slides 43-44,
  read at source, their radix, redundancy factor, estimate width and
  delay written here b, Mh, m and L). On the symmetric set {-a, ...,
  a} in radix b, with Mh = a/(b - 1), the slides print the bound
  Mh (1 - 2 b^-L) on the multiplier's scaled residual, the step's
  with the operands below 1; with the operands bounded by Mh, as the
  root box bounds them, the same step gives om = Mh (1 - 2 Mh b^-L),
  the slides' at Mh = 1 and the one read here. Selection
  constants exist when the residual is estimated to m fractional bits
  iff  T_m(om) >= (1 + 2^-m)/2,  T_m the truncation to m fractional
  bits. Of the four rows the slides tabulate, three are read here,
  (b, Mh, m, L) = (2, 1, 2, 3), (4, 1, 2, 2) and (4, 2/3, 3, 3); the
  fourth, (8, 2/3, 2, 3), is left out: 2/3 is no a/7, and the row
  fails the slide's own condition, T_2 = 1/2 < 5/8.
  THE ARGUMENT (written before the engine). T_m(om) <= om and
  (1 + 2^-m)/2 > 1/2, so some m works iff om > 1/2 STRICTLY: om > 1/2
  gives T_m(om) > om - 2^-m, which clears (1 + 2^-m)/2 once
  3 * 2^-m / 2 < om - 1/2. And om >= 1/2 unpacks to
  b^L (2a + 1 - b)(b - 1) >= 4a^2,  the product's law on the
  symmetric set, its lead the least o with b^o >= Mh (0 while
  a <= b - 1). The algebra asks nothing of a. So the least delay the
  condition reaches at any finite m is L* where the law holds
  strictly at L*, and L* + 1 where it holds with EQUALITY. At
  a = b - 1 equality reads b^L = 4: radix 2 at L = 2 and radix 4 at
  L = 1, two of the three published cells.

  PREDICTIONS.
  PH1 (the control) the three published rows satisfy the condition,
      and each fails at L - 1 at its own m.
  PH2 the least L over m <= 64 is L* + 1 at (2,1,1) and (4,3,3),
      where the law holds with equality at L*, and L* at (4,2,2),
      first reached at m = 4.
  PH3 over the 3166 symmetric cells b/2 <= a <= 2b of radices 2..64,
      the least L over m <= 64 is L* where the law is strict and
      L* + 1 where it is an equality; the equality cells are the two
      of PH2 (a guess, not derived for a != r - 1). manystream.law_of's
      lead and law L* are the formulas' at every cell.
  KILLS, as prints.
  K7 a PH1 row off: the condition is misread from the slides; every
     verdict below is void (they still print).
  K8 a cell whose least L is neither the argument's value nor
     unreached at m = 64: the argument is wrong.
  FINDINGS (entered after the run).
  - PH1 holds: the three published rows satisfy the condition at
    their L and fail at L - 1, at the bound read here and at the
    slides' own, which part only at (4, 2, 2): the control does not
    tell the two bounds apart. K7 did not fire.
  - PH2 holds: om at L* is exactly 1/2 at (2,1,1) and (4,3,3), where
    the least L over every m is 3 and 2, the published values;
    at (4,2,2) om = 11/18 and L = 2 is reached at m = 4, one
    below the published 3 at m = 3.
  - PH3 holds: over the 3166 cells the least L is L* at every strict
    cell and L* + 1 at the equality cells, which are the two of PH2
    and no others; the strict cells reach L* by m = 8 (m = 1 at 2001
    cells, 2 at 592, 3 at 279, 4 at 140, 5 at 72, 6 at 45, 7 at 33,
    8 at 2). K8 did not fire. law_of agrees with the formulas at every
    cell; x y's lead is 0 at 1024 cells, 1 at 2140 and 2 at 2.
    So the extra digit is the estimate's only where the law is an
    equality; elsewhere a wider estimate reaches the floor.

  THE FUSED UNIT, a third question: does the chapter's method, carried
  to the multiply-add x y + z, reach that map's floor, and where does
  its estimate cost a digit?
  THE ARGUMENT (written before the engine). The scaled residual
  W[j] = b^j (F(X[j+d]) b^-o - P[j]), F = x y + z, d the chapter's
  delay and o the output's lead, steps by (x' Y + y' X + z') b^-L,
  L = d + o, x', y', z' the fresh digits and X, Y prefix values: at
  most a (2 Mh + 1) b^-L in size, a sup approached and never attained.
  Selection by rounding keeps |W| <= om at every step iff
  b om + a (2 Mh + 1) b^-L <= a + om and om >= 1/2, so the largest
  bound is om = Mh (1 - (2 Mh + 1) b^-L), and om >= 1/2 is
  b^L rho >= Lam |I| with Lam = 2 Mh + 1, x y + z's rate. The
  multiplier is the same step without z', Lam = 2 Mh. The estimate's
  condition uses om and m alone, so the argument above carries: the
  least L over every finite m is L* where the law is strict, L* + 1
  where it is an equality. That rests on the estimate's error being
  below 2^(1-m), a residual held in two words each truncated to m
  bits: the selection constants then sit on the 2^-m grid between
  k + 1 - om and k + om - 2^-m. One truncation alone (error below
  2^-m) would ask only T_m(om) + om >= 1 (a TRANSPLANT from the
  carry-save reading, not run). At a = b - 1 equality reads b^L = 6:
  the cell (6, 5, 5) at L = 1, and no other. The lead: the root tile
  [-Mh b^o, Mh b^o] holds the range [-(Mh^2 + Mh), Mh^2 + Mh] iff
  b^o >= Mh + 1, so o = 1 iff a <= (b - 1)^2, and the chapter's
  delay is d = L - o. THE START: the first digit also needs the
  d-digit prefix's value inside om b^o. Read plainly, with
  p = Mh (1 - b^-d) the prefix's largest value, it is
  Mh (1 + b^-2d) <= b - 1 for x y + z at o = 1 and
  Mh (1 + b^-2L) <= 1 for x y at o = 0: the first fails at (2, 1, 1)
  alone below the radix, the second at every a = b - 1 cell, the
  published (2, 1, 1) at d = 3 included (49/64 > 48/64). The slides
  start at a zero residual, run L steps with no result digit and
  print no operand range, so only the per-step condition is compared.

  PREDICTIONS, over the 3166 symmetric cells b/2 <= a <= 2b of
  radices 2..64.
  PH4 the least L over m <= 64 is L* where x y + z's law is strict
      and L* + 1 where it is an equality; the one equality cell is
      (6, 5, 5) at L* = 1 (a guess for a != b - 1); manystream.law_of
      gives x y + z the lead the least o with b^o >= Mh + 1 and the
      formula's L* at every cell.
  PH5 (read, not a kill) the start as read plainly fails at x y's
      a = b - 1 cells and (2, 2), (2, 4), (3, 6), and at x y + z's
      (2, 1), (2, 3), (3, 4), at the least L.
  KILLS, as prints.
  K9  a cell whose least L is not PH4's value: the argument is wrong.
  K10 a cell where manystream.law_of's (o, L*) differs from the
      formulas': the rate or the lead is misread.
  PLANT, for K9: x y's om read against x y + z's law must fire K9,
      else K9 cannot see a wrong om. It fires by construction where
      the two laws differ, so it shows the comparator, not the
      derivation.
  CONTROL: PH1-PH3, run through the same generalised helpers.
  FINDINGS (entered after the run).
  - The control holds through the generalised helpers: PH1-PH3 print
    as before.
  - PH4 holds: over the 3166 cells K9 did not fire. The one equality
    cell is (6, 5, 5) at L* = 1, where the estimate costs L* + 1 = 2;
    the strict cells reach L* by m = 8 (m = 1 at 1927, 2 at 606, 3 at
    298, 4 at 149, 5 at 81, 6 at 62, 7 at 37, 8 at 5). K10 did not
    fire: the lead is 1 at 3161 cells, 2 at 4 and 3 at 1, and only
    its lead half is independent of the formula.
  - The plant fired: x y's om leaves 43 cells off, the first (2, 3, 3),
    (5, 3, 3), (5, 4, 4), each reading L one below x y + z's L*.
  - PH5 holds: the start read plainly fails at 66 x y cells, the 63
    with a = b - 1 and (2, 2), (2, 4), (3, 6), and at (2, 1), (2, 3),
    (3, 4) for x y + z.
    So the chapter's per-step condition, read at an exact residual,
    reaches x y + z's floor, and its estimate costs a digit at
    (6, 5, 5) alone among these cells, past the radix included:
    algebra the run confirms, no
    recurrence simulated.

  THE WELD, a fourth question: manystream.py reads its nine maps with
  the lead above L* (c* < 0) at 15 pairs over 6 cells past the radix,
  all a- >= b and a+ <= 2, and at none of the 180 pairs inside it; the
  absolute value reads at lookahead -2 at (2, 3, 1), (3, 5, 1),
  (4, 7, 1), (5, 9, 1), (6, 11, 1). Is that one fact?
  THE ARGUMENT (written before the engine). Each of the nine maps has
  f(0) = 0, and the root box [-M-, M+]^k is convex and holds 0, so on
  it |f(x)| <= Lam |x|_inf <= Lam Mh: hi, -lo <= Lam Mh. So
  K = max(hi/M+, -lo/M-) <= Lam a_max/a_min and Gamma = Lam/K >=
  a_min/a_max, a_min and a_max the smaller and larger of a+-. With
  the band c* > log_b(Gamma |I|/rho) - 1,
      c* > log_b B - 1,    B = a_min |I| / (a_max rho),
  and B < 1 iff a_min^2 < a_max (a_max + 1 - b), a LOPSIDED cell.
  Inside the radix a_max <= b - 1, the right side is <= 0, B > 1 and
  c* >= 0. The absolute value (Lam = 1, not C^2, read by its
  criterion: L = 0 iff (b - 1) | (a+ - a-), else 1; its lead the
  least o with b^o a+ >= a- when a- > a+) is negative only where
  o >= 1 at a divisible cell, a- = a+ + k(b - 1) >= b, or o >= 2
  elsewhere, a- > b a+; at both a+^2 < a-(a- + 1 - b).
  PREDICTIONS.
  PI0 (the control) B > 1 at all 20 cells and no map binds there; a
      PLANT, x y + 8 (x y's rate lifted off the origin), run through
      PI1-PI3's own comparisons at the 20 cells, fires PI1, PI2 and
      PI3's kill.
  PI1 Gamma >= a_min/a_max at every (map, cell), 9 maps x 109 cells.
  PI2 b^(c* + 1) > B at every pair, exact.
  PI3 every binding pair (c* < 0) at a B < 1 cell; 15 pairs over 6.
  PI4 |x| over the 265 cells of radices 2..6 with a+- <= 2b - 1 and
      rho >= 1: every negative lookahead at a B < 1 cell; 35
      negative, 5 at -2.
  KILLS, as prints: a PI1 or PI2 pair off, a PI3 binding pair at
  B >= 1, a PI4 cell negative at B >= 1. PI0 off: PI1-PI4 not read.
  FINDINGS (entered after the run).
  - PI0 holds: the plant is off PI1 at 20 cells, off PI2 at 10 and
    binds at B >= 1 at 9.
  - PI1, PI2 hold at every pair of the 9 maps and 109 cells.
  - PI3 holds (given PI2 it cannot fail: b^(c* + 1) > B >= 1 gives
    c* >= 0): the 15 binding pairs sit at (2, 3, 1), (3, 5, 1),
    (4, 5, 1), (4, 6, 1), (4, 7, 1), (4, 7, 2), c* = -1 at each, K
    leaning on hi/M+ at all 15 (the range's long end on the tile's
    short side). 54 of the 109 cells are lopsided, 48 binding no map:
    the condition is necessary, far from sufficient.
  - PI4 holds: 35 of the 265 read at a negative lookahead, -2 at the
    five, every one lopsided.
    So the two land on one cell condition by two implications, the
    band for the maps and the criterion for |x|.

  THE RUN-AHEAD CRITERION (PJ), a fifth question: is K = hi/M+ at the
  15 pairs the whole condition? Write the SHORT side as the side of the
  lesser of a+- (+ when a- >= a+; the mirror -f(-x) swaps the sides).
  THE ARGUMENT (written before the engine).
  S1 c* < 0 iff hi > M+ b^(L*). |f| <= Lam Mh on the convex box holding
     0, and b^(L*) rho >= Lam |I| > Lam rho, so the lead-L* tile holds
     lo: the long end never binds; at a- = a+ the same bound holds hi.
     Depth: for m >= 1, c* <= -m iff hi > M+ b^(L* + m - 1).
  S2 the REACH t = hi/(Lam M-), in [0, 1]. f(x) = int_0^1 grad f(sx).x ds
     and sx lies in the cube of radius s Mh, so t <= tbar =
     int_0^1 lamf(s Mh) ds / lamf(Mh), lamf manystream's Lam on the
     cube; a homogeneous map of degree d has tbar = 1/d. With S1 and
     b^(L*) rho >= Lam |I|, a map runs ahead only at a tbar-LOPSIDED
     cell, a+ |I| < tbar a- rho (d-lopsided, d a+ |I| < a- rho, for a
     homogeneous map; d = 1 is PI's lopsided).
  S3 x^2, x y, x^2 + x y put hi at the far corner, t = 1/2: there S1 is
     the cell condition a-^2 lam0/2 > a+ (b - 1) b^(L*), lam0 = Lam/M- =
     2, 2, 4. x^3, x^2 y, x y z have hi/M+ <= M-^2 = Lam/3 < b^(L*):
     never, at a+ > a- too, each being odd; -x^3 reaches 1/3 and can.
     At a+ > a- the three Euler-tight maps' short end -lo is at most
     M- M+ < M- b^(L*), so they never run ahead there (argued after the
     freeze; RA4 reads the form False there against c*).
  FAMILIES: the 109 cells, and WIDE, radices 2..7, a+ in {1, 2}, a-
  from b to 4b, rho >= 1, less the 109 (152 cells, so that c* = -2 is
  reachable). c* = L* - o: the cell's law_L at law_of's Lam, less
  law_of's lead o (law_of's own L is floored at o).
  KILLS over the nine maps: RA1 a pair where S1's test differs from
  c* < 0; RA2 S1's depth differing from max(0, -c*); RA3 t > 1/d at a
  homogeneous pair, or c* < 0 at a cell not d-lopsided; RA4 S3's form
  differing from c* < 0; RA5 a c* < 0 among x^3, x^2 y, x y z; RB t >
  tbar at a cell with a- >= a+, or a run-ahead pair off a tbar-lopsided
  cell (given RB's first clause and RA1 the second cannot fail).
  CONTROLS (PJ0): PI's 15 pairs (the same law_of: a regression read,
  not a second instrument); x y - 8 fires RA1 and RA2 ((2, 1, 1),
  range [-9, -7], o = 4, L* = 2); x y + 8 tagged degree 2 fires both
  RA3 clauses and RB at the cells with a- >= a+ (at a+ > a- the + 8
  lifts the long end, so it pushes no reach there); -x^3 tagged degree
  3 fires RA5; x^2's form on x^2 + y fires RA4 at (2, 3, 1); the hand
  witnesses; tbar against the hand integrals of x^2, x^3, x^2 + y and
  x(1 - y^2) (M^2 - 1 + 4/(3M) at M >= 1, else 1 + M^2/3).
  PREDICTIONS: no kill fires; c* = -2 first at x^2 (2, 6, 1); t = tbar
  at x^2, x y, x^2 + x y everywhere and at x^2 + y, x y + z iff a- = a+,
  the gap (M- - M+)/((2M- + 1)M-); x(1 - y^2) strictly below tbar.
  FINDINGS (entered after the run).
  - PJ0 holds: x y - 8 off RA1 and RA2 at 11 cells each; x y + 8 off
    RA3 at 88 entries and RB at all 63 cells with a- >= a+ of the 109;
    -x^3 off RA5 at 67, first (2, 6, 1), c* = -1.
  - RA1-RA5 and RB hold over 109 + 152 cells. The long end's largest
    share of its lead-L* tile is 7/18: S1's bound has slack.
  - 506 run-ahead pairs over 125 cells, c* in {-2, -1}: x^2 85 (5 at
    -2), x y 85 (5), x^2 + y 83 (5), x y + z 83 (5), x^2 + x y 110
    (10), x(1 - y^2) 60 (0, all in WIDE), x^3, x^2 y, x y z 0; the first
    c* = -2 at (2, 6, 1), as predicted.
  - t = tbar at x^2, x y, x^2 + x y at all 215 cells with a- >= a+; at
    x^2 + y, x y + z, and (read after the freeze) x^3, x^2 y, x y z at
    exactly the 17 with a- = a+; x(1 - y^2) at none. So tbar is a law,
    sharp only at the Euler-tight maps, and the reach a per-map number.
  - Exploratory: run-ahead is not monotone in a-. At radix 2, a+ = 1,
    x^2 and x y run ahead at a- = 3, 5, 6, 7, 8, not 4: at (2, 4, 1)
    hi = 16 = M+ b^(L*), the high end on the tile's edge. By hand (after
    the run) every a- >= 5 runs ahead there: b^(L*) < 4(a- + 1) <= a-^2.

  THE FED FACTOR (PK), a sixth question. In a chain the factor is a
  producer's output and may run ahead of the consumer's fresh stream.
  Read z y with digit t committed after nz = max(0, t + c) digits of z
  and ny = max(0, t + c + d) of y (WHOLE: y's value known at the
  start), y a free stream of D, its range the root box; a producer's
  narrower range is not read. Where does z y run ahead, c < 0, where
  lockstep x y does not?
  THE ARGUMENT (by hand, before the engine).
  SUFFICIENT. z y - z'y' = z(y - y') + y'(z - z'), so a box at depths
  (nz, ny) maps into an interval at most sup|y| w b^-nz + sup|z| w b^-ny
  long. At t + c >= 0 the zone is (w - 1) b^(L - nz), so by the tile
  lemma every box passes when Lam_d = sup(|y| + b^-d |z|) = Mh(1 + b^-d)
  <= Lam_law = (w - 1) b^L / w, and its descendants inherit the test
  (the scan's prune). The early levels pass: at t + c < 0 <= t + c + d,
  z the root box and ny < d, Mh w (1 + b^-ny) <= (w - 1) b^(L + d - ny);
  at t + c + d < 0 the image, the range, is at most 2 Mh w wide, the
  zone at least (w - 1) b^(L + d + 1) >= Mh w (b^(d+1) + b). WHOLE: the
  map z -> v z, the same test at Lam = Mh.
  NECESSARY, at finite d. Let P be the d-digit prefix of y on its long
  side (every digit -a- where M- >= M+, else a+), so y = P + b^-d y'.
  On the inputs whose y opens with P the fed reader is a lockstep
  reader of f_P(z, y') = z(P + b^-d y') on the root box, at the same c
  and lead: the digits of P it reads early carry nothing. f_P is C^2,
  |grad f_P|_1 = |y| + b^-d |z| has its sup Mh(1 + b^-d) = Lam_d at
  the corner z = y' = the long end, and its Hessian (off-diagonal
  b^-d) is nowhere zero. So below the law the many-stream theorem's
  necessity (below the lead by (1) above) gives a box of f_P, a fed
  box, whose image strictly contains a level-t zone, t = n - c >= 1:
  the fed reader is dead. WHOLE: where Mh > Lam_law take v irrational,
  Lam_law < |v| <= Mh, on the long end's side. A z-box of prefix j at
  depth n kills iff an integer lies in the window
  (v(j - M-) b^-L + M- - 1, v(j + M+) b^-L - M+) (v > 0; v < 0 its
  mirror), of length |v| w b^-L - (w - 1) > 0, whose left end steps by
  the irrational v b^-L over consecutive j: as n grows some window
  holds one. So
    c_d = law_L(Mh (1 + b^-d)) - o,   c_whole = law_L(Mh) - o,
  o the lead of the range, the same at every d. Lam_0/Lam_d <= 2 <= b,
  so L_0 - L_d is 0 or 1. At a- >= a+, c_d < 0 needs
  a+(1 + b^-d)|I| < a- rho (x y's T-bar = 1/2 bound at d = 0, T-bar = 1
  whole); at a+ > a- z y never runs ahead, -z y its mirror. WITNESS
  (2, 4, 1): o = 4; d = 0 L = 4, c = 0; d = 1 2^L >= 7.5, L = 3,
  c = -1.
  THE DESIGN. Frozen before the engine: the cells, the maps, the d, the
  kill and the predictions; set with the engine: NV = 3, the 40 values,
  the budget 400,000.
    CELLS: ms.census() + ms.over_cells() (109) and wide_cells (152).
    MAPS: z y and -z y; d in 0, 1, 2, 4 and WHOLE.
    THE SCAN (fed_scan): levels t = 1.., states the prefix pairs (j, k)
    at depths (nz, ny), deduplicated; a kill is an image strictly
    containing a level-t zone (e = b^(o - t)); the prune above, only at
    t + c >= 0. WHOLE (fed_scan_whole): y a point v, a depth-NV box's
    end, |v| > Lam_law, the 40 largest |v|, every z prefix at depths up
    to the budget. The scan WITNESSES NECESSITY (a kill at L_d - 1); its
    emptying at L_d is the prune, the sufficiency proof restated, with
    only the early levels (t + c < 0) read box by box.
  PREDICTIONS (frozen, verbatim; F0..F4 are PK0..PK4):
  F0 controls, read first: (i) d = 0 reproduces section_pj's 85 x y
     run-ahead pairs, cell for cell and c for c; (ii) the weighted scan
     at d = 0 agrees with manystream.scan on x y at L* - 1 (dead, same
     kill depth) at the 20 cells; (iii) PLANT: a scan whose prune drops
     the b^-d (reads sup|y| + sup|z|) must miss a kill at some pair the
     true scan kills at L_d - 1, d >= 1; a scan reading y at nz (d
     ignored) must kill at some L_d where the true one empties.
  F1 the lead o is the same at every d (the variable held).
  F2 c_d nonincreasing in d at every (map, cell); L_0 - L_d in {0, 1}.
  F3 new run-ahead pairs (c_d < 0 <= c_0) exist at d = 1 ((2, 4, 1)
     among them); every one satisfies a+(1 + b^-d)|I| < a- rho at
     a- >= a+; none at a+ > a- for z y; -z y's new pairs only at a+ > a-.
  F4 the scan at every new pair: a kill at L_d - 1, emptied at L_d.
  KILL (frozen, verbatim): the script prints, per d in (1, 2, 4, whole),
  the count of (map, cell) over the 109 + 152 cells and the maps z y,
  -z y with c_d < 0 <= c_0. KILL of "a factor fed ahead widens
  run-ahead": all four counts 0. KILL of the law c_d = law_L(Lam_d) - o:
  any pair where the scan at L_d - 1 finds no kill within its budget AND
  at L_d does not empty, or where it kills at L_d (a budget miss at
  L_d - 1 is printed as unread, not as a kill). Printed beside: the
  deepened pairs (c_d < c_0 < 0), and the absolute gain L_0 - L_d's
  values.
  CHANGED from the frozen design. The plants: 'nob' (prune on sup|y| +
  sup|z|) prunes less than the true scan and could never miss; its
  successor 'noz' (sup|y| alone) missed by construction wherever it
  could be read; both are gone, and only 'lock' (lockstep x y in full)
  stands. WHOLE's factor values: a depth-NV grid with a zero tail stops
  below M-, so at (2, 8, 2), L = 3 it held no v above the law and
  answered 'empty'; v now runs over the boxes' ends, 'empty' is
  returned only where Mh <= Lam_law, and an 'empty' at L_d - 1 is a law
  kill (run apart, a planted break restoring the old grid and its 'empty' fails
  PK4's law check at (2, 8, 2) whole and (2, 8, 1) whole). The law
  kill is read as an empty at L_d - 1 or a kill at L_d; at WHOLE both
  verdicts at L_d are the closed form, so there it fires only at
  L_d - 1. F0 (i) is read with F1 and F2 as arithmetic on the law, not
  as a control. The controls run first and stop the section. PK4 also
  scans the deepened triples. The necessity, first a sketch along a
  line of prefixes, is now the reduction to f_P above.
  FINDINGS (entered after the run).
  - PK0 holds: the scan at d = 0 kills x y at L* - 1 at
    manystream.scan's depth at the 20 cells; 'lock' kills at L_1 at
    6 of 6 new d = 1 pairs.
  - PK1, PK2 hold: d = 0 gives PJ's 85 pairs, cell for cell; the lead
    is the same at every d by construction (the range has no d), so its
    check was cut; c_d nonincreasing; L_0 - L_d takes 0 and 1.
  - PK3: THE KILL MISSED. New run-ahead pairs (c_d < 0 <= c_0), over
    the 109 + 152 cells and the maps z y, -z y:
        d = 1: 65 (z y 61, -z y 4), deepened (c_d < c_0 < 0) 29
        d = 2: 81 (71, 10), deepened 45
        d = 4: 84 (73, 11), deepened 49
        whole: 88 (75, 13), deepened 56
    z y runs ahead at 85, 146, 156, 158, 160 cells at d = 0, 1, 2, 4,
    whole; the least c_d is -2 to d = 2 and -3 at d = 4 and whole.
    (2, 4, 1) is new at d = 1. Every new pair sits inside
    a_short(1 + b^-d)|I| < a_long rho, z y's at a- > a+, -z y's at
    a+ > a-.
  - PK4 holds: at all 318 new and 179 deepened (map, cell, d) triples
    the scan kills at L_d - 1 (output depth 2 to 4) and empties at
    L_d; none unread, no law kill.
    So a factor fed d ahead is read at the margin law with its partial
    weighed by b^-d, Lam_d = Mh(1 + b^-d), sufficiency and necessity
    proved above and each kill exact. It widens run-ahead from x y's
    T-bar = 1/2 bound toward the whole factor's T-bar = 1, but buys at
    most one digit of delay per hop at any d.

FINDINGS (entered after the run; every number is a print).
  - PA holds: the exact floor of sqrt agrees with 60-digit decimals
    at 3000 of 3000 rationals, and the one-stream scan with
    manystream.scan on the reciprocal at 240 of 240 (pair, L). K1 did
    not fire.
  - PB holds: the closed forms equal the loops at 360 of 360. The
    root's c* runs from -7 to 0 and is negative at 65 of 120 pairs,
    as the transplant said; the reciprocal's from -6 to 2, negative at
    40 pairs over all 20 cells; the divider's c* is 0 at 5 pairs, 1 at
    75 and 2 at 40.
  - PC holds: all 360 (unit, pair) are alive at L* and dead at
    L* - 1, the 105 negative lookaheads included, every survival at
    L* read as the excess region running out, which at each unit's
    root box is the law's prune (sufficiency restated, below). The
    kills sit at
    output depth 1 to 9 for the root (the 9 at one pair), 1 to 8 for
    the reciprocal and 1 to 8 for the divider.
  - PD holds: the band at all 960 (family, cell, h), no near-tie. The
    greatest deviations are 0.999 (the root), 0.876 and 0.893 (the
    reciprocals), 1.000 printed for the divider (a float rounding),
    0.924 (exp(-h y)) and 0.952 (x exp(-h y)). PD' reads the four pole
    units' band exactly, b^(2c* - 2) < Gamma^2 |I|^2/rho^2 < b^(2c* + 2)
    in Fractions, and it holds at every pole-unit pair; a plant
    shifting the divider's c* by one fails it (run apart).
  - PE holds: the control reads c* = 3. Over 539164 dense pairs of
    the 109 cells c* is 0 at 278143, 1 at 259691, 2 at 1173, 3 at
    127, 4 at 22 and 5 at 8; at most 2 at every h >= Mh/(b - 1), at
    least 1 at every slack-1 cell, and 0 somewhere at exactly the 99
    cells of slack 2 or more. At h >= 1/(b - 1) it reaches 3 at 12
    pairs over 7 cells, all past the radix.
  - PF holds: from j = 1 to j = 8192, exp(-h y)'s c* rises by 5 to 13
    at every cell; the root's falls by 4 to 12, the reciprocal's and
    1/(s + y)^2's by 5 to 13.
  - PG holds: the product's c* is 2, 1 and 2 at (2,1,1), (4,3,3) and
    (4,2,2), each dead at L* - 1, against the literature's delta 3, 2 and
    3: the published multiplier sits one digit above the floor at all
    three digit sets.
  - PB's loops share each unit's Lam and range with its closed form,
    so PB checks the ceilings and the divider's lead; PC reads Lam
    against the scans.
  - The reciprocal's PC scans ran through the one-stream scan, not
    manystream.scan as the design says. PA shows that the two agree
    at exactly those 240 (pair, L).
  - One change after the first run, no verdict touched. The divider's
    scan at L* - 1 as frozen (manystream.scan over both streams) ran
    out of budget at (2,1,1), h = 128, where the excess is 0.008 of a
    zone. Given more budget it found the kill at output depth 7 but
    passed the 512 MB ceiling. Below the law the divider is now
    searched on the edge |x| = Mh alone (edge_scan): a search for a
    witness, which can only find a kill. Survival at L* is still read
    by the full scan, whose region is empty at the root box: at every
    unit the root box's rate is Lam, at most the law at L*, so the
    survival half restates sufficiency and only the kill at L* - 1 is
    evidence.

RUN RECORD: 21/21 checks, 2.1 s, peak commit 14.4 MB under a memory guard;
after an audit (survival at L* read only where the excess region ran
out, PG's kills asserted), 21/21, 2.0 s, 13.8 MB; with the fused
unit, 27/27, 3.5 s, 14.8 MB; with PD', 28/28, 3.5 s, 14.8 MB; with
PE and PH read past the radix, 29/29, 13.7 s, 14.4 MB; after an
audit (PE prints the largest c* at h >= 1/(b - 1)), 29/29, 14.1 s;
with the weld (PI), 38/38, 14.2 s, 15.0 MB; with the run-ahead
criterion (PJ), 53/53, 13.2 s, 16.4 MB; with the fed factor (PK),
64/64, 19.3 s, 22.8 MB; after an audit (the lead's check, true by
construction, cut; the (2, 4, 1) witness printed and checked), 63/63,
19.3 s, 22.7 MB. With counts moved into the conditions of PA to PF,
PI, RB and PK (other counts the findings quote are printed only, and
three checks name the 20 cells without counting them), RA4's plant
passed through ra, and PH1 read at both bounds: 63/63, 19.4 s,
24.8 MB.
"""

import math
import random
import time
from decimal import Decimal, getcontext
from fractions import Fraction as Fr

import manystream as ms

CHECKS = []
NMAX = 16
BUDGET = 300_000
JS = (1, 2, 4, 8, 32, 128)
JS_BAND = (1, 2, 4, 8, 32, 128, 1024, 8192)


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 least_pow(b, X):
    """The least integer k with b^k >= X, X a positive rational."""
    k = math.log(X.numerator) - math.log(X.denominator)
    k = math.floor(k / math.log(b)) - 2
    while Fr(b) ** k < X:
        k += 1
    while Fr(b) ** (k - 1) >= X:
        k -= 1
    return k


# ---- exact values: a rational, or the square root of one ----

def sqrt_ge(A, y):
    """sqrt(A) >= y, exactly."""
    return y <= 0 or y * y <= A


def vfloor(v, e, c):
    """floor(v/e + c), v = ('q', r) or ('r', A) meaning sqrt(A)."""
    kind, x = v
    if kind == "q":
        return math.floor(x / e + c)
    m = math.floor(math.sqrt(float(x)) / float(e) + float(c)) + 2
    while not sqrt_ge(x, (m - c) * e):
        m -= 1
    return m


def vgt(v, e, y):
    """v/e > y, exactly."""
    kind, x = v
    if kind == "q":
        return x / e > y
    return y * e < 0 or (y * e) ** 2 < x


def one_kills(cell, lo, hi, n, L):
    """manystream's zone test on an image [lo, hi] of exact values."""
    e = Fr(cell.b) ** (L - n)
    return vgt(hi, e, vfloor(lo, e, cell.Mm) + cell.Mp)


# ---- the units: s = M- + h ----

class Root:
    name = "sqrt(s + x)"

    def __init__(self, cell, h):
        self.c, self.h, self.s = cell, h, cell.Mm + h

    def law_L(self):
        X = Fr(self.c.I ** 2, 4 * self.c.rho ** 2) / self.h
        return -((-least_pow(self.c.b, X)) // 2)

    def lead(self):
        X = (self.h + self.c.w) / self.c.Mp ** 2
        return -((-least_pow(self.c.b, X)) // 2)

    def loops(self):
        c, L = self.c, -60
        while 4 * Fr(c.b) ** (2 * L) * c.rho ** 2 * self.h < c.I ** 2:
            L += 1
        o = -60
        while c.Mp ** 2 * Fr(c.b) ** (2 * o) < self.h + c.w:
            o += 1
        return L, o

    def image(self, x0, x1):
        return ("r", self.s + x0), ("r", self.s + x1)

    def steep(self, x0, x1, law):
        return 4 * law * law * (self.s + x0) < 1

    def gamma(self):
        h, w = float(self.h), float(self.c.w)
        return float(self.c.Mp) / (2 * math.sqrt(h * (h + w)))

    def gamma2(self):
        return self.c.Mp ** 2 / (4 * self.h * (self.h + self.c.w))


class Recip:
    name = "1/(s + x)"

    def __init__(self, cell, h):
        self.c, self.h, self.s = cell, h, cell.Mm + h
        self.lam = 1 / (h * h)
        self.rng = (1 / (h + cell.w), 1 / h)

    def law_L(self):
        return least_pow(self.c.b, self.lam * self.c.I / self.c.rho)

    def lead(self):
        return least_pow(self.c.b, self.rng[1] / self.c.Mp)

    def loops(self):
        return self.c.law_L(self.lam), self.c.lead(self.rng)

    def image(self, x0, x1):
        return ("q", 1 / (self.s + x1)), ("q", 1 / (self.s + x0))

    def steep(self, x0, x1, law):
        return (self.s + x0) ** 2 * law < 1

    def gamma(self):
        return float(self.c.Mp / self.h)

    def gamma2(self):
        return (self.c.Mp / self.h) ** 2

    def mapping(self):
        s = self.s
        return (self.name, 1,
                lambda B: (1 / (s + B[0][1]), 1 / (s + B[0][0])),
                lambda B: [(-1 / (s + B[0][0]) ** 2,
                            -1 / (s + B[0][1]) ** 2)],
                None)


class Recip2:
    name = "1/(s + y)^2"

    def __init__(self, cell, h):
        self.c, self.h = cell, h

    def law_L(self):
        return least_pow(self.c.b, 2 / self.h ** 3
                         * self.c.I / self.c.rho)

    def lead(self):
        return least_pow(self.c.b, 1 / (self.h ** 2 * self.c.Mp))

    def gamma(self):
        return float(2 * self.c.Mp / self.h)

    def gamma2(self):
        return (2 * self.c.Mp / self.h) ** 2


class Divider:
    name = "x/(s + y)"

    def __init__(self, cell, h):
        self.c, self.h, self.s = cell, h, cell.Mm + h
        self.lam = (h + cell.Mh) / (h * h)
        self.rng = (-cell.Mm / h, cell.Mp / h)

    def law_L(self):
        return least_pow(self.c.b, self.lam * self.c.I / self.c.rho)

    def lead(self):
        return least_pow(self.c.b, 1 / self.h)

    def loops(self):
        return self.c.law_L(self.lam), self.c.lead(self.rng)

    def gamma(self):
        return float(1 + self.c.Mh / self.h)

    def gamma2(self):
        return (1 + self.c.Mh / self.h) ** 2

    def mapping(self):
        s = self.s

        def image(B):
            (x0, x1), (y0, y1) = B
            v = [x / (s + y) for x in (x0, x1) for y in (y0, y1)]
            return (min(v), max(v))

        def partials(B):
            (x0, x1), (y0, y1) = B
            X = max(abs(x0), abs(x1))
            return [(1 / (s + y1), 1 / (s + y0)),
                    (-X / (s + y0) ** 2, X / (s + y0) ** 2)]
        return (self.name, 2, image, partials, None)


def one_scan(cell, unit, L, o):
    """The one-stream scan: least output depth of a kill at L, or None,
    with the boxes read and whether the excess region ran out."""
    c = L - o
    law = cell.lam_law(L)
    D = range(-cell.am, cell.ap + 1)
    level, read = [0], 0
    for n in range(NMAX + 1):
        kept = []
        for u in level:
            x0, x1 = cell.box(u, n)
            read += 1
            if not unit.steep(x0, x1, law):
                continue
            lo, hi = unit.image(x0, x1)
            if n - c >= 1 and one_kills(cell, lo, hi, n, L):
                return n - c, read, False
            kept.append(u)
        if not kept:
            return None, read, True
        if read > BUDGET:
            return None, read, False
        level = [cell.b * u + e for u in kept for e in D]
    return None, read, False


def many_scan(cell, unit, L, o):
    return ms.scan(cell, unit.mapping(), L, o)


def edge_scan(cell, unit, L, o):
    """A witness search for the divider below its law: the x prefix
    held on the edge |x| = Mh, only the y prefixes branching. A kill
    found here is a kill; a survival here reads nothing."""
    _, _, image, partials, _ = unit.mapping()
    c, law = L - o, cell.lam_law(L)
    top = cell.Mp >= cell.Mm
    level, read = [0], 0
    for n in range(NMAX + 1):
        ux = ms.repunit(cell.b, n) * (cell.ap if top else -cell.am)
        kept = []
        for uy in level:
            B = [cell.box(ux, n), cell.box(uy, n)]
            read += 1
            if ms.rate(partials(B)) <= law:
                continue
            if n - c >= 1 and cell.kills(image(B), n, L):
                return n - c, read
            kept.append(uy)
        if not kept or read > BUDGET:
            return None, read
        level = [cell.b * u + e for u in kept
                 for e in range(-cell.am, cell.ap + 1)]
    return None, read


# ---- the sections ----

def pairs():
    for (b, am, ap) in ms.census():
        cell = ms.Cell(b, am, ap)
        for j in JS:
            yield cell, Fr(j, b - 1)


def section_pa():
    print("PA  the controls")
    getcontext().prec = 60
    rng = random.Random(7)
    bad = 0
    for i in range(3000):
        if i % 3 == 0:
            q = Fr(rng.randint(1, 400), rng.randint(1, 60))
            A = q * q
        else:
            A = Fr(rng.randint(1, 10 ** 6), rng.randint(1, 10 ** 4))
        e = Fr(rng.randint(1, 50), rng.randint(1, 50))
        c = Fr(rng.randint(-30, 30), rng.randint(1, 9))
        exact = vfloor(("r", A), e, c)
        z = (Decimal(A.numerator) / Decimal(A.denominator)).sqrt()
        z = z / (Decimal(e.numerator) / Decimal(e.denominator))
        z += Decimal(c.numerator) / Decimal(c.denominator)
        if exact != int(z.to_integral_value(rounding="ROUND_FLOOR")):
            bad += 1
    check("PA the exact floor of sqrt against 60-digit decimals",
          bad == 0, f"3000 rationals, {bad} off")
    off = tot = 0
    for cell, h in pairs():
        u = Recip(cell, h)
        Ls, o = u.law_L(), u.lead()
        for L in (Ls - 1, Ls):
            k1, _, _ = one_scan(cell, u, L, o)
            k2, _ = many_scan(cell, u, L, o)
            tot += 1
            off += k1 != k2
    check("PA the one-stream scan equals manystream.scan on 1/(s + x)",
          tot == 240 and off == 0, f"{tot} (pair, L), {off} off")


def section_pb_pc():
    print("PB, PC  the three units at the 120 pairs")
    t0 = time.time()
    loops_off, neg, cstar, negcells = 0, {}, {}, {}
    alive_bad, dead_bad, depth, reads, least = [], [], {}, 0, {}
    for U in (Root, Recip, Divider):
        neg[U.name], cstar[U.name], depth[U.name] = 0, {}, {}
        negcells[U.name] = set()
        for cell, h in pairs():
            u = U(cell, h)
            Ls, o = u.law_L(), u.lead()
            loops_off += (Ls, o) != u.loops()
            cs = Ls - o
            cstar[U.name][cs] = cstar[U.name].get(cs, 0) + 1
            at = (cs, (cell.b, cell.am, cell.ap, str(h)))
            least[U.name] = min(least.get(U.name, at), at)
            if cs < 0:
                neg[U.name] += 1
                negcells[U.name].add((cell.b, cell.am, cell.ap))
            for L in (Ls, Ls - 1):
                if U is Divider and L < Ls:
                    k, r = edge_scan(cell, u, L, o)
                    ran_out = False
                elif U is Divider:
                    k, r = many_scan(cell, u, L, o)
                    ran_out = (k is None and r <= ms.BUDGET
                               and ms.scan.reached < ms.NMAX)
                else:
                    k, r, ran_out = one_scan(cell, u, L, o)
                reads += r
                tag = (U.name, cell.b, cell.am, cell.ap, str(h), L)
                # alive at L* only where the excess region ran out
                if L == Ls and (k is not None or not ran_out):
                    alive_bad.append(tag + (ran_out,))
                if L == Ls - 1:
                    if k is None:
                        dead_bad.append(tag + (ran_out,))
                    else:
                        depth[U.name][k] = depth[U.name].get(k, 0) + 1
        print(f"    {U.name}: c* {dict(sorted(cstar[U.name].items()))}, "
              f"negative at {neg[U.name]} pairs over "
              f"{len(negcells[U.name])} cells, least {least[U.name][0]} at "
              f"{least[U.name][1]}; kills at L* - 1 by "
              f"output depth {dict(sorted(depth[U.name].items()))}")
    n_up = sum(sum(v.values()) for v in cstar.values())
    check("PB the closed forms equal the loops at the 360 (unit, pair)",
          n_up == 360 and loops_off == 0,
          f"{n_up} (unit, pair), {loops_off} off")
    check("PB the divider's c* 0, 1, 2 at 5, 75 and 40 of its 120 pairs",
          cstar["x/(s + y)"] == {0: 5, 1: 75, 2: 40},
          f"read {cstar['x/(s + y)']}")
    check("PB the root negative at 65 of 120 pairs",
          neg["sqrt(s + x)"] == 65, f"read {neg['sqrt(s + x)']}")
    check("PB the reciprocal negative at 40 pairs, at every cell",
          neg["1/(s + x)"] == 40 and len(negcells["1/(s + x)"]) == 20,
          f"read {neg['1/(s + x)']} pairs, "
          f"{len(negcells['1/(s + x)'])} cells")
    kills = sum(sum(d.values()) for d in depth.values())
    ends = (min(min(d) for d in depth.values() if d),
            max(max(d) for d in depth.values() if d))
    check("PC alive at L*, dead at L* - 1, at each of the 360 (unit, pair)",
          kills == 360 and not alive_bad and not dead_bad,
          f"{kills} kills; killed at L*: {alive_bad}; alive at L* - 1: "
          f"{dead_bad}")
    check("PC the kills at output depth 1 to 9", ends == (1, 9),
          f"read {ends}")
    print(f"    {reads} boxes read, {time.time() - t0:.1f} s")


def exp_c(cell, h, times_x):
    """c* and the band deviation of exp(-h y) (times x if asked), in
    floating point; None when a ceiling's argument is a near-tie."""
    lb = math.log(cell.b)
    Mm, Mp, Mh = float(cell.Mm), float(cell.Mp), float(cell.Mh)
    hf = float(h)
    ratio = math.log(cell.I / cell.rho)
    if times_x:
        lam = math.log(1 + Mh * hf) + hf * Mm
        sig = hf * Mm
        gam = 1 + Mh * hf
    else:
        lam = math.log(hf) + hf * Mm
        sig = hf * Mm - math.log(Mp)
        gam = hf * Mp
    X, Y = (lam + ratio) / lb, sig / lb
    if min(abs(X - round(X)), abs(Y - round(Y))) < 1e-9:
        return None
    cs = math.ceil(X) - math.ceil(Y)
    return cs, cs - math.log(gam * cell.I / cell.rho) / lb


def section_pd_pf():
    print("PD, PF  the relative-gradient law over six families")
    worst, broken, ties, read, exact_off = {}, [], 0, 0, []
    first, last = {}, {}
    fams = [Root, Recip, Recip2, Divider, "exp(-h y)", "x exp(-h y)"]
    for (b, am, ap) in ms.census():
        cell = ms.Cell(b, am, ap)
        for j in JS_BAND:
            h = Fr(j, b - 1)
            for F in fams:
                if isinstance(F, str):
                    got = exp_c(cell, h, F.startswith("x"))
                    if got is None:
                        ties += 1
                        continue
                    cs, dev = got
                    name = F
                else:
                    u = F(cell, h)
                    name = u.name
                    cs = u.law_L() - u.lead()
                    dev = cs - math.log(u.gamma() * cell.I
                                        / cell.rho) / math.log(b)
                    x2 = u.gamma2() * Fr(cell.I, cell.rho) ** 2
                    if not Fr(b) ** (2 * cs - 2) < x2 < Fr(b) ** (2 * cs + 2):
                        exact_off.append((name, b, am, ap, j))
                worst[name] = max(worst.get(name, 0), abs(dev))
                read += 1
                if not abs(dev) < 1:
                    broken.append((name, b, am, ap, j))
                if j == JS_BAND[0]:
                    first[name, b, am, ap] = cs
                if j == JS_BAND[-1]:
                    last[name, b, am, ap] = cs
    print("    greatest |deviation|: " + ", ".join(
        f"{k} {v:.3f}" for k, v in worst.items()) + f"; near-ties {ties}; "
        f"{read} (family, cell, h) read")
    check("PD the band holds at each of the 960 (family, cell, h)",
          read == 960 and not broken, f"{read} read, broken at {broken}")
    check("PD' the four pole units' band read exactly, on Gamma^2",
          not exact_off, f"off at {exact_off}")
    for name, sign, band in (("exp(-h y)", 1, (5, 13)),
                             ("sqrt(s + x)", -1, (4, 12)),
                             ("1/(s + x)", -1, (5, 13)),
                             ("1/(s + y)^2", -1, (5, 13))):
        moves = [sign * (last[k] - first[k]) for k in first
                 if k[0] == name and k in last]
        print(f"    {name}: c* at j = 8192 less c* at j = 1 runs "
              f"{min(sign * m for m in moves)} to "
              f"{max(sign * m for m in moves)}")
        check(f"PF {name} {'rises' if sign > 0 else 'falls'} by "
              f"{band[0]} to {band[1]} at every cell",
              len(moves) == 20 and (min(moves), max(moves)) == band)


def section_pe():
    print("PE  the divider's dense sweep, past the radix included")
    t0 = time.time()
    u = Divider(ms.Cell(2, 3, 1), Fr(1))
    c0 = u.law_L() - u.lead()
    check("PE control: the divider at (2, 3, 1), h = 1, c* = 3",
          c0 == 3, f"read {c0}; the hand value 3")
    seen, low, high, zero_cells = 0, [], [], set()
    old, hist = [], {}
    cells = ms.census() + ms.over_cells()
    for (b, am, ap) in cells:
        cell = ms.Cell(b, am, ap)
        hs = {Fr(j, b - 1) for j in range(1, 4097)}
        hs |= {Fr(q, 10) for q in range(1, 1001)}
        for h in hs:
            u = Divider(cell, h)
            cs = u.law_L() - u.lead()
            seen += 1
            hist[cs] = hist.get(cs, 0) + 1
            if cs < 0 or (cell.rho == 1 and cs < 1):
                low.append((b, am, ap, str(h), cs))
            if h >= cell.Mh / (b - 1) and cs > 2:
                high.append((b, am, ap, str(h), cs))
            if h >= Fr(1, b - 1) and cs > 2:
                old.append((b, am, ap, cs))
            if cs == 0:
                zero_cells.add((b, am, ap))
    slack2 = {(b, am, ap) for (b, am, ap) in cells
              if am + ap + 1 - b >= 2}
    print(f"    {seen} pairs over {len(cells)} cells, c* by count "
          f"{dict(sorted(hist.items()))}; zeros at {len(zero_cells)} "
          f"cells; c* >= 3 at h >= 1/(b - 1) at {len(old)} pairs over "
          f"{len({c[:3] for c in old})} cells, at most "
          f"{max((c[3] for c in old), default=None)}, all past the radix: "
          f"{all(max(c[1:3]) >= c[0] for c in old)}; "
          f"{time.time() - t0:.1f} s")
    check("PE c* >= 0 at the 539164 pairs of the 109 cells, >= 1 at slack 1",
          (seen, len(cells)) == (539164, 109) and not low,
          f"{seen} pairs, {len(cells)} cells, off at {low[:5]}")
    check("PE c* at most 5, and <= 2 at every h >= Mh/(b - 1)",
          max(hist) == 5 and not high,
          f"greatest {max(hist)}, off at {high[:5]}")
    check("PE a zero at each of the 99 cells of slack 2 or more, none at "
          "slack 1", zero_cells == slack2 and len(slack2) == 99,
          f"{len(zero_cells)} cells, {len(slack2)} of slack >= 2")


def section_pg():
    print("PG  the product against the literature's multiplier delays")
    xy = ms.MAPS[2]
    got, kills = [], []
    for (b, am, ap), delta in (((2, 1, 1), 3), ((4, 3, 3), 2),
                               ((4, 2, 2), 3)):
        cell = ms.Cell(b, am, ap)
        lam, o, Ls = ms.law_of(cell, xy)
        k, _ = ms.scan(cell, xy, Ls - 1, o)
        got.append(Ls - o)
        kills.append(k)
        print(f"    ({b}, {am}, {ap}): lead {o}, L* {Ls}, c* {Ls - o}, "
              f"dead at L* - 1 at output depth {k}; the literature's delta "
              f"{delta}")
    check("PG c* = 2, 1, 2, each dead at L* - 1",
          got == [2, 1, 2] and None not in kills, f"read {got}")


def trunc(x, t):
    """x truncated to t fractional bits."""
    return Fr(math.floor(x * 2 ** t), 2 ** t)


def lam_xy(r, a):
    return Fr(2 * a, r - 1)


def lam_fused(r, a):
    return Fr(2 * a, r - 1) + 1


def el_om(r, a, delta, lam):
    """The chapter's residual bound for a step of size a lam r^-delta."""
    return Fr(a, r - 1) * (1 - lam / Fr(r) ** delta)


def el_ok(r, a, t, delta, lam):
    return trunc(el_om(r, a, delta, lam), t) >= Fr(1 + Fr(1, 2 ** t), 2)


def el_least(r, a, lam, tmax=64, dmax=40):
    """(least delta over t <= tmax, the least t reaching it)."""
    for delta in range(0, dmax):
        for t in range(1, tmax + 1):
            if el_ok(r, a, t, delta, lam):
                return delta, t
    return None, None


def sel_law(r, a, lam):
    """(L*, equality at L*) of r^L (2a + 1 - r) >= lam 2a."""
    L = 0
    while r ** L * (2 * a + 1 - r) < lam * 2 * a:
        L += 1
    return L, r ** L * (2 * a + 1 - r) == lam * 2 * a


SYM = [(r, a) for r in range(2, 65) for a in range((r + 1) // 2, 2 * r + 1)]


def lead_xy(r, a):
    return least_pow(r, Fr(a, r - 1))


def lead_fused(r, a):
    return least_pow(r, Fr(a, r - 1) + 1)


def ph_arm(law_lam, lam, label):
    """The census for one om against one law: off cells and equalities."""
    off, unreached, eqs, tneed = [], [], [], {}
    for r, a in SYM:
        L, eq = sel_law(r, a, law_lam(r, a))
        dl, tl = el_least(r, a, lam(r, a))
        if dl is None:
            unreached.append((r, a))
        elif dl != L + (1 if eq else 0):
            off.append((r, a, L, eq, dl))
        if eq:
            eqs.append((r, a, L))
        if dl == L:
            tneed[tl] = tneed.get(tl, 0) + 1
    print(f"    {label}, {len(SYM)} cells: equality cells (b, a, L*) {eqs}; "
          f"least m reaching L* at the strict cells "
          f"{dict(sorted(tneed.items()))}; unreached {unreached}")
    return off, eqs


def start_fails(lam, lead, fmax):
    """The cells whose d-digit prefix value leaves om b^o at the least L."""
    bad = []
    for r, a in SYM:
        L, _ = el_least(r, a, lam(r, a))
        o = lead(r, a)
        p = Fr(a, r - 1) * (1 - Fr(1, r ** (L - o)))
        if fmax(p) > el_om(r, a, L, lam(r, a)) * Fr(r) ** o:
            bad.append((r, a))
    return bad


def section_ph():
    print("PH  the literature's selection condition at an exact estimate")
    rows = ((2, 1, 2, 3), (4, 3, 2, 2), (4, 2, 3, 3))
    bad = [(r, a, t, d, lam) for r, a, t, d in rows
           for lam in (lam_xy(r, a), Fr(2))
           if not el_ok(r, a, t, d, lam) or el_ok(r, a, t, d - 1, lam)]
    check("PH1 the published rows hold at L and fail at L - 1, at the "
          "bound read here and at the slides' own",
          not bad, f"off at {bad}")
    for r, a, _, d in rows:
        L, eq = sel_law(r, a, lam_xy(r, a))
        dl, tl = el_least(r, a, lam_xy(r, a))
        print(f"    ({r}, {a}, {a}): om at L* {el_om(r, a, L, lam_xy(r, a))}"
              f", law L* {L}{' with equality' if eq else ''}; least L "
              f"{dl} first at m = {tl}; published {d}")
    got = [el_least(r, a, lam_xy(r, a)) for r, a, _, _ in rows]
    check("PH2 least L 3, 2, 2, the last first at m = 4",
          [g[0] for g in got] == [3, 2, 2] and got[2][1] == 4,
          f"read {got}")
    off, eqs = ph_arm(lam_xy, lam_xy, "x y")
    check("PH3 least L = L* strict, L* + 1 at equality", not off,
          f"off at {off[:6]}")
    check("PH3 the equality cells are (2, 1, 1) and (4, 3, 3)",
          eqs == [(2, 1, 2), (4, 3, 1)], f"read {eqs}")
    lawoff, leads = [], {}
    for r, a in SYM:
        cell = ms.Cell(r, a, a)
        lam, o, _ = ms.law_of(cell, ms.MAPS[2])
        leads[o] = leads.get(o, 0) + 1
        if (o, cell.law_L(lam)) != (lead_xy(r, a),
                                    sel_law(r, a, lam_xy(r, a))[0]):
            lawoff.append((r, a, o))
    print(f"    manystream's leads for x y by count "
          f"{dict(sorted(leads.items()))}")
    check("PH3 manystream's lead and L* are the formulas' at every cell",
          not lawoff, f"off at {lawoff[:6]}")
    off, eqs = ph_arm(lam_fused, lam_fused, "x y + z")
    check("K9 did not fire: x y + z's least L is L*, or L* + 1 at equality",
          not off, f"off at {off[:6]}")
    check("PH4 the one equality cell is (6, 5, 5) at L* = 1",
          eqs == [(6, 5, 1)], f"read {eqs}")
    poff, _ = ph_arm(lam_fused, lam_xy, "plant, x y + z's law at x y's om")
    check("PLANT K9 fires on the multiplier's om", bool(poff),
          f"{len(poff)} cells off, first {poff[:3]}")
    k10, leads = [], {}
    for r, a in SYM:
        cell = ms.Cell(r, a, a)
        lam, o, _ = ms.law_of(cell, ms.MAPS[4])
        leads[o] = leads.get(o, 0) + 1
        if (o, cell.law_L(lam)) != (lead_fused(r, a),
                                    sel_law(r, a, lam_fused(r, a))[0]):
            k10.append((r, a, o, cell.law_L(lam)))
    print(f"    manystream's leads for x y + z by count "
          f"{dict(sorted(leads.items()))}")
    check("K10 did not fire: (o, L*) the formulas' at every cell",
          not k10, f"off at {k10[:6]}")
    sx = start_fails(lam_xy, lead_xy, lambda p: p * p)
    sf = start_fails(lam_fused, lead_fused, lambda p: p * p + p)
    print(f"    the start read plainly fails at {len(sx)} x y cells "
          f"{sx[:8]}{' ...' if len(sx) > 8 else ''} and at the x y + z "
          f"cells {sf}")
    want = sorted([(r, r - 1) for r in range(2, 65)]
                  + [(2, 2), (2, 4), (3, 6)])
    check("PH5 the start fails at x y's a = b - 1 cells and (2, 2), "
          "(2, 4), (3, 6); at x y + z's (2, 1), (2, 3), (3, 4)",
          sorted(sx) == want and sorted(sf) == [(2, 1), (2, 3), (3, 4)],
          f"x y off {sorted(set(sx) ^ set(want))}, x y + z {sf}")


def weld_bound(b, am, ap):
    """B = a_min |I| / (a_max rho), with a_min and a_max."""
    lo, hi = min(am, ap), max(am, ap)
    return Fr(lo * (am + ap), hi * (am + ap + 1 - b)), lo, hi


def lopsided(b, am, ap):
    """B < 1, unpacked: a_min^2 < a_max (a_max + 1 - b)."""
    lo, hi = min(am, ap), max(am, ap)
    return lo * lo < hi * (hi + 1 - b)


# the PLANT: x y lifted off the origin, its rate unchanged
WELD_PLANT = ("x y + 8", 2,
              lambda B: ms.iadd(ms.imul(B[0], B[1]), (Fr(8), Fr(8))),
              ms.MAPS[2][3], ms.MAPS[2][4])


def weld_read(maps, cells):
    """PI1-PI3's comparisons over (map, cell): the pairs off PI1, off
    PI2, the binding pairs and the side K leans on at them."""
    off1, off2, binds, sides = [], [], [], {}
    for mp in maps:
        name, d, image = mp[0], mp[1], mp[2]
        for c in cells:
            cell = ms.Cell(*c)
            lam, o, _ = ms.law_of(cell, mp)
            lo, hi = image(ms.root_box(cell, d))
            K = max(hi / cell.Mp, -lo / cell.Mm)
            B, amin, amax = weld_bound(*c)
            if lam / K < Fr(amin, amax):
                off1.append((name, c, lam / K))
            cs = cell.law_L(lam) - o
            if not Fr(c[0]) ** (cs + 1) > B:
                off2.append((name, c, cs, B))
            if cs < 0:
                side = "hi/M+" if hi / cell.Mp >= -lo / cell.Mm else "-lo/M-"
                binds.append((name, c, cs, B, side))
                sides[side] = sides.get(side, 0) + 1
    return off1, off2, binds, sides


def section_pi():
    print("PI  where the lead can sit above L*")
    cs = ms.census()
    bad = [c for c in cs if weld_bound(*c)[0] <= 1 or lopsided(*c)]
    n0 = len(CHECKS)
    check("PI0 B > 1 at all 20 cells, none lopsided", not bad, f"{bad}")
    _, _, binds, _ = weld_read(ms.MAPS, cs)
    check("PI0 no map binds at the 20 cells", not binds, f"{binds[:5]}")
    off1, off2, pb, _ = weld_read([WELD_PLANT], cs)
    atone = [t for t in pb if t[3] >= 1]
    print(f"    the plant x y + 8 at the 20 cells: off PI1 at {len(off1)}, "
          f"off PI2 at {len(off2)}, binding at B >= 1 at {len(atone)}")
    check("PI0 the plant fires PI1 at 20 cells, PI2 at 10 and PI3's kill "
          "at 9", (len(off1), len(off2), len(atone)) == (20, 10, 9))
    if not all(CHECKS[n0:]):
        print("    PI CONTROL FAILED: PI1-PI4 are not read.")
        return
    cells = cs + ms.over_cells()
    off1, off2, binds, sides = weld_read(ms.MAPS, cells)
    check("PI1 Gamma >= a_min/a_max at every (map, cell)", not off1,
          f"off {off1[:5]}")
    check("PI2 b^(c* + 1) > B at every pair", not off2, f"off {off2[:5]}")
    bcells = sorted({t[1] for t in binds})
    atone = [t for t in binds if t[3] >= 1]
    lop = [c for c in cells if lopsided(*c)]
    print(f"    {len(binds)} binding pairs over {len(bcells)} cells "
          f"{bcells}; c* there {sorted({t[2] for t in binds})}; K leans "
          f"on {sides}")
    nb = {c: sum(1 for t in binds if t[1] == c) for c in lop}
    print(f"    lopsided cells (B < 1): {len(lop)} of {len(cells)}, "
          f"{sum(1 for v in nb.values() if v == 0)} binding no map")
    check("PI3 every binding pair at a B < 1 cell", not atone,
          f"off {atone[:5]}")
    check("PI3 15 binding pairs over 6 of the 109 cells",
          (len(binds), len(bcells), len(cells)) == (15, 6, 109),
          f"read {len(binds)}, {len(bcells)}, {len(cells)}")
    neg, off, deep = [], [], []
    n = 0
    for b in range(2, 7):
        for am in range(1, 2 * b):
            for ap in range(1, 2 * b):
                if am + ap + 1 - b < 1:
                    continue
                n += 1
                L = 0 if (ap - am) % (b - 1) == 0 else 1
                o = 0
                if am > ap:
                    while b ** o * ap < am:
                        o += 1
                if L - o < 0:
                    neg.append((b, am, ap))
                    if not lopsided(b, am, ap):
                        off.append((b, am, ap, L - o))
                    if L - o == -2:
                        deep.append((b, am, ap))
    print(f"    |x| by its criterion: {n} cells; negative lookahead at "
          f"{len(neg)}; -2 at {deep}")
    check("PI4 every negative lookahead of |x| at a B < 1 cell", not off,
          f"off {off}")
    check("PI4 35 of the 265 negative, -2 at the five",
          (len(neg), n) == (35, 265) and deep == [
              (2, 3, 1), (3, 5, 1), (4, 7, 1), (5, 9, 1), (6, 11, 1)],
          f"read {len(neg)} of {n}")


HOMOG = {"x^2": 2, "x y": 2, "x^2 + x y": 2,
         "x^3": 3, "x^2 y": 3, "x y z": 3}
TIGHT = {"x^2": 2, "x y": 2, "x^2 + x y": 4}
# the PLANT for RA1, RA2: the low end binds, (2, 1, 1) range [-9, -7]
PLANT_MINUS = ("x y - 8", 2,
               lambda B: ms.iadd(ms.imul(B[0], B[1]), (Fr(-8), Fr(-8))),
               ms.MAPS[2][3], ms.MAPS[2][4])


def wide_cells(known):
    """WIDE: radices 2..7, a+ in {1, 2}, a- from b to 4b, rho >= 1."""
    return [(b, am, ap) for b in range(2, 8) for ap in (1, 2)
            for am in range(b, 4 * b + 1)
            if am + ap + 1 - b >= 1 and (b, am, ap) not in known]


def ra_read(mp, c):
    """c* (law_L at law_of's Lam, less its lead) and S1's quantities at
    one (map, cell): the short
    end (hi at a- >= a+, else -lo), its M, the long end and its M."""
    cell = ms.Cell(*c)
    lam, o, _ = ms.law_of(cell, mp)
    Ls = cell.law_L(lam)
    lo, hi = mp[2](ms.root_box(cell, mp[1]))
    r = dict(lam=lam, o=o, Ls=Ls, cs=Ls - o, lo=lo, hi=hi,
             B=Fr(c[0]) ** Ls)
    if c[1] >= c[2]:
        r.update(short=hi, Ms=cell.Mp, Ml=cell.Mm, long=-lo)
    else:
        r.update(short=-lo, Ms=cell.Mm, Ml=cell.Mp, long=hi)
    return r


def ra_depth(r, b):
    """The least m >= 0 with short <= M_short b^(L* + m)."""
    m = 0
    while r["short"] > r["Ms"] * r["B"] * Fr(b) ** m:
        m += 1
    return m


def dlop(c, d):
    """d-lopsided: d a_min |I| < a_max rho."""
    b, am, ap = c
    return d * min(am, ap) * (am + ap) < max(am, ap) * (am + ap + 1 - b)


def tight_form(c, lam0):
    """The Euler-tight closed form of c* < 0, from the cell alone."""
    b, am, ap = c
    if am < ap:
        return False
    rho, I = am + ap + 1 - b, am + ap
    L = -40
    while (b - 1) * rho * Fr(b) ** L < lam0 * am * I:
        L += 1
    return Fr(am * am * lam0, 2) > ap * (b - 1) * Fr(b) ** L


def tbar(mp, M):
    """int_0^1 lamf(s M) ds / lamf(M), exact: Simpson on [0, s0] and
    [s0, 1], s0 = min(1, 1/M), each piece of degree <= 2 in s."""
    lamf = mp[4]
    s0 = min(Fr(1), 1 / M)

    def simp(a, b):
        return (b - a) * (lamf(a * M) + 4 * lamf((a + b) / 2 * M)
                          + lamf(b * M)) / 6
    return (simp(Fr(0), s0) + (simp(s0, Fr(1)) if s0 < 1 else 0)) / lamf(M)


def ra(maps, cells, homog=HOMOG, tight=TIGHT):
    """RA1..RA5's offending pairs over (map, cell), the long end's
    largest share of its lead-L* tile, the reach at the Euler-tight
    maps, the run-ahead pairs and the reach against tbar (RB)."""
    out = {k: [] for k in ("RA1", "RA2", "RA3", "RA4", "RA5", "RB")}
    slack, tvals, runs, eq = Fr(0), {}, [], []
    for mp in maps:
        name = mp[0]
        for c in cells:
            r = ra_read(mp, c)
            s1 = c[1] != c[2] and r["short"] > r["Ms"] * r["B"]
            if (r["cs"] < 0) != s1:
                out["RA1"].append((name, c, r["cs"]))
            slack = max(slack, r["long"] / (r["Ml"] * r["B"]))
            if ra_depth(r, c[0]) != max(0, -r["cs"]):
                out["RA2"].append((name, c, r["cs"]))
            if r["cs"] < 0:
                runs.append((name, c, r["cs"]))
            if c[1] >= c[2]:
                t, tb = r["short"] / (r["lam"] * r["Ml"]), tbar(mp, r["Ml"])
                if t > tb:
                    out["RB"].append((name, c, t, tb))
                eq.append((name, c, t == tb, tb - t))
            if name in homog:
                d = homog[name]
                t = r["short"] / (r["lam"] * r["Ml"])
                if t > Fr(1, d):
                    out["RA3"].append((name, c, t, "reach"))
                if r["cs"] < 0 and not dlop(c, d):
                    out["RA3"].append((name, c, t, "d-lopsided"))
                if name in tight:
                    if c[1] >= c[2]:
                        tvals.setdefault(name, set()).add(t)
                    if tight_form(c, tight[name]) != (r["cs"] < 0):
                        out["RA4"].append((name, c, r["cs"]))
                if d == 3 and r["cs"] < 0:
                    out["RA5"].append((name, c, r["cs"]))
    return out, slack, tvals, runs, eq


def section_pj():
    print("PJ  the run-ahead criterion: hi alone decides")
    census = ms.census() + ms.over_cells()
    wide = wide_cells(set(census))
    maps = {m[0]: m for m in ms.MAPS}
    n0 = len(CHECKS)
    _, _, binds, _ = weld_read(ms.MAPS, census)
    runs = ra(ms.MAPS, census)[3]
    check("PJ0 PI's 15 binding pairs reproduced",
          sorted((t[0], t[1]) for t in runs)
          == sorted((t[0], t[1]) for t in binds) and len(binds) == 15)
    o1 = ra([PLANT_MINUS], census)[0]
    r = ra_read(PLANT_MINUS, (2, 1, 1))
    print(f"    x y - 8 at (2, 1, 1): range [{r['lo']}, {r['hi']}], "
          f"o = {r['o']}, L* = {r['Ls']}; off RA1 at {len(o1['RA1'])}, "
          f"RA2 at {len(o1['RA2'])} cells")
    check("PJ0 x y - 8 fires RA1 at (2, 1, 1) and RA2",
          any(t[1] == (2, 1, 1) for t in o1["RA1"]) and o1["RA2"]
          and (r["o"], r["Ls"], r["lo"], r["hi"]) == (4, 2, -9, -7))
    # x y + 8 lifts the short end only at a- >= a+; at a+ > a- the + 8
    # lifts the long end, so the plant pushes no reach there
    side = [c for c in census if c[1] >= c[2]]
    o2 = ra([WELD_PLANT], side, homog={"x y + 8": 2})[0]
    why = {k[3] for k in o2["RA3"]}
    print(f"    x y + 8 tagged degree 2 at the {len(side)} cells with "
          f"a- >= a+: off RA3 at {len(o2['RA3'])} {sorted(why)}, off RB "
          f"at {len(o2['RB'])}")
    check("PJ0 x y + 8 fires both RA3 clauses at a- >= a+, and RB at "
          "every such cell", why == {"reach", "d-lopsided"}
          and len(o2["RB"]) == len(side))
    neg3 = ("-x^3", 1, lambda B: ms.iscale(-1, ms.ipow(B[0], 3)),
            ms.MAPS[1][3], ms.MAPS[1][4])
    o5 = ra([neg3], census + wide, homog={"-x^3": 3})[0]["RA5"]
    print(f"    -x^3 tagged degree 3: off RA5 at {len(o5)}, first {o5[:1]}")
    check("PJ0 -x^3 fires RA5", o5)
    o4 = ra([maps["x^2 + y"]], census, homog={"x^2 + y": 2},
            tight={"x^2 + y": 2})[0]["RA4"]
    check("PJ0 the x^2 form on x^2 + y fires RA4 at (2, 3, 1)",
          any(t[1] == (2, 3, 1) for t in o4), f"{o4[:3]}")
    w = [ra_read(maps["x^2"], (2, 3, 1)), ra_read(maps["x^2 + y"], (2, 3, 1)),
         ra_read(maps["x^2"], (3, 5, 1)), ra_read(maps["x^2"], (2, 6, 1)),
         ra_read(maps["x^2"], (2, 4, 1))]
    check("PJ0 the hand witnesses: (2,3,1) x^2 L* 3 hi 9 c* -1, x^2 + y "
          "L* 4 c* >= 0; (3,5,1) x^2 L* 2 c* -1; (2,6,1) x^2 L* 4 hi 36 "
          "c* -2; (2,4,1) x^2 hi 16 = M+ 2^L*, c* 0",
          (w[0]["Ls"], w[0]["hi"], w[0]["cs"]) == (3, 9, -1)
          and w[1]["Ls"] == 4 and w[1]["cs"] >= 0
          and (w[2]["Ls"], w[2]["cs"]) == (2, -1)
          and (w[3]["Ls"], w[3]["hi"], w[3]["cs"]) == (4, 36, -2)
          and w[4]["hi"] == w[4]["Ms"] * w[4]["B"] == 16 and w[4]["cs"] == 0)
    M = [Fr(1, 3), Fr(1), Fr(7, 2)]
    cf = {"x^2": lambda m: Fr(1, 2), "x^3": lambda m: Fr(1, 3),
          "x^2 + y": lambda m: (m + 1) / (2 * m + 1),
          "x(1 - y^2)": lambda m: ((m * m - 1 + Fr(4, 3) / m) if m >= 1
                                   else 1 + m * m / 3) / maps[
                                       "x(1 - y^2)"][4](m)}
    check("PJ0 tbar equals the hand integrals of x^2, x^3, x^2 + y, "
          "x(1 - y^2) at M = 1/3, 1, 7/2",
          all(tbar(maps[k], m) == f(m) for k, f in cf.items() for m in M))
    if not all(CHECKS[n0:]):
        print("    PJ CONTROL FAILED: RA1-RA5 and RB are not read.")
        return
    out, slack, tvals, runs, eq = ra(ms.MAPS, census + wide)
    print(f"    {len(census)} + {len(wide)} cells; the long end's largest "
          f"share of its lead-L* tile {slack}; reach at the Euler-tight "
          f"maps { {k: sorted(v) for k, v in tvals.items()} }")
    for k in ("RA1", "RA2", "RA3", "RA4", "RA5", "RB"):
        check(f"{k} no offending pair", not out[k], f"{out[k][:5]}")
    by = {}
    for name, c, cs in runs:
        by.setdefault(name, []).append((c, cs))
    print(f"    run-ahead pairs: {len(runs)} over "
          f"{len({t[1] for t in runs})} cells, c* in "
          f"{sorted({t[2] for t in runs})}; first c* = -2 "
          f"{min((c for _, c, cs in runs if cs == -2), default=None)}")
    for name in maps:
        v = by.get(name, [])
        print(f"      {name:10s} {len(v):3d} pairs, c* = -2 at "
              f"{sum(1 for _, cs in v if cs <= -2)}, in WIDE "
              f"{sum(1 for cc, _ in v if cc not in set(census))}")
    for b in (2, 3):
        row = {nm: [c[1] for c, _ in by.get(nm, []) if c[0] == b
                    and c[2] == 1] for nm in TIGHT}
        print(f"    radix {b}, a+ = 1, the a- that run ahead: {row}")
    for name in maps:
        e = [t for t in eq if t[0] == name]
        tight = [t[1] for t in e if t[2]]
        sym = [t[1] for t in e if t[1][1] == t[1][2]]
        print(f"      RB {name:10s} t = tbar at {len(tight)} of {len(e)}"
              f"{', exactly the a- = a+ cells' if tight == sym else ''}")
    gap = [t for t in eq if t[0] in ("x^2 + y", "x y + z") and t[3] != (
        Fr(t[1][1] - t[1][2], t[1][0] - 1)
        / ((2 * Fr(t[1][1], t[1][0] - 1) + 1) * Fr(t[1][1], t[1][0] - 1)))]
    check("RB x^2 + y's and x y + z's gap is (M- - M+)/((2M- + 1)M-) at "
          "every cell",
          not gap, f"{gap[:3]}")
    # given RB and RA1 this cannot fail: hi <= tbar Lam M- and
    # b^L* rho >= Lam |I| make hi > M+ b^L* force a+|I| < tbar a- rho
    lop = {}
    for name in maps:
        lop[name] = [c for c in census + wide if min(c[1], c[2]) * (
            c[1] + c[2]) < tbar(maps[name], ms.Cell(*c).Mh)
            * max(c[1], c[2]) * (c[1] + c[2] + 1 - c[0])]
    off = [(n, c) for n, c, _ in runs if c not in set(lop[n])]
    print(f"    tbar-lopsided cells per map: "
          f"{ {n: len(v) for n, v in lop.items()} }; binding there "
          f"{ {n: len(by.get(n, [])) for n in maps} }")
    split = {n: (len(v), sum(1 for cc, _ in v if cc not in set(census)))
             for n, v in by.items()}
    check("RB each of the 506 run-ahead pairs, c* -1 or -2, at a "
          "tbar-lopsided cell of the 109 + 152",
          not off and (len(census), len(wide)) == (109, 152)
          and {t[2] for t in runs} == {-2, -1}
          and split == {"x^2": (85, 82), "x y": (85, 82),
                        "x^2 + y": (83, 81), "x y + z": (83, 81),
                        "x^2 + x y": (110, 105), "x(1 - y^2)": (60, 60)},
          f"{off[:3]}, (pairs, in WIDE) {split}")


FED_BUDGET = 400_000
FED_TMAX = 14
FED_NV = 3
WHOLE = None
FED_DS = (0, 1, 2, 4, WHOLE)


def fed_name(d):
    return "whole" if d is None else str(d)


def fed_closed(cell, sign, d):
    """(L_d, o, c_d) by the law, Lam_d = Mh(1 + b^-d), whole Mh."""
    rng = ms.iscale(sign, ms.imul((-cell.Mm, cell.Mp), (-cell.Mm, cell.Mp)))
    lam = cell.Mh if d is None else cell.Mh * (1 + Fr(1, cell.b ** d))
    o, L = cell.lead(rng), cell.law_L(lam)
    return L, o, L - o


def zone_kill(cell, img, o, t):
    """The image strictly contains a level-t zone (e = b^(o - t))."""
    e = Fr(cell.b) ** (o - t)
    lo, hi = img[0] / e, img[1] / e
    return (lo + cell.Mm).__floor__() < hi - cell.Mp


def fed_scan(cell, sign, L, o, d, plant=None, budget=FED_BUDGET):
    """('kill', t) | ('empty', t) | ('unread', t): the prefix pairs (j, k)
    at depths (nz, ny), nz = max(0, t + c), ny = max(0, t + c + d); a
    box passes at t + c >= 0 when sup|y| + b^-d sup|z| <= Lam_law. The
    plant 'lock' reads y at nz, weight 1: lockstep x y."""
    c = L - o
    law = cell.lam_law(L)
    wd = Fr(1) if plant == "lock" else Fr(1, cell.b ** d)
    dd = 0 if plant == "lock" else d
    D = range(-cell.am, cell.ap + 1)
    nz = ny = 0
    pairs = {(0, 0)}
    read = 0
    for t in range(1, FED_TMAX + 1):
        tz, ty = max(0, t + c), max(0, t + c + dd)
        while nz < tz or ny < ty:
            if nz < tz:
                pairs = {(cell.b * j + e, k) for j, k in pairs for e in D}
                nz += 1
            if ny < ty:
                pairs = {(j, cell.b * k + e) for j, k in pairs for e in D}
                ny += 1
            if len(pairs) > budget:
                return "unread", t
        kept = set()
        for j, k in pairs:
            zb, yb = cell.box(j, nz), cell.box(k, ny)
            read += 1
            if t + c >= 0 and ms.isup(yb) + wd * ms.isup(zb) <= law:
                continue
            if zone_kill(cell, ms.iscale(sign, ms.imul(zb, yb)), o, t):
                return "kill", t
            kept.add((j, k))
        if not kept:
            return "empty", t
        if read > budget:
            return "unread", t
        pairs = kept
    return "unread", FED_TMAX


def fed_scan_whole(cell, sign, L, o, budget=FED_BUDGET):
    """WHOLE: y a point v, a depth-NV box's end; the 40 largest |v|
    above Lam_law. 'empty' only where Mh <= Lam_law, every v passing."""
    c = L - o
    law = cell.lam_law(L)
    if cell.Mh <= law:
        return "empty", 0
    R = ms.repunit(cell.b, FED_NV)
    vs = {e for k in range(-cell.am * R, cell.ap * R + 1)
          for e in cell.box(k, FED_NV)}
    vs = sorted((v for v in vs if abs(v) > law), key=abs, reverse=True)[:40]
    if not vs:
        return "unread", None
    D = range(-cell.am, cell.ap + 1)
    read = 0
    for v in vs:
        js, nz = {0}, 0
        for t in range(1, FED_TMAX + 1):
            while nz < max(0, t + c):
                js = {cell.b * u + e for u in js for e in D}
                nz += 1
            for j in js:
                read += 1
                if zone_kill(cell, ms.iscale(sign * v, cell.box(j, nz)), o, t):
                    return "kill", t
            if read > budget or len(js) * (cell.I + 1) > budget:
                break
    return "unread", None


def fed_run(cell, sign, L, o, d):
    if d is None:
        return fed_scan_whole(cell, sign, L, o)
    return fed_scan(cell, sign, L, o, d)


def section_pk():
    print("PK  a factor fed ahead: z y with y read d digits before z")
    census = ms.census() + ms.over_cells()
    cells = census + wide_cells(set(census))
    n0 = len(CHECKS)
    maps = [("z y", 1), ("-z y", -1)]
    tab = {(n, cc): {d: fed_closed(ms.Cell(*cc), sg, d) for d in FED_DS}
           for n, sg in maps for cc in cells}
    new, deep = {}, {}
    for d in FED_DS[1:]:
        new[d] = sorted(k for k, r in tab.items() if r[d][2] < 0 <= r[0][2])
        deep[d] = sorted(k for k, r in tab.items() if r[d][2] < r[0][2] < 0)

    # PK0, the scan's controls, read before any count
    xymap = [m for m in ms.MAPS if m[0] == "x y"][0]
    bad = []
    for cc in ms.census():
        cell = ms.Cell(*cc)
        L, o, _ = tab["z y", cc][0]
        ref, _ = ms.scan(cell, xymap, L - 1, o)
        got = fed_scan(cell, 1, L - 1, o, 0)
        if not (got[0] == "kill" and ref is not None and (
                got[1] == ref if L - 1 - o >= 0 else got[1] <= ref)):
            bad.append((cc, ref, got))
    check("PK0 the fed scan at d = 0 kills x y at L* - 1 at manystream."
          "scan's depth (at or above it where c < 0), the 20 cells",
          not bad, f"{bad[:3]}")
    probe = new[1][:6]
    lock = sum(1 for n, cc in probe if fed_scan(
        ms.Cell(*cc), 1 if n == "z y" else -1, tab[n, cc][1][0],
        tab[n, cc][1][1], 1, plant="lock")[0] == "kill")
    print(f"    plant 'lock' kills at L_1 at {lock} of {len(probe)} new "
          f"d = 1 pairs")
    check("PK0 plant 'lock' (lockstep) kills at L_d at every probe pair",
          lock == len(probe))
    if not all(CHECKS[n0:]):
        print("    PK CONTROL FAILED: nothing else is read.")
        return

    # the closed forms; these checks are arithmetic on the law
    xy = sorted((c, cs) for n, c, cs in ra(ms.MAPS, cells)[3] if n == "x y")
    mine = sorted((cc, tab["z y", cc][0][2]) for cc in cells
                  if tab["z y", cc][0][2] < 0)
    check("PK1 (arithmetic) d = 0 gives PJ's x y run-ahead pairs",
          xy == mine, f"{len(xy)} there, {len(mine)} here")
    mono, gains = [], set()
    for k, r in tab.items():
        cs = [r[d][2] for d in FED_DS]
        if any(cs[i + 1] > cs[i] for i in range(len(cs) - 1)):
            mono.append((k, cs))
        gains |= {r[0][0] - r[d][0] for d in FED_DS}
    least = [min(r[d][2] for r in tab.values()) for d in FED_DS]
    check("PK2 (arithmetic) c_d nonincreasing in d, its least -2, -2, -2, "
          "-3, -3", not mono and least == [-2, -2, -2, -3, -3],
          f"{mono[:3]}, least {least}")
    check("PK2 (arithmetic) L_0 - L_d in {0, 1}", gains <= {0, 1},
          f"{sorted(gains)}")
    for d in FED_DS[1:]:
        by = {n: sum(1 for m, _ in new[d] if m == n) for n, _ in maps}
        print(f"    d = {fed_name(d):5s}: new run-ahead pairs "
              f"{len(new[d]):3d} {by}; deepened {len(deep[d])}")
    print(f"    KILL READ: counts {[len(new[d]) for d in FED_DS[1:]]}"
          f" (all 0 kills 'fed ahead widens')")
    w = tab["z y", (2, 4, 1)]
    print(f"    witness (2, 4, 1): o = {w[0][1]}, L_0 = {w[0][0]}, "
          f"L_1 = {w[1][0]}")
    check("PK3 (2, 4, 1) newly runs ahead at d = 1, o = 4, L 4 then 3",
          ("z y", (2, 4, 1)) in new[1] and (w[0][1], w[0][0], w[1][0])
          == (4, 4, 3))
    side = []
    for d in FED_DS[1:]:
        for n, (b, am, ap) in new[d]:
            k = Fr(1) if d is None else 1 + Fr(1, b ** d)
            lo, hi = (ap, am) if n == "z y" else (am, ap)
            if not (hi > lo and lo * k * (am + ap) < hi * (am + ap + 1 - b)):
                side.append((n, (b, am, ap), fed_name(d)))
    check("PK3 each of the 65, 81, 84 and 88 new pairs inside "
          "a_short(1 + b^-d)|I| < a_long rho, z y at a- > a+, -z y at "
          "a+ > a-", not side
          and [len(new[d]) for d in FED_DS[1:]] == [65, 81, 84, 88],
          f"{side[:3]}")
    runs = {fed_name(d): sum(1 for (n, _), r in tab.items()
                             if n == "z y" and r[d][2] < 0) for d in FED_DS}
    print(f"    z y run-ahead cells per d: {runs}")
    print(f"    least c_d over all pairs: "
          f"{ {fed_name(d): min(r[d][2] for r in tab.values()) for d in FED_DS} }")

    # PK4: the scan at every new and deepened triple; a kill at L_d - 1
    # witnesses necessity, the emptying at L_d is the prune
    rows = []
    for d in FED_DS[1:]:
        for kind, group in (("new", new[d]), ("deepened", deep[d])):
            for n, cc in group:
                cell, sg = ms.Cell(*cc), (1 if n == "z y" else -1)
                L, o, _ = tab[n, cc][d]
                rows.append((n, cc, fed_name(d), kind,
                             fed_run(cell, sg, L - 1, o, d),
                             fed_run(cell, sg, L, o, d)))
    unread = [r for r in rows if "unread" in (r[4][0], r[5][0])]
    law_kill = [r for r in rows if r[5][0] == "kill" or r[4][0] == "empty"]
    for kind in ("new", "deepened"):
        rk = [r for r in rows if r[3] == kind]
        print(f"    PK4 {kind}: {len(rk)} triples; kill at L_d - 1 at "
              f"{sum(1 for r in rk if r[4][0] == 'kill')}; empty at L_d at "
              f"{sum(1 for r in rk if r[5][0] == 'empty')}")
    print(f"    kill depths at L_d - 1: "
          f"{sorted({r[4][1] for r in rows if r[4][0] == 'kill'})}; "
          f"unread {len(unread)} {unread[:4]}")
    check("PK4 no triple kills the law", not law_kill, f"{law_kill[:3]}")
    kinds = [sum(1 for r in rows if r[3] == k) for k in ("new", "deepened")]
    check("PK4 a kill at L_d - 1 at each of the 318 new and 179 deepened "
          "triples (necessity)",
          kinds == [318, 179] and all(r[4][0] == "kill" for r in rows),
          f"{kinds} triples")
    check("PK4 empty at L_d at every triple (the prune, or at WHOLE the "
          "closed form)", all(r[5][0] == "empty" for r in rows))


def main():
    t0 = time.time()
    section_pa()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        raise SystemExit(1)
    section_pb_pc()
    section_pd_pf()
    section_pe()
    section_pg()
    section_ph()
    section_pi()
    section_pj()
    section_pk()
    print(f"{sum(CHECKS)}/{len(CHECKS)} checks passed, "
          f"{time.time() - t0:.1f} s")
    raise SystemExit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()