sets.py
Checks: RULER: One live arc: the magnitude parent theorem; observation; SETS: A marginal coverage guarantee cannot rank two set predictors observation; SETS: The certificate brackets the optimum property; SETS: At equal masses the certificate is the optimum property; SETS: Off equal masses the certificate can overstate property; SETS: Three tests can prove the certificate exact property; SETS: An exact solver for the marginal optimum property.
To run it: save sets.py; standard library only.
"""sets.py -- set-valued prediction scored against its exact optimum:
what coverage can and cannot rank, the certificate that brackets the
marginal optimum, when that certificate is the optimum, and an exact
solver for the cells no enumeration reaches.
QUESTION. A set-valued predictor (a conformal predictor, say) returns
a set of labels, and it is sold on a coverage guarantee that holds by
construction, so coverage cannot rank two of them. What can rank them
is the set's size, and on natural data the least size is unknown. On
a family whose posterior is an exact Fraction it is a computation:
minimize the expected set size subject to marginal coverage
1 - alpha. What does that optimum look like, what does the textbook
form of the answer cost against it, and what proves a candidate
optimal without a search?
THE FAMILY. x in Z/N, N = Mc, under the prior proportional to theta^x,
read through its residue r = x mod M (an ATOM, of mass w_r) and
labelled by the magnitude class Y = floor(kx/N). The fiber over r is
r + jM, j < c, and P(j | r) is proportional to q^j, q = theta^M, the
theta^r cancelling: the fiber index reads the same at every atom. The
class is a contiguous block [lo, hi) of j, so
P(Y = y | r) = (q^lo - q^hi)/(1 - q^c) (hi - lo)/c at q = 1.
The blocks move with the atom's phase r/M and not with theta. Four
ring cells, alpha = 3/10 throughout:
TILT-3 N = 105, M = 15, c = 7, k = 3, theta = 24/25
FLAT-3 N = 105, M = 15, c = 7, k = 3, theta = 1
DEAD-7 N = 105, M = 15, c = 7, k = 7, theta = 1
TILT-4-WIDE N = 1155, M = 105, c = 11, k = 4, theta = 199/200
and a designed sweep with no ring in it: 400 equal-weight cells (300
at M = 3 atoms, 100 at M = 4) and 3,000 unequal-weight cells at M = 3, k = 3
labels, every posterior on the tenths, weights on the twentieths
(fixed seed), with an equal-weight arm.
THE OBJECTS. A PAIR (r, y) costs w_r and covers w_r p(y|r), so its
rate is p(y|r) and the atom's weight cancels from the ranking; a rule
is a set of pairs, its cost the expected set size. T = 1 - alpha. The
OPERATIVE LEVEL t* is the largest posterior value t whose pairs
{p >= t} cover at least T. A is the pairs strictly above t*, the TIED
BLOCK the b pairs at t*, and the DEFICIT delta = T - cov(A).
THR = cost(A) + cost(tied block): the best rule of the
thresholded-posterior form {p >= t}, the form Sadinle, Lei
and Wasserman (JASA 2019, Theorem 1) prove optimal for a
posterior without ties.
CERT = cost(A) + the least cost of a tied subset S with
t* cost(S) >= delta (the tied pairs all cover at rate t*).
L = cost(A) + delta/t*, the linear relaxation's value.
D = cov(CERT) - T, the SURPLUS the fill overshoots by.
OPT = the least cost of a rule covering T.
THE ARGUMENT (written before the engine).
(A) THE CHAIN (property). delta > 0: if A alone covered T, the next
posterior value above t* would be operative. For any rule R
covering T, with rc_i = w_i (1 - p_i/t*) the reduced cost at
price 1/t*,
cost(R) = sum_{i in R} rc_i + cov(R)/t*
>= sum_{rc < 0} rc_i + T/t* = L,
and the rc < 0 pairs are exactly A. So L <= OPT <= CERT <= THR.
And cov(CERT) = cov(A) + t* fill, so
CERT - L = fill - delta/t* = D/t*,
exactly, whatever fill is chosen: the certificate's whole room
over the relaxation is the surplus divided by the level.
(B) EQUAL WEIGHTS (property). Every pair costs w, so OPT is w times
the least count of pairs whose posteriors, largest first, cover
T; those pairs are A and then tied pairs, since t* is operative.
So CERT = OPT, and
THR - OPT = w (b - ceil(delta/(w t*))):
the form pays exactly when the level is tied past what the
deficit needs, and never at b = 1. And D < w t*, so D/t* < w.
(C) UNEQUAL WEIGHTS (property, by exhibited cell). Three atoms of
weights 3/10, 3/10, 2/5, each with posteriors (2/5, 2/5, 1/5),
T = 7/10: t* = 2/5, nothing above it, delta = 7/10, the fill
needs tied cost 7/4 and the least such sum of 3/10s and 2/5s
(four and two available) is 2, so CERT = THR = 2 with coverage
4/5. The sizes (2, 3, 1) cost 19/10 and cover exactly 7/10:
OPT <= 19/10 < CERT. The optimum drops a heavy tied pair and tops
up with a light BELOW-level one, spending the surplus.
(D) THREE TESTS OF EXACTNESS (property). CERT - OPT lies in [0, D/t*]
by (A). (i) It is an integer combination of the weights, so
D/t* < g, the least positive such combination (the LATTICE GAP,
the gcd of the weights), proves CERT = OPT; by (B) this decides
every equal-weight cell. (ii) It is sum_r (s_r - s'_r) w_r with
s the certificate's sizes and s' an optimum's, each in [0, k],
so the least positive value g_hat of sum c_r w_r over the box
c_r in [s_r - k, s_r] (the ANCHORED GAP) may replace g, and
g_hat >= g since the box sits in the lattice. (iii) A rule leaving
out a pair of A or holding a pair below t* costs at least
L + |rc_i| by the display in (A); so D/t* < rho, the least
nonzero |rc_i| (the PRICE GAP), confines every optimum to A plus
tied pairs, whose best is the fill: CERT = OPT.
(E) THE SOLVER (property). The same display fixes every pair with
|rc_i| > CERT - L, in if rc_i < 0 and out if rc_i > 0, since
flipping it costs more than CERT. An atom's rule of size s takes
its s largest posteriors, so after fixing each atom keeps a
range of sizes; the atoms are split in two halves, each half
folded to its Pareto frontier of (cost, coverage), and the
halves joined on the coverage axis. The answer is exact with or
without the fixing.
(F) COVERAGE (the demonstration). Split conformal thresholds one
global quantile of an estimated posterior; Mondrian conformal
takes the quantile within each atom. The conditional-coverage
impossibility (Barber, Candes, Ramdas and Tibshirani, Inf.
Inference 2021; Vovk, "Conditional validity of inductive
conformal predictors", 2012, Proposition 4) needs a marginal
without atoms; Vovk states that at an atom a predictor keeping
only that object's examples has conditional validity. The
observable x mod M has M atoms, so per-atom coverage is
attainable here and scoring it is legitimate. The true
posterior being exact, every set's coverage is computed
exactly, with no test sample.
DESIGN. A cell is read by one function, row_of: every field 0 or 1 (a
law's clause, a population's membership, a test's firing), so a census
is a sum of rows and a law is a count set against its population's.
The sweep scores every cell exactly in integers (costs and coverages
over one common denominator): its optimum by enumeration of all
(k+1)^M size vectors, the solver against it with the fixing and
without, the chain, the certificate's sizes, the equal-mass law and the
three tests. The sweep is a seeded sample, so its laws are read at the
recorded seed and at two further seeds (--seeds a,b,... names others),
and the counts no law fixes are a seed's own: eight pinned at the
recorded seed, three at each further one (the form's payers, the
overstated cells, those at b = 1), whose firings are printed only. The
ring cells take the solver alone, TILT-3 also without fixing (4^15 size
vectors, split 4^7 and 4^8); the anchored box at 105 atoms (5^105) is
not searched. The coverage section runs split and Mondrian conformal
(score 1 - phat(y|r), phat the training half's frequencies, pooled
label frequencies at an atom the training half misses; calibration
quantile the ceil((n_cal + 1)(1 - alpha))-th smallest score, all labels
where that exceeds the calibration count; phat and the scores are
floats, a label kept when its phat is within 1e-12 of the threshold) at
the four ring cells, n in {2000, 8000, 32000}, 20 trials each, one seed
per (cell, n, trial): a record of one stream, its integer counts and
its figures pinned to the places printed. Of the fifteen law fields,
six read a proof: the solver against enumeration with the fixing and
without, L <= OPT, (B)'s CERT = OPT and its form (one fact read
twice: the form is CERT = OPT once the fill is right), and no test
firing where CERT > OPT. Nine hold by construction when the engine is
right, and read the engine: OPT <= CERT (enumeration meets the
certificate's sizes, and the fixing never excludes them), the sizes'
cost and coverage, D >= 0, delta > 0 (the level's definition), g_hat
>= g and with it the anchored test wherever the lattice fires, and
at equal weights D/t* < w and the lattice test, one fact, the fill's
minimality. No field at all: CERT <= THR and, at b = 1, THR = CERT
(the fill is a nonempty subset of the tied block), and CERT - L =
D/t* (D is defined by the fill).
CONTROLS (before any sweep is read; a failure stops the run).
K1 (truth) the closed-form class mass equals the direct sum of
theta^x over the fiber at each of the 615 (atom, label) pairs of
the four ring cells, and each cell's masses sum to 1. And a cell
with an empty class at every atom, N = 6, M = 3, k = 3, theta =
1/2: q = 1/8, each fiber's two points weigh 8/9 and 1/9, the
classes floor(x/2) put them at labels (0, 1), (0, 2), (1, 2), and
the atoms weigh 4/7, 2/7, 1/7.
K3 (anatomy, solver) six cells held by hand: the cell of (C),
SPECIMEN; a b = 1 cell, B1, of weights (1/10, 9/20, 9/20) and
posteriors (1, 0, 0), (1, 0, 0), (4/5, 1/5, 0); FLAT-3; DEAD-7;
EDGE; FIXED. SPECIMEN: t* 2/5, A empty, b 6, delta 7/10, sizes
(2, 2, 2), L 7/4, CERT = THR = 2, D 1/10, D/t* 1/4, rho 3/20 (a
1/5 pair's w/2), g 1/10, g_hat 1/10 (4 - 3 tenths inside the box
[-1, 2]), OPT 19/10 at sizes (2, 3, 1), which cover 7/10. B1: t*
4/5, above (1, 1, 0), b 1, delta 3/20, L 11/20 + 3/16 = 59/80,
CERT = THR = 1, D 9/25 - 3/20 = 21/100, D/t* 21/80, rho 1/40 (the
light atom's top pair, (1/10)(1 - 5/4)), g 1/20, g_hat 1/10 (2a +
9m twentieths, a in [-2, 1], m in [-4, 2], reaches 2 and not 1),
OPT 9/10 at sizes (0, 1, 1), which cover 81/100. FLAT-3: t* 2/7,
15 pairs above, b 30, delta 19/70, delta/(w t*) = 57/4 so 15 tied
pairs, L 39/20, CERT = OPT = 2, THR 3, D 1/70, D/t* 1/20, rho
1/30, g = g_hat = 1/15: lattice and anchored fire, price does not.
DEAD-7: t* 1/7, b 105, delta 7/10, 147/2 so 74 pairs, L 49/10,
CERT = OPT = 74/15, THR 7, D 1/210, D/t* 1/30, no rho, g = g_hat =
1/15. No test fires at SPECIMEN or B1. EDGE, weights (7/10, 3/10)
and posteriors (1, 0), (1/2, 1/2), whose top level covers exactly
T: t* 1, nothing above, b 1, delta 7/10, sizes (1, 0), L = CERT =
THR = OPT = 7/10, D 0, rho 3/20 (the light atom's pairs' w/2), g
1/10, g_hat 1/10 (7 - 6 tenths), and all three tests fire: the one
hand cell a level strictly over T would read otherwise. FIXED,
weights (1/2, 1/2) and posteriors (1, 0), (3/5, 2/5): t* 3/5, CERT
1, L 5/6, so the gap is 1/6; atom 0's top pair has reduced cost
-1/3 and is fixed in, its other 1/2 and is fixed out, atom 1's are
0 and 1/6 and stay, so the fixed solver leaves atom 1 alone free,
the unfixed both, OPT 1. The anchored gap alone, on four weights
(7, 3, 20, 20) with sizes (1, 0, 1, 1) at k = 1, each atom
moving by one label: 4, by 7 - 3, where an atom counted in both
halves would reach 7 - 6. The solver equals enumeration at every
cell of the recorded sweep, fixed and unfixed, every atom free
without the fixing; at TILT-3 the unfixed search equals the fixed.
K4 (the row) twelve planted rows, each a hand cell with one input
bent (an optimum under CERT with the lattice test alone firing,
the anchored alone, the price alone, and a price gap equal to the
room; an anchored gap equal to the room, and one under the lattice
gap; an optimum over CERT, one under L; the certificate's sizes one
label short; a negative surplus; no deficit; a room of w), 32
named fields in all: every field the record leaves at 0 or at its
population moves there, the solver's own aside, which K3 holds.
And the law count: 15 on a census at its populations, 14 on each
of the 15 with one law field moved by one.
K0 (conformal) a hand sample of 16 over three atoms and two labels,
its training half giving phat (3/4, 1/4), (0, 1) and, at the atom
it misses, the pooled (3/8, 5/8); the calibration scores sort to
0, 0, 0, 1/4, 1/4, 1/4, 3/8, 1, the 7th is 3/8, so split keeps
{p >= 5/8}: {0}, {1}, {1}; Mondrian's atom 0 has three scores of
1/4 and its 3rd keeps {0}, atom 1 has 0, 0, 0, 1 and its 4th keeps
both labels, atom 2 has one score and takes all. Scored on the
cell of weights (1/2, 1/4, 1/4) and posteriors (3/4, 1/4), (1/4,
3/4), (1/2, 1/2), whose oracle sizes are 1, 1, 2: split 11/16,
worst atom 1/2, size 1; Mondrian 7/8, 3/4, 3/2. A second sample
for the pooled counts: phat (3/4, 1/4), (1/2, 1/2), pooled (5/8,
3/8); scores 1/4 three times, 3/8 twice, 1/2 twice, 3/4, the 7th
1/2, so split keeps {p >= 1/2}: {0}, {0, 1}, {0}, and Mondrian
every label (its 4th score of four is 3/4 at atom 0; two scores
at each other atom). Two edges the
stream never reaches or cannot tell: one atom with phat (3/4, 1/4)
and four calibration scores of 1/4, where the index 4 is the count
itself and both methods keep {0}; and a calibration half of two,
where the index 3 passes the count and both take every label. A
row (7/10, 3/10) has oracle size 1. And the bare cell, three equal
atoms with posteriors (0.8, 0.15, 0.05), (0.5, 0.3, 0.2), (0.34,
0.33, 0.33): per-atom oracle sizes 1, 2, 3; its threshold form
{p >= 0.33} has sizes 1, 1, 3; at n = 32000 split returns the
form's sets and Mondrian the oracle's.
K2 (sampler) the hand cell's six pairs carry masses 3/8, 1/8, 1/16,
3/16, 1/8, 1/8, so the cumulative weights the draw is handed are
0.375, 0.5, 0.5625, 0.75, 0.875, 1, exact in floats.
PREDICTIONS (P1 to P7 fixed before the first engine; figures carried
from an earlier record are TRANSPLANTS until re-measured. Pa to Pe
fixed before this engine, for what no function printed).
P1 (family) FLAT-3's atoms all carry the multiset {3/7, 2/7, 2/7};
DEAD-7's every mass is 1/7, and stays 1/7 under theta = 24/25;
TILT-3's and TILT-4-WIDE's atoms carry more than one multiset.
P2 (A) at every cell: delta > 0, L <= OPT <= CERT <= THR, and
CERT - L = D/t* exactly.
P3 (B) at every equal-weight cell: CERT = OPT, THR - OPT =
w (b - ceil(delta/(w t*))), D/t* < w.
P4 (C) the exhibited cell as derived; and the sweep holds an
unequal-weight cell with b = 1 and CERT > OPT, where THR = CERT
(TRANSPLANT: an earlier census printed such rows).
P5 (D) no test fires at any cell with CERT > OPT, and g_hat >= g at
every cell. At the ring the lattice test fires at FLAT-3 and
DEAD-7 only, the price gap at TILT-4-WIDE (TRANSPLANT: an earlier
solver fixed every non-tied pair there) and not at TILT-3.
P6 the ring optima, TRANSPLANTS: TILT-3 L 0.9008338, CERT 0.9287750,
OPT 0.9194957; FLAT-3 CERT = OPT = 2, THR = 3; DEAD-7 CERT =
OPT = 74/15, THR = 7; TILT-4-WIDE CERT = OPT = 0.8967012, THR = 1.
P7 (F) split conformal's mean marginal coverage lies in
[0.69, 0.74] at every cell and n, while its worst atom's exact
coverage is 0 in some trial at TILT-3 and TILT-4-WIDE at every n
(TRANSPLANT); Mondrian's worst atom, averaged over trials, is at
least 0.6 at both at n = 32000; split's mean set size sits below
THR at FLAT-3 and DEAD-7 at every n (sampling breaks the ties the
form is sunk by).
Pa the lattice test fires at all 402 equal-weight cells (by (B),
D/t* < w = g).
Pb the lattice test fires and the anchored does not at no cell
searched (g_hat >= g).
Pc Mondrian's worst atom is below 7/10 in 20 of 20 trials at
TILT-4-WIDE, n = 32000 (the earlier print's mean and least agree
to four places), and in none at TILT-3.
Pd split's mean size less OPT at DEAD-7, n = 2000, printed +0.040:
within 0.0005 of 0.040, which side unknown.
Pe at two further seeds every law holds at every cell, and the
counts no law fixes (the form's payers, the overstated cells, the
firings) move.
KILL. A control off: nothing is read. One of the six proof counts off
at any seed (short of its population, or the false firings over 0): a
proof above is wrong and its claim does not stand; one of the nine
others: the engine is wrong.
A number of the recorded seed's, or of the coverage stream'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 three seeds, and every count of the earlier engine's
census, every ring figure and every coverage figure is reprinted here
or held in a pinned comparison. Not reprinted: the earlier lines for
the exhibited cell and the first b = 1 cell, whose figures are now
hand rows compared field by field; the totals over the sweep and the
ring together (3,404 cells, 402 equal-weight, 117 paying), now sums
over three lines; K0's mean marginals and K2's 3.12 standard errors, cut
with what printed them. One
frozen clause was wrong, P1's: DEAD-7 does not stay flat under theta =
24/25. At k | c the class blocks do not move with the atom, so every
atom carries ONE law at every tilt, and under a tilt that law is the
truncated geometric of ratio q = theta^15 (0.4643, 0.2517, 0.1364,
0.074, 0.0401, 0.0217, 0.0118), not 1/7; P1' reads the atom-blind
form, 105 masses on the law and none at 1/7.
controls K1 615 of 615 pairs, the four cells' masses summing to 1,
and the cell with empty classes as by hand. K3 every hand
figure of SPECIMEN, B1 and EDGE (15 of 15 each), FLAT-3 and
DEAD-7 (14 of 14 each); the solver, fixed and unfixed, at
the hand optima 19/10, 9/10 and 7/10; FIXED's free atoms
[1] with the fixing and [0, 1] without; the solver equal to
enumeration at 3,400 of 3,400 cells of the recorded sweep
both ways, every atom free without the fixing, the fixing
leaving some atom one size at 1,586; TILT-3's unfixed
search (frontiers 300 and
510) == the fixed one (93 and 256). K4 32 of 32 planted
fields; the law count 15, and 14 at each of 15 plants. K0
the hand sample's sets and scores, the two edges and the
oracle sizes as by hand; at the bare cell split returned
the threshold form's sets and Mondrian the oracle's in 20
and 20 of 20 trials. K2 the six cumulative weights exact.
family distinct multisets over the atoms: TILT-3 3 of 15,
FLAT-3 1, DEAD-7 1, TILT-4-WIDE 4 of 105.
sweep the recorded seed, 3,400 cells, 400 equal-weight: delta >
0, L <= OPT <= CERT, and the certificate's sizes costing
CERT and covering T + D with D >= 0, at 3,400 of 3,400;
(B)'s three clauses at 400 of 400, the form paying at 115;
P4, CERT > OPT at 1,110 of 3,000 unequal-weight cells, 442
of them at b = 1; no test firing at any of the 1,110;
g_hat >= g at 3,400 of 3,400; the lattice test firing at
all 400 equal-weight cells (Pa) and nowhere without the
anchored (Pb); at the 1,890 exact unequal-weight cells
lattice 911, anchored 1,011, price 655.
seeds Pe held: at seeds 20260933 and 20260934 all 15 law counts
met their populations, and the counts no law fixes moved
(the form pays at 155 and 150; CERT > OPT at 1,171 and
1,116, 463 and 459 of them at b = 1; firings 858 / 961 /
670 of 1,829 and 877 / 981 / 665 of 1,884).
ring cell D/t* g g_hat rho
TILT-3 2.794e-02 2.345e-21 1.784e-09 1.414e-02
FLAT-3 5.000e-02 6.667e-02 6.667e-02 3.333e-02
DEAD-7 3.333e-02 6.667e-02 6.667e-02 none
TILT-4-WIDE 4.349e-06 6.024e-242 refused 1.813e-03
the lattice and the anchored gap deciding FLAT-3 and
DEAD-7, the price gap TILT-4-WIDE alone, nothing TILT-3,
the one ring cell with CERT > OPT. The chain holds at the
four; the two equal-weight ones obey (B) and the form pays
at both. L / OPT / CERT / THR: TILT-3
0.9008338 / 0.9194957 / 0.9287750 / 1; FLAT-3 1.95 / 2 / 2
/ 3; DEAD-7 4.9 / 74/15 / 74/15 / 7; TILT-4-WIDE 0.8966969
/ 0.8967012 / 0.8967012 / 1, CERT = OPT exactly, its 26
free atoms the 26 holding a tied pair, atom for atom, each
half 8,192 points.
coverage split's mean marginal 0.7037 to 0.7263 at every cell and n;
its worst atom at exact coverage 0 in 19, 20, 20 of 20
trials at TILT-3 and 20, 20, 20 at TILT-4-WIDE (n = 2000,
8000, 32000) and in none at FLAT-3 or DEAD-7; its mean size
within 1/25 of OPT at all twelve rows in exact fractions
(TILT-3 +0.0134 to +0.0180, TILT-4-WIDE +0.0057 to +0.0344,
FLAT-3 -0.0233 to +0.0033, DEAD-7 +0.0067 to exactly 1/25
at n = 2000, where Pd could not say which side) and below
THR (3, 7) at FLAT-3 and DEAD-7 (1.977 to 2.003, 4.940 to
4.973). Mondrian's worst atom, trial mean, 0.7160 at TILT-3
at every n and 0.6342, 0.6530, 0.6530 at TILT-4-WIDE, its
least over the trials 0.2779, 0.6530, 0.6530; it is below T
in no trial at TILT-3 and in 20 of 20 at TILT-4-WIDE at
every n (Pc, which named n = 32000), and in 3 of 20 at
DEAD-7, n = 2000; its mean excess over the per-atom oracle
falls with n at TILT-3 (+0.295, +0.199, +0.066).
pins entered from this engine's first prints: the below-T
trials, the four-place size differences, the cells where
the fixing leaves some atom one size, the further seeds'
counts and the number of check lines. From the earlier
print by one step of arithmetic: the form's 115 payers in
the sweep (117 less the two ring cells) and the 1/25 at
DEAD-7, n = 2000 (a mean size is a multiple of 1/300). A
prediction from the earlier print's marginals, which do
not force it, held on the first run: the bare cell's 20
and 20. Every other pin is the earlier engine's print or
a hand value.
unread what the stream cannot tell, held by the hand samples
alone: no training half of its 240 trials misses an atom
and no calibration half is short of its split index (a
count beside the run, not a check), so the pooled fallback
and the split overflow are read at K0 only. Two edits move
no line here, each equivalent on these inputs: the fill's
need by floor (in the engine's scaled integers no tied sum
equals the floor of delta/t* below it; a break by hand);
Mondrian's worst atom at <= T (none equals T).
mutants one token changed at each of 457 sites of the engine: 441
runs turn red, 16 move no line. The 16: a strict < or > made
<= or >= where it breaks a tie between equal values (the
anchored gap, enumeration, the fill, the solver's join, the
frontier, whose pinned sizes hold no equal-coverage pair);
the counts behind phat negated or doubled, phat being their
ratio; >= made > at a threshold the 1e-12 tolerance keeps
off every phat; the fill's split point; an eighth term of
the tilted law no label reads; w taken from atom 1 where
row_of reads it at equal weights only; the denominators of
the weights left out of the common one, each dividing one
of its pairs' at every cell read; the bare cell's seed, at
whose neighbours the control also holds; and Mondrian's
worst atom at <= T. Six checks are failed by no mutant,
standing behind the control stop; each fails to an edit by
hand with the stop lifted (the lattice test inverted, the
solver's join one unit low, its free list shifted, a
section's loop cut).
RUN RECORD. python sets.py: 49 of 49 checks, 4.1 s, peak commit
77.9 MB under a memory guard (512 MB).
"""
import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import random
import sys
import time
from bisect import bisect_left, bisect_right
from fractions import Fraction as F
from itertools import product
from math import ceil, gcd
from types import SimpleNamespace
T = F(7, 10)
NS = (2000, 8000, 32000)
TRIALS = 20
SEED = 20260928
FURTHER = (SEED + 5, SEED + 6)
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
class Cell:
"""Atoms with weights w (Fractions summing to 1) and per-atom
posteriors p[r] (Fractions, label order kept)."""
def __init__(self, name, w, p):
self.name, self.w, self.p = name, list(w), [list(x) for x in p]
self.M, self.k = len(w), len(p[0])
self.srt = [sorted(x, reverse=True) for x in self.p]
def equal(self):
return len(set(self.w)) == 1
def ring(name, N, M, k, theta, truth=False):
c = N // M
q = theta ** M
if truth:
tx = [theta ** x for x in range(N)]
Z = sum(tx)
w, p = [], []
for r in range(M):
ys = [k * (r + j * M) // N for j in range(c)]
row = []
for y in range(k):
js = [j for j in range(c) if ys[j] == y]
if not js:
row.append(F(0))
continue
lo, hi = js[0], js[-1] + 1
assert js == list(range(lo, hi))
row.append(F(hi - lo, c) if q == 1
else (q ** lo - q ** hi) / (1 - q ** c))
p.append(row)
w.append(F(1, M) if theta == 1 else
theta ** r * (1 - q ** c) / (1 - q) * (1 - theta)
/ (1 - theta ** N))
cell = Cell(name, w, p)
if truth:
hits = 0
for r in range(M):
for y in range(k):
direct = sum(tx[x] for x in range(r, N, M)
if k * x // N == y) / Z
hits += direct == w[r] * p[r][y]
cell.truth = (hits, sum(w))
cell.truth_ok = cell.truth == (M * k, 1)
return cell
RING = (("TILT-3", 105, 15, 3, F(24, 25)), ("FLAT-3", 105, 15, 3, F(1)),
("DEAD-7", 105, 15, 7, F(1)),
("TILT-4-WIDE", 1155, 105, 4, F(199, 200)))
# -------------------------------------------------- the certificate
class Scaled:
"""A cell in integers: cost W[r], prefix coverage V[r][s] of the s
largest posteriors, target TQ, all over one denominator Q."""
def __init__(self, cell):
dens = [x.denominator for x in cell.w]
dens += [(cell.w[r] * y).denominator for r in range(cell.M)
for y in cell.srt[r]]
Q = T.denominator
for d in dens:
Q = Q * d // gcd(Q, d)
self.Q, self.TQ = Q, int(T * Q)
self.W = [int(x * Q) for x in cell.w]
self.V = []
for r in range(cell.M):
acc, row = 0, [0]
for y in cell.srt[r]:
acc += int(cell.w[r] * y * Q)
row.append(acc)
self.V.append(row)
def least_sum_at_least(items, target):
"""Least subset sum of the positive integers `items` that is >= target,
with one witness mask; meet in the middle, sums deduplicated."""
def half(xs, off):
sums = {0: 0}
for i, x in enumerate(xs):
new = dict(sums)
for s, mask in sums.items():
new.setdefault(s + x, mask | (1 << (i + off)))
sums = new
return sums
h = len(items) // 2
left, right = half(items[:h], 0), half(items[h:], h)
rk = sorted(right)
best = None
for s, mask in left.items():
j = bisect_left(rk, target - s)
if j < len(rk):
v = s + rk[j]
if best is None or v < best[0]:
best = (v, mask | right[rk[j]])
return best
class Anatomy:
def __init__(self, cell):
self.cell, sc = cell, Scaled(cell)
self.sc = sc
levels = sorted({y for row in cell.srt for y in row}, reverse=True)
for t in levels:
cov = sum(cell.w[r] * y for r in range(cell.M)
for y in cell.srt[r] if y >= t)
if cov >= T:
self.t = t
break
t = self.t
self.above = [sum(1 for y in row if y > t) for row in cell.srt]
self.tied_n = [sum(1 for y in row if y == t) for row in cell.srt]
self.m = sum(self.tied_n)
costA = sum(sc.W[r] * self.above[r] for r in range(cell.M))
covA = sum(sc.V[r][self.above[r]] for r in range(cell.M))
self.delta = sc.TQ - covA
owners = [r for r in range(cell.M) for _ in range(self.tied_n[r])]
items = [sc.W[r] for r in owners]
need = ceil(F(self.delta) / t)
fill, mask = least_sum_at_least(items, need)
self.sizes = list(self.above)
for i, r in enumerate(owners):
if mask >> i & 1:
self.sizes[r] += 1
self.cert = costA + fill
self.thr = costA + sum(items)
self.L = costA + F(self.delta) / t
self.D = covA + t * fill - sc.TQ
self.room = self.D / t
rcs = [sc.W[r] - F(sc.V[r][i + 1] - sc.V[r][i]) / t
for r in range(cell.M) for i in range(cell.k)]
nz = [abs(x) for x in rcs if x != 0]
self.rho = min(nz) if nz else None
g = 0
for x in sc.W:
g = gcd(g, x)
self.g = g
def value(self, x):
return F(x) / self.sc.Q
def anchored_gap(an):
"""Least positive sum c_r W_r over c_r in [s_r - k, s_r]."""
W, k, s = an.sc.W, an.cell.k, an.sizes
def half(rs):
vals = {0}
for r in rs:
vals = {v + c * W[r] for v in vals
for c in range(s[r] - k, s[r] + 1)}
return vals
M = an.cell.M
left, right = half(range(M // 2)), sorted(half(range(M // 2, M)))
best = None
for v in left:
j = bisect_right(right, -v)
if j < len(right):
x = v + right[j]
if best is None or x < best:
best = x
return best
def enumerate_opt(an):
sc, M, k = an.sc, an.cell.M, an.cell.k
best = None
for sz in product(range(k + 1), repeat=M):
if sum(sc.V[r][sz[r]] for r in range(M)) >= sc.TQ:
c = sum(sc.W[r] * sz[r] for r in range(M))
if best is None or c < best:
best = c
return best
def pareto(points):
points = sorted(set(points), key=lambda x: (x[0], -x[1]))
out, top = [], None
for c, v in points:
if top is None or v > top:
out.append((c, v))
top = v
return out
def solve(an, fix=True):
"""The exact marginal optimum (E): fixing, then two Pareto halves
joined on the coverage axis. Returns (OPT, free atoms, frontier
sizes)."""
sc, cell, t = an.sc, an.cell, an.t
gap = an.cert - an.L
base_c = base_v = 0
free, rs = [], []
for r in range(cell.M):
lo, hi = 0, cell.k
if fix:
for i in range(cell.k):
rc = sc.W[r] - F(sc.V[r][i + 1] - sc.V[r][i]) / t
if -rc > gap:
lo = i + 1
if rc > gap:
hi = min(hi, i)
opts = [(sc.W[r] * s, sc.V[r][s]) for s in range(lo, hi + 1)]
if len(opts) == 1:
base_c += opts[0][0]
base_v += opts[0][1]
else:
free.append(opts)
rs.append(r)
def fold(group):
front = [(0, 0)]
for opts in group:
front = pareto([(a + c, b + v) for a, b in front
for c, v in opts])
return front
h = len(free) // 2
left, right = fold(free[:h]), fold(free[h:])
rv = [v for _, v in right]
best = None
for c, v in left:
j = bisect_left(rv, sc.TQ - base_v - v)
if j < len(right):
x = base_c + c + right[j][0]
if best is None or x < best:
best = x
return best, rs, (len(left), len(right))
# ------------------------------------------------------------ sweep
TENTHS = [tuple(F(x, 10) for x in (a, b, 10 - a - b))
for a in range(11) for b in range(11 - a) if a >= b >= 10 - a - b]
def sweep(seed=SEED):
rng = random.Random(seed)
cells = []
for i in range(400):
M = 3 if i < 300 else 4
cells.append(Cell(f"E{i}", [F(1, M)] * M,
[rng.choice(TENTHS) for _ in range(M)]))
comps = [(a, b, 20 - a - b) for a in range(1, 19)
for b in range(1, 20 - a)]
for i in range(3000):
ws = rng.choice(comps)
cells.append(Cell(f"U{i}", [F(x, 20) for x in ws],
[rng.choice(TENTHS) for _ in range(3)]))
return cells
SPECIMEN = Cell("SPECIMEN", [F(3, 10), F(3, 10), F(2, 5)],
[[F(2, 5), F(2, 5), F(1, 5)]] * 3)
# ------------------------------------------------------- the record
def rule_value(an, sizes):
"""(cost, coverage), scaled as an.cert is, of the rule taking each
atom's sizes[r] largest posteriors."""
sc = an.sc
return (sum(sc.W[r] * s for r, s in enumerate(sizes)),
sum(sc.V[r][s] for r, s in enumerate(sizes)))
def tests_of(an, gA):
"""Which tests of (D) fire: (lattice, anchored, price). gA is the
anchored gap, None where its box is not searched."""
return (an.room < an.g, gA is not None and an.room < gA,
an.rho is not None and an.room < an.rho)
def figures(an, opt, gA):
"""A cell's exact figures, unscaled: what the hand rows and the
ring table are read against."""
Q = an.sc.Q
return {"t": an.t, "above": tuple(an.above), "b": an.m,
"delta": F(an.delta, Q), "sizes": tuple(an.sizes),
"L": an.L / Q, "OPT": F(opt, Q), "CERT": F(an.cert, Q),
"THR": F(an.thr, Q), "D": an.D / Q, "room": an.room / Q,
"rho": None if an.rho is None else an.rho / Q,
"g": F(an.g, Q), "g_hat": None if gA is None else F(gA, Q),
"tests": tests_of(an, gA)}
def row_of(an, opt, gA):
"""One cell read against its optimum opt (scaled, as an.cert is):
every field 0 or 1, so that a census is a sum of rows."""
eq = an.cell.equal()
over = an.cert > opt
lat, anc, pri = tests_of(an, gA)
w = an.sc.W[0]
cost, cover = rule_value(an, an.sizes)
return {
"cells": 1,
"lower": an.L <= opt,
"upper": opt <= an.cert,
"cost": cost == an.cert,
"cover": cover - an.sc.TQ == an.D,
"surplus": an.D >= 0,
"deficit": an.delta > 0,
"box": gA is not None and gA >= an.g,
"equal": eq,
"eq_exact": eq and an.cert == opt,
"eq_form": eq and an.thr - opt
== w * (an.m - ceil(F(an.delta) / (w * an.t))),
"eq_room": eq and an.room < w,
"eq_pays": eq and an.thr > opt,
"eq_lattice": eq and lat,
"over": over,
"over_b1": over and an.m == 1,
"exact": not eq and not over,
"lattice": not eq and lat,
"anchored": not eq and anc,
"price": not eq and pri,
"false": over and (lat or anc or pri),
"lat_not_anc": lat and not anc,
}
def sweep_row(an):
"""A sweep cell: its optimum by enumeration, the solver read against
it with and without the fixing, then the cell's row."""
opt = enumerate_opt(an)
row = row_of(an, opt, anchored_gap(an))
fixed, free, _ = solve(an)
unfixed, loose, _ = solve(an, fix=False)
row["fixed"] = fixed == opt
row["unfixed"] = unfixed == opt
row["sheds"] = len(free) < an.cell.M
row["loose"] = len(loose) == an.cell.M
return row
def census(rows):
"""The sum of rows, field by field."""
tot = {}
for row in rows:
for key, v in row.items():
tot[key] = tot.get(key, 0) + int(v)
return tot
def sweep_census(seed):
return census(sweep_row(Anatomy(c)) for c in sweep(seed))
# A law field counts its population; a forbidden field counts nothing.
LAWS = (("fixed", "cells"), ("unfixed", "cells"), ("lower", "cells"),
("upper", "cells"), ("cost", "cells"), ("cover", "cells"),
("surplus", "cells"), ("deficit", "cells"), ("box", "cells"),
("eq_exact", "equal"), ("eq_form", "equal"),
("eq_room", "equal"), ("eq_lattice", "equal"), ("false", None),
("lat_not_anc", None))
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)
def ring_row(cell):
"""A ring cell through the solver: (anatomy, OPT, row, figures, the
free atoms, the atoms holding a tied pair, the frontier sizes)."""
an = Anatomy(cell)
opt, free, fronts = solve(an)
gA = anchored_gap(an) if cell.M <= 15 else None
tied = [r for r in range(cell.M) if an.tied_n[r]]
return an, opt, row_of(an, opt, gA), figures(an, opt, gA), free, \
tied, fronts
def at_seventh(cell):
"""How many of a cell's masses are exactly 1/7."""
return sum(y == F(1, 7) for row in cell.p for y in row)
def family_read(rings, dead_t):
"""THE FAMILY's counts: FLAT-3's atoms carrying {3/7, 2/7, 2/7};
DEAD-7's masses equal to 1/7; the tilted DEAD-7's masses equal to
the truncated geometric q^j (1 - q)/(1 - q^7), q = theta^15, and to
1/7; the distinct multisets a cell's atoms carry."""
q = F(24, 25) ** 15
law = [q ** j * (1 - q) / (1 - q ** 7) for j in range(7)]
return {
"flat": sum(sorted(row) == [F(2, 7), F(2, 7), F(3, 7)]
for row in rings["FLAT-3"].p),
"dead": at_seventh(rings["DEAD-7"]),
"tilted_law": sum(y == law[j] for row in dead_t.p
for j, y in enumerate(row)),
"tilted_flat": at_seventh(dead_t),
"multisets": {name: len({tuple(sorted(row)) for row in cell.p})
for name, cell in rings.items()},
}
# --------------------------------------------------------- conformal
def pair_weights(cell):
"""The (atom, label) pairs and their cumulative masses, floats."""
pairs = [(r, y) for r in range(cell.M) for y in range(cell.k)]
cum, acc = [], 0.0
for r, y in pairs:
acc += float(cell.w[r] * cell.p[r][y])
cum.append(acc)
return pairs, cum
def draw_pairs(cell, n, rng):
pairs, cum = pair_weights(cell)
return rng.choices(pairs, cum_weights=cum, k=n)
def conformal_sets(data, M, k):
"""Split and Mondrian sets per atom from a sample of (atom, label)
pairs: its first half trains, its second calibrates."""
n = len(data)
train, cal = data[: n // 2], data[n // 2:]
cnt = [[0] * k for _ in range(M)]
pool = [0] * k
for r, y in train:
cnt[r][y] += 1
pool[y] += 1
ph = []
for r in range(M):
tot = sum(cnt[r])
ph.append([x / tot for x in cnt[r]] if tot else
[x / len(train) for x in pool])
scores = sorted(1 - ph[r][y] for r, y in cal)
idx = ceil((len(cal) + 1) * T)
qg = scores[idx - 1] if idx <= len(cal) else 2.0
per = [[] for _ in range(M)]
for r, y in cal:
per[r].append(1 - ph[r][y])
split, mond = [], []
for r in range(M):
split.append([y for y in range(k) if ph[r][y] >= 1 - qg - 1e-12])
s = sorted(per[r])
i = ceil((len(s) + 1) * T)
if i > len(s):
mond.append(list(range(k)))
else:
mond.append([y for y in range(k)
if ph[r][y] >= 1 - s[i - 1] - 1e-12])
return split, mond
def conformal(cell, n, rng):
"""One trial: split and Mondrian sets per atom, from n draws."""
return conformal_sets(draw_pairs(cell, n, rng), cell.M, cell.k)
def oracle_sizes(cell):
out = []
for row in cell.srt:
acc, s = F(0), 0
while acc < T:
acc += row[s]
s += 1
out.append(s)
return out
def score(cell, sets):
cov = [float(sum(cell.p[r][y] for y in sets[r])) for r in range(cell.M)]
marg = sum(float(cell.w[r]) * cov[r] for r in range(cell.M))
size = sum(float(cell.w[r]) * len(sets[r]) for r in range(cell.M))
return marg, min(cov), size
def worst_exact(cell, sets):
"""The least exact coverage over the atoms, a Fraction."""
return min(sum((cell.p[r][y] for y in sets[r]), F(0))
for r in range(cell.M))
BARE = Cell("K0", [F(1, 3)] * 3,
[[F(80, 100), F(15, 100), F(5, 100)],
[F(50, 100), F(30, 100), F(20, 100)],
[F(34, 100), F(33, 100), F(33, 100)]])
def bare_read():
"""K0's seeded half: in how many of TRIALS trials at n = 32000 split
returns the sets `form` and Mondrian the sets `orc`."""
form, orc = [[0], [0], [0, 1, 2]], [[0], [0, 1], [0, 1, 2]]
rng = random.Random(SEED + 1)
hit_s = hit_m = 0
for _ in range(TRIALS):
split, mond = conformal(BARE, 32000, rng)
hit_s += split == form
hit_m += mond == orc
return hit_s, hit_m
def coverage_row(cell, ci, n, opt):
"""TRIALS trials at one ring cell and sample size, one seed a trial:
two integer counts, the trials' means, and split's mean size less
opt exactly. opt is the cell's optimum, a Fraction."""
orc = oracle_sizes(cell)
zero = below = 0
rows, exact = [], F(0)
for tr in range(TRIALS):
rng = random.Random(SEED + 1000 * ci + 10 * n + tr)
split, mond = conformal(cell, n, rng)
exc = sum(float(cell.w[r]) * (len(mond[r]) - orc[r])
for r in range(cell.M))
rows.append(score(cell, split) + score(cell, mond) + (exc,))
zero += worst_exact(cell, split) == 0
below += worst_exact(cell, mond) < T
exact += sum(cell.w[r] * len(split[r]) for r in range(cell.M))
ss = sum(x[2] for x in rows) / TRIALS
return {"trials": len(rows), "zero": zero, "below": below,
"sm": sum(x[0] for x in rows) / TRIALS,
"sw": min(x[1] for x in rows), "ss": ss,
"mmg": sum(x[3] for x in rows) / TRIALS,
"mw": sum(x[4] for x in rows) / TRIALS,
"mmin": min(x[4] for x in rows),
"me": sum(x[6] for x in rows) / TRIALS,
"gap": ss - float(opt), "gap_exact": exact / TRIALS - opt}
def coverage_text(row):
"""A coverage row's eight means as the table prints them."""
return (f"{row['sm']:.4f}", f"{row['sw']:.4f}", f"{row['ss']:.3f}",
f"{row['mmg']:.4f}", f"{row['mw']:.4f}", f"{row['mmin']:.4f}",
f"{row['me']:+.3f}", f"{row['gap']:+.4f}")
# ------------------------------------------------ hand rows and pins
BONE = Cell("B1", [F(1, 10), F(9, 20), F(9, 20)],
[[F(1), F(0), F(0)], [F(1), F(0), F(0)],
[F(4, 5), F(1, 5), F(0)]])
HALVES = Cell("H8", [F(1, 2), F(1, 4), F(1, 4)],
[[F(3, 4), F(1, 4)], [F(1, 4), F(3, 4)], [F(1, 2), F(1, 2)]])
SAMPLE2 = ([(0, 0), (0, 0), (0, 0), (0, 1), (1, 0), (1, 0), (1, 1), (1, 1)]
+ [(0, 0), (0, 0), (0, 0), (2, 0), (2, 0), (1, 0), (1, 1), (0, 1)])
SAMPLE = ([(0, 0), (0, 0), (0, 0), (0, 1), (1, 1), (1, 1), (1, 1), (1, 1)]
+ [(0, 0), (0, 0), (0, 0), (1, 1), (1, 1), (1, 1), (1, 0), (2, 1)])
EDGE = Cell("EDGE", [F(7, 10), F(3, 10)],
[[F(1), F(0)], [F(1, 2), F(1, 2)]])
FIXED = Cell("FIXED", [F(1, 2), F(1, 2)],
[[F(1), F(0)], [F(3, 5), F(2, 5)]])
NO = (False, False, False)
HAND = {
"SPECIMEN": {"t": F(2, 5), "above": (0, 0, 0), "b": 6,
"delta": F(7, 10), "sizes": (2, 2, 2), "L": F(7, 4),
"OPT": F(19, 10), "CERT": F(2), "THR": F(2),
"D": F(1, 10), "room": F(1, 4), "rho": F(3, 20),
"g": F(1, 10), "g_hat": F(1, 10), "tests": NO},
"B1": {"t": F(4, 5), "above": (1, 1, 0), "b": 1, "delta": F(3, 20),
"sizes": (1, 1, 1), "L": F(59, 80), "OPT": F(9, 10),
"CERT": F(1), "THR": F(1), "D": F(21, 100), "room": F(21, 80),
"rho": F(1, 40), "g": F(1, 20), "g_hat": F(1, 10), "tests": NO},
"EDGE": {"t": F(1), "above": (0, 0), "b": 1, "delta": F(7, 10),
"sizes": (1, 0), "L": F(7, 10), "OPT": F(7, 10),
"CERT": F(7, 10), "THR": F(7, 10), "D": F(0), "room": F(0),
"rho": F(3, 20), "g": F(1, 10), "g_hat": F(1, 10),
"tests": (True, True, True)},
"FLAT-3": {"t": F(2, 7), "above": (1,) * 15, "b": 30,
"delta": F(19, 70), "L": F(39, 20), "OPT": F(2),
"CERT": F(2), "THR": F(3), "D": F(1, 70), "room": F(1, 20),
"rho": F(1, 30), "g": F(1, 15), "g_hat": F(1, 15),
"tests": (True, True, False)},
"DEAD-7": {"t": F(1, 7), "above": (0,) * 15, "b": 105,
"delta": F(7, 10), "L": F(49, 10), "OPT": F(74, 15),
"CERT": F(74, 15), "THR": F(7), "D": F(1, 210),
"room": F(1, 30), "rho": None, "g": F(1, 15),
"g_hat": F(1, 15), "tests": (True, True, False)},
}
# The recorded seed's census: the populations and the counts the laws
# do not fix.
LINES = 48
PIN = {"cells": 3400, "equal": 400, "sheds": 1586, "eq_pays": 115,
"over": 1110,
"over_b1": 442, "exact": 1890, "lattice": 911, "anchored": 1011,
"price": 655}
SEED_PIN = {SEED + 5: (155, 1171, 463), SEED + 6: (150, 1116, 459)}
RING_PIN = {"TILT-3": ("0.9008338", "0.9194957", "0.9287750", "1.0000",
15, (93, 256), 10),
"FLAT-3": ("1.9500000", "2.0000000", "2.0000000", "3.0000",
15, (22, 25), 30),
"DEAD-7": ("4.9000000", "4.9333333", "4.9333333", "7.0000",
15, (50, 57), 105),
"TILT-4-WIDE": ("0.8966969", "0.8967012", "0.8967012",
"1.0000", 26, (8192, 8192), 26)}
TESTS_PIN = {"TILT-3": ("2.794e-02", "2.345e-21", "1.784e-09",
"1.414e-02", NO),
"FLAT-3": ("5.000e-02", "6.667e-02", "6.667e-02",
"3.333e-02", (True, True, False)),
"DEAD-7": ("3.333e-02", "6.667e-02", "6.667e-02", "none",
(True, True, False)),
"TILT-4-WIDE": ("4.349e-06", "6.024e-242", "refused",
"1.813e-03", (False, False, True))}
COVER_PIN = {
("TILT-3", 2000): (19, 0, "0.7263", "0.0000", "0.938", "0.8391",
"0.7160", "0.7160", "+0.295", "+0.0180"),
("TILT-3", 8000): (20, 0, "0.7229", "0.0000", "0.933", "0.8175",
"0.7160", "0.7160", "+0.199", "+0.0134"),
("TILT-3", 32000): (20, 0, "0.7262", "0.0000", "0.937", "0.7864",
"0.7160", "0.7160", "+0.066", "+0.0179"),
("FLAT-3", 2000): (0, 0, "0.7152", "0.4286", "2.003", "0.8438",
"0.7143", "0.7143", "+0.453", "+0.0033"),
("FLAT-3", 8000): (0, 0, "0.7076", "0.4286", "1.977", "0.8067",
"0.7143", "0.7143", "+0.323", "-0.0233"),
("FLAT-3", 32000): (0, 0, "0.7114", "0.4286", "1.990", "0.7638",
"0.7143", "0.7143", "+0.173", "-0.0100"),
("DEAD-7", 2000): (0, 3, "0.7105", "0.4286", "4.973", "0.8167",
"0.6929", "0.5714", "+0.717", "+0.0400"),
("DEAD-7", 8000): (0, 0, "0.7057", "0.4286", "4.940", "0.7857",
"0.7143", "0.7143", "+0.500", "+0.0067"),
("DEAD-7", 32000): (0, 0, "0.7071", "0.4286", "4.950", "0.7462",
"0.7143", "0.7143", "+0.223", "+0.0167"),
("TILT-4-WIDE", 2000): (20, 20, "0.7089", "0.0000", "0.931",
"0.8687", "0.6342", "0.2779", "+0.550", "+0.0344"),
("TILT-4-WIDE", 8000): (20, 20, "0.7049", "0.0000", "0.906",
"0.8223", "0.6530", "0.6530", "+0.040", "+0.0097"),
("TILT-4-WIDE", 32000): (20, 20, "0.7037", "0.0000", "0.902",
"0.8167", "0.6530", "0.6530", "-0.023",
"+0.0057"),
}
def fmt(x, spec):
return "none" if x is None else format(float(x), spec)
# --------------------------------------------------------- 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 section_controls(rings, tot):
section("CONTROLS")
hits = sum(c.truth[0] for c in rings.values())
ones = sum(c.truth[1] == 1 for c in rings.values())
oks = sum(c.truth_ok for c in rings.values())
check("K1 closed-form class mass == direct fiber sum at the 615 "
"(atom, label) pairs of the four ring cells, each cell's masses "
"summing to 1", (hits, ones, oks) == (615, 4, 4),
f"{hits} pairs, {ones} cells")
tiny = ring("K1", 6, 3, 3, F(1, 2), truth=True)
a, b, z = F(8, 9), F(1, 9), F(0)
check("K1 a ring cell with an empty class at every atom (N = 6, M = 3, "
"k = 3, theta = 1/2): weights and rows as by hand",
(tiny.w, tiny.p, tiny.truth)
== ([F(4, 7), F(2, 7), F(1, 7)],
[[a, b, z], [a, z, b], [z, a, b]], (9, 1)))
sp, b1 = Anatomy(SPECIMEN), Anatomy(BONE)
for an, key in ((sp, "SPECIMEN"), (b1, "B1"), (Anatomy(EDGE), "EDGE")):
opt = enumerate_opt(an)
check_hand(f"K3 {key}: every figure as by hand, the optimum by "
"enumeration", figures(an, opt, anchored_gap(an)),
HAND[key], 15)
both = (F(solve(an)[0], an.sc.Q), F(solve(an, fix=False)[0],
an.sc.Q))
check(f"K3 {key}: the solver, fixed and unfixed, returns the hand "
"optimum", both == (HAND[key]["OPT"],) * 2,
f"{both[0]}, {both[1]}")
for key in ("FLAT-3", "DEAD-7"):
an, opt, _, fig, _, _, _ = ring_row(rings[key])
check_hand(f"K3 {key}: every figure as by hand, the optimum by "
"the solver", fig, HAND[key], 14)
c, v = rule_value(sp, (2, 3, 1))
check("K3 SPECIMEN: the sizes (2, 3, 1) cost 19/10 and cover 7/10",
(F(c, sp.sc.Q), F(v, sp.sc.Q)) == (F(19, 10), F(7, 10)))
c, v = rule_value(b1, (0, 1, 1))
check("K3 B1: the sizes (0, 1, 1) cost 9/10 and cover 81/100",
(F(c, b1.sc.Q), F(v, b1.sc.Q)) == (F(9, 10), F(81, 100)))
stub = SimpleNamespace(sc=SimpleNamespace(W=[7, 3, 20, 20]),
cell=SimpleNamespace(k=1, M=4),
sizes=[1, 0, 1, 1])
check("K3 the anchored gap alone, on weights (7, 3, 20, 20) with "
"sizes (1, 0, 1, 1) at k = 1: 4", anchored_gap(stub) == 4,
f"{anchored_gap(stub)}")
fx = Anatomy(FIXED)
fa, fb = solve(fx), solve(fx, fix=False)
check("K3 FIXED: the fixing takes atom 0's top pair in and its other "
"out, leaving atom 1 free; unfixed, both atoms are free; OPT 1 "
"both ways",
(fa[1], fb[1], F(fa[0], fx.sc.Q), F(fb[0], fx.sc.Q))
== ([1], [0, 1], 1, 1), f"free {fa[1]} and {fb[1]}")
# planted rows: every field the record leaves at 0, or at its
# population, seen to move on a row built to move it
flat = ring_row(rings["FLAT-3"])[0]
bent, short, dry = Anatomy(SPECIMEN), Anatomy(SPECIMEN), Anatomy(SPECIMEN)
bent.sizes, short.D, dry.delta = [2, 2, 1], F(-1), 0
wide = Anatomy(rings["FLAT-3"])
wide.room = F(wide.sc.W[0])
dear, par = Anatomy(SPECIMEN), Anatomy(SPECIMEN)
dear.rho, par.rho = dear.room + 1, par.room
spo = enumerate_opt(sp)
plants = (
("an optimum under CERT, the lattice test alone firing", flat,
flat.cert - 1, 1, {"false": 1, "eq_exact": 0, "eq_form": 0,
"upper": 1}),
("an optimum under CERT, the anchored test alone firing", sp,
sp.cert - 1, 10 * sp.sc.Q, {"false": 1, "over": 1}),
("an optimum under CERT, the price test alone firing", dear,
dear.cert - 1, None, {"false": 1}),
("an optimum under CERT, a price gap equal to the room", par,
par.cert - 1, None, {"false": 0, "over": 1}),
("an anchored gap equal to the room", flat, flat.cert, flat.room,
{"lat_not_anc": 1, "eq_lattice": 1, "false": 0}),
("an anchored gap under the lattice gap", sp, spo, sp.g - 1,
{"box": 0, "lower": 1}),
("an optimum over CERT", sp, sp.cert + 1, None,
{"upper": 0, "lower": 1, "over": 0, "exact": 1}),
("an optimum under L", sp, spo - sp.sc.Q, None,
{"lower": 0, "upper": 1, "over": 1}),
("the certificate's sizes one label short", bent, spo, None,
{"cost": 0, "cover": 0, "surplus": 1}),
("a negative surplus", short, spo, None,
{"surplus": 0, "cover": 0, "cost": 1}),
("no deficit", dry, spo, None, {"deficit": 0, "surplus": 1}),
("a room of w at equal masses", wide, wide.cert, wide.g,
{"eq_room": 0, "eq_exact": 1, "eq_lattice": 0}),
)
hits = n = 0
off = []
for label, an, opt, gA, want in plants:
row = row_of(an, opt, gA)
for key, v in want.items():
n += 1
hits += int(row[key]) == v
if int(row[key]) != v:
off.append(f"{label}: {key}")
check("K4 the planted rows: each named field of row_of moves as by "
"hand", hits == n == 32, f"{hits} of {n}"
+ (f"; off: {off}" if off else ""))
good = {"cells": 3, "equal": 2, "false": 0, "lat_not_anc": 0}
good.update({f: good[pop] for f, pop in LAWS if pop})
bad = [dict(good, **{f: good[f] + (-1 if pop else 1)})
for f, pop in LAWS]
lost = sum(laws_held(d) == 14 for d in bad)
check("K4 the law count: 15 of 15 on a census at its populations, 14 "
"on each of the 15 with one law field moved by one",
(laws_held(good), lost, len(LAWS)) == (15, 15, 15),
f"{laws_held(good)}, {lost} of {len(bad)}")
check("K3 solver == enumeration at every sweep cell of the recorded "
"seed, with the fixing and without, every atom free without it",
(tot["fixed"], tot["unfixed"], tot["loose"], tot["cells"])
== (3400,) * 4,
f"{tot['fixed']}, {tot['unfixed']} and {tot['loose']} of "
f"{tot['cells']}; the fixing empties an atom's choice at "
f"{tot['sheds']}")
tilt = Anatomy(rings["TILT-3"])
a, _, fr_a = solve(tilt, fix=True)
b, _, fr_b = solve(tilt, fix=False)
check("K3 TILT-3: the unfixed split search == the fixed solver, the "
"frontiers as recorded",
a == b and (fr_a, fr_b) == ((93, 256), (300, 510)),
f"frontiers {fr_a} fixed, {fr_b} unfixed")
split, mond = conformal_sets(SAMPLE, 3, 2)
check("K0 the hand sample of 16 through the estimator: split's and "
"Mondrian's sets as by hand",
(split, mond) == ([[0], [1], [1]], [[0], [0, 1], [0, 1]]),
f"split {split}, Mondrian {mond}")
check("K0 the hand sample's sets scored on the hand cell: marginal, "
"worst atom, size",
(score(HALVES, split), score(HALVES, mond),
worst_exact(HALVES, split), worst_exact(HALVES, mond))
== ((0.6875, 0.5, 1.0), (0.875, 0.75, 1.5), F(1, 2), F(3, 4)),
f"{score(HALVES, split)}, {score(HALVES, mond)}")
check("K0 a second hand sample, its pooled phat (5/8, 3/8) deciding "
"the set of the atom its training half misses",
conformal_sets(SAMPLE2, 3, 2)
== ([[0], [0, 1], [0]], [[0, 1], [0, 1], [0, 1]]),
f"{conformal_sets(SAMPLE2, 3, 2)[0]}")
full = [[0, 1], [0, 1]]
check("K0 the estimator's edges: a calibration half of four takes "
"its largest score, one of two takes every label",
(conformal_sets([(0, 0)] * 3 + [(0, 1)] + [(0, 0)] * 4, 1, 2),
conformal_sets([(0, 0), (1, 1), (0, 0), (1, 1)], 2, 2))
== (([[0]], [[0]]), (full, full)))
check("K0 the per-atom oracle's sizes at the bare cell and the hand "
"cell, and at a row whose top label is exactly T",
(oracle_sizes(BARE), oracle_sizes(HALVES), oracle_sizes(
Cell("T", [F(1)], [[F(7, 10), F(3, 10)]])))
== ([1, 2, 3], [1, 1, 2], [1]))
hs, hm = bare_read()
check("K0 the bare cell at n = 32000: split returns the threshold "
"form's sets and Mondrian the per-atom oracle's, trial for trial",
(hs, hm) == (TRIALS, TRIALS) == (20, 20),
f"{hs} and {hm} of {TRIALS}")
check("K2 sampler: the hand cell's six pairs and their cumulative "
"masses as by hand", pair_weights(HALVES)
== ([(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)],
[0.375, 0.5, 0.5625, 0.75, 0.875, 1.0]),
f"{pair_weights(HALVES)[1]}")
def section_sweep(tot):
section("THE SWEEP AT THE RECORDED SEED (A to D)")
n, e = tot["cells"], tot["equal"]
u = n - e
print(f" {n} cells, {e} equal-mass, {u} unequal")
print(f" CERT > OPT at {tot['over']} of {u} unequal-mass cells, "
f"{tot['over_b1']} of them with b = 1")
print(f" at the {tot['exact']} exact unequal-mass cells the tests "
f"fire: lattice {tot['lattice']}, anchored {tot['anchored']}, "
f"price {tot['price']}")
check("P2 delta > 0 and L <= OPT <= CERT at every cell",
(tot["deficit"], tot["lower"], tot["upper"]) == (n, n, n),
f"{tot['deficit']}, {tot['lower']} and {tot['upper']} of {n}")
check("P2 the certificate's sizes cost CERT and cover T + D, D >= 0, "
"at every cell",
(tot["cost"], tot["cover"], tot["surplus"]) == (n, n, n),
f"{tot['cost']}, {tot['cover']} and {tot['surplus']} of {n}")
check("P3 at every equal-mass cell CERT = OPT, THR - OPT = "
"w(b - ceil(delta/(w t*))) and D/t* < w",
(tot["eq_exact"], tot["eq_form"], tot["eq_room"]) == (e, e, e),
f"{tot['eq_exact']}, {tot['eq_form']} and {tot['eq_room']} of "
f"{e}; the form pays at {tot['eq_pays']}")
check("P5 no test fires where CERT > OPT", tot["false"] == 0,
f"{tot['false']} of {tot['over']}")
check("P5 g_hat >= g at every cell; the lattice test fires at every "
"equal-mass cell, and the anchored wherever the lattice does",
(tot["box"], tot["eq_lattice"], tot["lat_not_anc"]) == (n, e, 0),
f"{tot['box']} of {n}; {tot['eq_lattice']} of {e}; "
f"{tot['lat_not_anc']} lattice alone")
hits = sum(tot[key] == v for key, v in PIN.items())
check("P4 the recorded seed's census: the populations, the cells the "
"fixing leaves an atom no choice, the form's payers, the "
"overstated cells and "
"those at b = 1, the exact unequal cells and the three tests' "
"firings", hits == len(PIN) == 10, f"{hits} of 10 counts")
def section_seeds(seeds, n, pinned):
section("THE LAWS AT FURTHER SEEDS")
held = sized = own = 0
for seed in seeds:
tot = sweep_census(seed)
got = laws_held(tot)
held += got
sized += (tot["cells"], tot["equal"]) == (3400, 400)
own += SEED_PIN.get(seed) == (tot["eq_pays"], tot["over"],
tot["over_b1"])
print(f" seed {seed}: {got} of 15 laws at every cell; "
f"pays {tot['eq_pays']}, CERT > OPT {tot['over']}, b = 1 "
f"{tot['over_b1']}, fired {tot['lattice']} / "
f"{tot['anchored']} / {tot['price']} of {tot['exact']}")
check("every law of the sweep holds at every cell of every further "
"seed, 3,400 cells a seed, 400 equal-mass",
(held, sized, len(seeds)) == (15 * n, n, n),
f"{held} of {15 * n} law counts, {sized} of {n} sweeps "
"sized")
want = sum(seed in SEED_PIN for seed in seeds)
check("each recorded further seed's own counts as recorded: the "
"form's payers, the overstated cells and those at b = 1",
own == want and pinned in (None, want),
f"{own} of {want} recorded seeds")
def section_ring(ring_rec):
section("THE RING CELLS (D, E)")
print(f" {'cell':12s} {'D/t*':>10s} {'g':>10s} {'g_hat':>10s} "
f"{'rho':>10s} lattice anchored price CERT=OPT")
hits_t = hits_o = 0
for name, (an, opt, row, fig, free, tied, fronts) in ring_rec.items():
gh = "refused" if fig["g_hat"] is None else fmt(fig["g_hat"], ".3e")
got = (fmt(fig["room"], ".3e"), fmt(fig["g"], ".3e"), gh,
fmt(fig["rho"], ".3e"), fig["tests"])
hits_t += got == TESTS_PIN[name]
print(f" {name:12s} {got[0]:>10s} {got[1]:>10s} {got[2]:>10s} "
f"{got[3]:>10s} {str(got[4][0]):7s} {str(got[4][1]):8s} "
f"{str(got[4][2]):5s} {an.cert == opt}")
print(f" {'cell':12s} {'L':>10s} {'OPT':>10s} {'CERT':>10s} "
f"{'THR':>8s} free atoms frontiers b")
for name, (an, opt, row, fig, free, tied, fronts) in ring_rec.items():
got = (fmt(fig["L"], ".7f"), fmt(fig["OPT"], ".7f"),
fmt(fig["CERT"], ".7f"), fmt(fig["THR"], ".4f"), len(free),
fronts, an.m)
hits_o += got == RING_PIN[name]
print(f" {name:12s} {got[0]:>10s} {got[1]:>10s} {got[2]:>10s} "
f"{got[3]:>8s} {got[4]:10d} {str(got[5]):9s} {got[6]}")
rt = census(rec[2] for rec in ring_rec.values())
print(f" the four: {rt['equal']} equal-mass, the form paying at "
f"{rt['eq_pays']}; CERT > OPT at {rt['over']}")
check("P2 the chain and the certificate's sizes at the four ring "
"cells",
(rt["cells"], rt["deficit"], rt["lower"], rt["upper"],
rt["cost"], rt["cover"], rt["surplus"]) == (4,) * 7)
check("P3 the equal-mass law at FLAT-3 and DEAD-7, the form paying at "
"both",
(rt["equal"], rt["eq_exact"], rt["eq_form"], rt["eq_room"],
rt["eq_pays"], rt["eq_lattice"]) == (2,) * 6)
check("P5 the four ring cells' gaps and firings as recorded, to the "
"places printed", hits_t == 4, f"{hits_t} of 4 rows")
check("P5 no test fires at a ring cell where CERT > OPT, which is "
"TILT-3 alone; TILT-4-WIDE's certificate is exact",
(rt["false"], rt["over"], ring_rec["TILT-3"][2]["over"],
ring_rec["TILT-4-WIDE"][2]["exact"]) == (0, 1, True, True),
f"{rt['false']} false firings, {rt['over']} overstated")
check("P6 the four ring cells' L, OPT, CERT, THR, free atoms, "
"frontiers and b as recorded, to the places printed",
hits_o == 4, f"{hits_o} of 4 rows")
_, _, _, _, free, tied, _ = ring_rec["TILT-4-WIDE"]
same = sum(a == b for a, b in zip(free, tied, strict=True))
check("P6' TILT-4-WIDE's free atoms are the atoms holding a tied pair, "
"atom for atom", same == 26, f"{same} of {len(tied)}")
def section_family(rings):
section("THE FAMILY: which atoms carry which law")
dead_t = ring("DEAD-7 tilted", 105, 15, 7, F(24, 25), truth=True)
fam = family_read(rings, dead_t)
for name, count in fam["multisets"].items():
print(f" {name:12s} {count} distinct multisets over "
f"{rings[name].M} atoms")
print(f" the tilted DEAD-7's law at every atom: "
f"{[round(float(y), 4) for y in dead_t.p[0]]}")
check("P1 FLAT-3: every atom carries the multiset {3/7, 2/7, 2/7}",
fam["flat"] == 15, f"{fam['flat']} of 15 atoms")
check("P1 DEAD-7: every mass is 1/7", fam["dead"] == 105,
f"{fam['dead']} of 105")
check("P1' the tilted DEAD-7 (theta = 24/25): every atom carries the "
"truncated geometric of ratio theta^15, no mass 1/7, each the "
"direct fiber sum",
(fam["tilted_law"], fam["tilted_flat"], dead_t.truth)
== (105, 0, (105, 1)),
f"{fam['tilted_law']} of 105 on the law, {fam['tilted_flat']} at "
f"1/7, {dead_t.truth[0]} the fiber sum")
check("P1 the distinct multisets over the atoms: TILT-3 3, FLAT-3 1, "
"DEAD-7 1, TILT-4-WIDE 4",
fam["multisets"] == {"TILT-3": 3, "FLAT-3": 1, "DEAD-7": 1,
"TILT-4-WIDE": 4})
def section_coverage(rings, ring_rec):
section("COVERAGE CANNOT RANK TWO SET RULES (F)")
print(f" {'cell':12s} {'n':>6s} | split marg worst(min) zero-trials "
f"size | mond marg worst(mean, min) below-T excess | THR OPT")
trials = near = 0
got = {}
for ci, (name, cell) in enumerate(rings.items()):
an, opt = ring_rec[name][:2]
thr, o = float(F(an.thr, an.sc.Q)), float(F(opt, an.sc.Q))
for n in NS:
row = coverage_row(cell, ci, n, F(opt, an.sc.Q))
near += abs(row["gap_exact"]) <= F(1, 25)
if (name, n) == ("DEAD-7", 2000):
edge = row["gap_exact"]
sm, sw, ss, mmg, mw, mmin, me, gap = coverage_text(row)
print(f" {name:12s} {n:6d} | {sm} {sw} "
f"{row['zero']:2d} {ss} | {mmg} {mw} {mmin} "
f"{row['below']:2d} {me} | {thr:.3f} {o:.3f} "
f"size - OPT {gap}")
trials += row["trials"]
got[name, n] = (row["zero"], row["below"], sm, sw, ss, mmg, mw,
mmin, me, gap)
rows = sum(got[key][2:9] == pin[2:9] for key, pin in COVER_PIN.items())
check("P7 the recorded stream: every row's seven figures to the "
"places printed, 20 trials a row",
(rows, trials, len(got), len(COVER_PIN)) == (12, 240, 12, 12),
f"{rows} of 12 rows, {trials} trials")
for i, what in ((0, "split's worst atom at exact coverage 0"),
(1, "Mondrian's worst atom below T"),
(9, "split's mean size less OPT, to four places")):
hits = sum(got[key][i] == pin[i] for key, pin in COVER_PIN.items())
check(f"P7 {what}: a row as recorded", hits == 12,
f"{[got[key][i] for key in COVER_PIN]}")
check("P7 split's mean size within 1/25 of OPT at every row, in exact "
"fractions, and 1/25 over it at DEAD-7, n = 2000",
(near, edge) == (12, F(1, 25)), f"{near} of 12 rows; {edge}")
def main():
t0 = time.time()
seeds = FURTHER
assert all(seed in SEED_PIN for seed in FURTHER)
if "--seeds" in sys.argv:
seeds = tuple(int(x) for x in
sys.argv[sys.argv.index("--seeds") + 1].split(","))
rings = {spec[0]: ring(*spec, truth=True) for spec in RING}
tot = sweep_census(SEED)
section_controls(rings, tot)
if not all(CHECKS):
print("\nCONTROL FAILED: nothing below is read.")
sys.exit(1)
ring_rec = {name: ring_row(cell) for name, cell in rings.items()}
section_sweep(tot)
if seeds is FURTHER:
section_seeds(seeds, 2, 2)
else:
section_seeds(seeds, len(seeds), None)
section_ring(ring_rec)
section_family(rings)
section_coverage(rings, ring_rec)
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()