fates.py
Checks: SETS: An exact solver for the marginal optimum property; SETS: At equal masses the operative level forbids the wrong forced fates property; SETS: Off equal masses the condition fails both ways property; SETS: The rest's integer price decides the fate, the atom's own numbers do not property.
Cited on: SETS.
To run it: save fates.py, with sets.py beside it; standard library only.
"""fates.py -- which atoms the marginal optimum hands the empty set:
the abandonment condition at equal masses, its failure in both
directions off them, the death of every predicate on one atom's own
numbers, and the finite key that decides an atom's fate exactly.
QUESTION. A set rule minimizing expected set size under marginal
coverage T = 1 - alpha can give a whole atom the EMPTY SET, and an
auditor asking whether a subpopulation is served wants a test run on
that subpopulation alone. The certificate of sets.py serves every atom
carrying a label above the operative level t* and abandons every atom
whose whole row sits below it. When is that the optimum's own verdict,
what decides an atom when it is not, and how much of the rest of the
cell does the deciding need?
THE OBJECTS (sets.py's: cells, pairs, t*, the certificate, the
enumeration of size vectors). An atom's FATE is FORCED-ABANDONED if
every optimum gives it size 0, FORCED-SERVED if every optimum gives it
size at least 1, and OPEN otherwise. The ABANDONMENT CONDITION: no atom
with max p > t* is forced-abandoned and no atom with max p < t* is
forced-served. With P_s the sum of an atom's s largest posteriors and
Lambda(v) the least cost at which the OTHER atoms cover at least v (0 at
v <= 0, infinite when they cannot), the atom's REST KEY is
(w, its sorted row, Lambda(T - w P_s) for s = 0..k).
THE ARGUMENT (written before the engine).
(A) EQUAL MASSES (property). The certificate is an optimum there
(sets.py) and gives size 0 to every atom below t*, size at
least 1 to every atom above it: so no above-level atom is
forced-abandoned and no below-level atom forced-served. The
condition holds; nothing says every optimum agrees with the
certificate, and where the surplus covers a swap another optimum
trades an above-level pair for a tied one or one below the level.
(B) THE OUTNUMBERED ATOM. Eight atoms of mass 1/8, seven peaked at
0.86, 0.85, ..., 0.80 and one at (0.40, 0.32, 0.28): the seven
tops cover 5.81/8 = 0.72625 >= 0.70 and the tops down to 0.81
cover 5.01/8 < 0.70, so t* = 4/5 with b = 1. Seven labels are
the fewest reaching the bar (the seven largest posteriors of the
cell are those tops), and dropping any top for any other label
falls below it, so the optimum is unique: seven singletons and
the empty set at the eighth, OPT = 7/8. The abandoned atom is
not light, rare or adversarial; it is outnumbered. Split
conformal thresholds an estimate of the same posterior, so its
worst atom is predicted to read 0, as the optimum's eighth does.
(C) OFF EQUAL MASSES (property, by two exhibited cells).
ABOVE: w = (1/10, 9/20, 9/20), rows (1, 0, 0), (1, 0, 0),
(4/5, 1/5, 0), T = 7/10. t* = 4/5; a cost 9/10 needs sizes with
s_0/10 + 9(s_1 + s_2)/20 = 9/10, so s_0 = 0 and s_1 + s_2 = 2,
and only (0, 1, 1) covers (0.81); every cheaper vector buys at
most one heavy label and covers at most 11/20. The atom at
p = 1 > t* is forced-abandoned.
BELOW: w = (17/20, 1/10, 1/20), rows (4/5, 1/5, 0),
(4/5, 1/5, 0), (3/5, 2/5, 0). Level 4/5 covers 0.76, so t* = 4/5
and the third atom sits wholly below it. (1, 0, 1) costs 9/10 and
covers 0.68 + 0.03 = 0.71; the certificate (1, 1, 0) costs 19/20;
no other vector reaches the bar at 9/10 or less. The below-level
atom is forced-served.
(D) NO PREDICATE ON ONE ATOM (property, by an exhibited pair). A
predicate reading an atom's own mass, its row and the level is a
function of the key (w, sorted row, t*); two cells sharing that
key with opposite forced fates kill every such predicate at
once. Min-cost covering is not pointwise once purchases are lumpy.
(E) THE REST PRICE DECIDES (property). A rule of size s at an atom
is no better than its top-s prefix, and the rest of the cell is
bought separately, at the remainder the atom leaves, so
OPT = min_s [ s w + Lambda(T - w P_s) ].
The atom is forced-abandoned iff the s = 0 term is strictly
below every s >= 1 term, forced-served iff some s >= 1 term is
strictly below the s = 0 term, and open on a tie. So the rest
key, k + 3 numbers, decides the fate exactly. The THIRD ARM is
the same key with Lambda replaced by the rest's FRACTIONAL price (its
pairs bought greedily by posterior, the last one in part): if
that key never collides, the lumps do no work.
(F) WHEN SPLIT CONFORMAL CAN RETURN THE OPTIMUM (property; written
after the first engine, before this one). At the eight-atom cell
the TOP PAIRS are the seven (atom, its top label) of atoms 0 to
6, of mass 581/800 together. Split conformal keeps the pairs
whose estimate is within the idx-th smallest calibration score,
idx = ceil((c + 1) T) at c calibration points (every label when
idx > c, and then never the optimum's sets). If it returns the
optimum's sets, every calibration point scoring at or under
that quantile sits on a kept pair (the estimator's tolerance
only widens what is kept), and there are at least idx such
points, so the count C of calibration points on top pairs is at
least idx. C counts c independent draws, each on a top pair with
probability 581/800 (the sampler's weights are that to a
float), so a trial returns the optimum's sets with probability
at most
P(Bin(c, 581/800) >= idx),
and 20 independent trials all do with at most its 20th power.
The converse (C >= idx gives the optimum's sets) needs the seven
estimated tops above every other estimate and no six of them
holding idx points; it is counted, not proved.
DESIGN. A cell is enumerated once: every size vector with its cost and
coverage in sets.py's scaled integers, the optima those of least cost
covering T, each atom's rest prices read off the vectors empty at it.
One function, atom_row, reads an atom against its cell's optima: every
field 0 or 1 (its fate, where its top label sits against t*, a law's
clause), so a census is a sum of rows and a law is a count set against
its population's. cell_row reads sets.py's solver against the
enumeration. The cells are sets.py's sweep (400 equal-mass cells of
three or four atoms, 3,000 unequal three-atom cells) and a four-atom
arm: 1,500 cells, masses on the tenths and each at least 1/10 (so never
all equal), rows on the sweep's tenths, from a fixed seed. The census
is a seeded sample, so its laws are read at the recorded seed and at
two further seeds (--seeds a,b,... names others; the arm is seeded by
each plus 4), and the counts no law fixes are a seed's own, pinned.
Four law fields. Three read a proof: no wrong forced fate at an
equal-mass cell, either way ((A)), and sets.py's solver equal to the
enumeration (its (E), here also at four unequal atoms, which its own
sweep does not hold). One reads the engine: the fate (E)'s formula
gives from the rest prices equals the enumerated fate; both are read
off one table of prefix rules, so (E)'s prefix step is the proof's
alone. (A) is read where it can speak. At three equal atoms a rule
emptying an atom covers at most 2/3 < T, so every atom is
forced-served, and no row sits wholly below the level (the pairs at or
above t* would lie in two rows, 2 of the 2.1 units of 1/3 they must
cover): the sweep's 300 such cells read nothing of (A), and its 100
four-atom ones are a sample. So a second census takes EVERY equal-mass
cell of three or four atoms with rows on the tenths, a multiset of
rows a cell: the tenths hold 14 rows, so C(16, 3) = 560 cells at three
atoms and C(17, 4) = 2,380 at four.
The exhibited cells are held by hand, field by field. The eight-atom
cell is run through sets.py's split and Mondrian estimators (n in
{2000, 8000, 32000}, 20 trials, one seed a trial: a record of one
stream), each trial classed by three bits (C >= idx, the sets the
optimum's, the worst atom at exact coverage 0); 200 more trials at
n = 2000 read (F) where it can miss, and the tail is exact, its terms
integers.
CONTROLS (before any census is read; a failure stops the run).
K1 (the arm) 1,500 cells of four masses in tenths, none under 1/10,
none equal-mass, every row one of the sweep's.
K2 (the rows) four hand cells, 14 atoms. E6: four atoms of 1/4, rows
(3/5, 3/10, 1/10), (1/2, 2/5, 1/10), (1, 0, 0), (3/5, 3/10, 1/10);
in units of 1/4 the bar is 2.8, the four largest posteriors sum
to 2.7 and five to 3.1, so t* 2/5, b 1, CERT = OPT = 5/4; the
five-pair rules reaching 2.8 hold atom 2's label and (1, 2, 1),
(2, 1, 1), (1, 1, 2), (2, 2, 0), (0, 2, 2) or (2, 0, 2) at the
others: six optima, fates O, O, S, O, every atom above the level.
EB: four atoms of 1/4, rows (1, 0, 0), (1, 0, 0), (1/2, 1/2, 0),
(2/5, 2/5, 1/5); level 1 sums to 2 and 1/2 to 3, so t* 1/2, b 2,
CERT = OPT = 1; the four-pair rules reaching 2.8 are (1, 1, 2, 0),
(1, 1, 1, 1), (1, 1, 0, 2): fates S, S, O, O, atom 2 at the level,
atom 3 wholly below it and served by two optima. ABOVE and BELOW
of (C): fates A, S, S and S, A, S, ABOVE's atom 2 and BELOW's
atoms 0 and 1 at the level. Summed: 14 atoms, 2 A, 7 S, 5 O; 8 at
equal masses, 6 above the level and 1 below, 3 above ones
abandoned by some optimum, the below one served by some, none
forced the wrong way; off equal masses one above-level atom
forced-abandoned and one below-level forced-served; the formula
at 14. Six planted rows, a hand cell's optima cut to one of them
so that an atom reads forced: 26 named fields, the two law fields
of (A) moving to 1 on an above-level atom emptied and a
below-level one served, and staying 0 on an atom at the level.
The cell row: the solver equal to enumeration at the nine hand
cells, and not at one whose optimum is moved by a unit. The law
count: 4 on a census at its populations, 3 on each of the 4 with
one law field moved by one.
K3 (the keys) over five hand cells (DA, DS, E6, FA, FS, below) the
forced atoms carry 11 distinct (w, sorted row, t*), 2 of them
with both forced fates (DA's and DS's atom 2; FA's atom 0 and
FS's atom 2, which share t* 3/10 too), both strictly off the
level; on the fractional key 12 distinct, 1 with both (DA's and
DS's first fractional prices are 59/50 and 7/5). BELOW's heavy
atom, mass 17/20: the rest covers at most 3/20, so no price at
s = 0; its top leaves 1/50, bought whole by the lightest atom's
top at 1/20 and in part from the middle atom's 4/5 at 1/40; then
nothing is owed. Prices none, 1/20, 0, 0; fractional none, 1/40,
0, 0; the formula reads it served.
K4 (the estimator's reading) the index ceil((c + 1) T) is 7 at
c = 9, 8 at 10 and 701 at 1,000, where ceil(c T) is 7, 7 and 700.
Two hand samples of 20, the first ten training: a top pair at
each of atoms 0 to 6 and atom 7 at labels 1, 2, 1, so phat is
(1, 0, 0) seven times and (0, 2/3, 1/3); idx = 8 of ten. HIT
calibrates on the seven top pairs, atom 0's again, and atom 7 at
labels 1 and 2: scores 0 eight times, 1/3, 2/3; the 8th is 0,
split keeps phat >= 1: the optimum's sets, C = 8, worst atom 0,
marginal 581/800; Mondrian takes every label at every atom (each
index passes its count), worst atom 1. MISS calibrates on the
seven top pairs and atom 7 at labels 1, 1, 2: C = 7, one short;
scores 0 seven times, 1/3 twice, 2/3; the 8th is 1/3, split keeps
phat >= 2/3, the tops and {1} at atom 7: worst atom 8/25,
marginal 613/800; Mondrian's atom 7 has index 3 of three scores,
2/3, and keeps {1, 2}: worst atom 3/5. The census of trials on
three rows built field by field, one reaching idx without the
optimum's sets and two holding them short of it: 3 trials, the
two classes at 1 and 2, 2 strays, sums 1 and 5/4. A rule of
atom 0's labels 0 and 1 and atom 7's label 2 covers (0.86 + 0.09
+ 0.28)/8 = 123/800.
K5 (the tail) a bound prints rounded up: 1/3 to two places 0.34,
1/4 0.25. P(Bin(4, 1/2) >= 3) = 5/16; P(Bin(3, 2/3) >= 2) =
20/27, >= 0 is 1, >= 4 is 0.
THE EXHIBITED CELLS (each figure by hand; read after the controls, in
the section of its claim; STRADDLE, ABOVE and BELOW are (B)'s and
(C)'s). Rows are written largest first; E6's atom 0, DS's atom 2 and
FS's atom 2 are entered with their labels in another order, which a
row read unsorted misreads.
STRADDLE six tops above the level and the 0.80 tied: CERT 7/8.
ABOVE b 1, CERT 1 (above cost 11/20, the tied pair 9/20).
BELOW nothing above the level, b 2; the fill needs tied cost
7/8, and of 17/20, 1/10, 19/20 the least reaching it is
19/20 = CERT. Below cost 9/10 only the heavy atom's top
fits, alone: 17/25 at most. Without the heavy atom the
others' whole rows cover 3/20.
DA w (11/20, 7/20, 1/10), rows (7/10, 3/10, 0), (1/2, 1/2, 0),
(1, 0, 0). The pairs at 7/10 or more cover 97/200, those
at 1/2 or more 167/200: t* 1/2, b 2. Above cost 13/20,
deficit 43/200,
tied cost needed 43/100, each tied pair 7/20: CERT 27/20.
With s_0 = 1 the others owe 63/200: atom 1 whole (7/20, at
7/10), its top with atom 2 giving only 11/40; with s_0 = 2
(11/10) atom 1's top is still needed, 29/20; with s_0 = 0
they reach 9/20. One optimum (1, 2, 0), OPT 5/4, covering
147/200, fates S, S, A; least cost without atom 2: 5/4.
DS w (3/5, 3/10, 1/10), rows (1/2, 1/2, 0), (1/2, 2/5, 1/10),
(1, 0, 0). The pair at 1 covers 1/10, those at 1/2 or more
17/20: t* 1/2,
b 3; above cost 1/10, deficit 3/5, tied cost needed 6/5,
atom 0's two pairs: CERT 13/10. Without atom 2, (2, 1)
covers 3/4 at 3/2 and (1, 3) only 3/5: 3/2. With it 3/5 is
owed: (2, 0) at 6/5, (1, 3) at 3/2. One optimum (2, 0, 1),
OPT 13/10, covering 7/10 exactly, fates S, A, S. Its atom
2 has DA's atom 2's key, (1/10, (1, 0, 0), 1/2).
FA w (1/20, 1/20, 9/10), rows (1/2, 3/10, 1/5), (2/5, 2/5,
1/5), (1/2, 3/10, 1/5), read at atom 0, which leaves 7/10,
27/40, 33/50, 13/20. The others cover any of the four only
with the heavy atom at size 2 (18/25 at 9/5; its top and
atom 1 whole give 1/2): integer prices 9/5 four times, the
s = 0 term strictly least. One optimum (0, 0, 2), OPT 9/5,
covering 18/25, fates A, A, S; the pairs at 2/5 or more
cover 103/200, so t* 3/10, b 2, above cost 21/20, tied cost
needed 37/60, the heavy tied pair: CERT 39/20. Fractional:
9/20 at 9/10, two pairs of 1/50 at 1/20 each, then the
heavy 3/10 pair in part, 1 + (v - 49/100)/(3/10): 17/10,
97/60, 47/30, 23/15.
FS w (7/20, 3/5, 1/20), three rows (1/2, 3/10, 1/5), read at
atom 2: FA's atom 0's mass, row and remainders. Sizes
(a, b) at the others cost 7a/20 + 3b/5: (1, 2) covers
131/200 at 31/20, (2, 2) covers 19/25 at 19/10, (3, 1)
covers 13/20 at 33/20. Integer prices 19/10, 19/10, 19/10,
31/20; terms 19/10, 39/20, 2, 17/10: forced-served, at
size 3. One optimum (1, 2, 3), OPT 17/10, covering
141/200, fates S, S, S; t* 3/10, b 3, above cost 1, tied
cost needed 2/3, least sum 19/20: CERT 39/20. Fractional:
3/10 at 3/5, 7/40 at 7/20, then 3/10 pairs in part,
19/20 + (v - 19/40)/(3/10): the same four. The pair is the
earlier engine's print, each figure then derived by hand.
PREDICTIONS (K1 to P6 fixed before the first engine, its K1 and K2
that engine's controls and not the K1 and K2 above; figures carried
from an earlier record are TRANSPLANTS until
re-measured. Pa to Pf fixed before this engine, for what no function
printed; Pg before the grid ran, after this engine's first run printed
no below-level atom at the recorded seed's equal-mass cells).
K1 CONTROL: at the eight-atom cell, sets.py's solver equals the
enumeration.
K2 CONTROL: the fate counter reads a forced-abandoned and a
forced-served atom somewhere in the sweep or the four-atom arm (it
can print both).
P1 (A) the condition holds at every atom of every equal-weight cell;
the counts of atoms whose fate some optimum reverses are printed.
P2 (B) t* = 4/5, b = 1, OPT = 7/8, one optimum, the eighth atom
empty; split conformal's worst atom at exact coverage 0 in every
trial at every n (TRANSPLANT) with mean marginal coverage at least
0.70; Mondrian's worst atom at least 0.6 on average at n = 32000.
P3 (C) both witnesses as derived: one optimum each, the named atom
forced-abandoned (ABOVE) and forced-served (BELOW).
P4 (D) some key (w, sorted row, t*) carries a forced-abandoned atom
in one cell and a forced-served one in another (TRANSPLANT).
P5 (E) the fate read off the rest key by the formula equals the
enumerated fate at every atom of every cell.
P6 the fractional key collides: some (w, sorted row, fractional
prices) carries both forced fates (TRANSPLANT).
Pa split returns the optimum's sets in all 60 recorded trials, each
marginal exactly 581/800 (the earlier print's 0.7262 beside 20 of
20 at coverage 0; one other trial would move the mean by 0.0006),
C >= idx in all 60; Mondrian's worst-atom means are 383/500, 3/4
and 18/25 (a mean of 20 hundredths is a multiple of 1/2000).
Pb over the 200 further trials: none with the optimum's sets and
C < 701; both other classes occur; C >= 701 in about 200 times
the tail, near 0.97 by a normal estimate, so about 193; the worst
atom at 0 in exactly the trials with the optimum's sets. A trial
reaching 701 without the optimum's sets: expected in none, not
proved.
Pc the solver equals the enumeration at all 4,900 cells.
Pd 4,900 cells, 400 equal-mass, 16,300 atoms, 1,300 at equal masses,
at every seed; the below-level atoms at equal masses are few.
Pe at two further seeds the four laws hold, and the counts no law
fixes move.
Pf the earlier engine's counts reprint at the recorded seed: 28
above-level atoms abandoned by some optimum and no below-level
one served, 276 of 1,255 keys with both forced fates, 206
strictly off the level, 115 of 12,190 fractional keys.
Pg on the grid: 560 cells and 1,680 atoms at three atoms, 2,380 and
9,520 at four; no wrong forced fate, the solver and the formula
at every cell and atom; no below-level atom at three atoms; some
at four, EB's among them, some of them served by an optimum.
KILL. A control off: nothing is read. A wrong forced fate at an
equal-mass cell, at any seed or on the grid, a cell where the solver
misses the enumeration, or a trial returning the optimum's sets with
C < idx: a proof above is wrong ((A), sets.py's solver, (F)). The
formula off at an atom, or a population off: the engine is wrong. P3,
P4 or P6 off: an argument above is wrong; P6 off, the fractional price
decides, and the claim that the lumps do the work dies. A count of the
recorded seed's moved by this engine from the earlier engine's print:
the rewrite changed what it reads.
FINDINGS. No kill fired: every control held, every law count met its
population at the recorded seed, at two further seeds and on the grid,
and every count of the earlier engine's print reprints (28 and 0, 276
of 1,255, 206, 16,300, 115 of 12,190). Not reprinted: the earlier
lines for the witnesses, the pair of (D) and the fractional pair, now
hand rows compared field by field; the float marginal 0.7262 and
Mondrian's 0.7660, 0.7500, 0.7200, now exact. Three frozen clauses
were off. (A) had the other optimum buy a tied pair only, where E6's
buys one below the level (repaired above).
(E)'s rest key is 2k + 2 numbers (mass, row, k + 1 prices), not
k + 3; the k + 1 sums s w + Lambda(T - w P_s) alone decide the fate.
And P1 read less than it says: the recorded seed's equal-mass cells
hold no atom wholly below the level, so its second half was read on
nothing, and its three-atom cells cannot abandon an atom at all; the
grid reads both halves.
controls K1 1,500 of 1,500 cells. K2 14 of 14 summed fields, 26 of
26 planted fields, the solver at 9 of 9 hand cells and at
neither moved one, the law count 4, and 3 at each of 4
plants. K3 the five cells' key counts and BELOW's heavy
atom as by hand. K4 the index, both samples, the built
rows and the two-label marginal. K5 the rounding and the
four tails.
census the recorded seed: 4,900 cells, 400 equal-mass; 16,300
atoms, 1,300 at equal masses; 1,616 forced-abandoned,
13,741 forced-served, 943 open. The solver equals the
enumeration at 4,900 of 4,900 cells (Pc), 1,500 of them the
four-atom arm's. Off equal masses 784 above-level atoms
are forced-abandoned and 45 below-level ones forced-served.
equal the recorded seed: 955 above-level atoms at equal masses,
none forced-abandoned, 28 abandoned by some optimum; no
below-level atom. E6 and EB as by hand: E6's optimum (0, 2,
1, 2), one of six at the certificate's cost 5/4, drops the
first atom's 3/5 and buys the fourth's 3/10, below the
level, covering exactly 7/10; EB's (1, 1, 1, 1) and (1, 1,
0, 2) serve the atom wholly below the level.
grid 560 cells at three atoms: all 1,680 atoms forced-served,
1,227 of them above the level, none below it. 2,380 cells
at four: 7,216 atoms above the level, none forced-abandoned,
846 abandoned by some optimum; 77 below it, none
forced-served, 15 served by some optimum. The solver and
the formula at every cell and atom of both (Pg).
straddle t* 4/5, b 1, CERT = OPT = 7/8, the one optimum (1, ..., 1,
0) covering 581/800. Split returned the optimum's own sets
in 20 of 20 trials at every n (Pa): marginal 581/800 each,
the eighth atom at coverage 0, the calibration half
holding idx (701, 2,801, 11,201) top pairs. Mondrian's
worst atom, trial mean: 383/500, 3/4, 18/25. Over 200
further trials at n = 2000 (Pb): 194 with idx reached, the
optimum's sets and the worst atom at 0; 6 with none of the
three; no other class, so the converse of (F) held in all
200. (F)'s bound, rounded up: 0.965196 at n = 2000,
0.999881 at 8000, 1 less about 8.593e-14 at 32000; 20
trials all return the optimum's sets with probability at
most 0.4924, 0.9977, 1, so the 20 of 20 at n = 2000 is
this stream's.
witnesses ABOVE: CERT 1, OPT 9/10, one optimum (0, 1, 1) covering
81/100, the p = 1 atom forced-abandoned, at most 11/20
below cost 9/10. BELOW: CERT 19/20, OPT 9/10, one optimum
(1, 0, 1) covering 71/100, the atom peaking at 3/5 < t* =
4/5 forced-served, at most 17/25 below cost 9/10 and 3/20
without the heavy atom.
dead DA and DS as by hand: the atom of mass 1/10 and row (1, 0,
0), at t* = 1/2 in both, is abandoned by DA's one optimum
(1, 2, 0), costing 5/4, and served by DS's one optimum (2,
0, 1), costing 13/10, every rule without it costing at
least 3/2. At the recorded seed 276 of the 1,255 keys (w,
sorted row, t*) the forced atoms carry hold both forced
fates, 206 with the atom's top label off the level.
rest the formula equals the enumerated fate at 16,300 of 16,300
atoms (P5). FA and FS as by hand: the atom of mass 1/20
and row (1/2, 3/10, 1/5) meets fractional prices 17/10,
97/60, 47/30, 23/15 in both, integer prices 9/5 four times
in FA and 19/10, 19/10, 19/10, 31/20 in FS: abandoned by
FA's one optimum (0, 0, 2), served whole by FS's one
optimum (1, 2, 3). The two cells share t* = 3/10, so the
pair is a second one for (D). At the recorded seed 115 of
12,190 fractional keys carry both forced fates.
seeds Pe held: at seeds 20260933 and 20260934 the four laws met
their populations and the counts no law fixes moved (1 and
3 below-level atoms at equal masses, 0 and 1 of them served
by some optimum; 36 and 26 above-level ones abandoned by
some; 271 of 1,258 and 270 of 1,251 keys with both forced
fates; 112 of 12,149 and 125 of 12,146 fractional).
pins entered from this engine's first prints: the fate census,
the wrong forced fates off equal masses, the 955 and the
no below-level atom of the recorded seed, the grid's five
counts, the further trials' classes, the tails, the
further seeds' counts and the number of check lines. From
the earlier print: 28, 0, 276, 1,255, 206, 115, 12,190, and
Mondrian's means by one step of arithmetic. That every atom
is forced-served at three equal atoms was derived on the
grid's first print, which showed no above-level atom
abandoned there. Every other pin is a hand value.
mutants one token changed at each of 210 sites of the engine: 208
runs turn red, 2 move no line, each equivalent here: a
need of exactly 0 priced through the first pair, 0 either
way; a ninth tenth allowed to a mass, which four positive
tenths summing to 10 never reach. Nine checks are failed
by no mutant: the rounding, whose function holds no site,
and eight standing behind the control stop. Each fails to
one of fourteen edits by hand with the stop lifted (the
rounding to
nearest, the solver's field never true, the first law
field counting every abandoned above-level atom, the
tail's loop a term short, the rest price free to use the
atom itself, the fractional price buying the atom's own
pairs, the formula reading a tie as served, a section
skipped).
RUN RECORD. python fates.py: 46 of 46 checks, 9.1 s, peak commit
167.6 MB under a memory guard (512 MB).
"""
import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import random
import sys
import time
from fractions import Fraction as F
from itertools import combinations_with_replacement, product
from math import ceil
from sets import (Anatomy, Cell, FURTHER, NS, SEED, T, TENTHS, TRIALS,
census, conformal_sets, draw_pairs, rule_value, solve,
sweep, worst_exact)
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))
# ------------------------------------------------------------- cells
def row(*xs):
return [F(x, 100) for x in xs]
STRADDLE = Cell("STRADDLE", [F(1, 8)] * 8,
[row(86, 9, 5), row(85, 11, 4), row(84, 13, 3),
row(83, 15, 2), row(82, 17, 1), row(81, 12, 7),
row(80, 14, 6), row(40, 32, 28)])
ABOVE = Cell("ABOVE", [F(1, 10), F(9, 20), F(9, 20)],
[row(100, 0, 0), row(100, 0, 0), row(80, 20, 0)])
BELOW = Cell("BELOW", [F(17, 20), F(1, 10), F(1, 20)],
[row(80, 20, 0), row(80, 20, 0), row(60, 40, 0)])
DA = Cell("DA", [F(11, 20), F(7, 20), F(1, 10)],
[row(70, 30, 0), row(50, 50, 0), row(100, 0, 0)])
DS = Cell("DS", [F(3, 5), F(3, 10), F(1, 10)],
[row(50, 50, 0), row(50, 40, 10), row(0, 100, 0)])
FA = Cell("FA", [F(1, 20), F(1, 20), F(9, 10)],
[row(50, 30, 20), row(40, 40, 20), row(50, 30, 20)])
FS = Cell("FS", [F(7, 20), F(3, 5), F(1, 20)],
[row(50, 30, 20), row(50, 30, 20), row(30, 20, 50)])
E6 = Cell("E6", [F(1, 4)] * 4,
[row(10, 60, 30), row(50, 40, 10), row(100, 0, 0),
row(60, 30, 10)])
EB = Cell("EB", [F(1, 4)] * 4,
[row(100, 0, 0), row(100, 0, 0), row(50, 50, 0),
row(40, 40, 20)])
def four_arm(seed=SEED):
"""1,500 four-atom cells: masses on the tenths, each at least 1/10,
rows on the sweep's tenths."""
rng = random.Random(seed + 4)
comps = [c for c in product(range(1, 8), repeat=4) if sum(c) == 10]
return [Cell(f"Q{i}", [F(x, 10) for x in rng.choice(comps)],
[rng.choice(TENTHS) for _ in range(4)])
for i in range(1500)]
# ------------------------------------------------------- the engine
class Fates:
"""A cell enumerated: every size vector with its (cost, coverage),
scaled as sets.py's Anatomy scales them, the optima, and each
atom's rest prices at the k + 1 remainders its prefixes leave,
integer and fractional."""
def __init__(self, cell):
self.cell = cell
an = self.an = Anatomy(cell)
sc, M, k = an.sc, cell.M, cell.k
self.table = {sz: rule_value(an, sz)
for sz in product(range(k + 1), repeat=M)}
self.opt = min(c for c, v in self.table.values() if v >= sc.TQ)
self.opts = [sz for sz, (c, v) in self.table.items()
if v >= sc.TQ and c == self.opt]
self.rest = [[self.price(r, sc.TQ - sc.V[r][s])
for s in range(k + 1)] for r in range(M)]
self.lp = [[self.fractional(r, sc.TQ - sc.V[r][s])
for s in range(k + 1)] for r in range(M)]
def price(self, r, need):
"""The least cost of a size vector empty at r covering need;
None when none does."""
costs = [c for sz, (c, v) in self.table.items()
if sz[r] == 0 and v >= need]
return min(costs) if costs else None
def fractional(self, r, need):
"""The same with the other atoms' pairs bought by posterior, the
last one in part."""
if need <= 0:
return F(0)
sc, cell = self.an.sc, self.cell
pairs = sorted(((cell.srt[q][i], q) for q in range(cell.M)
if q != r for i in range(cell.k)), reverse=True)
cost = F(0)
for p, q in pairs:
cov = sc.W[q] * p
if cov >= need:
return cost + F(need) / p
cost += sc.W[q]
need -= cov
return None
def fate_of(self, r):
"""A, S or O, read off the optima."""
sizes = {o[r] > 0 for o in self.opts}
return "O" if len(sizes) == 2 else "S" if True in sizes else "A"
def predicted(self, r):
"""The fate (E)'s formula gives from the rest prices. The s = k
term is never missing: the full row leaves T - w, and the
others cover 1 - w."""
w = self.an.sc.W[r]
terms = [None if R is None else s * w + R
for s, R in enumerate(self.rest[r])]
z, served = terms[0], min(x for x in terms[1:] if x is not None)
if z is None or served < z:
return "S"
return "A" if z < served else "O"
def value(self, x):
return F(x) / self.an.sc.Q
def prices(self, r):
"""Atom r's rest prices, unscaled."""
return [None if x is None else self.value(x) for x in self.rest[r]]
def fractions(self, r):
return [None if x is None else self.value(x) for x in self.lp[r]]
def key(self, r):
c = self.cell
return (c.w[r], tuple(c.srt[r]), self.an.t)
def fkey(self, r):
c = self.cell
return (c.w[r], tuple(c.srt[r]), tuple(self.fractions(r)))
def most_below(self, bound):
"""The most coverage of a size vector costing less than bound."""
return max(self.value(v) for c, v in self.table.values()
if self.value(c) < bound)
def most_without(self, r):
"""The most coverage of a size vector empty at r."""
return max(self.value(v) for sz, (c, v) in self.table.items()
if sz[r] == 0)
def figures(x):
"""A cell's exact figures, unscaled: what the hand rows are read
against."""
return {"t": x.an.t, "b": x.an.m, "CERT": x.value(x.an.cert),
"OPT": x.value(x.opt), "optima": x.opts,
"covers": [x.value(x.table[o][1]) for o in x.opts],
"fates": "".join(x.fate_of(r) for r in range(x.cell.M))}
def atom_row(x, r):
"""One atom read against its cell's optima: every field 0 or 1, so
that a census is a sum of rows."""
top, t = x.cell.srt[r][0], x.an.t
eq = x.cell.equal()
f = x.fate_of(r)
return {
"atoms": 1,
"A": f == "A",
"S": f == "S",
"O": f == "O",
"equal": eq,
"eq_above": eq and top > t,
"eq_below": eq and top < t,
"eq_A": eq and top > t and f == "A",
"eq_S": eq and top < t and f == "S",
"eq_drop": eq and top > t and f != "S",
"eq_buy": eq and top < t and f != "A",
"off_A": not eq and top > t and f == "A",
"off_S": not eq and top < t and f == "S",
"formula": x.predicted(r) == f,
}
def cell_row(x):
"""One cell: sets.py's solver read against the enumeration."""
return {"cells": 1, "equal_cells": x.cell.equal(),
"solver": solve(x.an)[0] == x.opt}
def collisions(fates, keyf):
"""The fates each key of keyf carries over the forced atoms, and
the keys carrying both."""
seen = {}
for x in fates:
for r in range(x.cell.M):
f = x.fate_of(r)
if f != "O":
seen.setdefault(keyf(x, r), set()).add(f)
return seen, [key for key, v in seen.items() if len(v) == 2]
def key_counts(fates):
"""How many keys (w, sorted row, t*) the forced atoms carry, how
many carry both forced fates, how many of those with the atom's top
label off the level; and the first two for the fractional key."""
seen, both = collisions(fates, lambda x, r: x.key(r))
fseen, fboth = collisions(fates, lambda x, r: x.fkey(r))
return {"keys": len(seen), "both": len(both),
"strict": sum(key[1][0] != key[2] for key in both),
"fkeys": len(fseen), "fboth": len(fboth)}
def equal_grid(M):
"""Every equal-mass cell of M atoms with rows on the sweep's tenths,
a multiset of rows a cell."""
return [Cell(f"G{M}.{i}", [F(1, M)] * M, rows) for i, rows in
enumerate(combinations_with_replacement(TENTHS, M))]
def read_cells(cells):
"""A census: the cells' atom rows and cell rows, summed, and their
key counts."""
fates = [Fates(c) for c in cells]
tot = census(atom_row(x, r) for x in fates for r in range(x.cell.M))
tot.update(census(cell_row(x) for x in fates))
tot.update(key_counts(fates))
return tot
def read_seed(seed):
"""A seed's census: sets.py's sweep and the four-atom arm."""
return read_cells(sweep(seed) + four_arm(seed))
# A law field counts its population; a forbidden field counts nothing.
LAWS = (("eq_A", None), ("eq_S", None), ("solver", "cells"),
("formula", "atoms"))
SIZES = {"cells": 4900, "equal_cells": 400, "atoms": 16300, "equal": 1300}
GRID = {3: {"cells": 560, "equal_cells": 560, "atoms": 1680, "equal": 1680},
4: {"cells": 2380, "equal_cells": 2380, "atoms": 9520,
"equal": 9520}}
def laws_held(tot):
"""How many of LAWS a census satisfies."""
return sum(tot[f] == (tot[pop] if pop else 0) for f, pop in LAWS)
# ------------------------------------------------- the estimator's arm
OPTSETS = [[0]] * 7 + [[]]
def marginal(cell, sets):
"""A rule's exact marginal coverage."""
return sum((cell.w[r] * cell.p[r][y] for r in range(cell.M)
for y in sets[r]), F(0))
def quantile_index(c):
"""The estimator's index at c calibration points: its quantile is
the ceil((c + 1) T)-th smallest score."""
return ceil((c + 1) * T)
def trial_read(data):
"""One sample through sets.py's estimators at the eight-atom cell:
whether its calibration half (the second, as the estimator splits)
holds idx top pairs, whether split's sets are the optimum's, whether
split's worst atom is at exact coverage 0, split's marginal and
Mondrian's worst atom."""
split, mond = conformal_sets(data, STRADDLE.M, STRADDLE.k)
cal = data[len(data) // 2:]
tops = sum(r < 7 and y == 0 for r, y in cal)
return {"reach": tops >= quantile_index(len(cal)),
"same": split == OPTSETS,
"zero": worst_exact(STRADDLE, split) == 0,
"marg": marginal(STRADDLE, split),
"mw": worst_exact(STRADDLE, mond)}
def trial_rows(n, first, count):
"""count samples of n draws, numbered from first, one seed a trial,
each through trial_read."""
for tr in range(first, first + count):
rng = random.Random(SEED + 7000 + 10 * n + tr)
yield trial_read(draw_pairs(STRADDLE, n, rng))
def trial_census(rows):
"""Trial rows summed: the trials, each class (reach, same, zero)
counted, the STRAYS (the optimum's sets short of idx, which (F)
forbids), and the sums of split's marginal and Mondrian's worst
atom."""
tot = {"trials": 0, "classes": {}, "stray": 0, "marg": F(0),
"mw": F(0)}
for got in rows:
key = (got["reach"], got["same"], got["zero"])
tot["trials"] += 1
tot["classes"][key] = tot["classes"].get(key, 0) + 1
tot["stray"] += got["same"] and not got["reach"]
tot["marg"] += got["marg"]
tot["mw"] += got["mw"]
return tot
def upward(x, places):
"""x to so many decimal places, rounded up: a bound printed keeps
its direction."""
return f"{ceil(x * 10 ** places) / 10 ** places:.{places}f}"
def tail(c, p, m):
"""P(Bin(c, p) >= m), exact: with p = a/d the terms
C(c, j) a^j (d - a)^(c - j) are integers, each from the one above
it, summed down from j = c."""
a, d = p.numerator, p.denominator
term, total = a ** c, 0
for j in range(c, m - 1, -1):
total += term
term = term * j * (d - a) // ((c - j + 1) * a)
return F(total, d ** c)
# ------------------------------------------------ hand rows and pins
HAND = {
"STRADDLE": {"t": F(4, 5), "b": 1, "CERT": F(7, 8), "OPT": F(7, 8),
"optima": [(1,) * 7 + (0,)], "covers": [F(581, 800)],
"fates": "SSSSSSSA"},
"ABOVE": {"t": F(4, 5), "b": 1, "CERT": F(1), "OPT": F(9, 10),
"optima": [(0, 1, 1)], "covers": [F(81, 100)],
"fates": "ASS"},
"BELOW": {"t": F(4, 5), "b": 2, "CERT": F(19, 20), "OPT": F(9, 10),
"optima": [(1, 0, 1)], "covers": [F(71, 100)],
"fates": "SAS"},
"DA": {"t": F(1, 2), "b": 2, "CERT": F(27, 20), "OPT": F(5, 4),
"optima": [(1, 2, 0)], "covers": [F(147, 200)], "fates": "SSA"},
"DS": {"t": F(1, 2), "b": 3, "CERT": F(13, 10), "OPT": F(13, 10),
"optima": [(2, 0, 1)], "covers": [F(7, 10)], "fates": "SAS"},
"FA": {"t": F(3, 10), "b": 2, "CERT": F(39, 20), "OPT": F(9, 5),
"optima": [(0, 0, 2)], "covers": [F(18, 25)], "fates": "AAS"},
"FS": {"t": F(3, 10), "b": 3, "CERT": F(39, 20), "OPT": F(17, 10),
"optima": [(1, 2, 3)], "covers": [F(141, 200)], "fates": "SSS"},
"E6": {"t": F(2, 5), "b": 1, "CERT": F(5, 4), "OPT": F(5, 4),
"optima": [(0, 2, 1, 2), (1, 1, 1, 2), (1, 2, 1, 1),
(2, 0, 1, 2), (2, 1, 1, 1), (2, 2, 1, 0)],
"covers": [F(7, 10), F(3, 4), F(31, 40), F(7, 10), F(3, 4),
F(7, 10)],
"fates": "OOSO"},
"EB": {"t": F(1, 2), "b": 2, "CERT": F(1), "OPT": F(1),
"optima": [(1, 1, 0, 2), (1, 1, 1, 1), (1, 1, 2, 0)],
"covers": [F(7, 10), F(29, 40), F(3, 4)], "fates": "SSOO"},
}
ROWS_HAND = {"atoms": 14, "A": 2, "S": 7, "O": 5, "equal": 8,
"eq_above": 6, "eq_below": 1, "eq_A": 0, "eq_S": 0,
"eq_drop": 3, "eq_buy": 1, "off_A": 1, "off_S": 1,
"formula": 14}
# (cell, the one optimum its optima are cut to, atom, fields by hand)
PLANTS = (
("E6", (0, 2, 1, 2), 0, {"A": 1, "eq_A": 1, "eq_drop": 1, "off_A": 0,
"formula": 0}),
("E6", (1, 2, 1, 1), 0, {"S": 1, "eq_A": 0, "eq_drop": 0}),
("EB", (1, 1, 0, 2), 3, {"S": 1, "eq_S": 1, "eq_buy": 1, "off_S": 0,
"formula": 0}),
("EB", (1, 1, 2, 0), 3, {"A": 1, "eq_S": 0, "eq_buy": 0, "eq_A": 0,
"eq_below": 1}),
("EB", (1, 1, 0, 2), 2, {"A": 1, "eq_A": 0, "eq_drop": 0,
"eq_above": 0, "eq_below": 0}),
("EB", (1, 1, 2, 0), 2, {"S": 1, "eq_S": 0, "eq_buy": 0}),
)
TOPS = [(r, 0) for r in range(7)]
TRAIN = TOPS + [(7, 1), (7, 2), (7, 1)]
HIT = TRAIN + TOPS + [(0, 0), (7, 1), (7, 2)]
MISS = TRAIN + TOPS + [(7, 1), (7, 1), (7, 2)]
BUILT = [{"reach": True, "same": False, "zero": False, "marg": F(1, 2),
"mw": F(1, 4)}] + [{"reach": False, "same": True, "zero": True,
"marg": F(1, 4), "mw": F(1, 2)}] * 2
# The recorded seed's counts no law fixes, a section each.
PIN_CENSUS = {"A": 1616, "S": 13741, "O": 943, "off_A": 784, "off_S": 45}
PIN_EQUAL = {"eq_above": 955, "eq_below": 0, "eq_drop": 28, "eq_buy": 0}
GRID_PIN = {3: {"eq_above": 1227},
4: {"eq_above": 7216, "eq_below": 77, "eq_drop": 846,
"eq_buy": 15}}
PIN_KEYS = {"keys": 1255, "both": 276, "strict": 206}
PIN_FRAC = {"fkeys": 12190, "fboth": 115}
OWN = ("eq_below", "eq_drop", "eq_buy", "both", "keys", "fboth", "fkeys")
SEED_PIN = {SEED + 5: (1, 36, 0, 271, 1258, 112, 12149),
SEED + 6: (3, 26, 1, 270, 1251, 125, 12146)}
MW_PIN = {2000: F(383, 500), 8000: F(3, 4), 32000: F(18, 25)}
FURTHER_TRIALS = (2000, 20, 200)
FURTHER_CLASSES = {(True, True, True): 194, (False, False, False): 6}
TAIL_PIN = (("0.965196", "3.480e-02", "0.4924"),
("0.999881", "1.197e-04", "0.9977"),
("1.000000", "8.593e-14", "1.0000"))
LINES = 45
# --------------------------------------------------------- sections
def check_hand(name, got, want, n):
hits = sum(got[key] == v for key, v in want.items())
miss = [key for key, v in want.items() if got[key] != v]
check(name, hits == len(want) == n, f"{hits} of {n} fields"
+ (f"; off: {miss}" if miss else ""))
def check_pins(name, tot, pins, n):
hits = sum(tot[key] == v for key, v in pins.items())
check(name, hits == len(pins) == n, f"{hits} of {n} counts: "
+ ", ".join(f"{key} {tot[key]}" for key in pins))
def section_controls():
section("CONTROLS")
arm = four_arm()
grid = sum(c.M == 4 and sum(c.w) == 1 and not c.equal()
and all(x >= F(1, 10) and (10 * x).denominator == 1
for x in c.w)
and all(tuple(p) in TENTHS for p in c.p) for c in arm)
check("K1 the four-atom arm: 1,500 cells of four masses in tenths, "
"none under 1/10, none equal-mass, every row one of the "
"sweep's", (grid, len(arm)) == (1500, 1500),
f"{grid} of {len(arm)}")
hand = {c.name: Fates(c) for c in (STRADDLE, ABOVE, BELOW, DA, DS, FA,
FS, E6, EB)}
four = [hand[name] for name in ("E6", "EB", "ABOVE", "BELOW")]
check_hand("K2 the atom rows of E6, EB, ABOVE and BELOW, summed: "
"every field as by hand",
census(atom_row(x, r) for x in four
for r in range(x.cell.M)), ROWS_HAND, 14)
hits = n = 0
off = []
for name, only, r, want in PLANTS:
bent = Fates(hand[name].cell)
bent.opts = [only]
got = atom_row(bent, r)
for key, v in want.items():
n += 1
hits += int(got[key]) == v
if int(got[key]) != v:
off.append(f"{name} cut to {only}, atom {r}: {key}")
check("K2 the planted rows, a hand cell's optima cut to one: each "
"named field of atom_row moves as by hand", hits == n == 26,
f"{hits} of {n}" + (f"; off: {off}" if off else ""))
rows = census(cell_row(x) for x in hand.values())
over, under = Fates(E6), Fates(E6)
over.opt += 1
under.opt -= 1
check("K2 the cell row: sets.py's solver equals the enumeration at "
"the nine hand cells, three of them equal-mass, and not at one "
"whose optimum is moved a unit up, nor a unit down",
(rows["solver"], rows["cells"], rows["equal_cells"],
cell_row(over)["solver"], cell_row(under)["solver"])
== (9, 9, 3, False, False),
f"{rows['solver']} of {rows['cells']}")
good = {"cells": 3, "atoms": 9, "eq_A": 0, "eq_S": 0, "solver": 3,
"formula": 9}
bad = [dict(good, **{f: good[f] + (-1 if pop else 1)})
for f, pop in LAWS]
lost = sum(laws_held(d) == 3 for d in bad)
check("K2 the law count: 4 of 4 on a census at its populations, 3 on "
"each of the 4 with one law field moved by one",
(laws_held(good), lost, len(LAWS)) == (4, 4, 4),
f"{laws_held(good)}, {lost} of {len(bad)}")
check_hand("K3 the keys of DA, DS, E6, FA and FS: 11 on (w, sorted "
"row, t*), 2 with both forced fates, both off the level; "
"12 on the fractional key, 1 with both",
key_counts([hand[name] for name in ("DA", "DS", "E6", "FA",
"FS")]),
{"keys": 11, "both": 2, "strict": 2, "fkeys": 12,
"fboth": 1}, 5)
bl = hand["BELOW"]
check("K3 BELOW's heavy atom: no price without it, 1/20 for what its "
"top leaves, then nothing; fractional none, 1/40, 0, 0; DA's "
"and DS's first fractional prices 59/50 and 7/5; the formula "
"reads the heavy atom served",
(bl.prices(0), bl.fractions(0), hand["DA"].fractions(2)[0],
hand["DS"].fractions(2)[0], bl.predicted(0))
== ([None, F(1, 20), 0, 0], [None, F(1, 40), 0, 0], F(59, 50),
F(7, 5), "S"),
f"{[str(x) for x in bl.prices(0)]}, "
f"{[str(x) for x in bl.fractions(0)]}")
idx = (quantile_index(9), quantile_index(10), quantile_index(1000))
check("K4 the estimator's index: 7 at nine calibration points, 8 at "
"ten, 701 at 1,000", idx == (7, 8, 701), f"{idx}")
got = trial_read(HIT)
check("K4 a hand sample of 20 whose calibration half holds eight top "
"pairs: split returns the optimum's sets, worst atom 0, "
"marginal 581/800; Mondrian's worst atom 1",
got == {"reach": True, "same": True, "zero": True,
"marg": F(581, 800), "mw": F(1)},
f"{got['marg']}, {got['mw']}")
got = trial_read(MISS)
check("K4 a hand sample of 20 whose calibration half holds seven, "
"one short: split serves the eighth atom one label, worst atom "
"8/25, marginal 613/800; Mondrian's worst atom 3/5",
got == {"reach": False, "same": False, "zero": False,
"marg": F(613, 800), "mw": F(3, 5)},
f"{got['marg']}, {got['mw']}")
got = trial_census(BUILT)
check("K4 the census of trials on three built rows: one reaching idx "
"without the optimum's sets, two holding them short of it, "
"which are the strays",
got == {"trials": 3, "classes": {(True, False, False): 1,
(False, True, True): 2},
"stray": 2, "marg": F(1), "mw": F(5, 4)},
f"{got['stray']} strays of {got['trials']}")
two = marginal(STRADDLE, [[0, 1]] + [[]] * 6 + [[2]])
check("K4 the marginal of a rule holding two labels at one atom and "
"one at another: 123/800", two == F(123, 800), f"{two}")
ups = (upward(F(1, 3), 2), upward(F(1, 4), 2))
check("K5 a bound's print rounds up: 1/3 to 0.34, 1/4 to 0.25",
ups == ("0.34", "0.25"), f"{ups}")
tails = (tail(4, F(1, 2), 3), tail(3, F(2, 3), 2), tail(3, F(2, 3), 0),
tail(3, F(2, 3), 4))
check("K5 the binomial tail by hand: 5/16 at (4, 1/2, 3); 20/27, 1 "
"and 0 at (3, 2/3) from 2, 0 and 4",
tails == (F(5, 16), F(20, 27), 1, 0),
f"{[str(x) for x in tails]}")
return hand
def section_census(tot):
section("THE CENSUS AT THE RECORDED SEED")
print(f" {tot['cells']} cells, {tot['equal_cells']} equal-mass; "
f"{tot['atoms']} atoms, {tot['equal']} at equal masses")
print(f" fates: {tot['A']} forced-abandoned, {tot['S']} "
f"forced-served, {tot['O']} open")
print(f" off equal masses {tot['off_A']} above-level atoms are "
f"forced-abandoned and {tot['off_S']} below-level ones "
f"forced-served")
check_pins("Pd the populations: 4,900 cells, 400 equal-mass, 16,300 "
"atoms, 1,300 at equal masses", tot, SIZES, 4)
check("Pc sets.py's solver equals the enumeration at every cell",
tot["solver"] == tot["cells"],
f"{tot['solver']} of {tot['cells']}")
check_pins("the recorded seed's fates, and the wrong forced fates "
"off equal masses, as recorded", tot, PIN_CENSUS, 5)
def section_equal(hand, tot):
section("EQUAL MASSES (A)")
for name in ("E6", "EB"):
check_hand(f"{name}: every figure as by hand, its optima by "
"enumeration", figures(hand[name]), HAND[name], 7)
print(f" {tot['eq_above']} above-level atoms and {tot['eq_below']} "
f"below-level ones at equal masses; some optimum abandons "
f"{tot['eq_drop']} of the first and serves {tot['eq_buy']} of "
f"the second")
check("P1 at the recorded seed's equal-mass cells no above-level "
"atom is forced-abandoned and no below-level one "
"forced-served", (tot["eq_A"], tot["eq_S"]) == (0, 0),
f"{tot['eq_A']} above-level atoms forced-abandoned, "
f"{tot['eq_S']} below-level ones forced-served")
check_pins("the recorded seed's equal-mass counts as recorded: the "
"atoms above and below the level, those some optimum "
"abandons or serves against it", tot, PIN_EQUAL, 4)
def section_grid():
section("EVERY EQUAL-MASS CELL ON THE TENTHS (A)")
sized = held = pins = 0
grid = {}
for M in (3, 4):
tot = grid[M] = read_cells(equal_grid(M))
sized += sum(tot[key] == v for key, v in GRID[M].items())
held += laws_held(tot)
pins += sum(tot[key] == v for key, v in GRID_PIN[M].items())
print(f" {M} atoms: {tot['cells']} cells, {tot['atoms']} atoms, "
f"{tot['equal']} at equal masses; {laws_held(tot)} of 4 "
f"laws; {tot['eq_above']} atoms above the level and "
f"{tot['eq_below']} below it, some optimum abandoning "
f"{tot['eq_drop']} of the first and serving "
f"{tot['eq_buy']} of the second")
check("Pg the grid's populations: 560 cells and 1,680 atoms at three "
"atoms, 2,380 and 9,520 at four, every one equal-mass",
sized == 8, f"{sized} of 8 counts")
check("Pg on the grid no above-level atom is forced-abandoned and no "
"below-level one forced-served; the solver at every cell and "
"the formula at every atom", held == 8,
f"{held} of 8 law counts; {grid[4]['eq_A']} and "
f"{grid[4]['eq_S']} wrong forced fates at four atoms")
check("Pg at three equal atoms every atom is forced-served and no "
"row sits wholly below the level",
(grid[3]["S"], grid[3]["eq_below"]) == (1680, 0),
f"{grid[3]['S']} of {grid[3]['atoms']} atoms, "
f"{grid[3]['eq_below']} below")
check("the grid's counts as recorded: the atoms above the level at "
"three atoms; at four those above it, those below it, and "
"those some optimum abandons or serves against it",
pins == 5, f"{pins} of 5 counts")
def section_straddle(hand):
section("THE OUTNUMBERED ATOM (B, F)")
check_hand("P2 STRADDLE: t* 4/5, b 1, CERT = OPT = 7/8, the one "
"optimum empties the eighth atom and covers 581/800",
figures(hand["STRADDLE"]), HAND["STRADDLE"], 7)
rows = hits = mw = 0
for n in NS:
tot = trial_census(trial_rows(n, 0, TRIALS))
print(f" n {n:6d}: classes (C >= {quantile_index(n - n // 2)}, "
f"the optimum's sets, worst atom 0) {tot['classes']}; "
f"split's mean marginal {tot['marg'] / TRIALS}; Mondrian's "
f"worst atom, trial mean {tot['mw'] / TRIALS}")
rows += tot["trials"] == TRIALS == 20
hits += (tot["classes"], tot["marg"]) == ({(True, True, True): 20},
20 * F(581, 800))
mw += tot["mw"] == 20 * MW_PIN[n]
check("Pa at each n, 20 trials: split returns the optimum's sets in "
"every one, each marginal 581/800, the calibration half "
"holding idx top pairs",
(rows, hits) == (3, 3), f"{hits} of 3 rows")
check("Pa Mondrian's worst atom, trial mean: 383/500, 3/4, 18/25",
mw == 3, f"{mw} of 3 rows")
n, first, count = FURTHER_TRIALS
tot = trial_census(trial_rows(n, first, count))
print(f" n {n:6d}, {tot['trials']} further trials: classes "
f"{tot['classes']}")
check("Pb (F) no further trial returns the optimum's sets with its "
"calibration half short of idx", (tot["stray"], tot["trials"])
== (0, 200), f"{tot['stray']} of {tot['trials']}")
check("Pb the further trials' classes as recorded",
tot["classes"] == FURTHER_CLASSES)
tails = []
for n in NS:
c = n - n // 2
p = tail(c, F(581, 800), quantile_index(c))
tails.append((upward(p, 6), f"{float(1 - p):.3e}",
upward(p ** TRIALS, 4)))
print(f" n {n:6d}: P(Bin({c}, 581/800) >= {quantile_index(c)}) "
f"at most {tails[-1][0]}, short of 1 by about "
f"{tails[-1][1]}; its {TRIALS}th power at most "
f"{tails[-1][2]}")
check("(F) the tail at the three sample sizes, and its 20th power, "
"the most 20 trials all return the optimum's sets with, as "
"recorded, each rounded up to the places printed",
tuple(tails) == TAIL_PIN)
def section_witnesses(hand):
section("OFF EQUAL MASSES (C)")
a, b = hand["ABOVE"], hand["BELOW"]
check_hand("P3 ABOVE: an above-level atom forced-abandoned, CERT 1, "
"OPT 9/10 at the one optimum (0, 1, 1), covering 81/100",
figures(a), HAND["ABOVE"], 7)
check_hand("P3 BELOW: a below-level atom forced-served, CERT 19/20, "
"OPT 9/10 at the one optimum (1, 0, 1), covering 71/100",
figures(b), HAND["BELOW"], 7)
low = (a.most_below(F(9, 10)), b.most_below(F(9, 10)),
b.most_without(0))
check("P3 the most coverage below cost 9/10: 11/20 at ABOVE, 17/25 "
"at BELOW; without BELOW's heavy atom 3/20",
low == (F(11, 20), F(17, 25), F(3, 20)),
f"{[str(x) for x in low]}")
def section_dead(hand, tot):
section("NO PREDICATE ON ONE ATOM (D)")
a, s = hand["DA"], hand["DS"]
check_hand("P4 DA: the one optimum (1, 2, 0) costs 5/4 and abandons "
"the atom of mass 1/10 and row (1, 0, 0)", figures(a),
HAND["DA"], 7)
check_hand("P4 DS: the one optimum (2, 0, 1) costs 13/10 and serves "
"it", figures(s), HAND["DS"], 7)
check("P4 the atom's key (1/10, (1, 0, 0), 1/2) in both cells; the "
"least cost without it 5/4 in DA and 3/2 in DS",
(a.key(2), s.key(2), a.prices(2)[0], s.prices(2)[0])
== ((F(1, 10), (1, 0, 0), F(1, 2)),) * 2 + (F(5, 4), F(3, 2)),
f"{a.prices(2)[0]} and {s.prices(2)[0]}")
print(f" {tot['both']} of {tot['keys']} keys (w, sorted row, t*) "
f"carry both forced fates, {tot['strict']} of them with the "
f"atom's top label off the level")
check_pins("Pf the recorded seed's keys as recorded: those the "
"forced atoms carry, those with both forced fates, those "
"of them off the level", tot, PIN_KEYS, 3)
def section_rest(hand, tot):
section("THE REST PRICE DECIDES (E)")
a, s = hand["FA"], hand["FS"]
check_hand("P6 FA: the one optimum (0, 0, 2) abandons the atom of "
"mass 1/20 and row (1/2, 3/10, 1/5)", figures(a),
HAND["FA"], 7)
check_hand("P6 FS: the one optimum (1, 2, 3) serves it whole",
figures(s), HAND["FS"], 7)
frac = [F(17, 10), F(97, 60), F(47, 30), F(23, 15)]
check("P6 the two atoms share mass, row and the fractional prices "
"17/10, 97/60, 47/30, 23/15; their integer prices are 9/5 four "
"times and 19/10, 19/10, 19/10, 31/20",
(a.fkey(0) == s.fkey(2), a.fractions(0), s.fractions(2),
a.prices(0), s.prices(2))
== (True, frac, frac, [F(9, 5)] * 4,
[F(19, 10)] * 3 + [F(31, 20)]),
f"{[str(x) for x in a.fractions(0)]}")
check("P5 the fate the formula reads off the rest prices equals the "
"enumerated fate at every atom", tot["formula"] == tot["atoms"],
f"{tot['formula']} of {tot['atoms']}")
print(f" fractional key: {tot['fboth']} of {tot['fkeys']} keys carry "
f"both forced fates")
check_pins("Pf the recorded seed's fractional keys as recorded",
tot, PIN_FRAC, 2)
def section_seeds(seeds, n, pinned):
section("THE LAWS AT FURTHER SEEDS")
held = sized = own = 0
for seed in seeds:
tot = read_seed(seed)
got = laws_held(tot)
held += got
sized += all(tot[key] == v for key, v in SIZES.items())
mine = tuple(tot[key] for key in OWN)
own += SEED_PIN.get(seed) == mine
print(f" seed {seed}: {got} of 4 laws; "
+ ", ".join(f"{key} {v}" for key, v in zip(OWN, mine,
strict=True)))
check("Pe every law holds at every further seed, each census sized "
"as the recorded one",
(held, sized, len(seeds)) == (4 * n, n, n),
f"{held} of {4 * n} law counts, {sized} of {n} sized")
want = sum(seed in SEED_PIN for seed in seeds)
check("each recorded further seed's own counts as recorded",
own == want and pinned in (None, want),
f"{own} of {want} recorded seeds")
def main():
t0 = time.time()
seeds = FURTHER
if "--seeds" in sys.argv:
seeds = tuple(int(x) for x in
sys.argv[sys.argv.index("--seeds") + 1].split(","))
hand = section_controls()
if not all(CHECKS):
print("\nCONTROL FAILED: nothing below is read.")
sys.exit(1)
tot = read_seed(SEED)
section_census(tot)
section_equal(hand, tot)
section_grid()
section_straddle(hand)
section_witnesses(hand)
section_dead(hand, tot)
section_rest(hand, tot)
if seeds is FURTHER:
section_seeds(seeds, 2, 2)
else:
section_seeds(seeds, len(seeds), None)
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()