gaplaw.py
Checks: SETS: On the geometric walk's tail the anchored gap is one product rule.
Cited on: SETS.
To run it: save gaplaw.py, with sets.py beside it; standard library only.
"""gaplaw.py -- the anchored gap along a geometric walk, in closed form:
where the certificate's size profile stops moving, what the least
positive value of the anchored box is from there on, and which rule is
the optimum there.
QUESTION. sets.py proves the certificate exact whenever its room D/t*
falls under the ANCHORED GAP g_hat, the least positive sum c_r w_r over
the box c_r in [s_r - k, s_r], s the certificate's sizes. On tilted
cells that gap is tiny and nothing said how tiny. Follow one family of
cells, the WALK W-n: sets.ring at N = 105, M = 15, k = 3, alpha = 3/10,
theta = (n - 1)/n (TILT-3 is W-25). What is g_hat as a function of n,
exactly, from which n on, and is the certificate the optimum there?
THE OBJECTS. At W-n the atom weights are geometric,
w_r = theta^r kappa, kappa = (1 - theta)/(1 - theta^15),
so a box vector c is a POLYNOMIAL P_c(x) = sum c_r x^r of degree < 15
and sum c_r w_r = kappa P_c(theta). Its MOMENTS m_j = sum_r C(r, j) c_r
are its coefficients at x = 1, P_c(x) = sum_j m_j (x - 1)^j, and its
FLATTENING is the least j with m_j != 0; it is FLATTENED TO J when
m_0 = ... = m_{J-1} = 0, as zero is to every J. Since theta - 1 = -1/n,
P_c(theta) = sum_j m_j (-1/n)^j. (*)
A CELL is a pair (atom r, fiber block [lo, hi)): the label owning the
block has posterior (q^lo - q^hi)/(1 - q^7), q = theta^15, and the
cell's mass is proportional to theta^x (1 - q^L), x = r + 15 lo its
first point and L = hi - lo its length. Atoms 0..4 carry blocks (0, 3),
(3, 5), (5, 7); atoms 5..9 (0, 2), (2, 5), (5, 7); atoms 10..14 (0, 2),
(2, 4), (4, 7). A cell is HEAVY at L = 3 (first points 0..4, 35..39,
70..74) and LIGHT at L = 2 (5..14, 40..49, 75..84). A RULE is a size
vector: each atom's s_r heaviest cells. The FAR PROFILE is
111112222233333, the NEAR one 111112222233332.
THE ARGUMENT.
(1) THE PROFILE IS DECIDED BY EIGHT SIGNS. The far profile keeps
block (0, 3) at atoms 0..4, (0, 2) and (2, 5) at atoms 5..9 and
all three at atoms 10..14: the level is t = q^2 - q^4, tied at
the five (2, 4) cells of atoms 10..14, and the fill takes all
five. The certificate prints that profile whenever
O the four other block values it keeps exceed t and the two
it leaves are below it (six comparisons);
C1 the far profile's cells cover T;
C2 the near profile's cells cover less than T.
C2 is the fill test: a tied cell covers t times its cost and the
costs fall with r, so the four heaviest tied cells are the best
four, and when they fail the fill is all five; it also puts the
cells above t under T, so t is the level. Every condition is the
sign of an integer polynomial in theta: a difference of block
numerators, or
10 (1 - theta) Phi(X) - 7 (1 - theta^15)(1 - theta^105),
Phi(X) the sum over the cells of X of theta^r (q^lo - q^hi),
which is 10 (1 - theta^15)(1 - theta^105) (cov(X) - 7/10). At
theta = 1 it vanishes twice and its sign nearby is that of
(the total length of X) - 73.5.
A sign constant on [theta_n0, 1) is a proof for every real
n >= n0: substitute theta = 1 - u, strip the powers of u, scale
u = z/n0, and bound the roots in (0, 1) by the sign variations
of (z + 1)^d p(1/(z + 1)) (Descartes), bisecting until each
piece reads 0 (no root) or 1 (one root); the sign is given only
when no piece holds a root and the two ends agree.
(2) THE CANDIDATE IS ONE PRODUCT, AT ONE SHIFT. The box is
c_r in [-2, 1] at atoms 0..4, [-1, 2] at 5..9, [0, 3] at 10..14.
V = (x - 1)(x^2 - 1)(x^3 - 1)^2 has coefficients
1, -1, -1, -1, 2, 2, -1, -1, -1, 1: its 2s need atoms >= 5 and
its -1s atoms <= 9, so x^a V threads the box at a = 1 only. And
x V(x) at theta = theta (1 + theta)(1 + theta + theta^2)^2 n^-4
since (theta - 1)^4 = n^-4, with m_4 = 18, m_5 = 63, m_6 = 93.
(3) THE PROOF'S SHAPE. Split the nonzero box vectors by flattening
j. For j <= 4, (*) gives
n^j |P_c(theta)| >= |m_j| - E_j,
E_j = X_{j+1}/n + sum_{i >= j+2} B_i n^(j-i),
X_{j+1} the largest |m_{j+1}| over the box's vectors with
m_0 = ... = m_{j-1} = 0, B_i the largest |m_i| over the whole
box, read coordinatewise. Both terms fall as n grows, so a margin
read at n0 holds on the whole tail. At theta < 1,
n^4 P_xV = theta (1 + theta)(1 + theta + theta^2)^2 < 18. Then:
j <= 3 has |P| > 18 n^-4 > P_xV once 1 - E_j > 18 n^(j-4), since
|m_j| >= 1; j = 4 with
m_4 <= -1 is negative and with m_4 >= 19 exceeds P_xV once
E_4 < 1; the least positive m_4 is 18, at xV alone; and nothing
nonzero is flattened past 4. So g_hat = kappa xV(theta).
(4) THE TAIL'S OPTIMUM. Let S0 say the lightest heavy cell (x = 74)
outweighs the heaviest light one (x = 5). Then every atom's top
cell is its heavy one, cells of one length are ordered by x, and
a rule of S slots serving sigma atoms covers at most the sigma
heavy cells of least x and the S - sigma light ones of least x.
At theta = 1 that is (2S + sigma)/105 against 73.5/105.
S1 the rule 011111133333333 covers T;
S2 the 15 heavy and the 14 light cells of least x cover less
than T, so no rule of 29 slots or fewer covers. These are
the near profile's 29 cells: S2 is C2, one polynomial;
S3b the 12 heavy and 18 light cells of least x cover less than
T, so no 30-slot rule serving 12 atoms or fewer covers
(by S0 the bound grows with sigma);
S3a for a served set of 13 atoms, its heavy cells and its 17
light cells of least x cover less than T, so no 30-slot
rule on that served set covers.
Cost: a rule costs kappa sum theta^r s_r, a 30-slot one at
most 30 kappa. With u = 1/n, theta^r = 1 - r u + e_r, e_r in
[0, C(r, 2) u^2]; two 30-slot rules differ by d with |d_r| <= 3
and sum d_r theta^r = -m_1(d) u + sum d_r e_r, the last at most
3 C(15, 3) u^2 = 1365 u^2. So for n > 1365 a 30-slot rule of
larger first moment sum r s_r is strictly cheaper, covering or
not, and a rule of 31 slots or more costs at least
31 theta^14 kappa > 30 kappa for n >= 428. The first moment of
011111133333333 is 273. Serving 14 atoms it is the only 30-slot
vector at 273 or more (abandon atom 0, the eight extra pairs of
slots on atoms 7..14); serving 15 the most is 266; a served set
of 13 reaches 273 only when it abandons a < b <= 5 with
a + b <= 6, eleven sets, and S3a is owed at those alone. So the
optimum's sizes are 011111133333333 for every real n >= 1451,
and CERT - OPT = kappa P_d(theta) for d the difference of the
two size vectors, with m_0 = 0, m_1 = -13, m_2 = -60.
DESIGN. A TEST is a row: its polynomial's degree, its multiplicity at
theta = 1, the sign tail_sign gives (None when a root is found or the
ends differ), the number of root brackets, and whether the transform
whose sign variations are counted equals one written apart from it,
coefficient for coefficient (a closed binomial sum in place of the
repeated shift). Every row is pinned by hand. The box is searched by
meet-in-the-middle on its moments (atoms 0..7 against 8..14, joined on
negated keys); what the proof reads of a box is one record (the deep
vectors, the X_j, the least positive m_4 and who attains it), set
against plain enumeration on six small boxes whose records are by
hand. The rungs are read through sets.py:
four for the gap (n = 1451, 2000, 10^4, 10^5), and for the profile and
the optimum every integer n from 1451 to 2000 with 10^4, 10^5 and 10^7,
each a row of 0/1 fields; a law is a count set against its population.
THE HAND CELLS.
Signs (degree, multiplicity at 1, far sign): the block (0, 2) above
the level (60, 2, +), (0, 3) (60, 1, +), (2, 5) (75, 1, +), (4, 7)
(105, 1, +); (3, 5) below it (75, 2, -), (5, 7) (105, 2, -); C1
(120, 2, +, length 75), C2 (120, 2, -, 73); S0 (119, 1, +); S1
(120, 2, +, 74); S3b (120, 2, -, 72); every S3a (120, 2, -, 73).
The isolator, in z on (0, 1): (4z-1)(4z-3) brackets (0, 1/2),
(1/2, 1); (4z-1)(2z-1)(4z-3) brackets (0, 1/2), the point 1/2,
(1/2, 1); (8z-1)(8z-3) brackets (0, 1/4), (1/4, 1/2); (3z-1)^2 never
isolates and raises; 1 + z^2 none. In theta at n0 = 1451:
(2000 theta - 1999)(3000 theta - 2999) two brackets, the ends' signs
equal; 1451 theta - 1450 and its negative, no root inside and the
end zero; (2902 theta - 2901)(2000 theta - 1999)(4000 theta - 3999)
three, the middle one the point; (theta - 1)^3 multiplicity 3, sign
-1; 1 + theta^2 with two zero coefficients appended, sign +1;
(2901 theta - 2899)(1 + theta^2), its root at n = 1450.5 off the
tail, sign +1.
Small boxes. At length 6 a vector flattened to 4 is
a (x-1)^4 + b x (x-1)^4 with m_4 = a + b and m_5 = b, so a box's
vectors flattened to 4 are listed by its pairs (a, b):
POINT the zero vector alone: every X is 0 and no m_4 is
positive.
CUBE [-3, 3]^6: (a, b) = (0, 0) and +-(1, 1). Least positive
m_4 2,
at (1, -3, 2, 2, -3, 1); nothing nonzero flattened past 4.
THIN lows (-1, 0, -10, 0, -5, 0), highs (0, 5, 0, 10, 0, 1):
(a, b) in (0, 0), (-1, 0), (0, 1), (-1, 1). Least positive
m_4 1, at (0, 1, -4, 6, -4, 1); one vector flattened past
4, (x - 1)^5; the largest |m_5| at flattening 4 is 1, met
from above only.
MIRROR THIN negated: least positive m_4 1, at (1, -4, 6, -4, 1,
0); one deep vector; the largest |m_5| is 1, from below
only.
LONG MIRROR with two coordinates fixed at 0 appended, split
after six: MIRROR's record, and a left group of several
members with the zero vector first.
FRONT MIRROR with two such coordinates in front, split after
two: the vectors are x^2 times MIRROR's, so m_4 = a + b
still and m_5 = 2a + 3b, the largest |m_5| 3; a right
group of several members.
The box's bounds: at sizes (0,)*6 and (3,)*6 both 18, 45, 60, 45,
18, 3, the first from the negative arm alone; at the far profile
B_0..B_7 = 30, 260, 1235, 3880, 8756, 14805, 19185, 19260. X_1 = B_1
and X_2 = 875 (the lows everywhere, atoms 10..14 at 3); X_3..X_5 =
600, 279, 72 are the search's, entered from its print. Margins at
1451 floored at five places: 0.82022, 0.39512, 0.58231, 0.78827 and
0.94126; E_4 ceiled, 0.05874.
Served sets of 13 owed, with their best moments 279 - a - b: (0, 1)
278, (0, 2) 277, (0, 3) 276, (0, 4) 275, (0, 5) 274, (1, 2) 276,
(1, 3) 275, (1, 4) 274, (1, 5) 273, (2, 3) 274, (2, 4) 273. The most
among the other 94 is 272; abandoning 13 and 14, 218; nine served
atoms cannot hold 30 slots. (By the argument of (4): the 17 extra
slots go two at a time to the atoms of largest index.) The table:
14 served, 273 once and 272 twice (a slot moved from atom 7 to atom
6; atom 1 abandoned for atom 0); 15 served, 266 at most, over
1,787,607 vectors, the central trinomial coefficient of 15.
The coverage polynomial of all 45 cells is 3 (1 - theta^15)
(1 - theta^105) and of no cell -7 times the same.
(CERT - OPT) n is (13/15)(1 + 2.385/n) to first order: 0.8681 at
1451, 0.8667 at 10^7.
CONTROLS, before any verdict is read; a failure stops the run.
K1 (THE ISOLATOR) the hand polynomials above; a root planted at
n = 2000 bracketed and one at n = 1450.5 read root-free.
K2 (POSITIVE, ON THE REAL TAIL) three coverage polynomials of the
family that do have a root: the fill test read from n0 = 1400
(the root between n = 1450.3068 and 1450.3070); the bound that
takes the 13 heavy and 17 light cells of least x, with no regard
to served sets (between 1877.3475 and 1877.3485); and S3a's bound
at the served set abandoning atoms 13 and 14.
K3 (THE WALK) the blocks and the cells' first points as above; the
two hand coverage polynomials; the identity (*) on 300 box
vectors.
K4 (THE JOIN) the six hand boxes' records, by hand and against
enumeration; the bounds at the two hand sizes; the moment table
against enumeration on six atoms.
PREDICTIONS. The first slate, frozen before the first engine: the
eight tests keep their far signs on the tail and the profile at 1450
differs (HELD); nothing in the box is flattened past 4, the least
positive m_4 is 18 and xV is the one shift of V (HELD); the margins
are positive at 1451 (HELD); the closed form equals sets.py's gap at
the rungs (HELD); the room sits near 1/20, ten orders over the gap
(HELD), and CERT = OPT at the rungs (REFUTED: the certificate
overstates on the whole tail). A second slate, for the optimum: S0 to
S2 root-free (HELD); a bound of the 13 heavy and 17 light cells of
least x root-free (FAILED: it spends light cells at atoms no rule
serving 13 serves; now K2's second polynomial); S3a at all 105 served
sets (FAILED at the set abandoning 13 and 14, whose rules reach
moment 218 and never needed it; now K2's third), then at the eleven
owed (HELD), with S3b (HELD). For this engine, frozen before its
first run: every hand cell above; the transform equal to the one
written apart at every test; S2's polynomial equal to C2's; the
coverage polynomial equal to 10 (1 - theta^15)(1 - theta^105)
(cov - 7/10), cov from sets.rule_value, at every rule tried at every
gap rung; at n = 1450 the certificate is the optimum (by hand: the 29
heaviest cells cover T with a surplus near 1e-6, any other 29 lose
at least a step of x on a light cell, near 1.3e-5, and 30 slots cost
at least 30 theta^14 kappa > 29 kappa); the cost of 011111133333333
equal to sets.solve's at every rung read. A guess, no derivation: the
root of S3a's bound at the set abandoning 13 and 14 sits below
n = 1877.
KILLS, as prints. A control off: nothing below is read. A test's row
off its hand row: (1) or (4) fails there, or the isolator does. A deep
vector, a least m_4 other than 18, a second vector at 18, or a margin
at or below 0: (3) has a hole. The closed form off sets.py's gap at a
rung: (2). A rung where the profile, the solver's cost or the
overstatement is off: the proof and the cell disagree.
RESOURCE NOTE. Exact integers and Fractions throughout; the box's
halves hold 65,536 and 16,384 vectors.
FINDINGS (copied from the printed output). No kill fired: every control
held and every row met its hand row.
controls K1 the isolator's hand polynomials, 4 of 4 in z and 7 of 7
in theta, the double root raising. K2 the three rooted
coverage polynomials each give no sign and one bracket:
the fill test's root lies between n = 1450.3068 and
1450.3070, the loose bound's between 1877.3475 and
1877.3485, and that of the served set abandoning 13 and
14 between 1455.134 and 1455.135 (below 1877, as guessed):
its bound reaches T only under n = 1455.135. K3 the
blocks, the two hand coverage polynomials, (*) at 300 of
300. K4 six hand boxes, 12 of 12; the bounds; the table
on six atoms; V's shift at a box's two ends.
profile the eight rows as by hand (degrees 60 to 120, multiplicity
1 or 2, root-free with their far signs), so the
certificate's sizes are 111112222233333 for every real
n >= 1451. The fill test alone is read below 1451 (from
1400); the profile's other seven are read root-free from
1451 only.
At n = 1450 it is the near profile, 29 slots,
and it is the optimum (CERT - OPT = 0, as predicted), its
room 3.5e-6, 1.292e7 times the gap.
box nothing nonzero flattened past 4.
B_1..B_5 = 260, 1235, 3880, 8756, 14805; X_1..X_5 = 260,
875, 600, 279, 72; the margins exceed 0.82022, 0.39512,
0.58231, 0.78827 (j = 0..3) and 0.94126 (j = 4), and
E_4 < 0.05874. The least positive m_4 is 18 at xV alone,
(0, 1, -1, -1, -1, 2, 2, -1, -1, -1, 1, 0, 0, 0, 0), with
m_5 = 63 and m_6 = 93. The box holds three vectors with
m_0 = ... = m_3 = 0 and no more: zero, xV, and
(x - 1)(x^2 - 1)(x^3 - 1)(x^4 - 1) = (1, -1, -1, 0, 0, 2,
0, 0, -1, -1, 1, 0, 0, 0, 0) at m_4 = 24, the vector whose
m_5 = 72 is X_5. So the class j = 4 of (3) is two vectors,
each a product of factors x^d - 1, the first times x.
gap sets.py's anchored gap equals kappa xV(theta) at n = 1451,
2000, 10^4 and 10^5, in both displays (24 of 24 fields
with the weights, the ring's direct sum, the profile and
the eleven orders): g_hat n^4 = 1.2028942, 1.2020998,
1.2004200, 1.2000420, toward 6/5.
The room D/t* = 0.066337, 0.061864, 0.052378, 0.050238,
toward 1/20, at 2.445e11, 8.234e11, 4.363e14 and 4.186e18
times the gap: eleven orders at the first two rungs. The
coverage polynomial equals sets.py's coverage at 100 of
100 (rule, rung) pairs.
optimum at 553 rungs (every integer from 1451 to 2000, and 10^4,
10^5, 10^7) the profile is the far one, 011111133333333
costs what sets.solve finds and covers T, and CERT > OPT:
2,212 of 2,212 fields. (CERT - OPT) n = 0.8680899,
0.8676995, 0.8666873, 0.8666669 at 1451, 2000, 10^5 and
10^7, toward 13/15; the two size vectors' difference has
moments 0, -13, -60.
proof S0 (degree 119, multiplicity 1), S1, S2 and S3b (120, 2)
are root-free with signs +, +, -, -; S2 is C2, coefficient
for coefficient; 11 of the 105 served sets of 13 are owed
S3a and all 11 pass; the most among the other 94 is 272;
the table holds 7,538,895 vectors of 30 slots serving 14
atoms (273 once, 272 twice) and 1,787,607 serving 15 (266
at most). So 011111133333333 is the optimal size vector
at every real n >= 1451: fewer than 30 slots never cover
(S2), more than 30 cost more (n >= 428), 30 slots at
moment 272 or less cost more (n > 1365), and 30 slots at
273 or more, other than it, do not exist serving 14 or 15
atoms and do not cover serving 13 (S3a) or fewer (S3b).
pins entered from a print, not derived: X_3..X_5 and 7,538,895
(an earlier engine's), the three roots' brackets, the
second vector at flattening 4 (found by the join, then
multiplied out by hand), the count of check lines. Every
other pin is a hand value.
One hand pin was wrong at this engine's first run: the
room was pinned twelve orders over the gap at every rung
past the first, and at n = 2000 it is 8.234e11.
mutants one token changed at each of 379 sites of the engine: 368
runs turn red. The 11 that stay green print what the
script prints, each for a reason: three comparisons made
strict where no rung meets equality (the room at eleven
and at twelve orders, the proved rule's coverage); four at
the isolator's depth bar (its start, its edge, a step of 2
on either side), which the hand polynomials end by depth 2
or never; a common positive factor, in the halved
polynomial and in the cleared one; the tally's key row;
and a shift of V one past the box's end, which fails
before it reaches the end. Three checks are failed by no
mutant: the box's vectors flattened to 4, whose mutants
stop at a control first; the cost step's arithmetic and the
count of check lines, which no engine token moves. Each
fails to an edit by hand with the stop lifted (the join's
key left unnegated, or the second vector's last factor made
x^5 - 1; 427 made 428; the count moved). An earlier engine
also read flatten.py's least heights of a free box, cut
with the sentence that quoted it. Edits by hand, each with
its FAIL lines named before its run: 65 over three drafts,
55 red. Three
of the green were predicted red and were repaired, then
red: two hand boxes that listed the vector the record
keeps first in its group, so a loop cut to its first
member lost zero alone, and a comparison of two variation
counts that both read zero, now of the two transforms
coefficient for coefficient. The other seven were named
green beforehand: the isolator's depth step; S3a read from
a later n0, twice (no row carries its n0); V's shift range
one short (since given its case); the eleven-order bar put
at ten (nothing sits between); the proved rule's coverage
clause (since a field of its own); and the least positive
m_4 taken as the first found (no hand box meets a larger
candidate first; one was sought at length 6 and not
found).
RUN RECORD. python gaplaw.py: 33 of 33 checks, 5.5 s, peak commit
62.0 MB under a memory guard (512 MB). Earlier engines of this script
(12 to 22 checks, about 2 s) carried a solver of their own that printed
the optimal size vector at four rungs; this one reads the proved
vector's cost against sets.solve's.
"""
import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import random
import sys
import time
from bisect import bisect_right
from fractions import Fraction as F
from itertools import product
from math import comb
import sets
NR, M, K, C = 105, 15, 3, 7
FAR = (1,) * 5 + (2,) * 5 + (3,) * 5
NEAR = FAR[:14] + (2,)
OPT_TAIL = (0,) + (1,) * 6 + (3,) * 8
LEVEL = (2, 4)
N0 = 1451
SPARSE = (1451, 2000, 10000, 100000)
DENSE = tuple(range(1451, 2001)) + (10 ** 4, 10 ** 5, 10 ** 7)
TOP = 7
SEED = 20260928
LINES = 32
CHECKS = []
def check(name, ok, detail=""):
CHECKS.append(bool(ok))
print(f" [{'PASS' if ok else 'FAIL'}] {name}"
+ (f" {detail}" if detail else ""))
def section(title):
print()
print(title)
print("-" * len(title))
# ------------------------------------------------------ polynomials
# Integer lists, low degree first.
def padd(a, b):
n = max(len(a), len(b))
return [(a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0)
for i in range(n)]
def pscale(a, s):
return [x * s for x in a]
def pmul(a, b):
out = [0] * (len(a) + len(b) - 1)
for i, x in enumerate(a):
for j, y in enumerate(b):
out[i + j] += x * y
return out
def mono(k, c=1):
return [0] * k + [c]
def peval(a, x):
v = 0
for c in reversed(a):
v = v * x + c
return v
def degree(a):
return max(i for i, x in enumerate(a) if x)
def sgn(x):
return (x > 0) - (x < 0)
def shift1(p):
"""p(z + 1) (a Taylor shift)."""
p = list(p)
n = len(p)
for i in range(n):
for j in range(n - 2, i - 1, -1):
p[j] += p[j + 1]
return p
def variations(p):
s = [sgn(x) for x in p if x]
return sum(a != b for a, b in zip(s, s[1:]))
def turned(p):
"""(z + 1)^d p(1/(z + 1)): its positive roots are p's in (0, 1)."""
return shift1(list(reversed(p)))
def var01(p):
"""Descartes's bound on the number of roots of p in (0, 1)."""
return variations(turned(p))
def turned_apart(p):
"""The same polynomial written apart: the coefficient of z^j in
sum_k p_k (z + 1)^(d-k) is sum_k C(d - k, j) p_k."""
d = len(p) - 1
return [sum(comb(d - k, j) * p[k] for k in range(d + 1))
for j in range(d + 1)]
def tail_poly(G, n0):
"""G at theta = 1 - z/n0, its zeros at z = 0 stripped, cleared to
integers: its roots in (0, 1] are the roots of G on [theta_n0, 1).
Returns the polynomial in z and the multiplicity stripped."""
h = [0] * len(G)
for k, g in enumerate(G):
if g:
for i in range(k + 1):
h[i] += g * comb(k, i) * (-1) ** i
if not any(h):
raise ValueError("identically zero")
m = min(i for i, x in enumerate(h) if x)
h = h[m:]
e = len(h) - 1
return [x * n0 ** (e - i) for i, x in enumerate(h)], m
def isolate(p, lo=F(0), hi=F(1), depth=0):
"""Brackets in z of the roots of p in (lo, hi), p read on (0, 1):
an open interval holding one root, or a point (mid, mid)."""
v = var01(p)
if v == 0:
return []
if v == 1:
return [(lo, hi)]
if depth > 90:
raise RuntimeError("isolation did not converge")
d = len(p) - 1
left = [x << (d - i) for i, x in enumerate(p)]
right = shift1(left)
mid = (lo + hi) / 2
out = isolate(left, lo, mid, depth + 1)
if right[0] == 0:
out.append((mid, mid))
return out + isolate(right, mid, hi, depth + 1)
def tail_sign(G, n0=N0):
"""(sign, roots as z-brackets, multiplicity at theta = 1, the
cleared polynomial). A sign is returned only when no root lies in
(0, 1) and both ends agree: a proof that G keeps that sign at
theta = (n - 1)/n for every real n >= n0."""
p, m = tail_poly(G, n0)
roots = isolate(p)
s0, s1 = sgn(p[0]), sgn(peval(p, 1))
sign = s0 if (not roots and s0 == s1) else None
return sign, roots, m, p
def sign_row(G, n0=N0):
"""A test's row: degree, multiplicity at 1, sign, root brackets,
and whether the transform whose sign variations are counted equals
the one written apart, coefficient for coefficient."""
sign, roots, m, p = tail_sign(G, n0)
return (degree(G), m, sign, len(roots), turned(p) == turned_apart(p))
def sign_at(G, n):
"""The sign of G at theta = 1 - 1/n, n a rational."""
return sgn(peval(G, 1 - 1 / F(n)))
# ------------------------------------------------------- the walk
def theta(n):
return F(n - 1, n)
def kappa(n):
return (1 - theta(n)) / (1 - theta(n) ** M)
def blocks():
"""Per atom, per label, the fiber block (lo, hi) the label owns."""
out = []
for r in range(M):
ys = [K * (r + j * M) // NR for j in range(C)]
row = []
for y in range(K):
js = [j for j in range(C) if ys[j] == y]
row.append((js[0], js[-1] + 1))
out.append(row)
return out
def num(lo, hi):
"""q^lo - q^hi as a polynomial in theta."""
return padd(mono(M * lo), mono(M * hi, -1))
def cell_num(r, lo, hi):
return pmul(mono(r), num(lo, hi))
def cells():
"""Every cell as (x, length, (r, lo, hi)), x its first point."""
return [(r + M * lo, hi - lo, (r, lo, hi))
for r, row in enumerate(blocks()) for lo, hi in row]
def rule_pairs(sizes):
"""The cells of a rule: at each atom its sizes[r] first cells, the
longer before the shorter and the lesser first point before the
greater."""
out = []
for r, row in enumerate(blocks()):
order = sorted(row, key=lambda b: (b[0] - b[1], b))
out += [(r, lo, hi) for lo, hi in order[:sizes[r]]]
return out
def coverage_test(pairs):
"""10 (1 - theta^15)(1 - theta^105) (cov(pairs) - 7/10)."""
tot = [0]
for r, lo, hi in pairs:
tot = padd(tot, cell_num(r, lo, hi))
lhs = pscale(pmul([1, -1], tot), 10)
rhs = pscale(pmul(padd([1], mono(M, -1)), padd([1], mono(NR, -1))), -7)
return padd(lhs, rhs)
def profile_tests():
"""The eight tests of (1), each (name, polynomial)."""
far = rule_pairs(FAR)
kept = {(lo, hi) for _, lo, hi in far}
every = {c[2][1:] for c in cells()}
t = num(*LEVEL)
tests = [(("above", b), padd(num(*b), pscale(t, -1)))
for b in sorted(kept - {LEVEL})]
tests += [(("below", b), padd(num(*b), pscale(t, -1)))
for b in sorted(every - kept)]
tests.append(("C1", coverage_test(far)))
tests.append(("C2", coverage_test(rule_pairs(NEAR))))
return tests
def by_length(length, gone=()):
"""The cells of one length at atoms not in gone, by first point."""
return [c[2] for c in sorted(cells())
if c[1] == length and c[2][0] not in gone]
def optimum_tests():
"""S0, S1, S2 and S3b of (4), each (name, polynomial)."""
heavy, light = by_length(3), by_length(2)
return [("S0", padd(cell_num(*heavy[-1]),
pscale(cell_num(*light[0]), -1))),
("S1", coverage_test(rule_pairs(OPT_TAIL))),
("S2", coverage_test(heavy + light[:14])),
("S3b", coverage_test(heavy[:12] + light[:18]))]
def served_bound(gone):
"""S3a's polynomial at the served set abandoning the atoms gone."""
return coverage_test(by_length(3, gone) + by_length(2, gone)[:17])
def loose_bound():
"""The 13 heavy and 17 light cells of least x, whoever is served."""
return coverage_test(by_length(3)[:13] + by_length(2)[:17])
def first_moment(s):
return sum(r * x for r, x in enumerate(s))
def best_moment(served):
"""Largest sum r s_r over s_r in 1..3 on the served atoms, sum 30,
by atoms over every slot total; -1 when 30 slots do not fit."""
best = {0: 0}
for r in served:
nxt = {}
for S, m in best.items():
for x in range(1, K + 1):
nxt[S + x] = max(nxt.get(S + x, 0), m + r * x)
best = nxt
return best.get(30, -1)
def served_moments():
"""Every pair of abandoned atoms with its served set's best moment."""
return {(a, b): best_moment([r for r in range(M) if r not in (a, b)])
for a in range(M) for b in range(a + 1, M)}
def moment_table(atoms=M):
"""(S, h) -> {first moment: count} over every size vector, by atoms."""
tab = {(0, 0): {0: 1}}
for r in range(atoms):
nxt = {}
for (S, h), mom in tab.items():
for x in range(K + 1):
d = nxt.setdefault((S + x, h + (x > 0)), {})
for m, c in mom.items():
d[m + r * x] = d.get(m + r * x, 0) + c
tab = nxt
return tab
def brute_table(atoms):
"""The same table by enumeration."""
tab = {}
for v in product(range(K + 1), repeat=atoms):
d = tab.setdefault((sum(v), sum(x > 0 for x in v)), {})
d[first_moment(v)] = d.get(first_moment(v), 0) + 1
return tab
# -------------------------------------------------------- the box
def moments(c, top=TOP):
return tuple(sum(comb(r, j) * x for r, x in enumerate(c))
for j in range(top))
def half(lows, highs, atoms):
"""Every sub-vector over `atoms` with its partial moments."""
out = []
for vals in product(*[range(lows[r], highs[r] + 1) for r in atoms]):
m = tuple(sum(comb(r, j) * x for r, x in zip(atoms, vals))
for j in range(TOP))
out.append((m, vals))
return out
def group(side, j):
g = {}
for m, v in side:
g.setdefault(m[:j], []).append((m, v))
return g
def reach(side, i, way):
"""The largest way * m_i over a group."""
return max(way * m[i] for m, _ in side)
def extreme_next(L, R, j, i):
"""max |m_i| over box vectors with m_0 = ... = m_{j-1} = 0."""
gl, gr = group(L, j), group(R, j)
best = []
for key, ls in gl.items():
rs = gr.get(tuple(-x for x in key))
if rs:
best += [reach(ls, i, way) + reach(rs, i, way)
for way in (1, -1)]
return max(best)
def flattened(L, R, j):
"""Every box vector with m_0 = ... = m_{j-1} = 0."""
gl, gr = group(L, j), group(R, j)
out = []
for key, ls in gl.items():
for _, vr in gr.get(tuple(-x for x in key), ()):
out += [vl + vr for _, vl in ls]
return out
def m4_census(L, R):
"""The least positive m_4 over vectors with m_0..m_3 = 0, and every
vector attaining it."""
gl, gr = group(L, 4), group(R, 4)
found = []
for key, ls in gl.items():
rs = gr.get(tuple(-x for x in key))
if not rs:
continue
r4 = sorted(m[4] for m, _ in rs)
for m, _ in ls:
k = bisect_right(r4, -m[4])
if k < len(r4):
found.append(m[4] + r4[k])
least = min(found, default=None)
hits = []
for key, ls in gl.items():
for mr, vr in gr.get(tuple(-x for x in key), ()):
hits += [vl + vr for ml, vl in ls if ml[4] + mr[4] == least]
return least, hits
def box_record(lows, highs, split):
"""What (3) reads of a box, by the join: the nonzero vectors
flattened past 4, X_1..X_5, the least positive m_4 and who attains
it."""
L = half(lows, highs, range(split))
R = half(lows, highs, range(split, len(lows)))
least, hits = m4_census(L, R)
return {"flat4": sorted(flattened(L, R, 4)),
"deep": sorted(v for v in flattened(L, R, 5) if any(v)),
"X": [extreme_next(L, R, j, j + 1) for j in range(5)],
"least": least, "hits": sorted(hits)}
def brute_record(lows, highs):
"""The same record by enumeration."""
full = [(moments(v), v) for v in
product(*[range(a, b + 1) for a, b in zip(lows, highs)])]
flat4 = [(m, v) for m, v in full if not any(m[:4])]
pos = [m[4] for m, _ in flat4 if m[4] > 0]
least = min(pos) if pos else None
return {"flat4": sorted(v for _, v in flat4),
"deep": sorted(v for m, v in flat4 if m[4] == 0 and any(v)),
"X": [max(abs(m[j + 1]) for m, _ in full if not any(m[:j]))
for j in range(5)],
"least": least,
"hits": sorted(v for m, v in flat4 if m[4] == least)}
def box_bounds(s):
"""B_i, the largest |m_i| over the box, read coordinatewise."""
return [max(sum(comb(r, i) * s[r] for r in range(len(s))),
-sum(comb(r, i) * (s[r] - K) for r in range(len(s))))
for i in range(len(s))]
def margins(B, X, n0):
"""(E_j, margin_j) for j = 0..4 at n0, exact: the margin is
1 - E_j - 18 n0^(j-4) at j <= 3 and 1 - E_4 at j = 4."""
out = []
for j in range(5):
E = F(X[j], n0) + sum(F(B[i], n0 ** (i - j))
for i in range(j + 2, len(B)))
out.append((E, 1 - E - (18 * F(n0) ** (j - 4) if j < 4 else 0)))
return out
V = pmul(pmul([-1, 1], [-1, 0, 1]), pmul([-1, 0, 0, 1], [-1, 0, 0, 1]))
XV = tuple(pmul(mono(1), V) + [0] * (M - len(V) - 1))
W4 = tuple(pmul(pmul([-1, 1], [-1, 0, 1]),
pmul([-1, 0, 0, 1], [-1, 0, 0, 0, 1])) + [0] * 4)
def thread_shifts(lows, highs):
"""The shifts a at which x^a V lies in the box."""
return [a for a in range(len(lows) - len(V) + 1)
if all(lows[a + i] <= c <= highs[a + i]
for i, c in enumerate(V))]
def closed_form(n):
"""kappa xV(theta): the anchored gap in cost units."""
return kappa(n) * peval(XV, theta(n))
def display_form(n):
"""theta (1 + theta)(1 + theta + theta^2)^2 / ((1 + ... + theta^14)
n^4), the same gap as the page displays it."""
th = theta(n)
return (th * (1 + th) * (1 + th + th * th) ** 2
/ (sum(th ** r for r in range(M)) * F(n) ** 4))
# ------------------------------------------------------ the rungs
def tally(rows):
return {key: sum(row[key] for row in rows) for key in rows[0]}
def walk(n, truth=False):
return sets.Anatomy(sets.ring(f"W-{n}", NR, M, K, theta(n), truth=truth))
def star_row(c, n):
"""(*) at one box vector."""
m = moments(c, M)
return peval(list(c), theta(n)) == sum(m[j] * F(-1, n) ** j
for j in range(M))
def cover_row(an, n, sizes):
"""The coverage polynomial of a rule against sets.py's coverage of
the same sizes, exactly."""
th = theta(n)
cov = F(sets.rule_value(an, sizes)[1], an.sc.Q)
return (peval(coverage_test(rule_pairs(sizes)), th)
== 10 * (1 - th ** M) * (1 - th ** NR) * (cov - F(7, 10)))
def gap_row(n):
"""A gap rung: every field 0 or 1 but the three it prints."""
an = walk(n, truth=True)
gap = F(sets.anchored_gap(an), an.sc.Q)
room = an.room / an.sc.Q
return {"weights": an.cell.w == [theta(n) ** r * kappa(n)
for r in range(M)],
"truth": an.cell.truth_ok,
"far": tuple(an.sizes) == FAR,
"gap": gap == closed_form(n),
"display": closed_form(n) == display_form(n),
"orders": room >= 10 ** 11 * gap,
"twelve": room >= 10 ** 12 * gap}, (gap * n ** 4, room,
room / gap)
def optimum_row(n):
"""A rung of the profile and the optimum: every field 0 or 1 but
the overstatement times n."""
an = walk(n)
opt = sets.solve(an)[0]
cost, cov = sets.rule_value(an, OPT_TAIL)
return {"rungs": 1,
"far": tuple(an.sizes) == FAR,
"near": tuple(an.sizes) == NEAR,
"tail": cost == opt,
"covers": cov >= an.sc.TQ,
"over": an.cert > opt}, F(an.cert - opt, an.sc.Q) * n
# ----------------------------------------------------- what is pinned
SIGNS_HAND = {
("above", (0, 2)): (60, 2, 1, 0, True),
("above", (0, 3)): (60, 1, 1, 0, True),
("above", (2, 5)): (75, 1, 1, 0, True),
("above", (4, 7)): (105, 1, 1, 0, True),
("below", (3, 5)): (75, 2, -1, 0, True),
("below", (5, 7)): (105, 2, -1, 0, True),
"C1": (120, 2, 1, 0, True),
"C2": (120, 2, -1, 0, True),
"S0": (119, 1, 1, 0, True),
"S1": (120, 2, 1, 0, True),
"S2": (120, 2, -1, 0, True),
"S3b": (120, 2, -1, 0, True),
}
ROOTED = (120, 2, None, 1, True)
BLOCKS_HAND = ([[(0, 3), (3, 5), (5, 7)]] * 5 + [[(0, 2), (2, 5), (5, 7)]] * 5
+ [[(0, 2), (2, 4), (4, 7)]] * 5)
HEAVY_X = [0, 1, 2, 3, 4, 35, 36, 37, 38, 39, 70, 71, 72, 73, 74]
LIGHT_X = (list(range(5, 15)) + list(range(40, 50)) + list(range(75, 85)))
# In z: the polynomial, its brackets as (lo, hi) pairs of halves' ends.
H = F(1, 2)
Z_HAND = (
([3, -16, 16], [(0, H), (H, 1)]),
([-3, 22, -48, 32], [(0, H), (H, H), (H, 1)]),
([3, -32, 64], [(0, H / 2), (H / 2, H)]),
([1, 0, 1], []),
)
# In theta at n0 = 1451: the polynomial, then (sign, brackets, m).
T_HAND = (
(pmul([-1999, 2000], [-2999, 3000]), (None, [(0, H), (H, 1)], 0)),
([-1450, 1451], (None, [], 0)),
([1450, -1451], (None, [], 0)),
(pmul(pmul([-2901, 2902], [-1999, 2000]), [-3999, 4000]),
(None, [(0, H), (H, H), (H, 1)], 0)),
([-1, 3, -3, 1], (-1, [], 3)),
([1, 0, 1, 0, 0], (1, [], 0)),
(pmul([-2899, 2901], [1, 0, 1]), (1, [], 0)),
)
# lows, highs, the split, then the record's hand fields: the vectors
# flattened to 4, deep, least, hits, X_5.
CUBE_F4 = [(-1, 3, -2, -2, 3, -1), (0,) * 6, (1, -3, 2, 2, -3, 1)]
THIN_F4 = [(-1, 4, -6, 4, -1, 0), (-1, 5, -10, 10, -5, 1), (0,) * 6,
(0, 1, -4, 6, -4, 1)]
MIRROR_F4 = [(0, -1, 4, -6, 4, -1), (0,) * 6, (1, -5, 10, -10, 5, -1),
(1, -4, 6, -4, 1, 0)]
THIN = ((-1, 0, -10, 0, -5, 0), (0, 5, 0, 10, 0, 1))
MIRROR = (tuple(-x for x in THIN[1]), tuple(-x for x in THIN[0]))
BOXES_HAND = (
("POINT", (0,) * 6, (0,) * 6, 3, ([(0,) * 6], [], None, [], 0)),
("CUBE", (-3,) * 6, (3,) * 6, 3,
(CUBE_F4, [], 2, [(1, -3, 2, 2, -3, 1)], 1)),
("THIN", THIN[0], THIN[1], 3,
(THIN_F4, [(-1, 5, -10, 10, -5, 1)], 1, [(0, 1, -4, 6, -4, 1)], 1)),
("MIRROR", MIRROR[0], MIRROR[1], 3,
(MIRROR_F4, [(1, -5, 10, -10, 5, -1)], 1, [(1, -4, 6, -4, 1, 0)],
1)),
("LONG", MIRROR[0] + (0, 0), MIRROR[1] + (0, 0), 6,
([v + (0, 0) for v in MIRROR_F4], [(1, -5, 10, -10, 5, -1, 0, 0)],
1, [(1, -4, 6, -4, 1, 0, 0, 0)], 1)),
("FRONT", (0, 0) + MIRROR[0], (0, 0) + MIRROR[1], 2,
([(0, 0) + v for v in MIRROR_F4], [(0, 0, 1, -5, 10, -10, 5, -1)],
1, [(0, 0, 1, -4, 6, -4, 1, 0)], 3)),
)
B_HAND = [30, 260, 1235, 3880, 8756, 14805, 19185, 19260]
X_PIN = [260, 875, 600, 279, 72]
MARGIN_HAND = [82022, 39512, 58231, 78827, 94126]
OWED_HAND = {(0, 1): 278, (0, 2): 277, (0, 3): 276, (0, 4): 275,
(0, 5): 274, (1, 2): 276, (1, 3): 275, (1, 4): 274,
(1, 5): 273, (2, 3): 274, (2, 4): 273}
TABLE_PIN = {14: (7538895, 273, 1, 2), 15: (1787607, 266, 1, 0)}
GAIN_HAND = {1451: 8681, 10 ** 7: 8667}
# --------------------------------------------------------- sections
def check_count(name, hits, n, detail=""):
check(name, hits == n, f"{hits} of {n}" + (f"; {detail}" if detail
else ""))
def section_controls():
section("CONTROLS")
check_count("K1 sgn at -1, 0 and 1",
sum(sgn(x) == x for x in (-1, 0, 1)), 3)
got = [isolate(p) == want for p, want in Z_HAND]
check_count("K1 the isolator in z: two roots split, a root at the "
"midpoint, two in one half, none", sum(got), len(Z_HAND))
try:
isolate([1, -6, 9])
raised = False
except RuntimeError as err:
raised = "converge" in str(err)
try:
tail_poly([0, 0], N0)
zero = False
except ValueError:
zero = True
check("K1 a double root off the halves raises, and the zero "
"polynomial is refused", raised and zero)
got = [tail_sign(G)[:3] == want for G, want in T_HAND]
check_count("K1 the sign in theta: two roots with equal ends, a root "
"at the end from either side, a root at the midpoint, "
"multiplicity 3, padding, a root at n = 1450.5", sum(got),
len(T_HAND))
s, roots, _, _ = tail_sign(pmul([-1999, 2000], [1, 0, 1]))
check("K1 a root planted at n = 2000 is bracketed and no sign given",
s is None and len(roots) == 1
and roots[0][0] < F(N0, 2000) < roots[0][1])
fill = dict(profile_tests())["C2"]
loose, far_set = loose_bound(), served_bound((13, 14))
rows = [sign_row(fill, 1400), sign_row(loose), sign_row(far_set)]
check_count("K2 three coverage polynomials with a root: the fill test "
"from n0 = 1400, the loose bound and the served set "
"abandoning 13 and 14 on the tail, each degree 120, "
"multiplicity 2, no sign, one bracket",
sum(row == ROOTED for row in rows), 3)
signs = [sign_at(fill, F(14503068, 10000)),
sign_at(fill, F(14503070, 10000)), sign_at(fill, 1450),
sign_at(loose, F(18773475, 10000)),
sign_at(loose, F(18773485, 10000)),
sign_at(far_set, F(1455134, 1000)),
sign_at(far_set, F(1455135, 1000))]
check("K2 the fill test changes sign between n = 1450.3068 and "
"1450.3070 and reads +1 at 1450; the loose bound between "
"1877.3475 and 1877.3485; the served set's between 1455.134 "
"and 1455.135", signs == [1, -1, 1, 1, -1, 1, -1], f"{signs}")
bl, cs = blocks(), cells()
check("K3 the blocks, and the first points of the heavy and the "
"light cells",
bl == BLOCKS_HAND
and sorted(x for x, n, _ in cs if n == 3) == HEAVY_X
and sorted(x for x, n, _ in cs if n == 2) == LIGHT_X
and len(cs) == 45)
full = pmul(padd([1], mono(M, -1)), padd([1], mono(NR, -1)))
check("K3 the coverage polynomial of all 45 cells and of none",
coverage_test([c[2] for c in cs]) == pscale(full, 3)
and coverage_test([]) == pscale(full, -7))
rng = random.Random(SEED)
hits = sum(star_row([rng.randint(x - K, x) for x in FAR], n)
for n in (1451, 2000, 100000) for _ in range(100))
check_count("K3 the moment identity on box vectors", hits, 300)
hand = brute = 0
for name, lows, highs, split, want in BOXES_HAND:
rec = box_record(lows, highs, split)
hand += (rec["flat4"], rec["deep"], rec["least"], rec["hits"],
rec["X"][4]) == want
brute += rec == brute_record(lows, highs)
print(f" {name}: {len(rec['flat4'])} flattened to 4, deep "
f"{len(rec['deep'])}, least positive m_4 "
f"{rec['least']} at {len(rec['hits'])} vector(s), X "
f"{rec['X']}")
check_count("K4 the join on the six hand boxes: the hand fields, "
"and the whole record against enumeration", hand + brute,
12)
six = [18, 45, 60, 45, 18, 3]
check("K4 the bounds at sizes (0,)*6 and (3,)*6, and the far "
"profile's first eight",
box_bounds((0,) * 6) == six and box_bounds((3,) * 6) == six
and box_bounds(FAR)[:8] == B_HAND)
check("K4 the moment table equals enumeration on six atoms",
moment_table(6) == brute_table(6))
ends = [(0, 0) + tuple(V), tuple(V) + (0, 0)]
check("K4 V threads a box that is x^2 V alone at shift 2, and one "
"that is V alone at shift 0",
[thread_shifts(b, b) for b in ends] == [[2], [0]])
def section_profile():
section("THE PROFILE: eight signs on the tail")
tests = profile_tests()
far = rule_pairs(FAR)
tied = [r for r, lo, hi in far if (lo, hi) == LEVEL]
print(f" the far profile holds {len(far)} cells, {len(tied)} at the "
f"level (atoms {tied})")
hits = 0
for name, G in tests:
row = sign_row(G)
hits += row == SIGNS_HAND.get(name)
print(f" {str(name):24s} degree {row[0]:3d} multiplicity {row[1]}"
f" sign {row[2]} roots on the tail {row[3]}")
check("P1 the eight tests' rows as by hand: degree, multiplicity at "
"1, far sign, root-free on n >= 1451",
hits == len(tests) == 8, f"{hits} of {len(tests)} tests")
check("P1 the level is tied at atoms 10..14 alone and the far "
"profile's 30 cells hold four block values above it",
tied == [10, 11, 12, 13, 14] and len(far) == 30
and [name for name, _ in tests[:6]] == list(SIGNS_HAND)[:6])
row, gain = optimum_row(1450)
below, (_, room, ratio) = gap_row(1450)
print(f" n = 1450: the near profile {bool(row['near'])}, CERT - OPT = "
f"{gain}, room D/t* = {float(room):.1e}, room/g_hat = "
f"{float(ratio):.3e}")
check("at n = 1450 the certificate is the near profile and is the "
"optimum, 011111133333333 covers T and is not, and the room is "
"under 1e-5, short of eleven orders over the gap",
row == {"rungs": 1, "far": 0, "near": 1, "tail": 0, "covers": 1,
"over": 0}
and gain == 0 and 0 <= room < F(1, 10 ** 5)
and (below["weights"], below["truth"], below["far"],
below["display"], below["orders"], below["twelve"])
== (1, 1, 0, 1, 0, 0))
def section_box():
section("THE BOX: flattening, margins, the vector at m_4 = 18")
lows, highs = [x - K for x in FAR], list(FAR)
rec = box_record(lows, highs, 8)
print(f" vectors with m_0..m_3 = 0: {len(rec['flat4'])}; nonzero "
f"with m_0..m_4 = 0: {len(rec['deep'])}")
for c in rec["flat4"]:
print(" " + "".join(f"{x:3d}" for x in c) + f" m_4 "
f"{moments(c)[4]}" + (" = xV" if c == XV else ""))
check("P2 the anchored box holds nothing nonzero flattened past 4: "
"its vectors flattened to 4 are zero, xV and "
"(x-1)(x^2-1)(x^3-1)(x^4-1), at m_4 = 0, 18 and 24",
rec["deep"] == [] and rec["flat4"] == [(0,) * M, XV, W4]
and [moments(c)[4] for c in rec["flat4"]] == [0, 18, 24])
B = box_bounds(FAR)
print(f" B_1..B_5 = {B[1:6]}; X_1..X_5 = {rec['X']}")
mg = margins(B, rec["X"], N0)
for j, (E, m) in enumerate(mg):
print(f" j = {j}: E_j < {float(E) + 5e-6:.5f} margin > "
f"{int(m * 10 ** 5) / 10 ** 5:.5f}")
floors = [int(m * 10 ** 5) for _, m in mg]
check("P3 X_1..X_5 as recorded and the margins at n0 = 1451 as by "
"hand, floored at five places; E_4 under 0.05874",
rec["X"] == X_PIN and floors == MARGIN_HAND
and F(5873, 10 ** 5) < mg[4][0] < F(5874, 10 ** 5),
f"{floors}")
shifts = thread_shifts(lows, highs)
m = moments(XV)
print(f" least positive m_4 = {rec['least']}; {len(rec['hits'])} "
f"vector(s) attain it; V threads the box at shifts {shifts}")
print(f" xV: m_4 {m[4]}, m_5 {m[5]}, m_6 {m[6]}")
check("P2 least positive m_4 is 18, attained by xV alone, the one "
"shift of V; its moments 0, 0, 0, 0, 18, 63, 93",
rec["least"] == 18 and rec["hits"] == [XV] and shifts == [1]
and m == (0, 0, 0, 0, 18, 63, 93))
def section_gap():
section("THE GAP AT THE RUNGS")
rows, g4s = [], {}
for n in SPARSE:
row, (g4s[n], room, ratio) = gap_row(n)
rows.append(row)
print(f" n = {n:6d} g_hat n^4 = {float(g4s[n]):.7f} room D/t* = "
f"{float(room):.6f} room/g_hat = {float(ratio):.3e}")
tot = tally(rows)
check_count("K5 at every gap rung the weights are theta^r kappa and "
"the cell the ring summed directly, the profile the far "
"one, sets.py's anchored gap the closed form in both "
"displays, the room eleven orders over it",
tot["weights"] + tot["truth"] + tot["far"] + tot["gap"]
+ tot["display"] + tot["orders"], 6 * len(SPARSE))
check("g_hat n^4 rounds to 1.2029 at 1451 and 1.2000 at 10^5, toward "
"6/5",
[int(g4s[n] * 10 ** 4 + F(1, 2)) for n in (1451, 100000)]
== [12029, 12000])
check("the room is twelve orders over the gap at 10^4 and 10^5 "
"and not at 1451 or 2000",
[row["twelve"] for row in rows] == [0, 0, 1, 1])
rng = random.Random(SEED + 1)
rules = [FAR, NEAR, OPT_TAIL, (3,) * M, (0,) * M] + [
tuple(rng.randint(0, K) for _ in range(M)) for _ in range(20)]
hits = sum(cover_row(walk(n), n, s) for n in SPARSE for s in rules)
check_count("the coverage polynomial equals sets.py's coverage at "
"every rule tried at every gap rung", hits,
len(rules) * len(SPARSE))
def section_optimum():
section("THE PROFILE AND THE OPTIMUM AT THE RUNGS")
rows, gains = [], {}
for n in DENSE:
row, gain = optimum_row(n)
rows.append(row)
gains[n] = gain
tot = tally(rows)
for n in (1451, 2000, 10 ** 5, 10 ** 7):
print(f" n = {n:8d} (CERT - OPT) n = {float(gains[n]):.7f}")
check_count("at every integer n from 1451 to 2000 and at 10^4, 10^5 "
"and 10^7 the profile is the far one, 011111133333333 "
"costs what sets.solve finds and covers T, and CERT > OPT",
tot["far"] + tot["tail"] + tot["covers"] + tot["over"],
4 * 553,
f"{tot['rungs']} rungs, {tot['near']} at the near profile")
d = [a - b for a, b in zip(FAR, OPT_TAIL)]
m = moments(d, 3)
print(f" moments of the two size vectors' difference: {list(m)}")
check("the difference has moments 0, -13, -60, and (CERT - OPT) n "
"rounds to 0.8681 at 1451 and 0.8667 at 10^7",
m == (0, -13, -60)
and all(int(gains[n] * 10 ** 4 + F(1, 2)) == v
for n, v in GAIN_HAND.items()))
def section_tail_proof():
section("THE TAIL'S OPTIMUM, PROVED")
tests = optimum_tests()
hits = 0
for name, G in tests:
row = sign_row(G)
hits += row == SIGNS_HAND.get(name)
print(f" {name:4s} degree {row[0]:3d} multiplicity {row[1]} sign "
f"{row[2]} roots on the tail {row[3]}")
s0 = padd(padd(mono(74), mono(119, -1)), padd(mono(35), mono(5, -1)))
check("S0, S1, S2 and S3b as by hand: degree, multiplicity at 1, "
"sign, root-free; S0 is theta^74 - theta^119 - theta^5 + "
"theta^35", hits == len(tests) == 4 and dict(tests)["S0"] == s0,
f"{hits} of {len(tests)} tests")
check("S2 is the fill test C2, coefficient for coefficient",
dict(tests)["S2"] == dict(profile_tests())["C2"])
best = served_moments()
bar = first_moment(OPT_TAIL)
owed = {gone: v for gone, v in best.items() if v >= bar}
rest = max(v for gone, v in best.items() if gone not in owed)
print(f" {len(owed)} of {len(best)} served sets of 13 atoms admit a "
f"30-slot moment >= {bar}; the most among the others {rest}; "
f"abandoning 13 and 14, {best[(13, 14)]}")
check("the served sets owed S3a and their best moments as by hand; "
"272 the most among the other 94; 218 abandoning 13 and 14; "
"nine atoms cannot hold 30 slots",
bar == 273 and owed == OWED_HAND and len(best) == 105
and rest == 272 and best[(13, 14)] == 218
and best_moment(list(range(9))) == -1)
hits = sum(sign_row(served_bound(gone)) == SIGNS_HAND["S3b"]
for gone in owed)
check("S3a at every owed served set: degree 120, multiplicity 2, "
"sign -1, root-free", hits == len(owed) == 11,
f"{hits} of {len(owed)} sets")
check("the cost step: 3 C(15, 3) = 1365 = sum 3 C(r, 2), and "
"31 theta^14 > 30 first at n = 428",
3 * comb(15, 3) == 1365 == sum(3 * comb(r, 2) for r in range(M))
and 31 * theta(428) ** 14 > 30 >= 31 * theta(427) ** 14)
tab = moment_table()
got = {}
for h in (14, 15):
mom = tab[(30, h)]
ms = sorted(mom, reverse=True)
got[h] = (sum(mom.values()), ms[0], mom[ms[0]], mom.get(272, 0))
print(f" 30 slots, {h} atoms served: {got[h][0]} vectors, largest "
f"first moment {ms[0]} ({mom[ms[0]]} vector(s)), "
f"{got[h][3]} at 272")
check("the table: 14 served, 273 once and 272 twice; 15 served, 266 "
"at most; the counts as recorded", got == TABLE_PIN)
def main():
t0 = time.time()
section_controls()
if not all(CHECKS):
print("\nCONTROL FAILED: nothing below is read.")
sys.exit(1)
section_profile()
section_box()
section_gap()
section_optimum()
section_tail_proof()
ran = len(CHECKS)
check("every check line of the run printed, this one aside",
ran == LINES, f"{ran} of {LINES}")
print()
print(f"{sum(CHECKS)} of {len(CHECKS)} checks, "
f"{time.time() - t0:.1f} s")
sys.exit(0 if all(CHECKS) else 1)
if __name__ == "__main__":
main()