lattice.py
Checks: LATENCY: The threshold-miss law theorem; rule; pattern.
Cited on: LATENCY.
To run it: save lattice.py, with chains.py, hulls.py, manystream.py, poles.py, redundant.py beside it; needs numpy.
"""
lattice.py -- the sum head's tree of hulls on its lattice: does x + y
feed z·U past its budget?
QUESTION, PREDICTIONS, KILL, ARMS and CONTROL: frozen before this
file. The sum x + y read at lead 1 hands
U = (x + y)/b, whose images at U's level m are windows d = 2w/b^L1 wide
starting on a lattice of pitch p = 1/b^L1, offset -2M-/b^L1, the same
relative to every string's value. A tree of hulls (hulls.py) holds every
LATTICE window of a parent's interval in one child; the DENSE arm holds
every window. On the grid of step 1/((b - 1) b^L1) every lattice start,
end and box end is a grid point.
THE DRIFT (the estimate behind P1, P2). In pitches, B = b^L1, a hull
holds j + 1 windows; the budget's is j = B - 1, one integer step and no
drift. At j = B - 1 - x the children's offsets fall x a step; a parent
of j holds 2b + bj + 1 windows, which takes all b + 1 children, a drift
of bx inside an offset range of B/(b - 1) - (2w - 1) + x pitches: so
x <= (b^2 - b - 1)/(b - 1)^2 at L1 = 2, under 2 at every b >= 3,
carried over from the product unchecked: that the first child's
alignment leaves room for it.
PREDICTIONS (frozen). (P1) eta*, the least lattice-tree hull, is the
budget's 1 + d - p or one pitch below it at every slack-1 sum-fed cell,
never two below. (P2) one below at most cells. (P3) where one below,
z·U gains at (L1*, L2* - 1) wherever 0 < Lam2 - 1 <= (Mh/w)(S + p) and
the room allows, cells the budget's criterion does not have.
KILL. "eta* = 1 + d - p at every cell" over the slack-1 sum-fed cells
of radices 3..24. P1 dies on any "two below" line.
CONTROL. (i), printed after the sweep and not gating it: at
eta = 1 + d - p the state o = -M- is sustained and the root covered at
every cell.
(ii)-(iv) run first and gate the sweep. (ii) The greedy with
pitch one grid step equals hulls.py's Grid greedy at (4, 2, 2) and
(20, 8, 12), F arrays identical. (iii) The exact checker passes a
certificate and finds a fault with one child moved past its box.
(iv) (added when the script was carried, since the checker shares
lat() with the greedy and cannot see a misplaced lattice): the image
starts, computed exactly from digit strings, are all lattice points,
and none is once the lattice is moved one grid step.
As run: control (ii) compares against hulls.py's greedy with this
greedy's d one grid step wider: hulls.py's holds every window whose
start lies between grid points (a child starting at most d below the
reach), this one only windows starting on its lattice, so at pitch one
step this dense arm is a looser model than hulls.py's. The DENSE arm's
eta* is
printed beside each cell (designed after the first run, as the
positive check that the engine finds drift on this geometry).
FINDINGS (entered after the run; the counts are read by checks, the
253 of radices 3..24 aside, a run with no record row, and the
per-cell rows are prints).
- The controls hold: pitch one step reproduces hulls.py's F arrays
at (4, 2, 2) and (20, 8, 12); at (5, 2, 3) the certificate at
1 + d - p has 0 faults and 2 once one child is moved past its box;
the narrowed state and the root live at 1 + d - p at every cell.
(iv): the 961 image starts at (5, 2, 3) are all lattice points, d
wide, and none is with the lattice moved one step, and so the 441
at (4, 1, 3), where the lattice's offset is not 0; a lattice
misplaced by one step in the engine fails (iv) while (iii) passes
(a scratch copy, run). A pitch too fine passes (iv).
- THE KILL FIRED. eta* = 1 + d - p at all 253 slack-1 sum-fed cells
of radices 3..24, and at all 741 to radix 40 (L1* = 2 at each):
not one pitch below anywhere. P1 holds, P2 and P3 die. The lattice
tree gains exactly the budget's 72 cells, (b, 2, b - 2) and its
mirror, every certificate exact, and nothing else.
- The dense arm drifts below its own 1 + d at all 741 cells, by
exactly b - 2 grid steps at each on the grid K = b^L1 (1 to 38),
and is dead at 1 + d - p at all 741: the drift buys
less than a pitch (b - 1 grid steps), which the lattice budget
already holds. The tree's drift and the lattice buy the same slack.
- A dead verdict prices nothing (whole intervals, increasing order);
the sum head's converse is L3's.
L2, SLACK 2 OR MORE (sum-fed, representable, L2* = 1, so the one pair
below the sum is (L1*, 0)). hulls.py's generic multiplier kills z.U at
L2 = 0 behind any producer wherever eta_max(0) < d, d = 2w/b^L1 the
width of the fibres near U's extreme; what of the rest?
PREDICTIONS (frozen). (R3) at the cells with eta_max(0) >= d the tree
(capped root, exact at L2 = 0) is live at eta_max(0) at none. (R4) the
same at (3, 2, 2), the one cell with L2* = 2, at (L1*, 1).
KILL of "no sum-fed gain at slack >= 2": a tree certificate at
eta_max(L2) with 0 exact-checker faults, printed as the list of live
cells.
CONTROLS, read first: at the R3 cells the narrowed state (o = -M-,
F = 1 + d - p) is sustained and the root covered at 1 + d - p; the
checker finds a fault with one child moved past its box. As run: the
planted fault runs at (3, 2, 2) only (R4); R3's control is computed in
its verdict's loop and printed before it.
FINDINGS, slack 2 (entered after the run; the counts are read by
checks, the ratio is a print).
- The controls read as by hand: at (3, 2, 2) the narrowed root lives
at 1 + d - p with 0 faults, 2 once one child is moved past its box;
the narrowed state and the root live at 1 + d - p at 5367 of 5367
tree cells.
- THE KILL MISSED (R3, R4 hold), radices 3..40: L2* = 1 at 6202
cells; eta_max(0) < 0 at 37 and in [0, d) at 798, all 835 dead by
hulls.py's (G) and (G'); >= d at 5367, where eta_max(0) is under
0.8373 of the budget's 1 + d - p (printed 0.8372, rounded) and the
tree is live at none (a
dead verdict prices nothing). At (3, 2, 2), L1* = 1, d = 4/3,
eta_max(1) = 5/3 < 1 + d - p = 2, the tree dead.
L3, THE BOX BEHIND A SUM (models and predictions frozen before the
code). Positions: B = b^L1; a window starts
at (i - 2M-)/B relative to its string's value, i in [lo, hi], lo =
ceil(-(B - 2) M-), hi = floor((B - 2) M+), P = hi - lo + 1; one more
digit of x and y sends start i to b i + k, k in [-2a-, 2a+]; child e
holds t iff t - B e lies in [lo, hi], its range R_e. A set of starts
has hull d + span/B, so z.U's cap is span <= Sigma =
floor((eta_max(L2) - d) B). THE EXACT MODEL: the greatest fixpoint over
sets of span <= Sigma, a set S kept iff its run U(S) splits among the
children, each part inside R_e and kept; z.U dies at (L1, L2) if no
singleton is kept, and a kept singleton prices nothing. THE COUNT: a
kept set of n starts sends at least 2I + 1 + b(n - 1) positions (I =
a- + a+ >= b) into a hull b span + 2I + 1 <= b Sigma + 2I + 1 long,
which meets at most H = min(floor((b Sigma + 2I + P - 1)/B) + 1, I + 1)
ranges, so one child's part, kept, has at least ceil of their ratio:
from a kept singleton the kept sizes climb, and if H <= b, or the
iterate from n = 1 passes Sigma + 1, nothing is kept. At L1 = 1 with
a+- <= b - 1, lo = 1 - a- and hi = a+ - 1, so P = I - 1 and H <= b iff
b Sigma + 3I - 2 < b^2; Sigma <= (eta_max(0) - d) b = b rho/m - 4I/(b
- 1), m = max a+-, and rho <= m (the other digit bound is at most
b - 1), so b^2 - b Sigma - 3I + 2 >= b^2(1 - rho/m) + I(4b/(b - 1) - 3)
+ 2 > 0: H <= b at every such cell, every radix (the proof). And L2* <=
1 iff Lam2 w <= b(w - 1), i.e. m(b + 2)I <= b^2 (b - 1) rho (m = max
a+-), which holds, as m <= b - 1 and I = b - 1 + rho, where (b + 2)(b
- 1) <= rho(b - 2)(b + 1), at rho >= 2 once b >= 4; at b = 3 the one
cell is (3, 2, 2),
L2* = 2, where L2 = 0 dies behind any producer (eta_max(0) = -1/3 <
0, hulls.py's generic multiplier). AT SLACK 1, L1* = 2 (the clause at
L1 = 2 is 2 - (b^2 - 2)/(b - 1) < 0 long, empty), B = b^2, I = b and
P = b(b + 1) - 1, so H <= b iff
Sigma <= b^2 - b - 3; at H = b + 1, every child, the iterate from n = 1 stalls
at n = b + 1 and keeps. By hand, with m = max a+- and Mh = m/(b - 1) >
1/2: eta_max(0) = w(1 - 2Mh)/(b Mh) < 0, so L2 = 0 dies behind any
producer and Sigma < 0 there; Lam2 = m(b + 2)/(b(b - 1)) > 1 only at
m = b - 1, and at m = b - 2 for b >= 5, the family (b, 2, b - 2) and
its mirror, L2 = 0 elsewhere; Sigma =
b^2 - b - 4 at m = b - 1 (b >= 4; 1 at b = 3), so H = b; Sigma = b^2 +
floor(4b/((b - 1)(b - 2))) at m = b - 2, so H = b + 1. The budget
(chains.py's two_unit): no L1 funds L2 = 0, its escape above w/b and
every S(L1) below w - 1 = w/b, so the gain is 0 or 1, at (2, 1), iff
Lam2 - 1 <= (Mh/w) S(2), S(2) = (b^2 - b - 1)/((b - 1) b^2) under the
room (b - 2)/(b - 1); at m = b - 1 the left side is 2/b and the right
under 1/b, and at the family it holds as b^2 + b + 2 > 0: the budget
gains, by 1, exactly at the family, every radix. And at L1 = 1 the
least integer above (b - 2)M+ is a+, below b - (b - 2)M- iff rho - 1 <
a-/(b - 1): L1* = 1 wherever a+- <= b - 1 and rho >= 2, 2 at rho = 1.
PREDICTIONS (frozen). (R5) z.U dies at (L1*, 0) at the cells L2
leaves; (R6) H <= b there, every radix, L1* = 1 checked beside it; run
(after the freeze) at every slack >= 2 cell with L2* = 1, eta_max(0) <
d included, first the representable ones, then (frozen again) all with
a+- <= b - 1, as the proof never uses (a-)^2 <= a+(b - 1); (R0, with
that widening) z.U's range fits its root tile there: a+ = 1 would force
a- >= b, so M+ >= 2/(b - 1), and 2Mh^2 <= b M+ (if a+ >= a-, as M+ <=
1; else 2Mh^2 <= 2 <= b M+); (R4') the count kills (3, 2, 2) at (L1*, 1)
(by hand Sigma 1, H 5, the iterate 1, 2, 3 past Sigma + 1); (Y1) at
slack 1 the count kills z.U at (L1*, L2* - 1) at every cell the budget
does not gain, H <= b at each; (Y2) it spares exactly the family,
(Sigma, H) at the hand values; (Y3) L1* = 1 at slack >= 2 and 2 at
slack 1, every cell; (Y4, designed after Y1-Y3's run, then proved) the
budget gains, by 1, exactly at the family; (R7, added after the
freeze, at the audit) L2* = 1 at every slack >= 2 cell but (3, 2, 2),
where it is 2, the hand test beside it.
CONTROLS, gating the verdicts: (Ca) the count spares the budget's gains
at slack 1, which L1's tree certifies; (C1) at Sigma = B - 1 the exact
model keeps a singleton at b <= bx, (Cb) the count spares it there;
(C2) the exact model dead wherever the count kills, b <= bx, and (Yc)
at slack 1 where Sigma >= 0, b <= 4 (at b = 5 its sets of span 16 over
29 positions are too many); (C3) with every set of span <= cap kept,
the exact split of a block is Box.cover's window cover (windows of
cap + 1 positions, one per child inside R_e, increasing e), at caps
Sigma, B - 2, B - 1, b <= bx. Plant (R4'): the iterate's bound Sigma + 1
raised to Sigma + 2 must spare (3, 2, 2).
FINDINGS, the box (entered after the run; the counts are read by
checks; the planted runs' numbers were printed by scratch copies).
- The controls hold (radices 3..40, the exact model to radix 9): Ca,
the count spares all 72 budget gains of the 741 sum-fed slack-1
cells; C1,
the exact model keeps a singleton at Sigma = B - 1 at the 6 cells to
radix 9, Cb, the count spares all 6; C2, the exact model dead at 6
of 6 (and, before the widening shipped, at the 23 non-representable
cells to radix 12 where the count kills), and Yc at (3, 1, 2) and
(4, 1, 3), the slack-1 cells to radix 4 with Sigma >= 0 where the
count kills; C3, 1059 (block, cap), 0 differ. Planted
(scratch copies, run): R0's loop widened to slack 1 fails at 10
cells to radix 12; in the lab script, H raised by 4 at (11, 10, 9),
the non-representable cell of least margin to radix 40, was read
there (3676 of 3677 H <= b, least b - H -1); with the exact split's
old fault restored (an overlap position handed to both children), C3
differs at 165 of 871 (before the widening). At the 55 sum-fed slack-1
cells to radix 12, 16
gains: with H one child more the count spares the 16 and 9 cells
more, (b, 1, b - 1) from b = 4, so Y1 fails; with H one child fewer
all 16 gains die, so Ca fails; with b more positions in the
iterate's bound no gain dies (Ca cannot see a count that harsh: at
H = b + 1 its iterate stalls at 2b + 1, below Sigma + 1). With the
iterate's bound at Sigma + 2 the count spares (3, 2, 2); with b + 3
for b + 2 in R7's hand test, 1 mismatch to radix 40, (4, 2, 3) (b + 1
is caught at (3, 2, 2) by construction, already in R7's list).
- R5 HOLDS: the count kills z.U at (L1*, 0) at all 8408 slack >= 2
cells with eta_max(0) >= d to radix 40 (5367 representable). R6
HOLDS: at all 1313399 slack >= 2 cells with L2* = 1 to radix 200
(31551 with eta_max(0) < d) L1* = 1 and H <= b, least b - H 2. R0
HOLDS at all
1313400. R7 HOLDS: to radix 200 the one slack >= 2 cell with L2* !=
1, or off the hand test, is (3, 2, 2), L2* = 2. R4' HOLDS: at (3, 2,
2), Sigma 1, H 5, the count kills z.U at (L1*, 1). So behind a sum
at slack 2 or more the chain pays the naive sum at every cell with
a+- <= b - 1, every radix (the proof).
- Y1 HOLDS: of the 741 sum-fed slack-1 cells to radix 40 the count
kills z.U
at (L1*, L2* - 1) at all 669 the budget does not gain, H <= b at
each, Sigma < 0 at 631. Y2 HOLDS: it spares exactly the 72 cells
(b, 2, b - 2) and their mirrors, (Sigma, H) at the hand values at
every cell, Sigma < 0 exactly where Lam2 <= 1. Y4 HOLDS: the budget
gains, by 1, exactly at that family at all 19701 sum-fed slack-1
cells to radix 200. Y3 HOLDS at all 1333299 cells to radix 200. So
at slack 1 behind a sum the gains are the budget's, by one digit,
every radix (the proof): the sum head's converse. At m = b - 1, H = b,
the count holding with no child to spare.
USAGE: python lattice.py [bmax [bmax2 [bmax3 [bx [bfar]]]]], bmax = 8
bare (L1), bmax2 = bmax (L2), bmax3 = 9 (L3), bx = min(9, bmax3) (L3's
exact model), bfar = 20 (L3's count); the record runs are python
lattice.py 40 and 8 40 40 9 200. The counts each printed are in
L1_RECORD, L2_RECORD, L3_RECORD and FAR_RECORD, read by the checks'
conditions: a run at other arguments fails them.
RUN RECORD: radices 3..8, 0.2 s, 17.0 MB (the rehearsal); 3..24,
5.9 s, 41.4 MB; with the dense eta*, 17.8 s, 42.6 MB; 3..40, 359.6 s,
185.2 MB; all under a memory guard, K = b^L1 (exact on the lattice).
Bare, with (iv): radices 3..8, 6/6 checks, 0.3 s; with the gains
checked against the budget's, 7/7, 0.2 s, 19.0 MB. With L2: bare
11/11; L2 to radix 40 (8 40), 11/11, 33.1 s, 22.7 MB, under a memory
guard. With L3's count at slack 1: bare 24/24,
71.9 s, 19.5 MB; 8 40 40 9 200, 24/24, 137.8 s, 71.5 MB, under a
memory guard; with R7, 8 40 40 9 200, 25/25, 145.9 s, 69.7 MB;
widened, with R0, bare 26/26, 83.3 s; 8 40 40 9 200, 26/26, 155.2 s,
96.6 MB, under a memory guard. With the counts read by the checks, the
kill, the dense arm and the positions P as checks and (iv) at (4, 1,
3): bare 29/29, 82.7 s; 8 40 40 9 200, 29/29, 182.5 s, 98.6 MB; 40,
29/29, 458.0 s (L1 351.1 s), 190.4 MB, both under a memory guard.
"""
import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import math # noqa: E402
import sys # noqa: E402
import time # noqa: E402
from fractions import Fraction as Fr # noqa: E402
import numpy as np # noqa: E402
import chains # noqa: E402
import hulls # noqa: E402
import manystream as ms # noqa: E402
CHECKS = []
# What the recorded runs printed, read by the checks' conditions. A run
# at arguments with no row fails its pinned checks by design.
L1_RECORD = { # bmax: slack-1 cells, the tree's gains
8: (21, 8),
40: (741, 72),
}
L2_RECORD = { # bmax2: cells with L2* = 1, eta_max(0) < 0, in [0, d),
# >= d (the tree cells)
8: (34, 5, 28, 1),
40: (6202, 37, 798, 5367),
}
L3_RECORD = { # (bmax3, bx): slack >= 2 cells with eta_max(0) >= d, of
# them b <= bx, C3's (block, cap), slack-1 cells, budget
# gains, slack-1 cells with Sigma < 0
(9, 9): (6, 6, 1059, 28, 10, 11),
(40, 9): (8408, 6, 1059, 741, 72, 631),
}
FAR_RECORD = { # bfar: cells with L2* = 1, of them eta_max(0) < d, least
# b - H, slack >= 2 cells, slack-1 cells, all cells
20: (1139, 411, 2, 1140, 171, 1329),
200: (1313399, 31551, 2, 1313400, 19701, 1333299),
}
def check(name, ok, detail=""):
CHECKS.append(bool(ok))
tail = f" ({detail})" if detail else ""
print(f" {'PASS' if ok else 'FAIL'} {name}{tail}")
class LGrid(hulls.Grid):
"""A tree on lattice windows: pitch P and offset c0 in grid units.
head 'sum' sets d, eta_max and the range from the sum head; 'xy'
keeps hulls.Grid's. dense=True sets P = 1, c0 = 0."""
def __init__(self, cell, L1, L2, K, head="sum", dense=False):
super().__init__(cell, L1, L2, K)
b, G = cell.b, self.G
B = b ** L1
if head == "sum":
assert K % B == 0
Mh, w = cell.Mh, cell.w
tau = 2 * Mh / b
self.d_fr = 2 * w / Fr(B)
self.eta_fr = (Fr(b) ** L2 * (w - 1) - tau * w) / Mh
self.d = int(self.d_fr * G)
self.eta_max = int(self.eta_fr * G // 1)
lo, hi = -2 * cell.Mm / b, 2 * cell.Mp / b
assert (lo * G).denominator == 1 and (hi * G).denominator == 1
self.lo, self.hi = int(lo * G), int(hi * G)
self.P = G // B
self.c0 = (-2 * cell.am * K // B) % self.P
if dense or head != "sum":
self.P, self.c0 = 1, 0
def lat(self, x):
"""The first lattice point >= x."""
return x + ((self.c0 - x) % self.P)
def greedy(self, F, start, record=False):
top = self.o + F
PM = np.maximum.accumulate(top)
if record:
idx = np.where(top == PM, np.arange(self.N), 0)
PA = np.maximum.accumulate(idx)
tn = self.lat(start)
picks = []
for e in range(-self.cell.am, self.cell.ap + 1):
j = tn - e * self.G + self.Mm
ok = j >= 0
jj = np.clip(j, 0, self.N - 1)
new = self.lat(e * self.G + PM[jj] - self.d + 1)
take = ok & (new > tn)
if record:
picks.append((e, np.where(take, PA[jj], -1)))
tn = np.where(take, new, tn)
me = tn + self.d - 1
return (me, picks) if record else me
def check(self, F, cert, eta, plant=None):
"""Exact, pure-integer: each state's lattice windows (and the
root's) held, each in one recorded child inside its box with
F <= eta, children in increasing order."""
b, G, d = self.b, self.G, self.d
Fl = [int(x) for x in F]
bad = sum(x > eta for x in Fl)
for s, kids in enumerate(cert):
if s < self.N:
o0 = s - self.Mm
lo, hi = b * o0, b * (o0 + Fl[s])
else:
lo, hi = b * self.lo, b * self.hi
tn, last_e = self.lat(lo), None
for e, i in kids:
oe, Fe = i - self.Mm, Fl[i]
if plant is not None and (s, e) == plant:
oe += G
if not (-self.cell.am <= e <= self.cell.ap):
bad += 1
if last_e is not None and e <= last_e:
bad += 1
if not (-self.Mm <= oe and oe + Fe <= self.Mp):
bad += 1
st = e * G + oe
if st > tn:
bad += 1
tn = max(tn, self.lat(st + Fe - d + 1))
last_e = e
if tn + d <= hi:
bad += 1
return bad
def section_control():
print("L0 controls")
for cell in (ms.Cell(4, 2, 2), ms.Cell(20, 8, 12)):
L1 = chains.floor_xy(cell)
g0 = hulls.Grid(cell, L1, 1, 40)
g1 = LGrid(cell, L1, 1, 40, head="xy")
g1.d += 1 # hulls.py's greedy holds windows one grid step wider
F0, _ = g0.fixpoint(g0.G + g0.d - 3)
F1, _ = g1.fixpoint(g0.G + g0.d - 3)
check(f"({cell.b},{cell.am},{cell.ap}): pitch one step is "
f"hulls.py's greedy", np.array_equal(F0, F1))
cell = ms.Cell(5, 2, 3)
L1 = chains.sum_floor(cell)
K = cell.b ** L1
g = LGrid(cell, L1, 1, K)
h0 = g.G + g.d - g.P
lv, F, _ = g.live(h0)
cert = g.certificate(F)
bad = g.check(F, cert, h0)
s = next(s for s, k in enumerate(cert) if len(k) >= 2 and F[s] >= g.d)
planted = g.check(F, cert, h0, plant=(s, cert[s][0][0]))
check("(5,2,3) sum head at 1 + d - p: live, 0 checker faults, two "
"(its box, its start) once one child is moved past its box",
lv and bad == 0 and planted == 2,
f"L1 {L1}, faults {bad}, planted {planted}")
for cell, images, c0 in ((cell, 961, 0), (ms.Cell(4, 1, 3), 441, 1)):
L1 = chains.sum_floor(cell)
g = LGrid(cell, L1, 1, cell.b ** L1)
starts, widths = image_starts(cell, L1, g.G)
on = sum(g.lat(x) == x for x in starts)
was = g.c0
g.c0 = (g.c0 + 1) % g.P
moved = sum(g.lat(x) == x for x in starts)
check(f"({cell.b},{cell.am},{cell.ap}) the {images} image starts "
f"from digit strings: every one a lattice point, offset "
f"{c0}, d wide; none once the lattice moves one step",
on == len(starts) == images and was == c0
and widths == {g.d} and moved == 0,
f"{len(starts)} images, {on} on, offset {was}, {moved} on "
f"when moved")
def image_starts(cell, L1, G):
"""The sum head's images at U's level 1, from the digit strings x
and y of length L1: U = (x + y)/b, read in grid units. Exact, and
independent of lat()."""
b, t = cell.b, L1
D = range(-cell.am, cell.ap + 1)
vals = {0}
for _ in range(t):
vals = {b * v + e for v in vals for e in D}
starts, widths = [], set()
for X in vals:
for Y in vals:
lo = (Fr(X) - cell.Mm + Fr(Y) - cell.Mm) / Fr(b) ** t / b
hi = (Fr(X) + cell.Mp + Fr(Y) + cell.Mp) / Fr(b) ** t / b
lo, hi = lo * b * G, hi * b * G
assert lo.denominator == 1 and hi.denominator == 1
starts.append(int(lo))
widths.add(int(hi - lo))
return starts, widths
def cells1(bmin, bmax):
for b in range(bmin, bmax + 1):
for am in range(1, b):
cell = ms.Cell(b, am, b - am)
if chains.sum_fed_ok(cell):
yield cell
def section_sweep(bmax):
print(f"L1 the lattice tree against the budget, radices 3..{bmax}")
rows = []
t0 = time.time()
for cell in cells1(3, bmax):
L1 = chains.sum_floor(cell)
K = cell.b ** L1
lam2 = cell.Mh * (1 + Fr(2, cell.b))
L2 = 1 if lam2 > 1 else 0
naive, least, _, S0 = chains.two_unit(cell, chains.sum_head)
g = LGrid(cell, L1, L2, K)
gd = LGrid(cell, L1, L2, K, dense=True)
P = g.P
h0 = g.G + g.d - P
nar = g.fixpoint(h0)[0][0] >= min(h0, g.Mp + g.Mm)
root0 = g.live(h0)[0]
below = 0
while below < 4 and g.live(h0 - (below + 1) * P)[0]:
below += 1
lv = g.eta_max >= g.d and g.live(g.eta_max)[0]
bad = None
if lv:
F = g.fixpoint(g.eta_max)[0]
bad = g.check(F, g.certificate(F), g.eta_max)
dv = gd.eta_max >= gd.d and gd.live(gd.eta_max)[0]
dbelow = 0
while dbelow < 4 and gd.live(h0 - (dbelow + 1) * P)[0]:
dbelow += 1
dzero = gd.live(h0)[0]
dstar = gd.eta_star(gd.G + gd.d + 2 * gd.G)
dgap = None if dstar is None else gd.G + gd.d - dstar
law = least < naive
rows.append((cell, L1, L2, nar, root0, below, lv, bad, dv, dzero,
dbelow, law, dgap))
tag = "GAIN" if lv and not law else ("gain" if lv else "")
print(f" ({cell.b},{cell.am},{cell.ap}) L1 {L1} L2 {L2}: "
f"narrowed {nar}, root at 1+d-p {root0}; pitches below "
f"{below}; z·U {'live' if lv else 'dead'}"
f"{'' if bad is None else f' (faults {bad})'}, law "
f"{'gain' if law else 'none'}; dense: at 1+d-p {dzero}, "
f"below {dbelow}, z·U {'live' if dv else 'dead'}, eta* "
f"below 1 + d by {dgap}/{gd.G} {tag}",
flush=True)
print(f" cells {len(rows)}, {time.time() - t0:.1f} s")
return rows
def section_slack2(bmax):
"""L2: the sum-fed slack >= 2 cells the generic multiplier leaves."""
print(f"L2 slack >= 2, sum-fed, radices 3..{bmax}")
cell = ms.Cell(3, 2, 2)
L1 = chains.sum_floor(cell)
K = cell.b ** L1
g = LGrid(cell, L1, 1, K)
h0 = g.G + g.d - g.P
lv, F, _ = g.live(h0)
cert = g.certificate(F)
s = next(s for s, k in enumerate(cert) if len(k) >= 2 and F[s] >= g.d)
planted = g.check(F, cert, h0, plant=(s, cert[s][0][0]))
check("C (3,2,2) the narrowed root lives at 1 + d - p, 0 faults, two "
"(its box, its start) once one child is moved past its box",
lv and g.check(F, cert, h0) == 0 and planted == 2,
f"L1 {L1}, planted {planted}")
ok = g.eta_max >= g.d and g.live(g.eta_max)[0]
print(f" (3,2,2) L1* {L1}, d {g.d_fr}, eta_max(1) {g.eta_fr}, "
f"1 + d - p {1 + g.d_fr - Fr(1, K)}; tree "
f"{'live' if ok else 'dead'}")
check("R4 (3,2,2) the tree is dead at (L1*, 1) = (1, 1), d 4/3, "
"eta_max(1) 5/3", not ok and L1 == 1
and (g.d_fr, g.eta_fr) == (Fr(4, 3), Fr(5, 3)))
rec = L2_RECORD.get(bmax, (None,) * 4)
t0 = time.time()
n = neg = small = 0
ctl, live, ratio = [], [], Fr(0)
for cell in chains.cells(3, bmax):
if cell.rho < 2 or not chains.representable(cell):
continue
if hulls.least_L2(cell, 2 * cell.Mh / cell.b) != 1:
continue
n += 1
L1 = chains.sum_floor(cell)
K = cell.b ** L1
g = LGrid(cell, L1, 0, K)
if g.eta_fr < 0:
neg += 1
continue
if g.eta_fr < g.d_fr:
small += 1
continue
h0 = g.G + g.d - g.P
nar = g.fixpoint(h0)[0][0] >= min(h0, g.Mp + g.Mm)
ctl.append(nar and g.live(h0)[0])
ratio = max(ratio, g.eta_fr / (1 + g.d_fr - Fr(1, K)))
if g.live(g.eta_max)[0]:
F = g.fixpoint(g.eta_max)[0]
live.append(((cell.b, cell.am, cell.ap),
g.check(F, g.certificate(F), g.eta_max)))
print(f" L2* = 1: {n} cells; eta_max(0) < 0 at {neg}, in [0, d) at "
f"{small}, >= d at {len(ctl)}; max eta_max(0)/(1 + d - p) "
f"{float(ratio):.4f}; {time.time() - t0:.1f} s")
check(f"C of {rec[0]} cells with L2* = 1, eta_max(0) is below 0 at "
f"{rec[1]}, in [0, d) at {rec[2]} and at least d at {rec[3]}, "
f"the tree cells: the narrowed state and the root at 1 + d - p "
f"at each", all(ctl) and (n, neg, small, len(ctl)) == rec,
f"{n}, {neg}, {small}; {sum(ctl)} of {len(ctl)}")
print(f" the tree live at eta_max(0): {live}")
check("R3 the tree is live at eta_max(0) at no cell", not live)
# ---- L3: the box behind a sum ----
class Box:
"""A sum-fed cell's positions at (L1, L2): window starts i in [lo, hi]
relative to a string's value, child e's range R_e = B e + [lo, hi],
and the consumer's cap Sigma."""
def __init__(self, cell, L1, L2=0):
b, Mm, Mp, w, Mh = cell.b, cell.Mm, cell.Mp, cell.w, cell.Mh
self.cell, self.b, self.L1 = cell, b, L1
self.am, self.ap = cell.am, cell.ap
B = self.B = b ** L1
self.lo = math.ceil(-(B - 2) * Mm)
self.hi = math.floor((B - 2) * Mp)
self.P = self.hi - self.lo + 1
self.d = 2 * w / Fr(B)
self.eta = (Fr(b) ** L2 * (w - 1) - 2 * Mh / b * w) / Mh
self.sigma = math.floor((self.eta - self.d) * B)
self.digits = list(range(-cell.am, cell.ap + 1))
self.R = {e: (B * e + self.lo, B * e + self.hi) for e in self.digits}
assert self.P <= 2 * B, "a position in three ranges"
def run(self, c1, c2):
return self.b * c1 - 2 * self.am, self.b * c2 + 2 * self.ap
def cover(self, r1, r2, sigma):
"""Windows of sigma + 1 positions, one per child inside R_e,
increasing e, cover [r1, r2]? (greedy)"""
t0 = r1
for e in self.digits:
a, z = self.R[e]
if z < t0:
continue
if a > t0:
return False
t0 = min(t0 + sigma, z) + 1
if t0 > r2:
return True
return False
def positions(mask, lo):
out, j = [], 0
while mask:
if mask & 1:
out.append(lo + j)
mask >>= 1
j += 1
return out
def splits(g, s, live):
"""The exact model's step: does U(s) split among the children, each
part inside R_e and in live? Overlap positions go to one child."""
lo, b, B = g.lo, g.b, g.B
U = set()
for i in positions(s, lo):
U.update(range(b * i - 2 * g.am, b * i + 2 * g.ap + 1))
kids = [e for e in g.digits
if g.R[e][0] <= max(U) and g.R[e][1] >= min(U)]
assert all(any(g.R[e][0] <= t <= g.R[e][1] for e in kids) for t in U)
states, prev = {frozenset()}, set()
for idx, e in enumerate(kids):
a, z = g.R[e]
mine = {t for t in U if a <= t <= z}
nxt = kids[idx + 1] if idx + 1 < len(kids) else None
shared = sorted(t for t in mine if nxt is not None
and g.R[nxt][0] <= t <= g.R[nxt][1])
forced_here = mine - set(shared) - prev
prev = set(shared)
new_states = set()
for inc in states:
base = forced_here | inc
for sub in range(1 << len(shared)):
take = {shared[j] for j in range(len(shared)) if sub >> j & 1}
part = base | take
if part:
m = 0
for t in part:
m |= 1 << (t - B * e - lo)
if m not in live:
continue
new_states.add(frozenset(set(shared) - take))
states = new_states
if not states:
return False
return frozenset() in states
def exact_dead(g, sigma):
"""The greatest fixpoint over sets in the box of span <= sigma: is
no singleton kept?"""
lo, hi = g.lo, g.hi
live = set()
for x in range(lo, hi + 1):
for m in range(1 << min(sigma, hi - x)):
live.add((1 | (m << 1)) << (x - lo))
while True:
keep = {s for s in live if splits(g, s, live)}
if len(keep) == len(live):
break
live = keep
return not any((1 << (i - lo)) in live for i in range(lo, hi + 1))
def box_cells(bmax, every=False):
"""The slack >= 2 cells (a+- <= b - 1) with L2* = 1, at (L1*, 0);
only those with eta_max(0) >= d unless every."""
for cell in chains.cells(3, bmax):
if cell.rho < 2:
continue
if hulls.least_L2(cell, 2 * cell.Mh / cell.b) != 1:
continue
g = Box(cell, chains.sum_floor(cell))
if every or g.eta >= g.d:
yield cell, g
def pigeon(g, sigma):
"""The count over positions: (dead, H, H <= b). A kept set of n
starts sends at least 2I + 1 + b(n - 1) positions to at most H
children, so one child's kept part has at least ceil of their
ratio: H <= b, or the iterate from n = 1 passing sigma + 1, keeps
nothing."""
b, B, P = g.b, g.B, g.P
I_ = g.am + g.ap
H = min((b * sigma + 2 * I_ + P - 1) // B + 1, len(g.digits))
if H <= b:
return True, H, True
n = 1
while n <= sigma + 1:
m = -(-(2 * I_ + 1 + b * (n - 1)) // H)
if m <= n:
return False, H, False
n = m
return True, H, False
def slack1_box(c):
lam2 = c.Mh * (1 + Fr(2, c.b))
return Box(c, chains.sum_floor(c), 1 if lam2 > 1 else 0)
def section_box(bmax, bx, bfar):
"""L3: the count at the cells L2 leaves and at slack 1, the exact
model as its control."""
print(f"L3 the box behind a sum, radices 3..{bmax}, exact to {bx}, "
f"the count to {bfar}")
t0 = time.time()
rec = L3_RECORD.get((bmax, bx), (None,) * 6)
far = FAR_RECORD.get(bfar, (None,) * 6)
key = lambda c: (c.b, c.am, c.ap) # noqa: E731
cells = list(box_cells(bmax))
small = [(c, g) for c, g in cells if c.b <= bx]
s1 = list(cells1(3, bmax))
gs1 = [slack1_box(c) for c in s1]
law = set()
for c in s1:
naive, least = chains.two_unit(c, chains.sum_head)[:2]
if least < naive:
law.add(key(c))
ca = [key(c) for c, g in zip(s1, gs1)
if key(c) in law and pigeon(g, g.sigma)[0]]
check(f"Ca the count spares each of the {rec[4]} budget gains of "
f"the {rec[3]} slack-1 cells (L1's certificates)",
not ca and (len(s1), len(law)) == rec[3:5],
f"{len(law)} gains of {len(s1)} cells, {len(ca)} killed")
c1x = [key(c) for c, g in small if exact_dead(g, g.B - 1)]
cb = [key(c) for c, g in small if pigeon(g, g.B - 1)[0]]
check(f"C1 the exact model keeps a singleton at Sigma = B - 1 at "
f"each of the {rec[1]} cells of b <= {bx}, and (Cb) the count "
f"spares it there", len(small) == rec[1] and not c1x
and not cb, f"{len(small)} cells, {len(c1x)} dead, {len(cb)} "
f"killed")
dead = {key(c): pigeon(g, g.sigma)[0] for c, g in cells}
c2 = [key(c) for c, g in small if dead[key(c)]
and not exact_dead(g, g.sigma)]
read = sum(dead[key(c)] for c, _ in small)
check(f"C2 the count kills and the exact model is dead at each of "
f"the {rec[1]} cells of b <= {bx}", read == rec[1] and not c2,
f"{read} read, {len(c2)} kept")
n3 = c3 = 0
for c, g in small:
for x in (g.sigma, g.B - 2, g.B - 1):
valid = set()
for s0 in range(g.lo, g.hi + 1):
for m in range(1 << min(x, g.hi - s0)):
valid.add((1 | (m << 1)) << (s0 - g.lo))
for a in range(g.lo, g.hi + 1):
for z in range(a, min(g.hi, a + x) + 1):
m = ((1 << (z - a + 1)) - 1) << (a - g.lo)
n3 += 1
c3 += splits(g, m, valid) != g.cover(*g.run(a, z), x)
check(f"C3 the exact split, every set of span <= cap kept, is the "
f"window cover at each of the {rec[2]} (block, cap), b <= {bx}",
n3 == rec[2] and not c3, f"{n3} (block, cap) read, {c3} differ")
rows = []
for c, g in zip(s1, gs1):
dead_c, H, small_k = pigeon(g, g.sigma)
rows.append((c, g, key(c) in law, dead_c, H, small_k))
ex = [(key(c), exact_dead(g, g.sigma)) for c, g, gain, d_, H, _ in rows
if c.b <= min(4, bx) and not gain and g.sigma >= 0 and d_]
print(f" slack 1, b <= {min(4, bx)}: the exact model where the "
f"count kills, Sigma >= 0 (cell, exact dead): {ex}")
check("Yc the exact model is dead at (3,1,2) and (4,1,3), where the "
"count kills at slack 1, Sigma >= 0, b <= 4",
ex == [((3, 1, 2), True), ((4, 1, 3), True)])
if not all(CHECKS):
print("A CHECK ABOVE FAILED (a control, or a count off its "
"record); nothing below is read")
return
check(f"R5 the count kills z.U at (L1*, 0) at each of the {rec[0]} "
f"cells with eta_max(0) >= d",
all(dead.values()) and len(cells) == rec[0],
f"{sum(dead.values())} of {len(cells)}")
n = kb = below = poff = 0
L1s, margin = set(), None
for c, g in box_cells(bfar, every=True):
n += 1
poff += g.P != c.I - 1
below += g.eta < g.d
L1s.add(g.L1)
dead_c, H, small_k = pigeon(g, g.sigma)
kb += small_k
margin = c.b - H if margin is None else min(margin, c.b - H)
print(f" radices 3..{bfar}: {n} cells with L2* = 1 ({below} with "
f"eta_max(0) < d), L1* in {sorted(L1s)}, least b - H {margin}")
check(f"R6 L1* = 1, P = I - 1 positions and H <= b, least b - H "
f"{far[2]}, at each of the {far[0]} cells with L2* = 1, radices "
f"3..{bfar}, eta_max(0) < d at {far[1]}",
kb == n and L1s == {1} and not poff
and (n, below, margin) == far[:3],
f"{kb} of {n}, {below}, least {margin}, P off at {poff}")
l2, n0, off0 = {}, 0, 0
for c in chains.cells(3, bfar):
if c.rho >= 2:
n0 += 1
off0 += not chains.sum_fed_ok(c)
L = hulls.least_L2(c, 2 * c.Mh / c.b)
hand = c.b ** 2 * (c.b - 1) * c.rho >= (
max(c.am, c.ap) * (c.b + 2) * c.I)
if L != 1 or hand != (L <= 1):
l2[key(c)] = (L, hand)
print(f" slack >= 2 cells, radices 3..{bfar}: {n0}; z.U's top off "
f"its root tile at {off0}; L2* != 1 or off the hand test: {l2}")
check(f"R0 z.U's range fits its root tile at each of the {far[3]} "
f"slack >= 2 cells (2 Mh^2 <= b M+, as a+ >= 2)",
n0 == far[3] and not off0, f"{n0} cells, {off0} off")
check("R7 L2* = 1 there but at (3,2,2), where it is 2; L2* <= 1 "
"iff m(b + 2)I <= b^2 (b - 1) rho", l2 == {(3, 2, 2): (2, False)})
c = ms.Cell(3, 2, 2)
g = Box(c, chains.sum_floor(c), 1)
d4, H4, _ = pigeon(g, g.sigma)
print(f" (3,2,2) at (L1*, 1): Sigma {g.sigma}, H {H4}, dead {d4}")
check("R4' the count kills (3,2,2) at (L1*, 1), Sigma 1, H 5",
d4 and (g.sigma, H4) == (1, 5))
non = [r for r in rows if not r[2]]
sp = [key(r[0]) for r in non if not r[3]]
print(f" slack 1: {len(rows)} cells, {len(rows) - len(non)} budget "
f"gains, {len(non)} not; H <= b at {sum(r[5] for r in non)} "
f"of those")
check("Y1 the count kills z.U at (L1*, L2* - 1) at every slack-1 "
"cell the budget does not gain, H <= b at each",
non and not sp and all(r[5] for r in non), f"spared {sp[:6]}")
fam = sorted(key(r[0]) for r in rows if not r[3])
check("Y2 it spares exactly (b, 2, b - 2) and its mirror, b >= 5",
fam == sorted(law) == sorted(
key(c) for c in s1 if c.b >= 5 and min(c.am, c.ap) == 2
and max(c.am, c.ap) == c.b - 2),
f"{len(fam)} spared, {len(law)} gains")
off = []
for c, g, gain, d_, H, _ in rows:
b, m = c.b, max(c.am, c.ap)
if g.eta - g.d < 0:
continue
if m == b - 1:
hand = (b * b - b - 4 if b >= 4 else 1, b)
elif m == b - 2 and b >= 5:
hand = (b * b + 4 * b // ((b - 1) * (b - 2)), b + 1)
else:
hand = None
if (g.sigma, H) != hand:
off.append((key(c), g.sigma, H, hand))
l2zero = [key(c) for c, g, *_ in rows if g.eta - g.d < 0]
l2bad = [key(c) for c, g, *_ in rows if (g.eta - g.d < 0)
!= (max(c.am, c.ap) <= c.b - 3 + Fr(6, c.b + 2))]
pbad = [key(c) for c, g, *_ in rows if g.P != c.b * (c.b + 1) - 1]
print(f" Sigma < 0 at {len(l2zero)} cells; (Sigma, H) off the hand "
f"values at {len(off)}")
check(f"Y2' (Sigma, H) = (b^2 - b - 4, b) at m = b - 1 (b >= 4), "
f"(b^2 + [4b/((b-1)(b-2))], b + 1) at m = b - 2, Sigma < 0 "
f"exactly where Lam2 <= 1, at {rec[5]} cells; P = b(b + 1) - 1 "
f"positions at every cell",
not off and not l2bad and len(l2zero) == rec[5] and not pbad,
f"off {off[:4]}, {len(l2bad)} misplaced, Sigma < 0 at "
f"{len(l2zero)}, P off {pbad[:4]}")
fam_off, n4 = [], 0
for c in cells1(3, bfar):
n4 += 1
naive, least = chains.two_unit(c, chains.sum_head)[:2]
f = (c.b >= 5 and min(c.am, c.ap) == 2
and max(c.am, c.ap) == c.b - 2)
if (naive - least) != (1 if f else 0):
fam_off.append(key(c))
check(f"Y4 the budget gains, by 1, exactly at (b, 2, b - 2) and its "
f"mirror, the {far[4]} slack-1 cells of radices 3..{bfar}",
n4 == far[4] and not fam_off, f"{n4} cells, off {fam_off[:6]}")
bad1, n2 = [], 0
for c in chains.cells(3, bfar):
n2 += 1
if chains.sum_floor(c) != (1 if c.rho >= 2 else 2):
bad1.append(key(c))
check(f"Y3 L1* = 1 at every cell of slack >= 2 and 2 at slack 1, "
f"the {far[5]} cells of radices 3..{bfar}",
n2 == far[5] and not bad1, f"{n2} cells, off {bad1[:6]}")
print(f" {time.time() - t0:.1f} s")
def main():
bmax = int(sys.argv[1]) if len(sys.argv) > 1 else 8
bmax2 = int(sys.argv[2]) if len(sys.argv) > 2 else bmax
bmax3 = int(sys.argv[3]) if len(sys.argv) > 3 else 9
bx = int(sys.argv[4]) if len(sys.argv) > 4 else min(9, bmax3)
bfar = int(sys.argv[5]) if len(sys.argv) > 5 else 20
section_control()
if not all(CHECKS):
print("CONTROL FAILED; nothing below is read")
raise SystemExit(1)
rows = section_sweep(bmax)
check("control (i): the narrowed state and the root at 1 + d - p, "
"every cell", all(r[3] and r[4] for r in rows))
rec = L1_RECORD.get(bmax, (None,) * 2)
hist = {}
for r in rows:
hist[r[5]] = hist.get(r[5], 0) + 1
check(f"eta* = 1 + d - p at each of the {rec[0]} cells, a pitch below "
f"at none (the kill fired)", hist == {0: rec[0]},
f"pitches below the budget's hull: {sorted(hist.items())}")
past = [(r[0].b, r[0].am, r[0].ap) for r in rows if r[6] and not r[11]]
lost = [(r[0].b, r[0].am, r[0].ap) for r in rows if r[11] and not r[6]]
dpast = [(r[0].b, r[0].am, r[0].ap) for r in rows
if r[8] and not r[11]]
print(f" lattice z·U live where the budget says none: {past}")
print(f" budget gains the lattice tree misses: {lost}")
print(f" dense z·U live where the budget says none: {dpast}")
nlive = sum(1 for r in rows if r[6])
check(f"the lattice tree gains exactly the budget's {rec[1]} cells, "
f"nothing else", not past and not lost and nlive == rec[1],
f"{nlive} live cells")
dg = [r[12] for r in rows]
check("the dense arm's eta* is b - 2 grid steps below its own 1 + d "
"and the arm is dead at 1 + d - p, every cell",
all(r[12] == r[0].b - 2 and not r[9] for r in rows))
print(f" dense arm (designed after the first run): eta* below its "
f"own 1 + d at {sum(1 for x in dg if x and x > 0)} of {len(dg)}"
f" cells, by {min(x for x in dg if x is not None)} to "
f"{max(x for x in dg if x is not None)} grid steps")
faults = [r[7] for r in rows if r[7]]
check("every live certificate exact", not faults, f"{faults[:5]}")
section_slack2(bmax2)
section_box(bmax3, bx, bfar)
print(f"{sum(CHECKS)}/{len(CHECKS)} checks passed")
raise SystemExit(0 if all(CHECKS) else 1)
if __name__ == "__main__":
main()