chains.py

Checks: LATENCY: The chained delay theorem; rule; LATENCY: The threshold-miss law theorem; rule; pattern; LATENCY: The matching law rule; REDUNDANT: A factor fed ahead buys one digit at most theorem; rule.

Cited on: LATENCY, REDUNDANT.

To run it: save chains.py, with manystream.py, poles.py, redundant.py beside it; standard library only.

"""
chains.py -- what a chain of on-line units pays: the inset law, the
threshold-miss law, the matching law, the led stream spent in one
hop, and the led chain.

QUESTION. manystream.py prices ONE reader of signed-digit streams:
a map f is read at the least L with b^L rho >= Lam |I|. A datapath
wires readers in series, the first unit's output digits being the
next unit's input stream. The literature prices a series by adding the
units' on-line delays (Usman, Ercegovac and Lee, Low-Latency Online
Multiplier with Reduced Activities and Minimized Interconnect for
Inner Product Arrays, J. Signal Processing Systems 95, 2023, section
4.2.2: "for a series of online operations, the overall latency is the
sum of online delays of the corresponding operation"). Four
questions. Can the first unit's choice among legal digits buy the
second a lower delay, or is the sum a floor? Where the sum is beaten,
by what law? What does a chain of many units pay? And when the first
unit runs AHEAD (poles.py: the reciprocal emits before it reads),
does the lead pass down the chain? Past the radix, where every chain
is led (10), the first question is asked again (11).

THE SETTING. Radix b, digits D = {-a-, ..., a+}, 1 <= a+- <= b - 1, slack
rho = a- + a+ + 1 - b >= 1, M+- = a+-/(b - 1), w = M- + M+,
w - 1 = rho/(b - 1), Mh = max(M-, M+). Every stream is a D-stream of
value in [-M-, M+]; after n digits it is confined to a BOX of width
w/b^n. The PRODUCER is x y read at lead 0. Its range is
[-M- M+, max(M-^2, M+^2)], which the root tile at lead 0 holds iff M-^2 <= M+,
that is a-^2 <= a+ (b - 1): the REPRESENTABLE cells. Its floor L1* is the
least L with b^L (w - 1) >= 2 Mh w (manystream: Lam = 2 Mh). The
CONSUMER reads the producer's stream U and a fresh stream z. Units
in series are ALIGNED: the consumer reads digit n of U and of z
together, and a chain at (L1, L2) pays L1 + L2 in the inputs.

THE ARGUMENT (written before the engine).
  (1) THE HULL. The consumer sees a prefix of U. What it knows of
      x y is the FIBRE: every value the producer's selector sends to that
      prefix. Its output tiles are intervals, so a tile holds the
      fibre plus a z box iff it holds the fibre's HULL plus that box.
      The hull is an interval inside U's own box, INSET by alpha from
      the box's bottom and beta from its top (in units of the box's
      level). So the producer's selector reaches the consumer only through
      its insets. The step uses that a tile is an interval and
      nothing else; it is the floor's whole scope.
  (2) THE INSET CLAUSE. By manystream's tile lemma the sum consumer
      U + z at delay L2 is dead iff some image strictly contains a
      zone. With U's hull shortened by (alpha, beta) the k = 2 clause
      becomes: dead iff an integer lies in
          ((b^L2 - 2) M+ + beta,  b^L2 - (b^L2 - 2) M- - alpha).
      Its ESCAPE COST E(L2) is the least alpha + beta that empties
      the interval: 0 when it is empty, and otherwise, with the
      integers j_1 < ... < j_r inside, the least over splits of
      (j_i - lo) + (hi - j_(i+1)).
  (3) THE BUDGET. At level n + L1 the product images of the (x, y)
      prefixes have widths up to 2 Mh w / b^L1 in level-n units near the
      product's corner x = y = +-Mh, where their starts are dense, and
      each must sit inside the hull its prefix is sent to. Hulls sit at
      unit spacing, so hulls there must overlap by the widest image in
      the limit of depth:
          alpha + beta <= S(L1) = (w - 1) - 2 Mh w / b^L1,
      nonnegative exactly from L1* on. This is an argument: it puts
      one hull at each value, while past level 1 digit strings that
      share a value carry hulls of their own and beat it (hulls.py).
  (4) THE INSET LAW predicts the chain dead at (L1, L2) when
      E(L2) > S(L1). For the adder it is proved without (3), by the
      ALIGNED UNIT. At L2 = 1 the clause at a hull [h0, h1] of the box
      at 0 is dead iff an integer lies in (a+ - h1, b - a- - h0), so a
      hull is permitted iff it lies in [k, k + rho] for an integer k:
      at slack 1, an aligned unit of its level. The clause's length is
      2 - rho (b - 2)/(b - 1) at L2 = 1 and 2w - b^L2 (w - 1) <= 0 at
      L2 >= 2, so it bites only at L2 = 1 and slack 1 (at rho = 2 the
      ends' fractions are s/(b - 1) and (s + 2)/(b - 1),
      s = b - 1 - a+ <= b - 3), where the adder's floor is 2. There x y
      hands it, at prefix level 1 and every L1, an image with 1
      strictly inside: y in the top box at depth 1 + L1, x in the boxes
      below with lower ends X >= 0, whose starts step less than each
      width (w > 1), the union running from below 1 to
      b Mh^2 >= b^3/(4 (b - 1)^2) > 1. That image is HOMELESS: no
      permitted hull at any value holds it, however many prefixes share
      one. So (L1, 1) is dead at every L1 and the chain's floor is the
      naive sum at every representable cell (a+- <= b - 1, which the
      rho >= 2 steps use), (L1*, L2*) living by (5) at zero insets.
  (5) THE NARROWED READER (sufficiency, by the tile lemma). A reader
      into tiles [q - M- + alpha, q + M+ - beta] is a reader on the
      tiles narrowed by alpha below and beta above, with the same integer digits,
      whose children still cover their parent since
      a+- >= (b - 1)(M+- - inset). Its zones have length
      w - 1 - alpha - beta, so it reads f wherever
          b^L (w - 1 - alpha - beta) >= Lam w,
      the input boxes unchanged. A producer so narrowed hands its
      consumer a hull inset by (alpha, beta).
  (6) A PRODUCT CONSUMER z U, U of TOP tau = sup |U| (tau = Mh^2
      behind a product, 2 Mh/b behind a sum read at lead 1), reading
      U through a hull
      inset by eta in total: its image of a z box times a hull is at
      most (tau w + Mh (w - eta))/b^n wide, so by (5) it reads at L2
      wherever tau w + Mh (w - eta) <= b^L2 (w - 1), and keeps for the
      next unit the LEFTOVER
          S2(L2, eta) = (w - 1) - (Lam2 w - Mh eta)/b^L2, Lam2 = tau + Mh.
      Its escape cost is its own threshold's miss read in the
      producer's coordinate: E2(L2) = max(0, Lam2 w - b^L2 (w - 1))/Mh.
  (7) THE THRESHOLD-MISS LAW. At slack 1, w - 1 = w/b, so the
      consumer's floor is 1 when Lam2 <= 1 and 2 when Lam2 > 1, and
      the only pair that can beat the sum is (L1*, L2* - 1). The chain
      reads one below the sum if
          0 < Lam2 - 1 <= (Mh / w) min(S(L1*), room),
      the threshold missed by at most the producer's budget, bounded
      by its range's room (the audit note below; corrected after
      the run). The
      survival side is (5) and (6), a proof. The death side rested on
      (3) and is false: hulls.py's tree of hulls reads (20, 8, 12)
      one below the sum. The root
      Lam2(Mh) = 1 is 1/phi behind a product (Lam2 = Mh + Mh^2) and
      the rational b/(b + 2) behind a sum (Lam2 = Mh (1 + 2/b)); the
      sum head's budget is (w - 1) - (2w - 1)/b^L1, its images on a
      lattice of pitch 1/b^L1.
  (8) THE MATCHING LAW. A chain of units, a head reading fresh streams
      alone, then product consumers numbered from 2, each consumer j
      of top tau_(j-1) = tau_1 Mh^(j-2) and Lam_j = Mh + tau_(j-1),
      priced by (6) link by link: a consumer below its floor spends
      its producer's leftover, and one at its floor passes on its own.
      The least total over every assignment is an UPPER bound on the
      chain's floor, proved by (5); that the floor reaches it rested
      on (3) and fails at the two-unit chain at (20, 8, 12). At slack 1
      three steps, each proved at every radix.
      GREEDY. Of two states (t, v) and (t + d, v'), d >= 1, the first
      answers a move of the second at L with one at L + 1 (at L* + 1
      against L* + 2) and keeps as much: keep(L + 1, v) - keep(L, v')
      = ((b - 1) Lam w - b Mh v' + Mh v)/b^(L+1) >= 0, as v' <= w - 1
      = w/b and Lam >= Mh; then it dominates. So the least total is
      the greedy one, each unit at the least delay alive on what its
      producer hands it.
      THE FIRST GAIN. A GAIN is a link (j - 1, j) at which unit j reads
      one below its floor on the FLOOR CHAIN's leftover, every unit at
      its floor; PAIRWISE if on its producer's at zero inset; CROSSED
      if a gain and not pairwise. A gain needs Lam_j > 1, so every
      consumer above it sits at floor 2, keeping A_j + Mh eta/b^2.
      Each consumer scales its producer's range by Mh, so the ROOMS
      rise along the chain; with Lam falling so does A_j, capped by
      its room, and either head's budget at its floor is below every
      A_j (behind a product L1* = 2 and Lam_j <= 2 Mh; behind a sum
      L1* <= 2 and (2w - 1)/b^L1* >= Lam_j w/b^2), all at Mh < 1; at
      Mh = 1 no link gains, every miss w (Lam_j - 1)/Mh exceeding w - 1.
      So a crossed gain's miss m_j = w (Lam_j - 1)/Mh lies
      within Mh w/b^3 of the miss of any gain above it, while
      consecutive misses differ by more than w (1 - Mh)^2/Mh^2 >=
      w/(Mh^2 (b - 1)^2): a crossed gain is its chain's first gain.
      THE LAW. Outside the ADJACENT range (two units below their
      floors side by side, which needs the second's miss under about
      Mh^2/b^2) the least total is the naive sum less nu, a MAXIMUM
      MATCHING of the path's gains. Upper: matched downstream units one
      below, the rest at their floors; a crossed gain is the first, so
      its producer reads the floor chain. Lower: a low unit keeps less
      than Mh w/b^2 <= A_j; charge it to the nearest unit above it not
      at its floor when that one is high, which nothing else charges;
      otherwise its producer hands it at most the floor chain's
      leftover, so its link is a gain, and these links are disjoint.
  (9) A LED STREAM IS SPENT IN ONE HOP. Let a unit multiply a fresh
      stream z by a stream r >= 0 (corrected after the run) whose
      range has top tau > 0 (so the map's range is [-M- tau, M+ tau]
      and its scale K = tau). The least lead o has b^(o - 1) < tau,
      so a level-1 cell, of length w b^(o - 1), is shorter than the
      range's w tau. At a negative lookahead the first digit is
      committed before any digit of z, so, r read however deep, it
      must hold z r's image at an r near tau, w r long: dead. So such
      a unit reads at
      c >= 0 whatever r's producer did, and its own output is an
      ordinary stream. The reciprocal's lead is not lost, though: a
      consumer reading r as deep as the reciprocal runs ahead, d =
      -c1* digits past z, sees r's box b^d times narrower, and by (5)
      reads wherever (tau + Mh b^-d) w <= b^L (w - 1), against
      (tau + Mh) w for the aligned consumer.
  (10) REPRESENTABLE IS LEAD 0. Read at any cell, a+- past b - 1
      allowed, U's range [-M- M+, Mh^2] sits in the lead-0 tile
      [-M-, M+] iff M+ <= 1 and Mh^2 <= M+. If a+ >= b, M+ > 1; if
      a- >= b and a+ <= b - 1, Mh^2 >= M-^2 > 1 >= M+. So past the
      radix, max(a+-) >= b, U never sits at lead 0 and every chain is
      LED, the case (1)-(5) leave unpriced. Inside the radix M+ <= 1
      holds and Mh^2 <= M+ is a-^2 <= a+ (b - 1): representable is
      exactly lead 0. At lead o the tile holds the range iff
      b^o >= max(M+, Mh^2/M+).
  (11) THE LED CHAIN, read past (10), 1 <= a+- <= 2b - 1. Delays are
      absolute level gaps: U's digit at level m arrives at m + L1, z's
      at m, so the x path pays L1 + L2 whatever the leads. The adder
      is not held to its lead: at U's integer depths n <= 0, z is its
      root box, an additive blur w b^n wide in level-n units, and the
      clause there is the k = 2 clause with k_n = 1 + b^n <= 2, its
      interval the n >= 0 one shrunk at both ends; so the adder's
      floor is the clause's, L2* = sum_floor, at any output lead. (An
      adder held to c2 >= 0 pays max(L2*, o_f), o_f the lead of
      U + z: the naive sum L1* + L2* is the smaller incumbent.) The
      producer reads at its floor L1* = law_L(2 Mh) at any lead: the
      many-stream theorem holds at every L in Z (poles.py), so where
      U's lead o sits above it (the CLAMP) it runs ahead, its first
      o - L1* digits committed on the root box alone. A narrowed
      producer (5) at insets (alpha, beta) needs a lead o1 with
      b^o1 (M- - alpha) >= M- M+ and b^o1 (M+ - beta) >= Mh^2, which
      exists iff alpha < M- and beta < M+. Above L1 it runs ahead as
      the plain one does: its first o1 - L1 digits meet level-t zones
      (w - 1 - alpha - beta) b^(o1 - t) >= (w - 1 - alpha - beta) b^L1
      long against a root image at most 2 Mh w wide, so under (5)'s
      own condition none is dead. So the chain reads at
      (L1*, 1), one below the naive sum, wherever L2* = 2 and an
      escape option at L2 = 1 has b^L1* (w - 1 - alpha - beta) >=
      2 Mh w with alpha < M-, beta < M+: a proof, by (5) and the
      clause. It is at most one
      digit (L1 >= L1*, and L2 = 0 is dead). At slack 1 the escape
      costs the whole slack and (4)'s homeless image closes the cell at
      every L1 >= 1, led or not: no step of (4) reads U's lead, and its
      one bound, Mh < b^L1 for the lowest image to start below 1, holds
      as slack 1 forces a+- <= b - 1.
      Where L2* = 2, rho >= 2 and no narrowed producer gains, the
      corner node can kill. U through level n is a function of the
      input prefixes at depth n + L1, so the corner input pair (every digit of x and of y
      at the extreme of largest magnitude) sits in one node at level n;
      its |D|^2 refined images each go to one child b u + e, e in D, and
      at n + 1 >= 1 a child holds a hull the adder accepts iff it lies
      in its box ∩ [k, k + rho], k an integer. A node whose family
      splits among its children at no u, one window or none each, kills
      (L1*, 1) at every lead (the node exists whatever o1), and other
      routed boxes only add images, so the naive sum is the floor. A
      live producer at (L1*, 1) gives the node children holding
      accepted hulls, each refined image inside its child's, so at a
      gain the corner splits at every level: a split is no life. At
      slack 1 the homeless straddler of (4) need not sit at the corner
      in x, so nothing by hand puts the slack-1 death there. By hand: a
      gain at (b, 1, b) and (b, b, 1) for every b >= 4 (L1* = 2, the
      option 1/(b - 1) on one side, b^2/(b - 1) >= 2 Mh w iff b >= 4),
      and at (2, 2, 2) (L1* = 3, option (1, 0), lead 2). The clause
      at L2 = 1 is 2 - rho (b - 2)/(b - 1) long, empty at b >= 4 from
      rho = 3; at rho = 2, b >= 3, it holds an integer iff
      a+ = 1 mod (b - 1), with a- + a+ = b + 1 at those two cells alone.
      So past radix 3 the law is a theorem at every a+- (no bound),
      and CP's census decides radix 3 (its clause empty from rho = 4,
      so L2* = 2 needs a+- <= 4). Radix 2 is a theorem at every a+-:
      the narrowed producer pays, and the chain gains, iff no power of
      2 lies in [2 Mh w/rho, 2 Mh w/(rho - 1)), which fails exactly at
      Mh = 2^k - 1 and (2, 1, 2^k - 2), (2, 2^k - 2, 1); there
      2^L1* = 2^(k+1), a child's two windows make the node a path of
      w + 2 starts, and one corner image holds no integer start at
      level k + 1, resp. k - 1, so the corner is dead (CP's R1..R3
      check each step). Past radix 3
      no clamp cell has L2* = 2, which there needs slack 1 or (b, 1, b),
      (b, b, 1): at slack 1 a+- <= b - 1 puts U's lead at most 1
      (M+ <= 1, Mh^2/M+ <= 1/M+ <= b - 1, by (10)) and 2 Mh I > 1 = rho
      (I = a- + a+) puts law_L at least 1; (b, 1, b) has lead 1 and
      (b, b, 1) lead 2, both L1* = 2. So a clamp cell with L2* = 2 has
      b in {2, 3}, and CP reads them to a+- <= 2b - 1.

THE DESIGN, frozen before the engine.
  CA THE CONTROLS. (i) The inset clause at zero insets equals
     manystream.clause_dead at k = 2 at the 20 cells of radices 2..5
     (manystream.census) and L2 = 0..3. (ii) The inset clause against
     an exact zone scan: U's hulls nested (a prefix's hull its own
     inset box cut to its parent's), every (U, z) prefix pair to
     depth 4 at radices 2..4, L2 in {1, 2}, insets on a grid of
     sixths and tenths of the slack w - 1; the scan's death verdict
     equals the clause's at every triple. (iii) The narrowed reader
     (5) at zero insets reproduces manystream's product floor at the
     representable cells.
  CB THE INSET LAW at the 20 cells. Per cell: L1*, L2* (the k = 2
     clause), the naive sum, the inset law's least L1 + L2 over
     L1 in [L1*, L1* + 5], L2 in [0, 5], and the FUSED floor of
     x y + z (manystream's law, Lam = 2 Mh + 1, at its own lead). The
     aligned unit (4) (designed after the record run, in place of a
     covering search with one hull at each value, exact at n = 1
     where a prefix is one digit, not past it): at every cell
     of radices 2..60, every escape option's hull at L2 = 1 at slack 1
     inside an aligned unit, the clause empty at slack 2 or more and
     at L2 = 2, 3; at every representable slack-1 cell and
     L1 = L1*..L1* + 3, the straddling image of the row, checked
     homeless against every option hull at every value. Controls,
     printed first, not gating the sweep: (2, 1, 1) at L1 = 2, whose straddler by hand is the
     image 15/16..7/4 of i = 1, and aligned halves [j/2, (j + 1)/2],
     never homeless.
  CC THE THRESHOLD-MISS LAW at every slack-1 cell of radices 2..40,
     both consumers, each at its representable cells (the product
     consumer where Mh^2 fits the root tile at lead 0; the sum-fed where 2 Mh^2
     <= b M+): the least L1 + L2 by (6) over
     L1 in [L1*, L1* + 5], L2 in [0, 5], against the criterion (7).
     And every cell of slack 2 or more to radix 40 read the same way.
  CD THE MATCHING LAW. A dynamic programme over a chain's units,
     keeping the largest leftover at each (total, below-floor run)
     state (every verdict is monotone in the inset), at slack 1,
     radices 3..40, n = 3..12, both heads; and at radices 3..24 along
     each finite run of floor-2 consumers. Printed: where the greedy
     total differs from the programme's least, and the chains where
     the least differs from naive - nu, inside the adjacent range or
     out.
  CG THE CROSSED LINKS, every prefix (designed after the record run).
     Every slack-1 product-head chain, representable, Mh < 1, its
     whole floor-2 run plus one unit, radices 3..60 (3..200 with
     --cg200), and every prefix of 3 units or more, priced greedily:
     the crossed links, any gain above one (ABOVE), the prefixes
     outside the adjacent range where greedy differs from naive - nu
     (OFF), and the arm with the floor chain removed, nu read on the
     pairwise links. Control, read first: three chains the full
     programme prices, (31, 3, 28) n = 34 at 67, (29, 2, 27) n = 74 at
     147 and (24, 3, 21) n = 23 at 46.
  CE THE LED STREAM at every reciprocal pair of poles.py (the 20
     cells, h = j/(b - 1), j in 1, 2, 4, 8, 32, 128) with c1* < 0:
     tau = b^-o1 / h; the consumer's lead from its range; its aligned
     and eager L by (9); c2 = L - o2; and the fused divider z/(s + x)
     from poles.Divider, in the consumer's output scale.
  CL LEAD 0 (10). Control: over the 20 cells, representable and
     manystream's lead of x y (law_of's o, another code path) agree,
     o = 0 at exactly the 13 representable cells; a PLANT, the test
     read with a+ and a- swapped, disagrees with the lead somewhere.
     Then every cell of radices 2..40 with 1 <= a+- <= 2b - 1 and
     rho >= 1: law_of's lead is 0 iff representable, and is the least
     o with b^o >= max(M+, Mh^2/M+); printed, its distribution past
     the radix.
  CP THE LED CHAIN (11). Controls, read first: the adder's zone scan,
     U's hulls walked from U's lead (the root hull U's range, each
     child its narrowed tile cut to its parent's hull), z its root box
     at n <= 0, equals the inset clause at every past-the-radix cell
     of radices 2..4, L2 = 1 (and 2 at radix 2), insets 0, 1/6, 1/3,
     1/2 of w - 1 per side and each escape option, to level 3 (2 at
     radix 4; at 0 < n < L2 it reads z prefixes past reach, which can
     only add deaths, and none arose); the narrowed
     producer (manystream.scan against the narrowed zones, at lead o1)
     at one escape option of (2, 2, 2), (4, 1, 4), (4, 4, 1), (3, 1, 3)
     and, running ahead under lead 5 past CP's census, (2, 5, 1): at
     (5)'s L it lives, and one below it dies. A product's rate at its
     root box is the 2 Mh of (5), so the live verdict is the scan's
     rate prune at the root, (5)'s condition computed again and no
     more; the death is a kill, read by its depth and against the tile
     lemma's other side (Tiled: the image lies in no narrowed tile). At
     (3, 1, 3), beta = 1/2, the narrowed one dies at L1* = 2, where the
     plain producer lives; the corner
     split (the node's value u tried over every
     integer whose children's boxes could meet the family, a superset
     of the legal ones, each child one window or none), searched by
     backtracking (corner_split's docstring), equals the product over
     every window choice at every u, level 0..3 and L2* = 2 cell of
     radices 2, 3 whose product has at most 2*10^5 picks (so not at
     three of the nine deaths, where the search rests on its exactness,
     argued in its docstring), and fails at
     (3, 1, 3) for the pair [1/10, 21/20], [-2/5, 3/5], each housed
     alone at u = 0 (a value conflict). Then every led cell of radices
     2..40, the producer at law_L(2 Mh): the adder's floor by count,
     the gains, the corner
     split at levels 0..3 at every L2* = 2 cell (at a gain a necessary
     check), the OPEN cells, the homeless straddler at every slack-1
     led cell inside the radix at L1*..L1* + 3, the clamp count and
     its L2* = 2 cells (the options, the gain, the corner at L1* and,
     a control, at U's lead, where a lead-held producer lives), the
     cells where a held adder's lead o_f exceeds L2*, and the fused
     x y + z at its own law_L against the chain. Past radix 3 the
     census re-measures (11)'s theorem; it runs to radix 40 as that
     theorem's check at every radix it reads and as the only evidence
     for the fused clause, which has no proof. Then radix 2 past the
     census, (11)'s proof step by step. R1: L2* = 2 (sum_floor), and the
     closed form (Mh =
     2^k - 1, or Mh = 2^k - 2 with min a+- = 1) against gain_option at
     L1* at every radix-2 led cell, a+- <= 128. R2: the path splitter
     (each image's starts I = [ceil(y - rho), floor(x)]; u splits iff
     every I meets T(u) = 2u - 2a- .. 2u + a+ - a- + 1 and the least
     stabbing set of the I cut to T(u) has at most w + 1 points)
     against corner_split at every u of corner_range, levels 0..3,
     a+- <= 7, and its node search against corner_lives; its plant,
     T(u) one start short. R3: the hand formula for the corner images
     (a = Mh = a+ >= a-, the mirror by the sorted pair) against
     corner_family as sorted lists at every led cell a+- <= 7, levels
     0..3, and every non-gain cell a+- <= 31 at levels 0..3 and n0;
     2^L1* = 2q at every non-gain cell to a+- = 128; the witness, the
     formula's own image at the pair (ex, ey) of least
     (2a + a- - ex)(2a + a- - ey) whose residue a(t - 2a- - 4a) mod 2q
     is 2a- - 1 (Mh = q - 1, n0 = k + 1), resp. 2q - 2 (Mh = q - 2,
     n0 = k - 1), homeless at n0 at every non-gain cell to a+- = 128,
     and the splitter's corner dead at n0 to a+- = 31; the predicate's
     negative, no formula image homeless at levels 0..3 at any gain
     cell a+- <= 7 (a gain splits its corner at every level, so every
     image is housed). And (31, 31)'s corner at levels 0..8, printed.

PREDICTIONS.
  PA (i), (ii), (iii) agree everywhere.
  PB the inset law's floor equals the naive sum at all 20 cells;
     no aligned-unit line off to radix 60; representable at 13 of 20;
     the fused floor below the chain at 9
     of those 13 and equal at the 4 with L1* = 1.
  PC the search equals the criterion at every slack-1 cell of both
     consumers; the product-fed gains at 17 cells, all at (2, 1):
     (4,2,2), (9,4,5), (12,5,7), (17,7,10), (22,9,13), (25,10,15),
     (30,12,18), (33,13,20), (38,15,23) and the mirrors of all but
     the symmetric first; the sum-fed gains at (b, 2, b - 2) and its
     mirror at every radix 5..40 and nowhere else; no cell of slack 2
     or more gains to radix 40.
  PD greedy is the least total at every chain; outside the adjacent
     range the programme reads naive - nu at every cell; the five-unit
     sum-fed chain at (9, 2, 7) reads 7 against the matching's 8, an
     adjacent pair; the sum-fed four-unit chain at (b, 2, b - 2) reads
     naive - 2 at every radix 8..40.
  PG (its counts a TRANSPLANT from an earlier sweep of the same
     chains by a footprint engine) ABOVE and OFF empty; the crossed
     links at (29, 2, 27) j = 74,
     (31, 3, 28) j = 34, (46, 2, 44) j = 140 and, past radix 60,
     (91, 3, 88) j = 152; the pairwise arm off by one at 27 prefixes
     to radix 60 and 36 to radix 200.
  PE c2 >= 0 at every pair; the eager L below the aligned at 25 of
     the 40 pairs; the fused divider at or below the chain at all 40.
  PL lead 0 iff representable at every CL cell, never past the radix;
     the hand formula equals law_of's lead at every one.
  PP the controls as stated; the adder's floor 1 or 2 at every led
     cell; no gain inside the radix; at b >= 4 the gains exactly
     (b, 1, b) and (b, b, 1); (2, 2, 2) gains; L2* = 2 at one clamp
     cell, (2, 3, 1), no gain there (frozen before a lab run, folded
     since); the corner split at levels 0..3 at every gain and
     unsplit at some level at every cell with no gain, L2* = 2,
     rho >= 2 (the counts frozen as 76 and 8 before the clamp fold
     moved (2, 3, 1)), and at 102 of the 300 at
     slack 1; OPEN empty; the fused x y + z
     never above the chain. Radix 2 (TRANSPLANTS from two lab runs of
     the same arms): R1 0 disagree over 16383 led cells, 498 non-gain;
     R2 0 disagree over 3342 (cell, level, u), the plant off at some,
     the node searches agreeing at every (cell, level); R3 the formula
     equal at every (cell, level) read, 2^L1* = 2q at 498 of 498, the
     witness homeless at 498 of 498 and the corner dead at n0 at 116
     of 116, the negative's count 0; (31, 31) split at levels 0..3
     and dead at 4..8.

KILLS, as what the script prints.
  K1 a CA line off: the clause or the scan is wrong; nothing below is
     read.
  K2 the inset law's floor below the naive sum at some cell, or an
     "AU OFF" line: (4) is wrong.
  K3 a slack-1 cell where the search and the criterion disagree: (7)
     is wrong.
  K4 a cell outside the adjacent range where the programme is not
     naive - nu, a CD chain where greedy is not the least, or an ABOVE
     or OFF line non-empty: (8) is wrong.
  K5 c2 < 0 at a pair: (9) is wrong.
  K6 a CL cell past the radix at lead 0, or a CL mismatch: (10) is
     wrong.
  K7 a CP control off: nothing in CP is read. A gain inside the
     radix, or a radix b >= 4 whose gain set is not the two cells:
     (11) is wrong; a gain the corner does not split: the corner node
     or the gain is wrong. An OPEN cell: the corner does not close it,
     and it stays open. Radix 2: "L2* != 2 at N", "closed form vs
     gain_option: N disagree", "path splitter vs corner_split: N
     disagree" or "the node search vs corner_lives: N disagree" with
     N > 0, the plant off at none, "the formula vs corner_family: N
     off" with N > 0, 2^L1* != 2q at a cell, "witness homeless at n0: X of
     498" with X < 498, or a homeless image at a gain cell: (11)'s
     radix-2 proof is wrong at that step.

POSITIVE CONTROL: CA, read before any verdict line.

FINDINGS (entered after the run; every number is a print).
  - PA holds: the inset clause at zero insets is the k = 2 clause at
    80 of 80 (cell, L); the zone scan agrees with the clause at 524 of
    524 (cell, L2, insets); the narrowed reader at zero insets is the
    product's floor at the 13 representable cells. K1 did not fire.
    Run apart: on the grid of fractions alone no inset moves the
    clause, and a scan with the inset dropped from its nested hulls
    passed; the triples added are the escape options at L2 = 1, where
    the insets empty the clause and the scan agrees (the 12), and each
    option at 9/10, where both are dead.
  - PB holds. The inset law's floor equals the
    naive sum at 20 of 20 cells. The aligned unit holds to radix 60:
    1770 slack-1 cells, every option hull in an aligned unit and the
    adder's floor 2; 34220 cells of slack 2 or more, the clause empty
    at L2 = 1; none biting at L2 = 2, 3; 4364 representable
    (cell, L1) pairs, each with a homeless image at prefix level 1.
    The controls read as by hand. Run apart, a break (every hull widened
    by 10^-6 at its top) prints AU OFF from radix 13 on, where the
    straddle is thinner. Representable at 13; the fused x y + z (lead 1)
    reads below the chain at 9 of the 13 and level at 4, the cells
    with L1* = 1; at the 7 cells where U needs a lead, below at 6 and
    level at 1. K2 did not fire.
  - PC holds: the search equals the criterion at every slack-1 cell
    of both consumers. The product-fed consumer gains at the 17
    predicted cells, 9 radices; the sum-fed at 72 cells, (b, 2, b - 2)
    and its mirror at all 36 radices 5..40; no cell of slack 2 or
    more gains (no head skipped for want of budget). K3 did not fire.
  - PD holds: 12242 chains read; greedy is the least at all of them;
    the programme differs from naive - nu at 49, every one inside the
    adjacent range and every one by 1. The five-unit sum-fed chain at
    (9, 2, 7) reads 7 against naive 10 and the matching's 8; the
    four-unit sum-fed chain reads naive - 2 at every radix 8..40, its
    two gains not adjacent (asserted since; the (9, 2, 7) witness reads
    adjacent). K4 did not fire.
  - PE holds: 40 pairs; the eager consumer's L below the aligned at
    25; the fused divider at or below the eager chain at 40, equal at
    33. c2 >= 0 held by construction (the L of (9) is the sufficiency
    law's, which puts b^L above the range's scale), so K5 could never
    fire; it is now argued, not checked: a multiplied stream's first
    digit must hold its whole range. The least c2 is printed: 1 at the
    aligned consumer, 0 at the eager.
  - Two changes after the first run, no verdict touched. The whole-run
    read first built each chain to 400 units, which at Mh = 1 (where
    every consumer's Lam exceeds 1 and the run never ends) read
    400-unit chains and cost 350 s; the run is now read only at
    Mh < 1, and the 76 (cell, head) with Mh = 1 are read at n <= 12,
    where every consumer's miss is the same and nothing bunches. And
    the programme now prices every length of a chain in one pass.

  - Settled at the audit, after the record run: (5) holds only while
    the narrowed root tile still holds the unit's range at lead 0, so
    every budget and leftover is now bounded by that ROOM, (M- + lo) +
    (M+ - hi) for a range [lo, hi]. The room binds at the head's floor
    at 3539 (cell, head) of the product head and 1 of the sum head,
    and moves no verdict: every PC and PD line reprints unchanged,
    and (7)'s criterion on the raw budget parts from it on the room's
    at 0 of the 1222 slack-1 (cell, head).
    CB's inset law keeps the raw budget, its least total the naive
    sum at every cell either way.
  - As run, against the frozen design: CA(i) reads L = 1..4, CA(ii)'s
    scan reaches depth 3 with insets 0, 1/10, 1/6, 1/3 and 1/2 of the
    slack and the escape options, CB's L2 runs 1..5 (the sum's lead is
    1), and
    CD keys its states by total alone. PC's "all at (2, 1)" is not
    read out: the 17 cells are. CA(iii) is a cross-engine control,
    chains.narrowed_L against manystream.law_of.

  - PG holds. The control reads 67, 147 and 46, each equal to the
    full programme's least. To radix 200, 264787 prefixes, 486 inside
    the adjacent range: ABOVE 0, OFF 0; the crossed links are the four
    predicted, each its chain's only crossed link; the pairwise arm
    is off by one at 36 prefixes, all at those four cells (27 at the
    three to radix 60): the floor chain is the whole correction. K4
    did not fire.

  - PL holds. The control: lead 0 at exactly the 13 representable
    cells of the 20; the swapped plant is off at 14. Over 75439
    cells, 64779 past the radix, lead 0 iff representable, never past
    the radix, and the hand formula equals law_of's lead at every
    cell. Past the radix the lead is 1 at 63198 cells, 2 at 1577, 3 at
    (2, 3, 2), (3, 5, 1), (4, 7, 1) and 4 at (2, 3, 1); a+ <= 4
    wherever it is 2 or more (checked since an audit). The formula against law_of checks the
    interval product, which computes the same max: little more. K6
    did not fire.

  - PP holds. The zone scan from U's lead equals the inset clause at
    998 (cell, L2, insets), 78 dead; 240 skipped, no lead <= 8 with
    room. The narrowed producer lives at (5)'s L at all five options,
    one box read, and one below it is killed at output depths 2, 1, 1,
    1 and 3, the tile test's depths; the plain producer lives one below
    at (3, 1, 3) alone.
    The backtracking split equals the product at 252 (cell, level, u),
    0 off, 12 (cell, level) past the budget, all at (2, 2, 3), (2, 3, 2),
    (2, 3, 3); the value-conflict pair
    (each alone at u = 0) splits at no u.
    Over 68756 led cells of radices 2..40, 3977 inside the radix, the
    adder's floor is 1 at 68372 and 2 at 384. GAIN at 75: (b, 1, b)
    and (b, b, 1) at every radix 4..40, and (2, 2, 2);
    none at radix 3 and none inside the radix; the corner splits at
    levels 0..3 at every one. With no gain at L2* = 2, rho >= 2, the
    corner is unsplit at every level 0..3 at (2, 1, 2), (2, 1, 3),
    (2, 2, 1), (2, 2, 3), (2, 3, 1), (2, 3, 2) and at levels 1..3 at
    (2, 3, 3), (3, 1, 3), (3, 3, 1), so the naive sum is the floor of
    all 9 (4 at
    the two of radix 3, L1* = L2* = 2); OPEN at 0. At slack 1 with no
    gain, 300 cells, the corner is unsplit at some level at 102.
    (3, 3, 1) is (3, 1, 3) under (x, y) -> (-x, -y),
    which fixes x y and swaps the corner families: (3, 3, 1)'s box at
    value v is (3, 1, 3)'s at v - 1, the same interval, so its node u
    and child b u + e are (3, 1, 3)'s u - 1 and b (u - 1) + (e + 2),
    integer windows unmoved, and L1* = 2 at both (U's lead 1 and 2):
    the prints are one computation. Every slack-1 led cell inside
    the radix has a homeless
    image at L1*..L1* + 3, so (4)'s theorem holds at every led cell
    inside the radix to radix 40. Everywhere else the naive sum is the
    floor. The clamp at 1495 cells, L2* = 2 at (2, 3, 1) alone: at
    L1* = 3 under lead 4 both options (1, 0), (0, 1) need narrowed
    L 4, no gain, the corner unsplit at levels 0..3, and split at every
    level at L1 = 4, the lead-held producer's (whose gain there only
    repaid its lead). A held adder's lead above L2* at 1606. The fused
    x y + z at its law_L below the chain's least at 68029 and level at
    727. Radix 2 past the census, as the transplants said: R1 over
    16383 led cells, L2* != 2 at 0, 498 non-gain by hand, 0 disagree;
    R2 0 disagree over 3342 (cell, level, u), the plant off at 109,
    the node search 0 disagree; R3 the formula
    0 off of 673 (cell, level), 2^L1* = 2q at all 498, n0 = 1..8 at
    2, 2, 7, 15, 31, 63, 125, 253 cells, the witness homeless at 498
    of 498, the corner dead at n0 at 116 of 116, no homeless image at
    a gain cell; (31, 31) splits at levels [0, 1, 2, 3] of 0..8, so
    the proof's level n0 = 6 is a sufficient one, not the least. K7
    did not fire.

RUN RECORD: 15/15 checks, 12.1 s, peak commit 12.8 MB under a memory guard;
after an audit (CE's c2 check, which held by construction, cut), 14/14,
12.5 s, 14.5 MB; with CG at radix 60, 20/20, 14.7 s, 13.2 MB; with
--cg200, 20/20, 126.0 s, 19.6 MB; with the aligned unit in CB for the
covering search, 22/22, 15.2 s, 10.9 MB; with CL, 25/25, 26.6 s,
11.2 MB; with manystream's law_L and lead started at a float guess
(every verdict unchanged), 25/25, 16.5 s; with CP, 32/32, 29.2 s,
13.5 MB; with CP's homeless search, 33/33, 29.3 s, 14.0 MB; with
the corner split, 34/34, 31.0 s, 13.9 MB; with its widened-image
arm cut (caught by construction), 34/34, 31.1 s, 13.9 MB; with the
homeless search cut for the corner, split by backtracking at every
L2* = 2 cell, 34/34, 54.0 s, 17.6 MB; with the producer read at
law_L(2 Mh), running ahead (the clamp folded), 35/35, 53.8 s, 17.4 MB;
with the running-ahead narrowed row, 35/35, 54.5 s, 16.9 MB; with
radix 2's R1..R3, 38/38, 74.6 s, 24.0 MB; with R1's L2* row and
R2's node search printed apart (an audit), 38/38, 74.9 s, 23.9 MB;
with CA(ii) read at its escape options, the narrowed producer by its
kills, the crossed links and the counts in the checks' conditions,
40/40, 78.2 s, 24.3 MB, and with --cg200 40/40, 219.9 s, 26.9 MB.
"""

import itertools
import math
import sys
import time
from fractions import Fraction as Fr

import manystream as ms
import poles

CHECKS = []


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 cells(bmin, bmax, slack=None):
    for b in range(bmin, bmax + 1):
        for am in range(1, b):
            for ap in range(1, b):
                rho = am + ap + 1 - b
                if rho >= 1 and (slack is None or rho == slack):
                    yield ms.Cell(b, am, ap)


def representable(cell):
    """(10): U = x y at lead 0, a+- <= b - 1 and a-^2 <= a+ (b - 1)."""
    return (max(cell.am, cell.ap) <= cell.b - 1
            and cell.am ** 2 <= cell.ap * (cell.b - 1))


# ---- (2) the inset clause and its escape cost ----

def clause_ends(cell, L2):
    B = Fr(cell.b) ** L2
    return (B - 2) * cell.Mp, B - (B - 2) * cell.Mm


def clause_dead(cell, L2, alpha, beta):
    lo, hi = clause_ends(cell, L2)
    lo, hi = lo + beta, hi - alpha
    return math.floor(lo) + 1 < hi


def escape_options(cell, L2):
    """The minimal (alpha, beta) emptying the clause; [(0, 0)] when it
    is already empty."""
    lo, hi = clause_ends(cell, L2)
    ints = [j for j in range(math.floor(lo) + 1, math.ceil(hi))
            if lo < j < hi]
    if not ints:
        return [(Fr(0), Fr(0))]
    opts = []
    for i in range(len(ints) + 1):
        beta = ints[i - 1] - lo if i > 0 else Fr(0)
        alpha = hi - ints[i] if i < len(ints) else Fr(0)
        opts.append((alpha, beta))
    return opts


def escape_cost(cell, L2):
    return min(a + c for a, c in escape_options(cell, L2))


def sum_floor(cell):
    L = 1
    while clause_dead(cell, L, 0, 0):
        L += 1
    return L


# ---- (3) the budgets, (5) the narrowed reader ----

def budget_xy(cell, L1):
    return cell.w - 1 - 2 * cell.Mh * cell.w / Fr(cell.b) ** L1


def budget_sum(cell, L1):
    return cell.w - 1 - (2 * cell.w - 1) / Fr(cell.b) ** L1


def floor_xy(cell):
    L = 0
    while budget_xy(cell, L) < 0:
        L += 1
    return L


def narrowed_L(cell, lam, inset):
    """(5): least L with b^L (w - 1 - inset) >= lam w, or None."""
    z = cell.w - 1 - inset
    if z <= 0:
        return None
    L = -40
    while Fr(cell.b) ** L * z < lam * cell.w:
        L += 1
    return L


# ---- the zone scan of the inset clause ----

def zone_scan_dead(cell, L2, alpha, beta, nmax=3):
    """Every nested hull of U to depth nmax plus every z box over a
    period of prefix values: does an image strictly contain a zone?"""
    b, Mm, Mp = cell.b, cell.Mm, cell.Mp
    D = range(-cell.am, cell.ap + 1)
    level = {(0, (-Mm + alpha, Mp - beta))}
    period = b ** L2
    for n in range(1, nmax + 1):
        s = Fr(1, b ** n)
        new = set()
        for p, (plo, phi) in level:
            for e in D:
                q = b * p + e
                lo = max((q - Mm + alpha) * s, plo)
                hi = min((q + Mp - beta) * s, phi)
                if lo < hi:
                    new.add((q, (lo, hi)))
        level = new
        if n < L2:
            continue
        hulls = {h for _, h in level}
        umin = -cell.am * ms.repunit(b, n)
        for (hlo, hhi) in hulls:
            for u in range(umin, umin + period + 1):
                img = (hlo + (u - Mm) * s, hhi + (u + Mp) * s)
                if cell.kills(img, n, L2):
                    return True
    return False


# ---- (4) the aligned unit ----

def homeless(cell, opts, img):
    """True iff the level-1 image fits no hull [q - M- + a, q + M+ - c]
    at any integer q under any option (a, c): a death however many
    prefixes share a value."""
    u, v = img
    for q in range(math.floor(v - cell.Mp) - 1, math.ceil(u + cell.Mm) + 2):
        if any(q - cell.Mm + a <= u and v <= q + cell.Mp - c
               for a, c in opts):
            return False
    return True


def straddler(cell, L1):
    """(4)'s witness at prefix level 1, in level-1 units: y in the top
    box at depth 1 + L1, x in the box of lower end X = Mh - (w + i) s'
    with i the least whose image starts below 1 (mirrored to the
    positive corner when M- > M+). Returns (i, image)."""
    s = Fr(1, cell.b ** (1 + L1))
    top = cell.Mh - cell.w * s
    i = max(0, math.floor((cell.Mh - 1 / (cell.b * top)) / s - cell.w) + 1)
    while cell.b * (cell.Mh - (cell.w + i) * s) * top >= 1:
        i += 1
    X = cell.Mh - (cell.w + i) * s
    return i, (cell.b * X * top,
               cell.b * (X + cell.w * s) * (top + cell.w * s))


# ---- (6), (7) a product consumer ----

def consumer_escape(cell, A, L2):
    lam2 = A + cell.Mh
    miss = lam2 * cell.w - Fr(cell.b) ** L2 * (cell.w - 1)
    return max(Fr(0), miss) / cell.Mh


def xy_head(cell):
    """(the largest magnitude tau_1, the head's floor, its budget
    bounded by its room, its range) behind a product."""
    rng = (-cell.Mm * cell.Mp, max(cell.Mm, cell.Mp) ** 2)
    r = room(cell, rng)
    return (cell.Mh ** 2, floor_xy(cell),
            lambda L: min(budget_xy(cell, L), r), rng)


def sum_head(cell):
    rng = (-2 * cell.Mm / cell.b, 2 * cell.Mp / cell.b)
    r = room(cell, rng)
    return (2 * cell.Mh / cell.b, sum_floor(cell),
            lambda L: min(budget_sum(cell, L), r), rng)


def room(cell, rng):
    """The most a narrowed reader may inset in total and still hold
    the range [lo, hi] in its root tile at lead 0."""
    return (cell.Mm + rng[0]) + (cell.Mp - rng[1])


def times_z(cell, rng):
    c = [z * p for z in (-cell.Mm, cell.Mp) for p in rng]
    return (min(c), max(c))


def sum_fed_ok(cell):
    return 2 * cell.Mh ** 2 <= cell.b * cell.Mp


def two_unit(cell, head):
    """(naive, least, the consumer's Lam2, the head's floor budget)."""
    A, L1s, S, _ = head(cell)
    lam2 = A + cell.Mh
    L2s = 0
    while consumer_escape(cell, A, L2s) > 0:
        L2s += 1
    least = L1s + L2s
    for L1 in range(L1s, L1s + 6):
        for L2 in range(0, 6):
            if consumer_escape(cell, A, L2) <= S(L1):
                least = min(least, L1 + L2)
    return L1s + L2s, least, lam2, S(L1s)


# ---- (8) the chain programme ----

def chain_units(cell, head, n):
    A1, L1s, S, rng = head(cell)
    lams = [cell.Mh + A1 * cell.Mh ** (j - 2) for j in range(2, n + 1)]
    rooms = []
    for _ in lams:
        rng = times_z(cell, rng)
        rooms.append(room(cell, rng))
    return L1s, S, lams, rooms


def leftover(cell, lam, L, inset):
    scale = Fr(cell.b) ** L
    return cell.w - 1 - (lam * cell.w - cell.Mh * inset) / scale


def unit_floor(cell, lam):
    L = 0
    while leftover(cell, lam, L, 0) < 0:
        L += 1
    return L


def pareto(states):
    """Drop every (total, leftover) another beats on both."""
    out, best = {}, Fr(-1)
    for t in sorted(states):
        if states[t] > best:
            out[t] = best = states[t]
    return out


def links(cell, head, n):
    """Per consumer j = 2..n: (its floor, GAIN: it reads one below its
    floor on the floor chain's leftover, PAIRWISE: on its producer's at
    zero inset)."""
    L1s, S, lams, rooms = chain_units(cell, head, n)
    v0 = A = S(L1s)
    out = []
    for lam, rm in zip(lams, rooms):
        Ls = unit_floor(cell, lam)

        def low(eta):
            return Ls >= 1 and leftover(cell, lam, Ls - 1,
                                        min(eta, cell.w - 1)) >= 0
        out.append((Ls, low(v0), low(A)))
        v0 = min(leftover(cell, lam, Ls, min(v0, cell.w - 1)), rm)
        A = min(leftover(cell, lam, Ls, 0), rm)
    return out


def matchings(flags):
    """The maximum matching of the flagged links (j - 1, j) along a
    path, for every prefix: m[i] within consumers 2..i + 2."""
    take, skip, out = -1, 0, []
    for g in flags:
        take, skip = (skip + 1 if g else -1), max(take, skip)
        out.append(max(take, skip))
    return out


def adjacent_from(cell, lams):
    """The least chain length whose units carry an adjacent-range pair,
    or None."""
    w, Mh, b = cell.w, cell.Mh, cell.b
    for j in range(len(lams) - 1):
        l1, l2 = lams[j], lams[j + 1]
        keep = Mh * (Mh * (w - 1) - w * (l1 - 1)) / b
        if l1 > 1 and l2 > 1 and w * (l2 - 1) < keep:
            return j + 3
    return None


def programme_all(cell, head, nmax, full=True):
    """For every chain length n = 3..nmax, the prefix of one chain:
    {n: (naive, the matching, the least total, greedy, the pairwise
    matching, inside the adjacent range)}. A chain of n units is the
    first n units of the chain of nmax, so one pass prices every
    length. GREEDY sets each unit at the least delay alive on what its
    producer hands it, the head at L1*; full=False skips the
    programme (least total None)."""
    L1s, S, lams, rooms = chain_units(cell, head, nmax)
    ls = links(cell, head, nmax)
    nu = matchings([g for _, g, _ in ls])
    nu2 = matchings([p for _, _, p in ls])
    first = adjacent_from(cell, lams)
    states = {}
    for L1 in range(L1s, L1s + 3):
        if S(L1) >= 0:
            states[L1] = max(S(L1), states.get(L1, Fr(-1)))
    states = pareto(states)
    naive, greedy = L1s, (L1s, S(L1s))
    out = {}
    for j, (lam, (Ls, _, _)) in enumerate(zip(lams, ls)):
        if full:
            new = {}
            for t, v in states.items():
                for L in range(max(0, Ls - 1), Ls + 3):
                    r = leftover(cell, lam, L, min(v, cell.w - 1))
                    if r >= 0:
                        r = min(r, rooms[j])
                    if r >= 0 and r > new.get(t + L, Fr(-1)):
                        new[t + L] = r
            states = pareto(new)
        t, v = greedy
        for L in range(max(0, Ls - 1), Ls + 3):
            r = leftover(cell, lam, L, min(v, cell.w - 1))
            if r >= 0:
                greedy = (t + L, min(r, rooms[j]))
                break
        naive += Ls
        n = j + 2
        if n >= 3:
            out[n] = (naive, naive - nu[j], min(states) if full else None,
                      greedy[0], naive - nu2[j],
                      first is not None and n >= first)
    return out


def programme(cell, head, n):
    return programme_all(cell, head, n)[n]


def run_units(cell, A1):
    """A chain's whole floor-2 run plus one unit, at least 3 units."""
    run, top = 0, A1
    while cell.Mh + top > 1:
        run, top = run + 1, top * cell.Mh
    return max(3, run + 2)


# ---- the sections ----

def section_ca():
    print("CA  the controls")
    off = n = 0
    for cell in cells(2, 5):
        for L in range(1, 5):
            n += 1
            off += clause_dead(cell, L, 0, 0) != ms.clause_dead(
                cell.b, cell.am, cell.ap, 2, L)
    check("CA(i) the inset clause at zero insets is the k = 2 clause at "
          "80 (cell, L)", n == 80 and off == 0, f"{n} (cell, L), {off} off")
    fr = [Fr(0), Fr(1, 10), Fr(1, 6), Fr(1, 3), Fr(1, 2)]
    tot, off, turned, where = 0, 0, 0, []
    for cell in cells(2, 4):
        for L2 in (1, 2):
            pairs = {(fa * (cell.w - 1), fb * (cell.w - 1))
                     for fa in fr for fb in fr}
            for a, c in escape_options(cell, L2):
                pairs |= {(a, c), (a * Fr(9, 10), c * Fr(9, 10))}
            for a, c in sorted(pairs):
                tot += 1
                dead = clause_dead(cell, L2, a, c)
                turned += dead != clause_dead(cell, L2, 0, 0)
                if zone_scan_dead(cell, L2, a, c) != dead:
                    off += 1
                    where.append((cell.b, cell.am, cell.ap, L2,
                                  str(a), str(c)))
    check("CA(ii) the zone scan equals the inset clause at 524 triples, "
          "the insets emptying it at 12",
          (tot, turned) == (524, 12) and off == 0,
          f"{tot} triples, {turned} emptied by their insets, {off} off "
          f"{where[:4]}")
    n = off = 0
    for cell in cells(2, 5):
        if representable(cell):
            n += 1
            lam, o, Ls = ms.law_of(cell, ms.MAPS[2])
            off += narrowed_L(cell, 2 * cell.Mh, 0) != Ls - o
    check("CA(iii) the narrowed reader at zero insets is the product's "
          "floor at 13 cells", n == 13 and off == 0, f"{n} cells, {off} off")


def section_cb():
    print("CB  the inset law at the 20 cells")
    below, fused_cmp, rep, level = [], {}, 0, []
    for cell in cells(2, 5):
        L1s, L2s = floor_xy(cell), sum_floor(cell)
        naive = L1s + L2s
        least = naive
        for L1 in range(L1s, L1s + 6):
            for L2 in range(1, 6):
                if escape_cost(cell, L2) <= budget_xy(cell, L1):
                    least = min(least, L1 + L2)
        if least < naive:
            below.append((cell.b, cell.am, cell.ap))
        lam, o, Lf = ms.law_of(cell, ms.MAPS[4])
        tag = "rep" if representable(cell) else "led"
        rep += tag == "rep"
        rel = "below" if Lf < naive else (
            "equal" if Lf == naive else "above")
        fused_cmp.setdefault(tag, {}).setdefault(rel, 0)
        fused_cmp[tag][rel] += 1
        if tag == "rep" and (rel == "equal" or L1s == 1):
            level.append((rel, L1s))
        print(f"    ({cell.b},{cell.am},{cell.ap}) {tag}: L1* {L1s}, "
              f"L2* {L2s}, naive {naive}, inset law {least}, fused "
              f"{Lf} (lead {o})")
    print(f"    fused against the chain: {fused_cmp}; representable "
          f"{rep}")
    check("CB the inset law never below the naive sum at the 20 cells",
          sum(sum(v.values()) for v in fused_cmp.values()) == 20
          and not below, f"below at {below}")
    check("CB the fused unit below the chain at 9 of the 13 representable "
          "cells and level at the 4 of L1* = 1, below at 6 of the 7 led",
          fused_cmp == {"rep": {"below": 9, "equal": 4},
                        "led": {"below": 6, "equal": 1}}
          and level == [("equal", 1)] * 4, f"read {fused_cmp}, {level}")

    print("CB  the aligned unit (4): controls, then radices 2..60")
    hand = ms.Cell(2, 1, 1)
    i, img = straddler(hand, 2)
    o1 = escape_options(hand, 1)
    fine = [(Fr(j, 2), Fr(j + 1, 2)) for j in range(-4, 6)]
    print(f"    (2,1,1) L1 2: i {i}, image {img[0]}..{img[1]} (by hand "
          f"i 1, 15/16..7/4), homeless {homeless(hand, o1, img)}; the "
          f"aligned halves [j/2, (j+1)/2]: homeless at "
          f"{sum(homeless(hand, o1, im) for im in fine)} of {len(fine)}")
    check("CB control: the hand straddler, homeless",
          (i, img) == (1, (Fr(15, 16), Fr(7, 4))) and homeless(hand, o1, img))
    check("CB control: aligned images are never homeless",
          not any(homeless(hand, o1, im) for im in fine))
    off, s1, s2, pairs, worst_i = [], 0, 0, 0, 0
    for cell in cells(2, 60):
        for L2 in (2, 3):
            if escape_options(cell, L2) != [(Fr(0), Fr(0))]:
                off.append(("bites at L2", L2, cell.b, cell.am, cell.ap))
        opts = escape_options(cell, 1)
        if cell.am + cell.ap + 1 - cell.b >= 2:
            s2 += 1
            if opts != [(Fr(0), Fr(0))]:
                off.append(("bites at slack 2+", cell.b, cell.am, cell.ap))
            continue
        s1 += 1
        for a, c in opts:
            h0, h1 = -cell.Mm + a, cell.Mp - c
            if h1 > math.floor(h0) + 1:
                off.append(("hull past its unit", cell.b, cell.am, cell.ap))
        if sum_floor(cell) != 2:
            off.append(("adder floor", cell.b, cell.am, cell.ap))
        if not representable(cell):
            continue
        L1s = floor_xy(cell)
        for L1 in range(L1s, L1s + 4):
            pairs += 1
            i, img = straddler(cell, L1)
            worst_i = max(worst_i, i)
            X = cell.Mh - (cell.w + i) * Fr(1, cell.b ** (1 + L1))
            if not (X >= 0 and img[0] < 1 < img[1]
                    and homeless(cell, opts, img)):
                off.append(("no homeless image", cell.b, cell.am,
                            cell.ap, L1))
    for o in off[:12]:
        print(f"    AU OFF {o}")
    print(f"    slack-1 cells {s1}, every option hull in an aligned unit, "
          f"adder floor 2; slack-2+ cells {s2}, clause empty at L2 = 1; "
          f"no cell bites at L2 = 2, 3; representable (cell, L1) pairs "
          f"{pairs}, each with a homeless image at n = 1 (largest i "
          f"{worst_i}); off {len(off)}")
    check("CB the aligned unit at 1770 slack-1 cells, the clause empty at "
          "34220 of slack 2 or more, a homeless image at 4364 pairs",
          (s1, s2, pairs) == (1770, 34220, 4364) and not off,
          f"{len(off)} off")


def section_cc():
    print("CC  the threshold-miss law, radices 2..40")
    off, gains, deep = [], {"xy": [], "sum": []}, []
    bound = {"xy": 0, "sum": 0}
    unfunded = n1 = moved = 0
    for cell in cells(2, 40):
        for name, head, ok in (("xy", xy_head, representable),
                               ("sum", sum_head, sum_fed_ok)):
            if not ok(cell):
                continue
            naive, least, lam2, S0 = two_unit(cell, head)
            if S0 < 0:
                unfunded += 1
                continue
            _, L1s, _, rng = head(cell)
            raw = (budget_xy if name == "xy" else budget_sum)(cell, L1s)
            if room(cell, rng) < raw:
                bound[name] += 1
            if cell.rho >= 2:
                if least < naive:
                    deep.append((name, cell.b, cell.am, cell.ap))
                continue
            n1 += 1
            law = 0 < lam2 - 1 <= cell.Mh / cell.w * S0
            moved += law != (0 < lam2 - 1 <= cell.Mh / cell.w * raw)
            if law != (least < naive):
                off.append((name, cell.b, cell.am, cell.ap))
            if least < naive:
                gains[name].append((cell.b, cell.am, cell.ap))
    for name, g in gains.items():
        more = " ..." if len(g) > 12 else ""
        print(f"    {name}-fed: {len(g)} gaining cells at "
              f"{len({c[0] for c in g})} radices: {g[:12]}{more}")
    print(f"    the range's room below the budget at the head's floor: "
          f"{bound}, the criterion moved by it at {moved} of the {n1} "
          f"slack-1 (cell, head); heads with no budget at their floor, "
          f"skipped: {unfunded}")
    check("CC the search equals the criterion at the 1222 slack-1 "
          "(cell, head)", n1 == 1222 and unfunded == 0 and not off,
          f"{n1} read, off at {off[:6]}")
    check("CC the room binds at 3539 product heads and 1 sum head and "
          "moves the criterion at none",
          bound == {"xy": 3539, "sum": 1} and moved == 0,
          f"read {bound}, {moved} moved")
    want = [(4, 2, 2)]
    for b, am, ap in ((9, 4, 5), (12, 5, 7), (17, 7, 10), (22, 9, 13),
                      (25, 10, 15), (30, 12, 18), (33, 13, 20),
                      (38, 15, 23)):
        want += [(b, am, ap), (b, ap, am)]
    check("CC the product-fed gains are the 17 predicted cells",
          sorted(gains["xy"]) == sorted(want),
          f"read {len(gains['xy'])}")
    want = sorted([(b, 2, b - 2) for b in range(5, 41)]
                  + [(b, b - 2, 2) for b in range(5, 41)])
    check("CC the sum-fed gains are (b, 2, b - 2) and mirrors, 5..40",
          sorted(gains["sum"]) == want, f"read {len(gains['sum'])}")
    check("CC no cell of slack >= 2 gains", not deep, f"at {deep[:6]}")


def section_cd():
    print("CD  the matching law")
    t0 = time.time()
    outside, inside, greedy_off, reads, unending = [], {}, [], 0, 0
    for cell in cells(3, 40, slack=1):
        for name, head, ok in (("xy", xy_head, representable),
                               ("sum", sum_head, sum_fed_ok)):
            if not ok(cell):
                continue
            A1, L1s, S, _ = head(cell)
            if S(L1s) < 0:
                continue
            ns = set(range(3, 13))
            if cell.Mh == 1:
                unending += 1
            elif cell.b <= 24:
                ns.add(run_units(cell, A1))
            every = programme_all(cell, head, max(ns))
            for n in sorted(ns):
                naive, match, least, greedy, _, adj = every[n]
                reads += 1
                key = (name, cell.b, cell.am, cell.ap, n)
                if greedy != least:
                    greedy_off.append(key + (least, greedy))
                if least != match:
                    if adj:
                        inside[key] = match - least
                    else:
                        outside.append(key + (naive, match, least))
    print(f"    {reads} chains read, {time.time() - t0:.1f} s; whole run "
          f"unread at {unending} (cell, head) with Mh = 1")
    print(f"    window 0 (greedy against the programme) off at "
          f"{len(greedy_off)} {greedy_off[:4]}")
    print(f"    off the matching inside the adjacent range at "
          f"{len(inside)}, by {sorted(set(inside.values()))}")
    check("CD greedy is the least total at each of the 12242 chains, 76 "
          "(cell, head) of Mh = 1 read to 12 units",
          (reads, unending) == (12242, 76) and not greedy_off)
    check("CD naive - nu outside the adjacent range, one below it at 49 "
          "inside", not outside and len(inside) == 49
          and set(inside.values()) == {1}, f"off at {outside[:4]}")
    naive, match, least, *_, adj = programme(ms.Cell(9, 2, 7), sum_head, 5)
    print(f"    (9, 2, 7) sum-fed, five units: naive {naive}, matching "
          f"{match}, least {least}, adjacent {adj}")
    check("CD the witness reads 7 against the matching's 8, adjacent",
          (match, least, adj) == (8, 7, True))
    off = []
    for b in range(8, 41):
        for cell in (ms.Cell(b, 2, b - 2), ms.Cell(b, b - 2, 2)):
            naive, match, least, *_, adj = programme(cell, sum_head, 4)
            if least != naive - 2 or adj:
                off.append((b, cell.am, cell.ap, naive, least, adj))
    check("CD the sum-fed four-unit chain reads naive - 2, its gains not "
          "adjacent, radices 8..40", not off, f"off at {off[:4]}")


def section_ce():
    print("CE  the led stream")
    rows = []
    for cell, h in poles.pairs():
        u = poles.Recip(cell, h)
        c1 = u.law_L() - u.lead()
        if c1 >= 0:
            continue
        R = Fr(1) / (Fr(cell.b) ** u.lead() * h)
        o2 = poles.least_pow(cell.b, R)
        La = narrowed_L(cell, R + cell.Mh, 0)
        Le = narrowed_L(cell, R + cell.Mh / Fr(cell.b) ** (-c1), 0)
        dv = poles.Divider(cell, h)
        cd = dv.law_L() - dv.lead()
        rows.append((La - o2, Le - o2, cd))
    eb = sum(1 for a, e, _ in rows if e < a)
    fz = sum(1 for _, e, c in rows if c <= e)
    fe = sum(1 for _, e, c in rows if c == e)
    print(f"    {len(rows)} pairs; eager below aligned at {eb}; the fused "
          f"divider at or below the eager chain at {fz}, equal at {fe}")
    print(f"    least c2 over the pairs: aligned "
          f"{min(a for a, _, _ in rows)}, eager {min(e for _, e, _ in rows)}"
          " (at least 0 by the sufficiency law, printed, not checked)")
    check("CE 40 pairs, eager below aligned at 25",
          len(rows) == 40 and eb == 25, f"read {len(rows)}, {eb}")
    check("CE the fused divider at or below at every pair, equal at 33",
          fz == len(rows) and fe == 33, f"read {fz}, {fe}")


def section_cg(bmax):
    print(f"CG  the crossed links, every prefix, radices 3..{bmax}")
    for b, am, ap, n, want, sum_ in ((31, 3, 28, 34, 67, 68),
                                     (29, 2, 27, 74, 147, 148),
                                     (24, 3, 21, 23, 46, 46)):
        cell = ms.Cell(b, am, ap)
        naive, match, least, greedy, pair, adj = programme(cell, xy_head,
                                                           n)
        print(f"    ({b},{am},{ap}) n = {n}: naive {naive}, least {least}, "
              f"greedy {greedy}, matching {match}, pairwise {pair}")
        check(f"CG control ({b},{am},{ap}) n = {n} reads {want} against "
              f"the naive {sum_}", least == greedy == match == want
              and naive == pair == sum_ and not adj)
    if not all(CHECKS):
        return
    t0 = time.time()
    crossed, above, off, pair_off = [], [], [], []
    reads = adj = 0
    for b in range(3, bmax + 1):
        for cell in cells(b, b, slack=1):
            if not representable(cell) or cell.Mh == 1:
                continue
            A1, L1s, S, _ = xy_head(cell)
            if S(L1s) < 0:
                continue
            n = run_units(cell, A1)
            ls = links(cell, xy_head, n)
            gains = [j for j, (_, g, _) in enumerate(ls, 2) if g]
            for j, (_, g, p) in enumerate(ls, 2):
                if g and not p:
                    crossed.append((b, cell.am, cell.ap, j))
                    above += [(b, cell.am, cell.ap, i, j)
                              for i in gains if i < j]
            for m, (naive, match, _, greedy, pair, a) in programme_all(
                    cell, xy_head, n, full=False).items():
                reads += 1
                if a:
                    adj += 1
                    continue
                key = (b, cell.am, cell.ap, m)
                if greedy != match:
                    off.append(key + (match, greedy))
                if greedy != pair:
                    pair_off.append(key + (pair - greedy,))
    print(f"    {reads} prefixes, {adj} inside the adjacent range, "
          f"{time.time() - t0:.1f} s")
    print(f"    crossed links {crossed}")
    print(f"    ABOVE {above[:6]} ({len(above)})")
    print(f"    OFF {off[:6]} ({len(off)})")
    print(f"    the pairwise reading off at {len(pair_off)} prefixes, by "
          f"{sorted({d for *_, d in pair_off})}, at cells "
          f"{sorted({k[:3] for k in pair_off})}")
    links4 = [(29, 2, 27, 74), (31, 3, 28, 34), (46, 2, 44, 140),
              (91, 3, 88, 152)]
    want = {60: (links4[:3], 13393, 108, 27),
            200: (links4, 264787, 486, 36)}.get(bmax)
    read = (crossed, reads, adj, len(pair_off))
    check(f"CG the crossed links are {len(want[0]) if want else '?'} to "
          f"radix {bmax}, no gain above one",
          want is not None and crossed == want[0] and not above,
          f"read {crossed}")
    check("CG greedy is naive - nu at every prefix outside the adjacent "
          f"range, the zero-inset reading one short at "
          f"{want[3] if want else '?'}, each at a crossed cell",
          want is not None and read[1:] == want[1:] and not off
          and {d for *_, d in pair_off} == {1}
          and {k[:3] for k in pair_off} == {c[:3] for c in crossed},
          f"read {reads} prefixes, {adj} inside, {len(pair_off)} short")


def lead_formula(cell):
    """(10): the least o with b^o >= max(M+, Mh^2/M+)."""
    X = max(cell.Mp, cell.Mh ** 2 / cell.Mp)
    o = 0
    while Fr(cell.b) ** o < X:
        o += 1
    return o


def section_cl():
    print("CL  lead 0 is representable (10)")
    xy = ms.MAPS[2]

    def lead(b, am, ap):
        return ms.law_of(ms.Cell(b, am, ap), xy)[1]

    cs = ms.census()
    rep = [c for c in cs if representable(ms.Cell(*c))]
    off = [c for c in cs if (lead(*c) == 0) != representable(ms.Cell(*c))]
    check("CL control: lead 0 iff representable, 13 of 20",
          not off and (len(rep), len(cs)) == (13, 20),
          f"read {len(rep)} of {len(cs)}, off {off}")
    plant = [c for c in cs if (lead(*c) == 0)
             != representable(ms.Cell(c[0], c[2], c[1]))]
    print(f"    the plant (a+, a- swapped) is off at {len(plant)} cells")
    check("CL control: the plant disagrees at 14 cells", len(plant) == 14)
    n = past = 0
    off1, off2, hist, wide, deep = [], [], {}, [], []
    for b in range(2, 41):
        for am in range(1, 2 * b):
            for ap in range(1, 2 * b):
                if am + ap + 1 - b < 1:
                    continue
                n += 1
                cell = ms.Cell(b, am, ap)
                o = lead(b, am, ap)
                if (o == 0) != representable(cell):
                    off1.append((b, am, ap, o))
                if o != lead_formula(cell):
                    off2.append((b, am, ap, o))
                if max(am, ap) >= b:
                    past += 1
                    hist[o] = hist.get(o, 0) + 1
                    if o >= 2 and ap > 4:
                        wide.append((b, am, ap, o))
                    if o >= 3:
                        deep.append((b, am, ap, o))
    print(f"    radices 2..40, a+- <= 2b - 1: {n} cells, {past} past the "
          f"radix; x y's lead there by count {dict(sorted(hist.items()))}; "
          f"lead 3 or more at {deep}; lead 2 or more with a+ > 4 at "
          f"{len(wide)}")
    check("CL lead 0 iff representable at 75439 cells, never at the 64779 "
          "past the radix; the least o with b^o >= max(M+, Mh^2/M+); "
          "a+ <= 4 wherever it is 2 or more",
          (n, past) == (75439, 64779)
          and hist == {1: 63198, 2: 1577, 3: 3, 4: 1}
          and not off1 and not off2 and not wide,
          f"off {off1[:5]} {off2[:5]} wide {wide[:5]}")


# ---- (11) the led chain ----

XY, FUSED = ms.MAPS[2], ms.MAPS[4]
assert XY[0] == "x y" and FUSED[0] == "x y + z"


def led_cells(bmin, bmax):
    for b in range(bmin, bmax + 1):
        for am in range(1, 2 * b):
            for ap in range(1, 2 * b):
                cell = ms.Cell(b, am, ap)
                if cell.rho >= 1 and not representable(cell):
                    yield cell


def rng_xy(cell):
    return -cell.Mm * cell.Mp, cell.Mh ** 2


def floor_led(cell):
    """The producer's floor at a led cell: law_L(2 Mh), at whatever lead
    U's range needs, running ahead where that lead sits above it (the
    many-stream theorem holds at every L in Z, poles.py)."""
    return cell.law_L(XY[4](cell.Mh))


def room_lead(cell, alpha, beta, top=None):
    """The least lead o1 >= 0 (o1 <= top when top is given) whose
    narrowed root tile holds U's range; one exists iff alpha < M- and
    beta < M+."""
    lo, hi = rng_xy(cell)
    if alpha >= cell.Mm or beta >= cell.Mp:
        return None
    o1 = 0
    while top is None or o1 <= top:
        B = Fr(cell.b) ** o1
        if B * (cell.Mm - alpha) >= -lo and B * (cell.Mp - beta) >= hi:
            return o1
        o1 += 1
    return None


def gain_option(cell, L1):
    """An escape option at L2 = 1 that a narrowed producer at L1 pays,
    at any lead (running ahead allowed): (alpha, beta, o1), or None."""
    for a, c in escape_options(cell, 1):
        Ln = narrowed_L(cell, 2 * cell.Mh, a + c)
        if Ln is None or Ln > L1:
            continue
        o1 = room_lead(cell, a, c)
        if o1 is not None:
            return a, c, o1
    return None


def zone_scan_led(cell, L2, alpha, beta, o1, nmax=3):
    """The adder's zone scan, U's hulls walked from U's lead -o1 (the
    root hull U's range, each child its narrowed tile cut to its
    parent's hull), z its root box at n <= 0: dead at L2?"""
    b, Mm, Mp = cell.b, cell.Mm, cell.Mp
    D = range(-cell.am, cell.ap + 1)
    lo, hi = rng_xy(cell)
    level = {(0, (lo, hi))}
    period = b ** L2
    for n in range(-o1, nmax + 1):
        if n > -o1:
            s = Fr(b) ** -n
            new = set()
            for p, (plo, phi) in level:
                for e in D:
                    q = b * p + e
                    tlo = max((q - Mm + alpha) * s, plo)
                    thi = min((q + Mp - beta) * s, phi)
                    if tlo < thi:
                        new.add((q, (tlo, thi)))
            level = new
        hulls = {h for _, h in level}
        if n <= 0:
            if any(cell.kills((hlo - Mm, hhi + Mp), n, L2)
                   for hlo, hhi in hulls):
                return True
            continue
        s = Fr(1, b ** n)
        umin = -cell.am * ms.repunit(b, n)
        for (hlo, hhi) in hulls:
            for u in range(umin, umin + period + 1):
                if cell.kills((hlo + (u - Mm) * s, hhi + (u + Mp) * s),
                              n, L2):
                    return True
    return False


class Narrowed(ms.Cell):
    """(5)'s reader as a manystream cell: zones w - 1 - alpha - beta."""

    def __init__(self, cell, alpha, beta):
        super().__init__(cell.b, cell.am, cell.ap)
        self.alpha, self.beta = alpha, beta

    def lam_law(self, L):
        return ((self.w - 1 - self.alpha - self.beta) * Fr(self.b) ** L
                / self.w)

    def kills(self, img, n, L):
        e = Fr(self.b) ** (L - n)
        lo, hi = img[0] / e, img[1] / e
        return (math.floor(lo + self.Mm - self.alpha)
                < hi - self.Mp + self.beta)


class Tiled(Narrowed):
    """Narrowed's kill read off the tiles: the image lies in no narrowed
    tile [k - M- + alpha, k + M+ - beta]."""

    def kills(self, img, n, L):
        e = Fr(self.b) ** (L - n)
        lo, hi = img[0] / e, img[1] / e
        return not any(k - self.Mm + self.alpha <= lo
                       and hi <= k + self.Mp - self.beta
                       for k in range(math.floor(hi - self.Mp) - 1,
                                      math.ceil(lo + self.Mm) + 2))


def lives(cell, L, o):
    k, _ = ms.scan(cell, XY, L, o)
    return k is None and ms.scan.emptied


def corner_family(cell, L1, n):
    """The corner input pair at depth n + L1 (every digit of x and of y
    at the extreme of largest magnitude), refined once: its |D|^2
    images at level n + 1, level units."""
    b, m = cell.b, n + L1
    R = ms.repunit(b, m)
    c = cell.ap * R if cell.Mp >= cell.Mm else -cell.am * R
    sc = Fr(b) ** (n + 1)
    imgs = []
    for ex in range(-cell.am, cell.ap + 1):
        for ey in range(-cell.am, cell.ap + 1):
            X0, X1 = cell.box(b * c + ex, m + 1)
            Y0, Y1 = cell.box(b * c + ey, m + 1)
            ps = [X0 * Y0, X0 * Y1, X1 * Y0, X1 * Y1]
            imgs.append((min(ps) * sc, max(ps) * sc))
    return imgs


def adder_windows(cell, v):
    """The hulls the adder accepts at L2 = 1 for a child at value v:
    box ∩ [k, k + rho] of positive length, k an integer."""
    lo, hi = v - cell.Mm, v + cell.Mp
    out = []
    for k in range(math.floor(lo - cell.rho) - 1, math.ceil(hi) + 1):
        a, c = max(lo, k), min(hi, k + cell.rho)
        if a < c:
            out.append((a, c))
    return out


def split_product(cell, imgs, u):
    """The control's reference: every choice of one window or none per
    child b u + e, e in D; does one hold every image?"""
    vals = [cell.b * u + e for e in range(-cell.am, cell.ap + 1)]
    opts = [[None] + adder_windows(cell, v) for v in vals]
    for pick in itertools.product(*opts):
        ws = [w for w in pick if w is not None]
        if all(any(a <= s and t <= c for a, c in ws) for s, t in imgs):
            return True
    return False


def corner_split(cell, imgs, u):
    """Does imgs split among the children b u + e, one window or none
    each? Backtracking: the lowest unhoused image (by start, then end)
    branches over the (child, window) pairs that hold it from children
    not yet used; a window inside another of its child is dropped.
    Exact: in any split the lowest image is housed by some (child,
    window) with the child unused, and a window inside a larger one of
    the same child can be swapped for it, housing no fewer images."""
    vals = [cell.b * u + e for e in range(-cell.am, cell.ap + 1)]
    opts = []
    for i, v in enumerate(vals):
        ws = adder_windows(cell, v)
        opts += [(i, w) for w in ws
                 if not any(x != w and x[0] <= w[0] and w[1] <= x[1]
                            for x in ws)]
    im = sorted(imgs)

    def rec(rest, used):
        if not rest:
            return True
        s, t = im[rest[0]]
        for i, (a, c) in opts:
            if i in used or not (a <= s and t <= c):
                continue
            if rec([j for j in rest if not (a <= im[j][0] and im[j][1] <= c)],
                   used | {i}):
                return True
        return False

    return rec(list(range(len(im))), frozenset())


def corner_range(cell, imgs):
    """The node values tried: every integer whose children's boxes
    could meet the family, a superset of the legal ones."""
    lo = min(s for s, _ in imgs)
    hi = max(t for _, t in imgs)
    b = cell.b
    return range(math.floor((lo - cell.Mp - cell.ap) / b) - 1,
                 math.ceil((hi + cell.Mm + cell.am) / b) + 2)


def corner_lives(cell, imgs):
    """Some node value u whose children split imgs: u, or None."""
    for u in corner_range(cell, imgs):
        if corner_split(cell, imgs, u):
            return u
    return None


def corner_dead(cell, L1):
    """The levels 0..3 at which the corner family splits at no u."""
    return [n for n in range(4)
            if corner_lives(cell, corner_family(cell, L1, n)) is None]


# ---- (11) at radix 2: the path, the formula, the witness ----

def pow2_minus(x, m):
    """x = 2^k - m for some k >= 2."""
    y = x + m
    return y >= 4 and y & (y - 1) == 0


def closed2(cell):
    """The radix-2 non-gain cells by hand: Mh = 2^k - 1, or Mh = 2^k - 2
    with min a+- = 1."""
    a = max(cell.am, cell.ap)
    return pow2_minus(a, 1) or (pow2_minus(a, 2) and min(cell.am, cell.ap) == 1)


def start_intervals(cell, imgs):
    """Each image [x, y]'s window starts s, [s, s + rho] holding it:
    (ceil(y - rho), floor(x)), empty when the first exceeds the second."""
    return [(math.ceil(y - cell.rho), math.floor(x)) for x, y in imgs]


def path_split(cell, Is, u, short=False):
    """Radix 2: the children 2u + e offer the starts T(u) = 2u - 2a- ..
    2u + a+ - a- + 1, child e the two at 2u + e - a-, a path, so a set
    of starts goes to distinct children iff it is not all of T(u). u
    splits iff every I meets T(u) and the least stabbing set of the I
    cut to T(u) (greedy by right end) has at most w + 1 points. short:
    the plant, T(u) one start short."""
    t0 = 2 * u - 2 * cell.am
    t1 = t0 + cell.w + (0 if short else 1)
    iv = []
    for lo, hi in Is:
        lo, hi = max(lo, t0), min(hi, t1)
        if lo > hi:
            return False
        iv.append((hi, lo))
    iv.sort()
    pts, last = 0, None
    for hi, lo in iv:
        if last is None or last < lo:
            last, pts = hi, pts + 1
    return pts <= t1 - t0


def path_lives(cell, imgs):
    """Some node value u where path_split holds, or None; only the u at
    which every I can meet T(u) are tried."""
    Is = start_intervals(cell, imgs)
    if any(lo > hi for lo, hi in Is):
        return None
    am = cell.am
    umax = (min(hi for _, hi in Is) + 2 * am) // 2
    umin = -((-(max(lo for lo, _ in Is) - cell.w - 1 + 2 * am)) // 2)
    for u in range(umin, umax + 1):
        if path_split(cell, Is, u):
            return u
    return None


def corner_formula(cell, L1, n, pairs=None):
    """Radix 2: the corner images by hand, a = Mh = a+ >= a- (a mirror
    cell by its sorted pair), P = 2^L1, N = 2^(n+1) P, Z = a^2 2^(n+1),
    t = ex + ey: [Z + a(t - 2a- - 4a)/P + (2a + a- - ex)(2a + a- - ey)/NP,
    Z + a(t - 2a)/P + (a - ex)(a - ey)/NP], at every digit pair or at
    the pairs given."""
    am, a = sorted((cell.am, cell.ap))
    P = 2 ** L1
    N = 2 ** (n + 1) * P
    Z = a * a * 2 ** (n + 1)
    if pairs is None:
        pairs = [(ex, ey) for ex in range(-am, a + 1)
                 for ey in range(-am, a + 1)]
    out = []
    for ex, ey in pairs:
        t = ex + ey
        out.append((Z + Fr(a * (t - 2 * am - 4 * a), P)
                    + Fr((2 * a + am - ex) * (2 * a + am - ey), N * P),
                    Z + Fr(a * (t - 2 * a), P)
                    + Fr((a - ex) * (a - ey), N * P)))
    return out


def corner_witness(cell):
    """At a radix-2 non-gain cell: (q, n0, pair, image). q = Mh + 1,
    n0 = k + 1, residue 2a- - 1 at Mh = 2^k - 1; q = Mh + 2, n0 = k - 1,
    residue 2q - 2 at Mh = 2^k - 2; the pair of least
    (2a + a- - ex)(2a + a- - ey) with a(t - 2a- - 4a) = residue mod 2q,
    its image by corner_formula at L1 = k + 1, P = 2q."""
    am, a = sorted((cell.am, cell.ap))
    if pow2_minus(a, 1):
        q, j = a + 1, 2 * am - 1
        n0 = q.bit_length()
    else:
        q, j = a + 2, 2 * (a + 2) - 2
        n0 = q.bit_length() - 2
    best = min(((2 * a + am - ex) * (2 * a + am - ey), ex, ey)
               for ex in range(-am, a + 1) for ey in range(-am, a + 1)
               if (a * (ex + ey - 2 * am - 4 * a)) % (2 * q) == j)
    pair = best[1:]
    img = corner_formula(cell, q.bit_length(), n0, [pair])[0]
    return q, n0, pair, img


def section_cp(bmax):
    print("CP  the led chain (11): controls")
    fr = [Fr(0), Fr(1, 6), Fr(1, 3), Fr(1, 2)]
    tot, off, where, skipped, dead = 0, 0, [], 0, 0
    for b, L2s in ((2, (1, 2)), (3, (1,)), (4, (1,))):
        for cell in led_cells(b, b):
            if max(cell.am, cell.ap) < b:
                continue
            for L2 in L2s:
                pairs = {(fa * (cell.w - 1), fb * (cell.w - 1))
                         for fa in fr for fb in fr}
                pairs |= set(escape_options(cell, L2))
                for a, c in sorted(pairs):
                    o1 = room_lead(cell, a, c, 8)
                    if o1 is None:
                        skipped += 1
                        continue
                    tot += 1
                    v = zone_scan_led(cell, L2, a, c, o1,
                                      nmax=3 if b < 4 else 2)
                    dead += v
                    if v != clause_dead(cell, L2, a, c):
                        off += 1
                        where.append((cell.b, cell.am, cell.ap, L2,
                                      str(a), str(c)))
    print(f"    the adder's zone scan: {tot} (cell, L2, insets) past the "
          f"radix, {dead} dead; {skipped} skipped, no lead <= 8 with room")
    check("CP control: the zone scan from U's lead equals the inset clause "
          "at 998 (cell, L2, insets), 78 dead, 240 skipped",
          (tot, dead, skipped) == (998, 78, 240) and off == 0,
          f"{off} off {where[:4]}")
    rows = [((2, 2, 2), Fr(1), Fr(0), 3, 2, False),
            ((4, 1, 4), Fr(0), Fr(1, 3), 2, 1, False),
            ((4, 4, 1), Fr(1, 3), Fr(0), 2, 1, False),
            ((3, 1, 3), Fr(0), Fr(1, 2), 3, 1, True),
            ((2, 5, 1), Fr(1), Fr(0), 4, 3, False)]
    ok = True
    for (b, am, ap), a, c, L, depth, below in rows:
        cell = ms.Cell(b, am, ap)
        o1 = room_lead(cell, a, c)
        nar, o = Narrowed(cell, a, c), cell.lead(rng_xy(cell))
        root = ms.scan(nar, XY, L, o1)
        k, _ = ms.scan(nar, XY, L - 1, o1)
        kt, _ = ms.scan(Tiled(cell, a, c), XY, L - 1, o1)
        plain = lives(cell, L, o), lives(cell, L - 1, o)
        print(f"    ({b},{am},{ap}) insets ({a}, {c}) lead {o1}: at L1 {L} "
              f"narrowed (kill, boxes read) {root}, plain "
              f"{'lives' if plain[0] else 'dies'}; at L1 {L - 1} narrowed "
              f"killed at depth {k}, by the tile test at {kt}, plain "
              f"{'lives' if plain[1] else 'dies'}")
        ok &= (root == (None, 1) and k == kt == depth
               and plain == (True, below))
    check("CP control: the narrowed producer lives at its law at 5 options, "
          "its root box within the rate, and one below dies by a kill at "
          "depths 2, 1, 1, 1, 3, the tile test's; the plain one lives "
          "there at (3, 1, 3) alone", ok)
    cmp = off = over = 0
    far = set()
    for cell in led_cells(2, 3):
        if sum_floor(cell) != 2:
            continue
        L1 = floor_led(cell)
        for n in range(4):
            imgs = corner_family(cell, L1, n)
            us = corner_range(cell, imgs)
            W = max(len(adder_windows(cell, cell.b * u + e))
                    for u in us for e in range(-cell.am, cell.ap + 1))
            if (W + 1) ** (cell.am + cell.ap + 1) > 2 * 10 ** 5:
                over += 1
                far.add((cell.b, cell.am, cell.ap))
                continue
            for u in us:
                cmp += 1
                off += split_product(cell, imgs, u) != corner_split(
                    cell, imgs, u)
    c = ms.Cell(3, 1, 3)
    A, B = (Fr(1, 10), Fr(21, 20)), (Fr(-2, 5), Fr(3, 5))
    alone = [corner_split(c, [x], 0) for x in (A, B)]
    both = [u for u in range(-3, 4) if corner_split(c, [A, B], u)]
    print(f"    the corner split, backtracking against the product: "
          f"{cmp} (cell, level, u) at L2* = 2, radices 2, 3, {off} off, "
          f"{over} (cell, level) past 2*10^5 picks, at {sorted(far)}; "
          f"(3,1,3) the pair "
          f"[1/10, 21/20], [-2/5, 3/5] splits alone at u = 0 {alone}, "
          f"together at u in {both}")
    check("CP control: the backtracking split equals the product at 252 "
          "(cell, level, u), 12 (cell, level) past the picks, and fails "
          "when value-conflicted",
          (cmp, over) == (252, 12) and off == 0 and all(alone) and not both)
    if not all(CHECKS[-3:]):
        print("    CP CONTROL FAILED: nothing below is read.")
        return
    print(f"CP  every led cell, radices 2..{bmax}, a+- <= 2b - 1")
    n = inside = clamp = held = 0
    gains, opens, inside_gain, homeless_off, clamp2 = [], [], [], [], []
    cornered, gain_dead, slack1 = [], [], [0, 0]
    by_b, fused, split = {}, {}, {}
    for cell in led_cells(2, bmax):
        n += 1
        b = cell.b
        past = max(cell.am, cell.ap) >= b
        inside += not past
        L1s = floor_led(cell)
        L2s = sum_floor(cell)
        if L1s < cell.lead(rng_xy(cell)):
            clamp += 1
            if L2s == 2:
                clamp2.append(cell)
        split[L2s] = split.get(L2s, 0) + 1
        g = gain_option(cell, L1s) if L2s == 2 else None
        least = L1s + L2s - (1 if g else 0)
        if g:
            gains.append((b, cell.am, cell.ap))
            by_b.setdefault(b, []).append((cell.am, cell.ap))
            if not past:
                inside_gain.append((b, cell.am, cell.ap))
            if corner_dead(cell, L1s):
                gain_dead.append((b, cell.am, cell.ap))
        elif L2s == 2:
            nd = corner_dead(cell, L1s)
            if cell.rho >= 2:
                (cornered if nd else opens).append((b, cell.am, cell.ap, nd))
            else:
                slack1[0] += 1
                slack1[1] += bool(nd)
        if L2s == 2 and cell.rho == 1:
            opts = escape_options(cell, 1)
            for L1 in range(L1s, L1s + 4):
                i, img = straddler(cell, L1)
                X = cell.Mh - (cell.w + i) * Fr(1, b ** (1 + L1))
                if not (X >= 0 and img[0] < 1 < img[1]
                        and homeless(cell, opts, img)):
                    homeless_off.append((b, cell.am, cell.ap, L1))
        lf, of, _ = ms.law_of(cell, FUSED)
        Lf = cell.law_L(lf)
        held += of > L2s
        rel = "below" if Lf < least else ("equal" if Lf == least
                                         else "above")
        fused[rel] = fused.get(rel, 0) + 1
    print(f"    {n} led cells, {inside} inside the radix; the clamp "
          f"law_L(2 Mh) < o at {clamp}; the adder's floor by count "
          f"{dict(sorted(split.items()))}; a held adder's lead above it at "
          f"{held}")
    for cell in clamp2:
        L1s, o = floor_led(cell), cell.lead(rng_xy(cell))
        opts = [(str(a), str(c), narrowed_L(cell, 2 * cell.Mh, a + c))
                for a, c in escape_options(cell, 1)]
        print(f"    the clamp at L2* = 2: ({cell.b},{cell.am},{cell.ap}) at "
              f"L1* = {L1s} (lead {o}): options (alpha, beta, narrowed L) "
              f"{opts}; a gain {gain_option(cell, L1s)}; the corner unsplit "
              f"at levels {corner_dead(cell, L1s)}, at L1 = {o} "
              f"{corner_dead(cell, o)}")
    print(f"    GAIN at {len(gains)}: b = 2 {by_b.get(2)}; b = 3 "
          f"{by_b.get(3)}")
    off4 = [b for b in range(4, bmax + 1)
            if sorted(by_b.get(b, [])) != sorted([(1, b), (b, 1)])]
    print(f"    b >= 4: the gain set is (b, 1, b), (b, b, 1) at "
          f"{bmax - 3 - len(off4)} of {bmax - 3} radices; off at {off4}")
    print(f"    the corner unsplit at some level 0..3 at {len(gain_dead)} "
          f"gains {gain_dead[:6]}")
    print(f"    adder floor 2, rho >= 2, no narrowed gain, the corner "
          f"unsplit (cell, levels 0..3 with no split): {cornered}")
    print(f"    OPEN (rho >= 2, the corner splits at levels 0..3) at "
          f"{len(opens)}: {opens[:20]}")
    print(f"    slack 1, no gain: {slack1[0]} cells, the corner unsplit "
          f"at some level 0..3 at {slack1[1]}; without (4)'s homeless "
          f"straddler at L1*..L1* + 3: {homeless_off[:8]} "
          f"({len(homeless_off)})")
    print(f"    the fused x y + z against the chain's least: {fused}")
    check("CP the adder's floor is 1 at 68372 and 2 at 384 of the 68756 "
          "led cells, 3977 inside the radix; the clamp at 1495, a held "
          "adder's lead above its floor at 1606",
          (n, inside, clamp, held) == (68756, 3977, 1495, 1606)
          and split == {1: 68372, 2: 384}, f"{split}")
    check("CP no gain inside the radix; each of the 300 slack-1 led cells "
          "of adder floor 2 homeless, its corner unsplit at 102",
          slack1 == [300, 102] and not inside_gain and not homeless_off,
          f"{slack1} {inside_gain[:4]} {homeless_off[:4]}")
    check("CP the 75 gains: (2, 2, 2), and at b >= 4 exactly (b, 1, b), "
          "(b, b, 1)", len(gains) == 75 and by_b.get(2) == [(2, 2)]
          and not off4, f"{len(gains)} gains, off at {off4[:6]}")
    check("CP the corner splits at levels 0..3 at every gain",
          gains and not gain_dead, f"{gain_dead[:4]}")
    nine = [(2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 3), (2, 3, 1),
            (2, 3, 2), (2, 3, 3), (3, 1, 3), (3, 3, 1)]
    check("CP the corner closes the 9 rho >= 2 non-gain cells, unsplit at "
          "levels 1..3 at each; OPEN empty",
          [c[:3] for c in cornered] == nine
          and all(c[3][-3:] == [1, 2, 3] for c in cornered) and not opens)
    check("CP the clamp: L2* = 2 at (2, 3, 1) alone, its corner split at "
          "U's lead and unsplit at L1*",
          [(c.b, c.am, c.ap) for c in clamp2] == [(2, 3, 1)]
          and corner_dead(clamp2[0], clamp2[0].lead(rng_xy(clamp2[0]))) == []
          and corner_dead(clamp2[0], floor_led(clamp2[0])))
    check("CP the fused x y + z below the chain at 68029 led cells, level "
          "at 727", fused == {"below": 68029, "equal": 727}, f"{fused}")
    cp_radix2()


def cp_radix2(amax=128, af=7, ad=31):
    """(11)'s radix-2 proof, step by step (the design's R1..R3)."""
    t0 = time.time()
    print(f"CP  radix 2 past the census, a+- <= {amax}")
    led = [ms.Cell(2, am, ap) for am in range(1, amax + 1)
           for ap in range(1, amax + 1) if (am, ap) != (1, 1)]
    off = [(c.am, c.ap) for c in led
           if closed2(c) != (gain_option(c, floor_led(c)) is None)]
    ng = [c for c in led if closed2(c)]
    l2 = [(c.am, c.ap) for c in led if sum_floor(c) != 2]
    print(f"    R1 {len(led)} led cells, L2* != 2 at {len(l2)} {l2[:4]}; "
          f"{len(ng)} non-gain by hand; closed form vs gain_option: "
          f"{len(off)} disagree {off[:4]}")
    check("CP R1 radix 2: L2* = 2 at the 16383 led cells, and a gain off "
          "the 498 of Mh = 2^k - 1, (2, 1, 2^k - 2), (2, 2^k - 2, 1)",
          (len(led), len(ng)) == (16383, 498) and not l2 and not off)
    nu, bad, plant, fbad, nf, hom_gain = 0, [], 0, [], set(), []
    lbad = []
    for c in led:
        if max(c.am, c.ap) > af:
            continue
        L1 = floor_led(c)
        for n in range(4):
            imgs = corner_family(c, L1, n)
            Is = start_intervals(c, imgs)
            for u in corner_range(c, imgs):
                nu += 1
                s = corner_split(c, imgs, u)
                if s != path_split(c, Is, u):
                    bad.append((c.am, c.ap, n, u))
                plant += s != path_split(c, Is, u, short=True)
            if (corner_lives(c, imgs) is None) != (path_lives(c, imgs) is None):
                lbad.append((c.am, c.ap, n))
            nf.add((c.am, c.ap, L1, n))
            form = corner_formula(c, L1, n)
            if sorted(imgs) != sorted(form):
                fbad.append((c.am, c.ap, n))
            if not closed2(c) and any(lo > hi for lo, hi
                                      in start_intervals(c, form)):
                hom_gain.append((c.am, c.ap, n))
    print(f"    R2 {nu} (cell, level, u), a+- <= {af}: path splitter vs "
          f"corner_split: {len(bad)} disagree {bad[:4]}; the plant (T(u) "
          f"one start short) off at {plant}; the node search vs "
          f"corner_lives: {len(lbad)} disagree {lbad[:4]}   "
          f"({time.time() - t0:.1f} s)")
    check("CP R2 the path splitter equals corner_split at 3342 (cell, "
          "level, u); its plant is off at 109",
          (nu, plant) == (3342, 109) and not bad and not lbad)
    pq, hom, dead, ns, fails = [], 0, 0, {}, []
    for c in ng:
        q, n0, pair, (x, y) = corner_witness(c)
        if 2 ** floor_led(c) != 2 * q:
            pq.append((c.am, c.ap))
        h = math.ceil(y - c.rho) > math.floor(x)
        hom += h
        if not h:
            fails.append((c.am, c.ap, n0, pair))
        ns[n0] = ns.get(n0, 0) + 1
        if max(c.am, c.ap) <= ad:
            L1 = floor_led(c)
            for n in sorted({0, 1, 2, 3, n0}):
                nf.add((c.am, c.ap, L1, n))
                if sorted(corner_family(c, L1, n)) != sorted(
                        corner_formula(c, L1, n)):
                    fbad.append((c.am, c.ap, n))
            dead += path_lives(c, corner_formula(c, L1, n0)) is None
    nsm = sum(max(c.am, c.ap) <= ad for c in ng)
    print(f"    R3 the formula vs corner_family: {len(fbad)} off of {len(nf)} "
          f"(cell, level) {fbad[:4]}; 2^L1* != 2q at {len(pq)} {pq[:4]}")
    print(f"    R3 n0 over the non-gain cells {dict(sorted(ns.items()))}; "
          f"witness homeless at n0: {hom} of {len(ng)} {fails[:4]}; the "
          f"corner dead at n0 at {dead} of {nsm} (a+- <= {ad}); a homeless "
          f"image at a gain cell a+- <= {af}, levels 0..3: {len(hom_gain)} "
          f"{hom_gain[:4]}")
    check("CP R3 the formula is the corner at 673 (cell, level); a homeless "
          "witness at each of the 498 non-gain cells, at levels 1 to 8, the "
          "corner dead there at the 116 to 31; none at a gain",
          not fbad and not pq and len(nf) == 673
          and hom == len(ng) == 498 and dead == nsm == 116
          and ns == {1: 2, 2: 2, 3: 7, 4: 15, 5: 31, 6: 63, 7: 125, 8: 253}
          and not hom_gain)
    c = ms.Cell(2, 31, 31)
    L1 = floor_led(c)
    sp = [n for n in range(9)
          if path_lives(c, corner_family(c, L1, n)) is not None]
    print(f"    (31, 31) splits at levels {sp} of 0..8   "
          f"({time.time() - t0:.1f} s)")


def main():
    t0 = time.time()
    section_ca()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        raise SystemExit(1)
    section_cb()
    section_cc()
    section_cd()
    section_ce()
    section_cg(200 if "--cg200" in sys.argv else 60)
    section_cl()
    section_cp(40)
    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()