erring_cells.py
Checks: SIZE: The cell tent bound theorem; property; rule; observation.
Cited on: SIZE.
To run it: save erring_cells.py, with erring_label.py, erring_lower.py, erring_widths.py, erring_zones.py beside it; needs numpy.
"""
erring_cells.py -- the cell tent bound: each cell pair errs at least the
larger of its two one-boundary tent integrals, and over nondecreasing
widths that bound puts the error at least (1 - o(1))/(2 log m), and the
sorted bound that would carry it to every partition, if true, is sharp
on a grid; the per-shift bound LB3 holds it where the tents fail.
QUESTION. erring_lower.py's LB charges a cell one label boundary at a
time and reaches liminf kappa_m log m >= 1/4. Charging the cell pair
{(a, b), (b, a)} the larger of its two directions, does the continuum
error E(P) reach (1 - o(1))/(2 log m), the upper side's constant? Over
which partitions, and does sorting the widths ever lower E? Does E
itself stay above the increasing bound of its sorted widths, and how
close does it come?
PROOF (P, E and LB as in erring_lower.py; widths w_a, boundaries c_a).
(1) T_ab is the integral over y in I_b of h_a(mid_a + y), h_a(t) the
largest (r - |t - beta|)_+ over boundaries beta, r = w_a/2: the
cell I_a x I_b errs at least T_ab (erring_lower.py's step (2)
with the boundary nearest the shifted midpoint at each y). The
cells (a, b) and (b, a) hold the same sums, so each errs at least
max(T_ab, T_ba), and E >= LB2 = sum over ordered (a, b) of
max(T_ab, T_ba). In closed form: a gap of length g holds r^2 of
H_a, the integral of h_a, if g >= 2r, else rg - g^2/4.
From here the widths are nondecreasing, w_1 <= ... <= w_m,
c_j = w_1 + ... + w_j, S_j = w_1^2 + ... + w_j^2.
(2) LB2 >= G2 = sum_a T_aa + (1/2) sum_j S'_j, S'_j the sum of w_b^2
over b <= j with c_(b-1) >= c_j/2. LB2 >= sum T_aa +
2 sum_b sum_{a<b} T_ba, and sum_{a<b} T_ba integrates I_b's tent
over t in [mid_b, 2c_(b-1) + r), r = w_b/2. Each boundary c_j,
j >= b, c_j <= 2c_(b-1), carries a whole tent there (its ends
c_j - r >= c_(b-1) + r and c_j + r <= 2c_(b-1) + r, a tie
included), the tents disjoint as later gaps are at least w_b:
w_b^2/4 each, and the pairs b <= j, c_(b-1) >= c_j/2 sum to
sum_j S'_j.
(3) J = the j with w_j <= c_(j-1); S'_j >= w_j^2 there. A j outside J
(a doubling step) is wider than all earlier widths together, so
the doubling widths past any point sum below twice the last.
(4) For j in J, rho_j = (S_j - S'_j)/S_j <= 3/4: S_j - S'_j = S_i,
i the least index with c_i >= c_j/2, S_i <= w_i c_i, S'_j >= w_i s with
s = c_j - c_i >= max(w_i, c_j/2 - w_i) >= c_j/4.
(5) LEMMA. If c_j > delta for every j > j0 >= 1, then
Lambda = sum_{j in J, j0 < j < m} w_j^2/S'_j
<= log(S_(m-1)/S_j0) + 8 W, W = ceil(log2(1/delta)). By (4),
w^2/S' <= w^2/S + 4 w^2 X/S^2, X = S - S'; the first telescopes;
in a window c_j in (U/2, U], U = 2^-k, with f its first index,
X_j <= S_f, the term j = f is at most 1 and the rest sum to at
most S_f sum (1/S_(j-1) - 1/S_j) <= 1.
(6) j0 the last j with c_j <= delta, A = c_j0. A < delta/2 gives
E >= LB >= S_m/8 > delta(2 - delta)/32; w_m >= eta gives
E >= S_m/8 >= eta^2/8; else S_j0 >= delta^2/(4m), the J widths
strictly between j0 and m sum past 1 - delta - 3 eta (w_m < eta,
and by (3) the doubling widths there sum below 2 w_(m-1) < 2 eta),
and Cauchy-Schwarz with (5) gives E >= G2 >= F3's third term:
F3 = min(delta(2 - delta)/32, eta^2/8,
max(0, 1 - delta - 3 eta)^2
/ (2 log(4m/delta^2) + 16 ceil(log2(1/delta)))).
(7) delta = 8/log m, eta = 2/sqrt(log m): F3 = (1 - o(1))/(2 log m).
So over nondecreasing widths E(P) >= (1 - o(1))/(2 log m). The bound
does not pass to kappa_m by sorting: sorting the widths increasing
can raise E (the run's rounding cut set).
THE SORTED BOUND. E(P) >= G2(sort P), sort P the widths sorted
increasing, would carry (7) to every P. The tents alone cannot give it:
LB2(P) < G2(sort P) at a seven-interval P (section_sorted). It is sharp
if true, on the half-shifted grid H_n: widths w/2, w, ..., w, w/2 (n - 1
full ones, m = n + 1, w = 1/n), I_0 = [0, w/2), I_a = [(a - 1/2)w,
(a + 1/2)w), I_n = [(n - 1/2)w, 1), boundaries (a + 1/2)w and 1 = nw.
(H1) E(H_n) = (n^2 + 3n - 1)/(8n^2), n >= 2. A full cell (a, b) has
its sums on a tent over [(a + b - 1)w, (a + b + 1)w): for
a + b <= n - 1 the boundaries (a + b -+ 1/2)w leave 3/4 in the
middle label, error w^2/4, (n - 1)(n - 2)/2 cells; for a + b = n
the tent's peak sits at 1, half of it overflows, error w^2/2,
n - 1 cells; past n every sum overflows. I_0 with a full I_b (both
orders, 2(n - 1) cells) is a trapezoid of mass w^2/2 over
[(b - 1/2)w, (b + 1)w) with 3w^2/8 below the boundary
(b + 1/2)w: error w^2/8. I_n with a full interval overflows
whole. The half-half cells (0, 0), (0, n), (n, 0) split their
tents of mass w^2/4 at w/2 or at 1: w^2/8 each; (n, n) overflows.
Summed: (w^2/8)((n - 1)(n - 2) + 4(n - 1) + 2(n - 1) + 3).
(H2) G2(sort H_n) = (n^2 + n - 1/2)/(8n^2). Sorted, c_1 = w/2 and
c_j = (j - 1)w for j >= 2: S'_1 = 0, S'_2 = w^2/4 (the tie
c_1 = c_2/2) and for j >= 3 the b counted are b >= (j + 3)/2, so
S'_j = w^2 floor((j - 1)/2), summing with S'_2 to
w^2(floor(n^2/4) + 1/4), with a tie at b = (j + 3)/2 for every
odd j: the closed form is the inclusive G2's (ties out it is
smaller). T_11 = w^2/16 (the boundary w/2 at the
middle of mid_1 + I_1), T_22 = 0 (mid_2 + I_2 = [5w/4, 7w/4)
keeps w/4 from both w and 2w), and for a >= 3 mid_a + I_a centres
on (2a - 3)w, a whole tent w^2/4 while 2a - 3 <= n, nothing
past: floor((n - 1)/2) of them. At n = 2k and 2k + 1 the sum is
8G2 = n^2 + n - 1/2 times w^2.
So E/G2(sort H_n) = 1 + (2n - 1/2)/(n^2 + n - 1/2) -> 1: a constant
above 1 in front of G2 fails on H_n.
LB3, the per-shift bound. e_a(y) = w_a less the longest piece of
I_a + y cut at the boundaries; U_ab its integral over y in I_b;
LB3 = sum over ordered (a, b) of max(U_ab, U_ba). The cell's one
label holds at most the longest piece at each y, so E_ab >= U_ab,
U_ba; e_a(y) >= h_a(mid_a + y), equal with one boundary inside. So
LB2 <= LB3 <= E. Between breakpoints (the c_b and beta - c_(a-1),
beta - c_a) the longest piece is max(p - y, q + y, r), linear
between its crossings, so the trapezoid rule cut there is exact.
At the tie (2, 4, 2, 5)/13 by hand (lengths in 1/13, areas in
1/169): U rows (1, 1, 1,
1), (2, 6, 1/2, 7/2), (1, 1/2, 1/2, 0), (2, 17/4, 0, 0), LB3 = 27/169;
sorted (2, 2, 4, 5), T^s diagonal (1, 0, 7/2, 0), S' = (0, 4, 16,
25) with both ties in, G2 = 27/169: equal.
DESIGN. tents computes T exactly (partials of H_a through
Q(z) = rz - z^2/2, z <= r, r^2/2 past); shifts the exact U, the
interior's longest gap from a sparse table; pair_sum the sum over
ordered pairs of the larger direction, LB2 of T and LB3 of U. G2's
membership c_(b-1) >= c_j/2 is read at c_j/2 (1 - 1e-12), a tie in, as
step (2) allows; the guard carries the reading: without it H_n's ties
break in floats and C9 fails, so an exact comparison is right only on
widths without ties or on a dyadic lattice. A kill over a population
is a count of agreements x <= y, to the factor 1 + 1e-9 (agree), set
against the population's size, so a NaN agrees with nothing: the size
by hand for K0, K7, K9 and, but for four draws of the stream, K1, as
first printed for K2 to K5. "Past j0" in a check's name is strictly
between j0 and m, as the lemma sums. K3 counts the pairs with an index
of J there and K4 those with two or more doubling widths, since Lambda
= 0 without the first and one doubling width is its own last. K7 is
read cell by cell at an additive 1e-12; K6 and K8 are pinned rows.
The general population (general): erring_lower.py's partitions, the
exponential cuts t -> t + eps e^(K(t - 1)) at K = 3..8, eps in 1/K,
1/K^2 (m <= 3100), and the eps = 1/K widths shuffled (seed 1616);
read_general gives each its m, LB, sum T, LB2 and, where m <= 2500, E
and G2 of its widths sorted. The increasing population
(rising_population): the members with nondecreasing widths, the
exponential cuts (a clipped last width narrower than the one before it
merged into it), constant widths (m = 2, 10, 100, 1000) and geometric
widths w_j ~ q^j (q in 1.01, 1.1, 1.5, 1.9, 2, 2.1, 3; m in 10, 40,
200); read_rise gives each its LB2, G2, the rho_j over J and, at each
delta in {1/2, 1/4, 0.1} with A >= delta/2, Lambda, the lemma's bound
with and without 8W, the doubling widths past j0 with the last of
them, the J widths strictly between j0 and m, and the count of each
kind. Step (6)'s main case
is read at eta in {1/8, 1/16}, where 1 - delta - 3 eta > 0 at every
delta. At q = 2 the doubling steps from j = 40 on (2^j >= 10^12) pass
the guard and count in J. F3 is read at the limit's choice alone, in
closed form in log m: on a grid of fixed delta and eta its least term
is a constant at every m a run reaches.
Fixed partitions: the tent witness (a search's least point, its widths
to 10 places); H_n; the scaled grid, H_n scaled onto [0, 1/2) beside
one interval [1/2, 1) (m = n + 2); the tie (2, 4, 2, 5)/13; the
rearrangement, four widths to four places. The lattice: integer
widths, every composition (every order) of N <= 12 and those of at
most five parts to N = 20, where every tie of small denominator sits
exactly and the least of LB3/G2(sort P), which sits on ties, is not
left to a search's luck.
CONTROLS. Before any sweep. T_11 at [0, 1] (C1); T and U against a
midpoint grid of 200,000 points, cell by cell, within 1e-9 (the rule
is exact off the integrand's kinks and errs at most h^2/4 at each, h a
width over 200,000, under 7e-12, a cell holding a few dozen), T at
three small
partitions and the tent witness, U at five, one with several
boundaries inside a shifted interval and one of two intervals with the
wider first (C2, C11). By hand: the sorted tie (2, 2, 4, 5)/13, in
1/169, T's diagonal (1, 0, 7/2, 0), S = (4, 8, 24, 49), S' = (0, 4,
16, 25), J = all but the first, G2 = 27 and 99/2 at the coefficient 1
(ties out S' would be (0, 0, 0, 25) and G2 17), and the tie's U rows
above with LB3 = 27 (H1, H2); at the widths (1, 2, 2, 6, 9)/20, S' =
(0, 0, 4, 0, 81)/400, J = (3, 5), split at five delta (j0 = 2 with J
part (3) and doubling part (4) at 0.2; 3, (), (4) at 0.3; 4, (), () at
0.6; none at 0.12, where A = 0.05 < delta/2, and none at 0.04) and
Lambda = 1 against log 9 + 24, log 9 without 8W (H3); read_rise at the
widths (2, 3, 3, 5, 8, 9)/30, S' = (0, 0, 9, 25, 64, 81)/900: rho =
13/22, 22/47, 47/111, 111/192, and at delta = 1/2, 1/4, 0.1 the rows
(j0 = 4: Lambda 1, log(111/47) + 8, no doubling, J widths 8/30), (2:
3, log(111/13) + 16, none, 16/30), (1: 3, log(111/4) + 32, the one
doubling width 1/10, 16/30), and at (1, 2, 2, 6, 9)/20 the row at
delta = 0.1, where A = 1/20 is delta/2 and stays in: Lambda 1, log 45
+ 32, the doubling widths 2/20 and 6/20, the last 6/20, J widths 2/20
(H4); F3 at log m = log 2 with each term
binding, 199/320000 at (0.01, 1/8), 1/2048 at (1/2, 1/16), 1/(64(2 log
32 + 16)) at (1/2, 1/8), and 0 at (1/2, 1/4) (H5); h_grid(2), top(2)
and rising at three cut lists (H6); agree on its edge, and at a NaN
(H7).
After each sweep and before its kills are read, a plant goes through
the same count, owed failures at some members and not all: C3 to C8,
C12, C14 below.
Pinned as first printed, no hand value: the plants' counts; P0's two
spans; the largest rho, Lambda over its bound and doubling ratio, and
K5's least margin; the least E/G2(sort P) over the general population;
rounding's ratio; the witness's two ratios and its LB3's; the scaled
grid's rows; LB2's and LB3's on H_n; the rearrangement's ratio; C14's
least; and of the sizes, the 23084 indices of J, the 723 pairs, the
576 with an index of J past j0, the 14 with two or more doubling
widths and the 66 main-case triples. The laws' draws are numpy's
stream at seed 1567.
PREDICTIONS AND KILLS (written before the first run; restated where a
repair changed what a check reads, RUN RECORD says how).
C1 [0, 1]: T_11 = 1/4.
C2 closed-form T against the brute grid: every cell within 1e-9.
C3 a planted break, LB with its pair constant doubled, fails
LB <= sum T at some sets and not at all; so does LB2 raised by a
twentieth against E.
K0 LB <= sum T at every set, and LB2 <= E wherever E is computed.
P0 E/LB2 on the exponential cuts about 1.03 to 1.10 (E/LB 1.6 to 1.9).
C4 a planted break, G2 with the S' coefficient 1, fails G2 <= LB2 at
some increasing sets and not at all.
K1 G2 <= LB2 at every increasing set; kills (2).
C5 a planted break, rho's bound 1/2 for 3/4, fails at some j of J.
K2 rho_j <= 3/4 at every j of J; kills (4).
C6 a planted break, the lemma's bound without 8W, fails at some
(partition, delta) pairs.
K3 Lambda <= log(S_(m-1)/S_j0) + 8W at every pair with A >= delta/2
and an index of J past j0; kills (5).
C7 a planted break, the doubling widths past j0 against 3/2 of their
last, not twice it, fails at some pairs with two or more.
K4 the doubling widths past j0 at most twice the last of them at
every pair with two or more; kills (3).
C8 a planted break, the J widths strictly between j0 and m against
1 - delta (no allowance for w_m or the doubling widths), fails at
some triples of (6)'s main case.
K5 those widths at least 1 - delta - 3 eta at every triple of (6)'s
main case (A >= delta/2, w_m < eta); kills (6)'s count.
P1 F3 log m at the limit's choice about 0.37 at m = 10^1024.
P2 sorting the widths increasing can raise E (rounding), and E(P) >=
G2(sort P) over the general population, which a planted S'
coefficient 1 fails at some sets and not at all.
C9 (H1) and (H2) against cont_error and g2 at n = 2..60, 100, 200,
400, 800: |diff| < 1e-12.
P3 the tent witness: LB2(P)/G2(sort P) 0.960165, E/G2(sort P)
1.151538 there.
P4 m(E/G2(sort P) - 1) on H_n near 2 (1.990 at n = 50); on the
scaled grid 0.414 to 0.402 at n = 100..800; m(LB2/G2(sort P) - 1)
0.490, 0.498 on H_50, H_200, about 0.10 on the scaled grid.
K6 E(P) >= G2(sort P) at these partitions: read off P3's and P4's
rows, each pinned above 1.
C11 exact U against the midpoint grid: every cell within 1e-9.
C12 a planted break, U + U^t in place of their max, fails
<= E_ab at some cells and not at all; so does 2T against U.
K7 T <= U and max(U_ab, U_ba) <= E_ab (1e-12) at every cell read.
P5 LB3/G2(sort P) 1.015148 at the tent witness; 169 LB3 = 169 G2 =
27 at the tie; m(LB3/G2(sort P) - 1) 0.980, 0.995 on H_50, H_200,
0.201 on the scaled grid at n = 200.
P6 LB3(P)/LB3(sort P) below 1 at the rearrangement (0.945197), so
the bound does not pass through sorting.
K8 LB3(P) >= G2(sort P) at these: read off P5's rows and H2.
C14 a planted break, LB2 in place of LB3, fails over the lattice at
some points and not at all.
K9 LB3(P) >= G2(sort P) at every lattice point, to the factor
1 + 1e-9.
FINDINGS (from the printed run; the controls passed first, C1
0.250000000000, C2 at 78 of 78 cells, max |diff| 9.14e-13, C11 at 69 of
69, 1.63e-12, and each plant before its kills: C3 fails at 736 of 1202
sets and at 140 of 1200; C4 to C8 at 174 of 511 sets, 5203 of 23084
indices, 399 of 576 pairs, 8 of 14 and 56 of 66 triples; P2's at 347
of 1200 sets; C12 at 833 and 821 of 1526 cells; C14 at 20 of 24209
points).
K0 silent: LB <= sum T at 1202 of 1202 sets (m up to 2984), LB2 <= E
at 1200 of 1200.
P0 held: E/LB2 1.029 to 1.105 over the nine exponential cut sets with
E (m = 21 to 2418), where E/LB is 1.633 to 1.905. On this one
family LB2 holds nearly all of E.
K1 silent at 511 of 511 increasing sets (m up to 2984). K2 at 23084
of 23084 indices of J: the largest rho is 0.7497 (3/4 is approached
where c_j/2 falls just past a boundary among nearly equal widths).
K3 at 576 of 576 pairs: the largest Lambda over its bound is
0.2988, and a term of Lambda is at most 1, so only a pair with
more than 8W indices of J past j0 could fail by size: the run
reads the bound's form, not its 8. K4 at 14 of 14: the doubling
widths reach 0.8818 of twice
their last. K5 at 66 of 66 triples: the least margin is 0.1266.
P1 held: F3 log m reads 0.0000 at m = 10^8 and 10^16
(1 - delta - 3 eta <= 0 there), 0.0772, 0.2458 and 0.3679 at
m = 10^64, 10^256 and 10^1024, against its limit 1/2: the 1/2 is
asymptotic.
P2 held: rounding at m = 162 errs 0.570625 of what its widths sorted
increasing err, so sorting increasing can raise E. G2(sort P) <=
E(P) at 1200 of 1200 sets, the least E(P)/G2(sort P) 1.0066, at a
sorted draw.
C9 at 126 of 126, max |diff| 4.4e-14.
P3 held: LB2/G2(sort P) 0.960165, E/G2(sort P) 1.151538. The tents
lose 4% at a narrow interval just after a wide one, where E keeps
15%.
P4 held: m(E/G2(sort P) - 1) 1.990 and 1.998 on H_50 and H_200, as
(H1)/(H2) give, and 0.414, 0.407, 0.404, 0.402 on the scaled grid
at n = 100..800; m(LB2/G2(sort P) - 1) 0.490 and 0.498 on H_n,
0.101, 0.100, 0.100, 0.100 on the scaled grid. On both grids the
tents hold G2 too, so their only loss read is the witness's shape.
K6 is these rows, each above 1.
K7 silent at 1526 of 1526 cells, both ways, max excess 1.1e-16.
P5 held: LB3/G2(sort P) 1.015148 at the tent witness; at the tie 169
LB3 = 27.000000000, G2's hand value (H2); m(LB3/G2(sort P) - 1)
0.980, 0.995 on H_50, H_200 and 0.201 on the scaled grid at
n = 200, twice LB2's. K8 is these rows.
P6 held: LB3(P)/LB3(sort P) 0.945197 at the four-place widths:
sorting can raise LB3.
K9 silent at 24209 of 24209 lattice points. The primitive unsorted
points within 1e-9 of equality are (2, 4, 2, 5) and (1, 1, 4, 2,
5), the tie and its first 2 split; LB2's least there is 0.962617,
at (1, 1, 4, 2, 5).
Run: 32.8 s, peak commit 163.1 MB (T and U are m by m), 39/39.
RUN RECORD. First runs, 24/24: each kill read the largest of a ratio
folded through max(), which keeps its value past a NaN, over
populations whose sizes were printed and compared with nothing; split's
conventions (j0, either end, the filter A >= delta/2) sat inside K3 to
K5's slack; F3 was printed over a grid where its least term is a
constant; the per-shift arm ran inside the fixed partitions' and fell
silent with C9. After a code read, 39/39: K0 to K5 and K9 counts of
agreements against their populations' sizes, K7 a count of cells, K6
and K8 pinned rows, each plant through its kill's count. C3's plant
was T + T^t in place of their max, which every set fails. A second
read found K3 counting 147 pairs with no index of J past j0 and K4 87
with one doubling width, where neither can fail, C7 failing at
exactly the other 14, and C2's and C11's bars at 1e-6 and 1e-8. Cut,
each for the reason
DESIGN gives or as implied by a check that stays: F3 over the grid
(its best times log m read at most 0.0156) and the limit's delta and
eta in it (eta is past 0.7 at every m run, K5's target negative;
over that grid's 936 triples K5's least margin read 0.1783);
K0's middle link, an identity; the errors of the widths sorted
increasing and decreasing over the general population (E/E(sort P)
read 0.9889 at one Dirichlet draw, decreasing over increasing at least
1.0002); G2 with ties out (17/169 at the tie; the witness has none);
the lattice's strict reading one width up, which no LB3 point reached,
and its guard G2 <= 0, which never fired; the brute grid at the
witness, C2's now; H_n at n = 100, 400, 800 (E's excess 1.995, 1.999,
1.999, LB2's 0.495, 0.499, 0.499); K6 and K8 as bars and the coefficient
plant at H_400, their rows pinned above 1 and P2's plant read over
1200 sets; the tie's difference, H2's now; the rows by key, P0's nine
rows and LB2/G2(sort P) over the general population, prints no page
quoted; the rearrangement's LB3/G2(sort P), 1.540309, K8's sixth row;
and lines another line implies: shifts' filter of empty pieces
(np.unique leaves none), its guard at one boundary (the gap table is
then never read) and its nan_to_num (the clip follows), split's j0 < 1
(c_0 = 0 < delta/2), window's where and minimum around S_j - S_i
(i <= j always). cell_errs is erring_zones.py's, cont_error's own
terms.
"""
import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import itertools # noqa: E402
import math # noqa: E402
from collections import namedtuple # noqa: E402
import numpy as np # noqa: E402
from erring_lower import cuts_of, exp_cuts, lb as lb1, partitions # noqa: E402
from erring_zones import cell_errs, cont_error # noqa: E402
CHECKS = []
GUARD = 1e-12
TOL = 1 + 1e-9
DELTAS = (0.5, 0.25, 0.1)
ETAS = (0.125, 0.0625)
Gen = namedtuple("Gen", "key m E LB sumT LB2 G2s G2x")
Pair = namedtuple("Pair", "d lam bound bound0 D last sJ nJ nD")
Rise = namedtuple("Rise", "m LB2 G2 G2x rho wm pairs")
# Counted by hand. key: (sets, sets with E, largest m). A law is 59
# values of m by 4 reads (two laws draw nothing: one set read four
# times); the exponential sets are K = 3..8 at two eps
# less the two past m = 3100, the shuffles one a K; K = 8 (m = 2984)
# has no E.
SIZES = {
"dirichlet": (236, 236, 60),
"log-uniform": (236, 236, 60),
"tiny then wide": (236, 236, 60),
"alternating": (236, 236, 60),
"sorted": (236, 236, 60),
"profile p = 1": (2, 2, 400),
"profile p = 2": (1, 1, 400),
"rounding": (3, 3, 162),
"exp": (10, 9, 2984),
"shuf": (6, 5, 2984),
}
# The increasing population by key: two laws whole, ten exponential
# sets, four constant, seven q by three m; dirichlet's and log-uniform's
# two each are the stream's.
RISING = {"tiny then wide": 236, "sorted": 236, "dirichlet": 2,
"log-uniform": 2, "exponential": 10, "constant": 4,
"geometric": 21}
# F3 log m at delta = 8/log m, eta = 2/sqrt(log m), m = 10^ex, by hand.
LIMIT = [(8, "0.0000"), (16, "0.0000"), (64, "0.0772"), (256, "0.2458"),
(1024, "0.3679")]
# (grid, n): m(E/G2 - 1), m(LB2/G2 - 1), m(LB3/G2 - 1) against G2(sort P),
# as first printed but H_n's first, which (H1) and (H2) give.
GRIDS = [("H", 50, "1.990", "0.490", "0.980"),
("H", 200, "1.998", "0.498", "0.995"),
("top", 100, "0.414", "0.101", None),
("top", 200, "0.407", "0.100", "0.201"),
("top", 400, "0.404", "0.100", None),
("top", 800, "0.402", "0.100", None)]
# As first printed, no hand value. The plants' failures: C3's two, C4
# to C8's five, P2's, C12's two, C14's.
PLANTS = {"C3": (736, 140), "C4 to C8": (174, 5203, 399, 8, 56), "P2": 347,
"C12": (833, 821), "C14": 20}
# The largest rho, Lambda over its bound, doubling widths over twice
# their last, and K5's least margin.
PINS = {"rise": ("0.7497", "0.2988", "0.8818", "0.1266")}
WITNESS = [0.0720326820, 0.0042024314, 0.0752904574, 0.3027208640,
0.0753392577, 0.0760274920, 0.3943868156]
TIE = [2 / 13, 4 / 13, 2 / 13, 5 / 13]
REARRANGED = [0.0821, 0.3561, 0.2057, 0.3561]
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 agree(pairs):
"""How many (x, y) have x <= y to the factor TOL."""
return sum(bool(x <= y * TOL) for x, y in pairs)
def Q(z, r):
z = np.clip(z, 0.0, None)
return np.where(z <= r, r * z - z * z / 2, r * r / 2)
def tents(cuts):
"""T[a, b]: the one-boundary tent bound of cell (a, b), exact."""
C = np.asarray(cuts, dtype=float)
m = len(C) - 1
B = C[1:]
g = np.diff(B)
T = np.empty((m, m))
for a in range(m):
r = (C[a + 1] - C[a]) / 2
J = 2 * Q(g / 2, r)
HB = r * r / 2 + np.concatenate([[0.0], np.cumsum(J)])
t = (C[a] + r) + C
i = np.searchsorted(B, t, side="right") - 1
H = np.empty_like(t)
lead = i < 0
H[lead] = r * r / 2 - Q(B[0] - t[lead], r)
tail = i == len(B) - 1
H[tail] = HB[-1] + Q(t[tail] - B[-1], r)
mid = ~lead & ~tail
k = i[mid]
s, gk = t[mid] - B[k], g[k]
H[mid] = (HB[k] + Q(np.minimum(s, gk / 2), r)
+ np.where(s > gk / 2, Q(gk / 2, r) - Q(gk - s, r), 0.0))
T[a] = np.diff(H)
return T
def tents_brute(cuts, n=200_000):
C = np.asarray(cuts, dtype=float)
m = len(C) - 1
B = C[1:]
T = np.empty((m, m))
for a in range(m):
r = (C[a + 1] - C[a]) / 2
for b in range(m):
y = C[b] + (np.arange(n) + 0.5) * (C[b + 1] - C[b]) / n
t = C[a] + r + y
h = np.clip(r - np.abs(t[:, None] - B[None, :]), 0, None).max(1)
T[a, b] = h.sum() * (C[b + 1] - C[b]) / n
return T
def pair_sum(X):
"""The sum over ordered (a, b) of max(X_ab, X_ba): LB2 of T, LB3 of U."""
return float(np.maximum(X, X.T).sum())
def sparse(g):
st = [np.asarray(g, dtype=float)]
while 2 ** len(st) <= len(g):
h = 2 ** (len(st) - 1)
st.append(np.maximum(st[-1][:-h], st[-1][h:]))
return st
def range_max(st, lo, hi):
"""max g[lo:hi] where hi > lo, else -inf."""
out = np.full(len(lo), -np.inf)
ok = hi > lo
if ok.any():
n = hi[ok] - lo[ok]
k = np.floor(np.log2(n)).astype(int)
for kk in np.unique(k):
s = k == kk
idx = np.flatnonzero(ok)[s]
out[idx] = np.maximum(st[kk][lo[ok][s]],
st[kk][hi[ok][s] - 2 ** kk])
return out
def shifts(cuts):
"""U[a, b]: the integral over y in I_b of w_a less the longest piece
of I_a + y cut at the boundaries c_1..c_m strictly inside, exact."""
C = np.asarray(cuts, dtype=float)
m = len(C) - 1
B = C[1:]
st = sparse(np.diff(B))
U = np.zeros((m, m))
for a in range(m):
L0, R0 = C[a], C[a + 1]
w = R0 - L0
y = np.unique(np.clip(np.concatenate([C, B - L0, B - R0]), 0, 1))
y0, y1 = y[:-1], y[1:]
ym = (y0 + y1) / 2
ilo = np.searchsorted(B, L0 + ym, side="right")
ihi = np.searchsorted(B, R0 + ym, side="left") - 1
has = ilo <= ihi
e = np.zeros(len(ym))
if has.any():
lo, hi = ilo[has], ihi[has]
p = B[lo] - L0
q = R0 - B[hi]
r = range_max(st, lo, hi)
s0, s1 = y0[has], y1[has]
pts = np.stack([s0, (p - q) / 2, p - r, r - q, s1], axis=1)
pts = np.sort(np.clip(pts, s0[:, None], s1[:, None]), axis=1)
f = np.maximum(np.maximum(p[:, None] - pts, q[:, None] + pts),
r[:, None])
longest = ((f[:, 1:] + f[:, :-1]) / 2 * np.diff(pts, axis=1)
).sum(1)
e[has] = w * (s1 - s0) - longest
bb = np.searchsorted(C, ym, side="right") - 1
U[a] = np.bincount(bb, weights=e, minlength=m)[:m]
return U
def shifts_brute(cuts, n=200_000):
C = np.asarray(cuts, dtype=float)
m = len(C) - 1
B = C[1:]
U = np.empty((m, m))
for a in range(m):
w = C[a + 1] - C[a]
for b in range(m):
y = C[b] + (np.arange(n) + 0.5) * (C[b + 1] - C[b]) / n
L, R = C[a] + y, C[a + 1] + y
ins = (B[None, :] > L[:, None]) & (B[None, :] < R[:, None])
pts = np.where(ins, B[None, :], np.nan)
pts = np.concatenate([L[:, None], pts, R[:, None]], axis=1)
pts = np.sort(pts, axis=1)
longest = np.nanmax(np.diff(pts, axis=1), axis=1)
U[a, b] = (w - longest).sum() * (C[b + 1] - C[b]) / n
return U
def rising(cu):
return bool(np.all(np.diff(np.diff(np.asarray(cu, dtype=float)))
>= -1e-15))
def window(cu):
"""S (S_0 = 0), S'_j and the J mask for j = 1..m, ties c_(b-1) =
c_j/2 in."""
C = np.asarray(cu, dtype=float)
w = np.diff(C)
S = np.concatenate([[0.0], np.cumsum(w * w)])
j = np.arange(1, len(C))
i = np.searchsorted(C, C[1:] / 2 * (1 - GUARD), side="left")
Sp = S[j] - S[i]
return S, Sp, i <= j - 1
def g2(cu, T, coef=0.5):
return float(np.trace(T) + coef * window(cu)[1].sum())
def sorted_g2(w, coef=0.5):
"""G2 of the widths sorted increasing, ties in."""
cs = cuts_of(np.sort(w))
return g2(cs, tents(cs), coef)
def split(cu, d):
"""j0 (the last j with c_j <= delta) and its J and doubling indices
strictly between j0 and m, or None when A < delta/2."""
C = np.asarray(cu, dtype=float)
m = len(C) - 1
j0 = int(np.searchsorted(C, d, side="right")) - 1
if C[j0] < d / 2:
return None
inJ = window(cu)[2]
idx = np.arange(j0 + 1, m)
return j0, idx[inJ[idx - 1]], idx[~inJ[idx - 1]]
def lam(cu, d, window_term=True):
"""Lambda and the lemma's bound at delta, or None if A < delta/2."""
got = split(cu, d)
if got is None:
return None
j0, idx, _ = got
S, Sp, _ = window(cu)
w = np.diff(np.asarray(cu, dtype=float))
L = float((w[idx - 1] ** 2 / Sp[idx - 1]).sum())
bound = math.log(S[len(w) - 1] / S[j0])
if window_term:
bound += 8 * math.ceil(math.log2(1 / d))
return L, bound
def f3(L, d, e):
"""F3(delta, eta) at log m = L, step (6)'s floor under E."""
W = math.ceil(math.log2(1 / d))
return min(d * (2 - d) / 32, e * e / 8,
max(0.0, 1 - d - 3 * e) ** 2
/ (2 * (math.log(4) + L - 2 * math.log(d)) + 16 * W))
def general():
"""(key, cuts): erring_lower's partitions, the exponential cuts and
the eps = 1/K widths shuffled."""
rng = np.random.default_rng(1567)
for name, cu in partitions(rng):
yield name.split(",")[0].split(" m")[0], np.asarray(cu, dtype=float)
shuf = np.random.default_rng(1616)
for K in (3, 4, 5, 6, 7, 8):
for eps in (1 / K, 1 / K ** 2):
cu = np.asarray(exp_cuts(K, eps))
if len(cu) - 1 > 3100:
continue
yield "exp", cu
if eps == 1 / K:
w = np.diff(cu)
shuf.shuffle(w)
yield "shuf", cuts_of(w)
def rising_population():
rng = np.random.default_rng(1567)
for name, cu in partitions(rng):
if rising(cu):
yield name.split(",")[0].split(" m")[0], np.asarray(cu)
for K in (3, 4, 5, 6, 7, 8):
for eps in (1 / K, 1 / K ** 2):
cu = np.asarray(exp_cuts(K, eps))
if not rising(cu):
cu = np.delete(cu, -2)
if len(cu) - 1 <= 3100:
yield "exponential", cu
for m in (2, 10, 100, 1000):
yield "constant", cuts_of(np.ones(m))
for q in (1.01, 1.1, 1.5, 1.9, 2.0, 2.1, 3.0):
for m in (10, 40, 200):
yield "geometric", cuts_of(q ** np.arange(1.0, m + 1))
def read_general(key, cu):
"""A cut set's readings: m, LB, sum T, LB2 and, where m <= 2500, E
and G2 of its widths sorted increasing, at the S' coefficients 1/2
and 1 (None past)."""
m = len(cu) - 1
T = tents(cu)
sumT, two = float(T.sum()), pair_sum(T)
del T
E = G = Gx = None
if m <= 2500:
w = np.diff(cu)
E, G, Gx = cont_error(cu), sorted_g2(w), sorted_g2(w, coef=1.0)
return Gen(key, m, E, lb1(cu), sumT, two, G, Gx)
def read_rise(cu):
"""A nondecreasing cut set's readings for steps (2) to (6): m, LB2,
G2 at the S' coefficients 1/2 and 1, rho_j over J, w_m, and at each
delta with A >= delta/2 a Pair: Lambda, the lemma's bound with and
without 8W, the doubling widths strictly between j0 and m with the
last of them (None if none), the J widths there, and how many
indices of each kind."""
w = np.diff(np.asarray(cu, dtype=float))
T = tents(cu)
two, G, Gx = pair_sum(T), g2(cu, T), g2(cu, T, coef=1.0)
S, Sp, inJ = window(cu)
rho = 1 - Sp[inJ] / S[1:][inJ]
out = []
for d in DELTAS:
got = split(cu, d)
if got is None:
continue
_, idx, dbl = got
L, b = lam(cu, d)
b0 = lam(cu, d, window_term=False)[1]
last = float(w[dbl[-1] - 1]) if len(dbl) else None
out.append(Pair(d, L, b, b0, float(w[dbl - 1].sum()), last,
float(w[idx - 1].sum()), len(idx), len(dbl)))
return Rise(len(w), two, G, Gx, rho, float(w[-1]), out)
def h_grid(n):
return np.concatenate([[0.5], np.ones(n - 1), [0.5]])
def top(n):
return np.concatenate([h_grid(n) / (2 * n), [0.5]])
def against_sorted(w):
"""E(P), LB2(P) and G2(sort P), ties in."""
cu = cuts_of(w)
return cont_error(cu), pair_sum(tents(cu)), sorted_g2(w)
def lb3_over(w):
"""LB3(P)/G2(sort P), ties in."""
return pair_sum(shifts(cuts_of(w))) / sorted_g2(w)
def lattice():
"""Integer widths: every composition of N <= 12, and those of at most
five parts to N = 20."""
for N in range(1, 21):
for m in range(1, min(N, N if N <= 12 else 5) + 1):
for cut in itertools.combinations(range(1, N), m - 1):
yield np.diff((0,) + cut + (N,))
def section_controls():
print("controls, before any sweep")
t11 = tents([0.0, 1.0])[0, 0]
check("C1: T_11 at [0, 1] is 1/4", abs(t11 - 0.25) < 1e-12,
f"{t11:.12f}")
small = [[0, 0.3, 1], [0, 0.1, 0.25, 0.6, 1], [0, 0.5, 0.55, 1]]
ok, worst = 0, 0.0
for cu in small + [cuts_of(WITNESS)]:
d = np.abs(tents(cu) - tents_brute(cu))
ok, worst = ok + int((d < 1e-9).sum()), max(worst, d.max())
check("C2: closed-form T against the brute grid, cell by cell",
ok == 78, f"{ok} of 78 cells, max |diff| {worst:.2e}")
ok, worst = 0, 0.0
for cu in small + [[0, 0.5, 0.52, 0.55, 0.6, 0.62, 1], [0, 0.7, 1]]:
d = np.abs(shifts(cu) - shifts_brute(cu))
ok, worst = ok + int((d < 1e-9).sum()), max(worst, d.max())
check("C11: exact U against the midpoint grid, cell by cell",
ok == 69, f"{ok} of 69 cells, max |diff| {worst:.2e}")
cs = cuts_of((2, 2, 4, 5))
T = tents(cs)
S, Sp, inJ = window(cs)
got = [*np.diag(T), *S, *Sp, g2(cs, T), g2(cs, T, coef=1.0),
sorted_g2((2, 4, 2, 5)), sorted_g2((2, 4, 2, 5), coef=1.0),
pair_sum(np.array([[1.0, 2.0], [3.0, 4.0]])) / 169]
want = [1, 0, 3.5, 0, 0, 4, 8, 24, 49, 0, 4, 16, 25, 27, 49.5, 27, 49.5,
11]
ok = sum(abs(169 * x - y) < 1e-12 for x, y in zip(got, want))
check("H1: the sorted tie (2, 2, 4, 5)/13 by hand: T's diagonal, S, S' "
"with both ties in, J, G2 at the coefficients 1/2 and 1; "
"pair_sum of a hand matrix",
(ok, len(got)) == (18, 18) and inJ.tolist() == [False, True, True,
True],
f"{ok} of {len(got)}, J {inJ.tolist()}")
U = shifts(cuts_of(TIE))
rows = [1, 1, 1, 1, 2, 6, 0.5, 3.5, 1, 0.5, 0.5, 0, 2, 4.25, 0, 0]
ok = sum(abs(169 * x - y) < 1e-12 for x, y in zip(U.ravel(), rows))
three = 169 * pair_sum(U)
check("H2: the tie (2, 4, 2, 5)/13 by hand: U's sixteen cells, and LB3 "
"is 27/169, G2(sort P)", ok == 16 and abs(three - 27) < 1e-12
and abs(lb3_over(TIE) - 1) < 1e-12,
f"{ok} of 16, 169 LB3 {three:.9f}, LB3/G2(sort P) - 1 "
f"{lb3_over(TIE) - 1:.1e}")
cu = cuts_of((1, 2, 2, 6, 9))
S, Sp, inJ = window(cu)
sp = [abs(400 * x - y) < 1e-12 for x, y in zip(Sp, (0, 0, 4, 0, 81))]
cases = [(0.2, (2, [3], [4])), (0.3, (3, [], [4])), (0.6, (4, [], [])),
(0.12, None), (0.04, None)]
ok = 0
for d, want in cases:
got = split(cu, d)
if got is not None:
got = (got[0], got[1].tolist(), got[2].tolist())
ok += got == want
L, b = lam(cu, 0.2)
L0, b0 = lam(cu, 0.2, window_term=False)
check("H3: the widths (1, 2, 2, 6, 9)/20 by hand: S', J, split at five "
"delta, two of them none, and Lambda against log 9 + 24, log 9 "
"without 8W",
sum(sp) == 5 and inJ.tolist() == [False, False, True, False, True]
and ok == 5 and lam(cu, 0.12) is None
and max(abs(L - 1), abs(L0 - 1), abs(b - math.log(9) - 24),
abs(b0 - math.log(9))) < 1e-12,
f"S' {sum(sp)} of 5, split {ok} of 5, Lambda {L:.6f}, bounds "
f"{b:.6f} and {b0:.6f}")
r = read_rise(cuts_of((2, 3, 3, 5, 8, 9)))
want = [(0.5, 1, math.log(111 / 47) + 8, math.log(111 / 47), 0, None,
8 / 30, 1, 0),
(0.25, 3, math.log(111 / 13) + 16, math.log(111 / 13), 0, None,
16 / 30, 3, 0),
(0.1, 3, math.log(111 / 4) + 32, math.log(111 / 4), 0.1, 0.1,
16 / 30, 3, 1)]
edge = read_rise(cuts_of((1, 2, 2, 6, 9))).pairs[-1]
want.append((0.1, 1, math.log(45) + 32, math.log(45), 0.4, 0.3, 0.1, 1,
2))
ok = 0
for p, q in zip(r.pairs + [edge], want):
ok += sum(x is None if y is None else x is not None
and abs(x - y) < 1e-12 for x, y in zip(p, q))
rho = [13 / 22, 22 / 47, 47 / 111, 111 / 192]
check("H4: read_rise at the widths (2, 3, 3, 5, 8, 9)/30 by hand: m, "
"w_m, four rho, three rows of nine fields; and its row at "
"delta = 0.1 of the widths (1, 2, 2, 6, 9)/20, where A is "
"delta/2 and two doubling widths differ",
(r.m, len(r.pairs), len(r.rho), ok) == (6, 3, 4, 36)
and abs(r.wm - 0.3) < 1e-12
and np.abs(r.rho - rho).max() < 1e-12,
f"{ok} of 36 fields, rho " + ", ".join(f"{x:.4f}" for x in r.rho))
L2 = math.log(2)
got = [f3(L2, 0.01, 0.125), f3(L2, 0.5, 0.0625), f3(L2, 0.5, 0.125),
f3(L2, 0.5, 0.25)]
want = [199 / 320000, 1 / 2048, 1 / (64 * (2 * math.log(32) + 16)), 0]
ok = sum(abs(x - y) < 1e-15 for x, y in zip(got, want))
check("H5: F3 by hand at log m = log 2, each term binding and the "
"third at 0", ok == 4,
f"{ok} of 4: " + ", ".join(f"{x:.7f}" for x in got))
check("H6: h_grid(2), top(2) and rising by hand",
h_grid(2).tolist() == [0.5, 1.0, 0.5]
and top(2).tolist() == [0.125, 0.25, 0.125, 0.5]
and [rising(c) for c in ([0, 0.1, 0.3, 1], [0, 0.3, 0.4, 1],
[0, 0.5, 1])] == [True, False, True],
f"top(2) {top(2).tolist()}")
u = 1 + 5e-10
got = agree([(1, 1), (u, 1), (TOL, 1), (1 + 1e-8, 1), (math.nan, 1),
(1, math.nan), (0, 0)])
check("H7: agree counts x <= y at the factor 1 + 1e-9, on its edge, "
"and no NaN", got == 4, f"{got} of 7")
def section_chain(pop):
"""The sizes, C3, K0 and P0; returns the readings."""
print("the chain LB <= sum T <= LB2 <= E over the general population")
n0 = len(CHECKS)
reads = [read_general(key, cu) for key, cu in pop]
withE = [r for r in reads if r.E is not None]
sizes = {}
for r in reads:
s = sizes.setdefault(r.key, [0, 0, 0])
s[0], s[1], s[2] = s[0] + 1, s[1] + (r.E is not None), max(s[2], r.m)
check("the sizes by key are the hand counts: sets, sets with E, the "
"largest m",
{k: tuple(v) for k, v in sizes.items()} == SIZES
and (len(reads), len(withE)) == (1202, 1200),
f"{len(reads)} sets, {len(withE)} with E")
half = len(reads) - agree((lb1(cu, 1 / 2), r.sumT)
for (_, cu), r in zip(pop, reads))
raised = len(withE) - agree((1.05 * r.LB2, r.E) for r in withE)
check("C3: LB with its pair constant doubled fails LB <= sum T, and "
"LB2 raised by a twentieth fails LB2 <= E, each at some sets, "
"not all, as first printed",
(half, raised) == PLANTS["C3"],
f"{half} of {len(reads)}, {raised} of {len(withE)}")
if not all(CHECKS[n0:]):
print(" CONTROL FAILED: K0 and P0 are not read.")
return reads
ok = agree((r.LB, r.sumT) for r in reads)
check("K0: LB <= sum T at the 1202 sets", ok == 1202,
f"{ok} of {len(reads)}")
ok = agree((r.LB2, r.E) for r in withE)
check("K0: LB2 <= E at the 1200 sets with E", ok == 1200,
f"{ok} of {len(withE)}")
ex = [r for r in withE if r.key == "exp"]
two = [r.E / r.LB2 for r in ex]
one = [r.E / r.LB for r in ex]
got = (len(ex), min(r.m for r in ex), max(r.m for r in ex),
f"{min(two):.3f}..{max(two):.3f}",
f"{min(one):.3f}..{max(one):.3f}")
check("P0: the nine exponential sets with E, m = 21 to 2418: E/LB2 and "
"E/LB as first printed",
got == (9, 21, 2418, "1.029..1.105", "1.633..1.905"),
f"{got[0]} sets, m = {got[1]} to {got[2]}, E/LB2 {got[3]}, E/LB "
f"{got[4]}")
return reads
def section_rise():
"""The sizes, C4 to C8, K1 to K5, and F3 at the limit's choice."""
print("K1 to K5 over the increasing population")
n0 = len(CHECKS)
pop = list(rising_population())
reads = [read_rise(cu) for _, cu in pop]
sizes = {}
for key, _ in pop:
sizes[key] = sizes.get(key, 0) + 1
up = sum(rising(cu) for _, cu in pop)
rho = [float(x) for r in reads for x in r.rho]
pairs = [p for r in reads for p in r.pairs]
withJ = [p for p in pairs if p.nJ > 0]
dbl = [p for p in pairs if p.nD > 1]
main = [(p, e) for r in reads for p in r.pairs for e in ETAS if r.wm < e]
got = (len(reads), up, max(r.m for r in reads), len(rho), len(pairs),
len(withJ), len(dbl), len(main))
check("the sizes are the hand counts by key, every member "
"nondecreasing, the largest m 2984; the indices of J, the "
"pairs, those with an index of J past j0, those with two or "
"more doubling widths and the main-case triples as first printed",
sizes == RISING
and got == (511, 511, 2984, 23084, 723, 576, 14, 66),
f"{got[0]} sets, {got[3]} indices of J, {got[4]} pairs, {got[5]} "
f"with an index of J, {got[6]} with two or more doubling widths, "
f"{got[7]} triples")
planted = (
len(reads) - agree((r.G2x, r.LB2) for r in reads),
len(rho) - agree((x, 0.5) for x in rho),
len(withJ) - agree((p.lam, p.bound0) for p in withJ),
len(dbl) - agree((p.D, 1.5 * p.last) for p in dbl),
len(main) - agree((1 - p.d, p.sJ) for p, _ in main))
check("C4 to C8: each plant fails at some members, not all, as first "
"printed: G2 at the S' coefficient 1 against LB2; rho against "
"1/2; Lambda against its bound without 8W; the doubling widths "
"against 3/2 of their last; the J widths against 1 - delta",
planted == PLANTS["C4 to C8"],
f"{planted[0]} of {len(reads)}, {planted[1]} of {len(rho)}, "
f"{planted[2]} of {len(withJ)}, {planted[3]} of {len(dbl)}, "
f"{planted[4]} of {len(main)}")
if not all(CHECKS[n0:]):
print(" CONTROL FAILED: K1 to K5 are not read.")
return
ok = agree((r.G2, r.LB2) for r in reads)
check("K1: G2 <= LB2 at the 511 sets", ok == 511,
f"{ok} of {len(reads)}")
ok = agree((x, 0.75) for x in rho)
check("K2: rho <= 3/4 at the 23084 indices of J", ok == 23084,
f"{ok} of {len(rho)}")
ok = agree((p.lam, p.bound) for p in withJ)
check("K3: Lambda <= log(S_(m-1)/S_j0) + 8W at the 576 pairs with an "
"index of J past j0", ok == 576, f"{ok} of {len(withJ)}")
ok = agree((p.D, 2 * p.last) for p in dbl)
check("K4: the doubling widths past j0 sum to at most twice the last, "
"at the 14 pairs with two or more", ok == 14,
f"{ok} of {len(dbl)}")
ok = agree((1 - p.d - 3 * e, p.sJ) for p, e in main)
check("K5: the J widths between j0 and m sum to at least 1 - delta - "
"3 eta at the 66 main-case triples", ok == 66,
f"{ok} of {len(main)}")
tops = (f"{max(rho):.4f}",
f"{max(p.lam / p.bound for p in withJ):.4f}",
f"{max(p.D / (2 * p.last) for p in dbl):.4f}",
f"{min(p.sJ - (1 - p.d - 3 * e) for p, e in main):.4f}")
check("the largest rho, Lambda over its bound and doubling widths "
"over twice their last, and K5's least margin, as first printed",
tops == PINS["rise"], ", ".join(tops))
print("P1: the limit's choice delta = 8/log m, eta = 2/sqrt(log m):")
ok = 0
for ex, pin in LIMIT:
L = ex * math.log(10)
v = f"{f3(L, 8 / L, 2 / math.sqrt(L)) * L:.4f}"
ok += v == pin
print(f" m = 10^{ex:<5d} F3 log m {v}")
check("P1: F3 log m at the limit's choice, m = 10^8 to 10^1024, by "
"hand", ok == 5, f"{ok} of {len(LIMIT)}")
def section_rearrange(pop, reads):
"""P2: E(P) against G2(sort P) over the general population, and
rounding against its own widths sorted."""
print("P2: E(P) against G2(sort P), and rounding against its sorted "
"widths")
withE = [r for r in reads if r.E is not None]
one = len(withE) - agree((r.G2x, r.E) for r in withE)
check("P2: a planted S' coefficient 1 fails G2(sort P) <= E at some "
"sets, not all, as first printed", one == PLANTS["P2"],
f"{one} of {len(withE)}")
if not CHECKS[-1]:
print(" CONTROL FAILED: P2 is not read.")
return
ok = agree((r.G2s, r.E) for r in withE)
check("P2: G2(sort P) <= E(P) at the 1200 sets with E", ok == 1200,
f"{ok} of {len(withE)}")
low, key = min((r.E / r.G2s, r.key) for r in withE)
check("P2: the least E(P)/G2(sort P) as first printed",
(f"{low:.4f}", key) == ("1.0066", "sorted"), f"{low:.4f} ({key})")
at = [n for n, r in enumerate(reads) if (r.key, r.m) == ("rounding", 162)]
cu = pop[at[0]][1]
up = cont_error(cuts_of(np.sort(np.diff(cu))))
ratio = f"{reads[at[0]].E / up:.6f}"
check("P2: rounding at m = 162 against its widths sorted increasing, "
"E(P)/E(sort P) as first printed",
len(at) == 1 and ratio == "0.570625", ratio)
def section_sorted():
"""C9, P3 and P4."""
print("E(P) and LB2(P) against G2(sort P) at fixed partitions")
ns = list(range(2, 61)) + [100, 200, 400, 800]
ok, worst = 0, 0.0
for n in ns:
E, _, G = against_sorted(h_grid(n))
d = (abs(E - (n * n + 3 * n - 1) / (8 * n * n)),
abs(G - (n * n + n - 0.5) / (8 * n * n)))
ok, worst = ok + sum(x < 1e-12 for x in d), max(worst, *d)
check("C9: (H1) and (H2) at n = 2..60, 100, 200, 400, 800",
(ok, len(ns)) == (126, 63),
f"{ok} of {2 * len(ns)}, max |diff| {worst:.1e}")
if not CHECKS[-1]:
print(" CONTROL FAILED: P3 and P4 are not read.")
return
E, two, G = against_sorted(WITNESS)
got = (f"{two / G:.6f}", f"{E / G:.6f}")
check("P3: the tent witness, LB2/G2(sort P) and E/G2(sort P) as first "
"printed", got == ("0.960165", "1.151538"), ", ".join(got))
rows = []
for name, n, _, _, _ in GRIDS:
w = h_grid(n) if name == "H" else top(n)
E, two, G = against_sorted(w)
rows.append((name, n, f"{len(w) * (E / G - 1):.3f}",
f"{len(w) * (two / G - 1):.3f}"))
check("P4: m(E/G2(sort P) - 1) and m(LB2/G2(sort P) - 1) on H_n and "
"the scaled grid, H_n's first by (H1) and (H2), the rest as "
"first printed", rows == [g[:4] for g in GRIDS],
"; ".join(f"{a} n = {n}: {x}, {y}" for a, n, x, y in rows))
def section_lb3():
"""C12, K7, P5 and P6."""
print("LB3: each cell charged w_a less the longest piece of I_a + y")
n0 = len(CHECKS)
n = k7t = k7e = c12t = c12e = 0
worst = -math.inf
for w in (WITNESS, h_grid(30), top(20), TIE, REARRANGED):
cu = cuts_of(w)
E, T, U = cell_errs(cu), tents(cu), shifts(cu)
n += E.size
k7t += int((T <= U + 1e-12).sum())
k7e += int((np.maximum(U, U.T) <= E + 1e-12).sum())
c12t += int((2 * T <= U + 1e-12).sum())
c12e += int((U + U.T <= E + 1e-12).sum())
worst = max(worst, (T - U).max(), (np.maximum(U, U.T) - E).max())
check("C12: 2T against U, and U + U^t in place of their max against "
"E, each fails at some cells, not all, as first printed",
(n - c12t, n - c12e) == PLANTS["C12"],
f"{n - c12t} and {n - c12e} of {n}")
if not all(CHECKS[n0:]):
print(" CONTROL FAILED: K7, P5 and P6 are not read.")
return
check("K7: T <= U and max(U_ab, U_ba) <= E_ab at the 1526 cells",
(k7t, k7e, n) == (1526, 1526, 1526),
f"{k7t} and {k7e} of {n}, max excess {worst:.1e}")
rows = []
for name, n, _, _, pin in GRIDS:
if pin is not None:
w = h_grid(n) if name == "H" else top(n)
rows.append((name, n, f"{len(w) * (lb3_over(w) - 1):.3f}"))
wit = f"{lb3_over(WITNESS):.6f}"
check("P5: LB3/G2(sort P) at the tent witness, and m(LB3/G2(sort P) - "
"1) on H_50, H_200 and the scaled grid at n = 200, as first "
"printed",
wit == "1.015148"
and rows == [(g[0], g[1], g[4]) for g in GRIDS if g[4] is not None],
f"{wit}; " + "; ".join(f"{a} n = {n}: {x}" for a, n, x in rows))
w = np.asarray(REARRANGED)
r = (pair_sum(shifts(cuts_of(w)))
/ pair_sum(shifts(cuts_of(np.sort(w)))))
check("P6: the rearrangement, LB3(P)/LB3(sort P) as first printed",
f"{r:.6f}" == "0.945197", f"{r:.6f}")
def section_lattice():
"""C14 and K9."""
print("LB3/G2(sort P) over the integer lattice, ties in")
n = ok2 = ok3 = 0
low, eq = (math.inf, None), []
for w in lattice():
G = sorted_g2(w)
cu = cuts_of(w)
two, three = pair_sum(tents(cu)), pair_sum(shifts(cu))
n += 1
ok2 += agree([(G, two)])
ok3 += agree([(G, three)])
low = min(low, (two / G, tuple(w.tolist())))
if abs(three / G - 1) <= 1e-9 and np.any(np.diff(w) < 0) \
and math.gcd(*w.tolist()) == 1:
eq.append(tuple(w.tolist()))
check("the lattice: every composition of N <= 12 and of at most five "
"parts to N = 20", n == 24209, f"{n} points")
got = (n - ok2, f"{low[0]:.6f}", low[1])
check("C14: LB2 in place of LB3 fails at some points, not all; its "
"count and its least as first printed",
got == (PLANTS["C14"], "0.962617", (1, 1, 4, 2, 5)),
f"{got[0]} of {n}, least {got[1]} at {got[2]}")
if not all(CHECKS[-2:]):
print(" CONTROL FAILED: K9 is not read.")
return
check("K9: G2(sort P) <= LB3(P) at the 24209 lattice points",
ok3 == 24209, f"{ok3} of {n}")
check("the primitive unsorted points within 1e-9 of equality are "
"(2, 4, 2, 5) and (1, 1, 4, 2, 5)",
eq == [(2, 4, 2, 5), (1, 1, 4, 2, 5)], f"{eq}")
def main():
section_controls()
if not all(CHECKS):
print("\nCONTROL FAILED: nothing below is read.")
raise SystemExit(1)
pop = list(general())
reads = section_chain(pop)
section_rise()
section_rearrange(pop, reads)
section_sorted()
section_lb3()
section_lattice()
print(f"{sum(CHECKS)}/{len(CHECKS)} checks passed")
raise SystemExit(0 if all(CHECKS) else 1)
if __name__ == "__main__":
main()