swaps.py
Checks: SETS: Off equal masses the condition fails both ways property; SETS: A rescue is an exchange whose masses balance property.
Cited on: SETS.
To run it: save swaps.py, with fates.py, sets.py beside it; standard library only.
"""swaps.py -- how an optimum that abandons an atom turns into one that
serves it: two mass bounds, on an atom a rule can empty and on one
wholly below the level, and the exchange every serving optimum is,
sorted by what a rescue that only drops labels would need.
QUESTION. fates.py reads which atoms the marginal optimum abandons.
An atom abandoned by SOME optimum but not by every one has a serving
optimum too; what exchange carries the one to the other, and what
decides whether a simple exchange exists? And what do the masses and
the level alone say of an atom a rule can empty, or of one below the
level?
THE OBJECTS (sets.py's and fates.py's). Atoms have positive masses
w_q summing to 1, each a row of k posteriors summing to 1. A rule
takes the top R_q labels at atom q, costing sum w_q R_q and covering
sum w_q P(q, R_q), P(q, s) the sum of q's s largest posteriors; an
optimum is a rule of least cost covering T, and OPT its cost.
D_R = cov(R) - T is a rule's overshoot. t* is the operative level, the
largest t whose labels {p >= t} cover T; psi_q is the posterior mass
atom q holds at or above t*, psi_max the largest. An optimum R with
R_r = 0 ABANDONS r, and the other atoms it serves are r's PARTNERS; a
RESCUE is an optimum serving r; an atom some optimum abandons and some
serves is OPEN. A PAIR is an atom with one optimum abandoning it.
THE ARGUMENT (written before the engine).
(A) TWO MASS BOUNDS (property). A rule empty at r covers at most the
others' mass, 1 - w_r, and their whole rows cover exactly that:
some rule empty at r covers T if and only if w_r <= 1 - T. An
atom wholly below t* holds none of the labels {p >= t*}, which
cover T, so T <= sum_{q != r} w_q psi_q <= (1 - w_r) psi_max and
w_r <= 1 - T/psi_max, the stronger bound on those atoms since
psi_max <= 1. The second bound reads no optimum, and
binds the atoms below the level only: an atom with a label at or
above t* can be abandoned at a mass over it.
(B) THE EXCHANGE (property). Let R abandon r and R' serve it at size
s, both optima. On another atom where R' is lower it DROPS d_i
labels, where higher it GAINS a_j; both costing OPT,
sum w_i d_i - sum w_j a_j = s w_r.
A rescue that gains nowhere is DOMINATED: R' <= R off r. It
needs a DROP-SET: d with 0 <= d_q <= R_q off r and
sum w_q d_q = s w_r for some 1 <= s <= k. The drop-set's RULE,
R - d + s e_r, then costs OPT, so it is an optimum exactly when
it covers T. Three KINDS of a pair that has a rescue: DOMINATED
(some drop-set's rule covers T), ARITHMETIC (no drop-set exists:
every rescue gains somewhere, whatever the posteriors), COVERAGE
(drop-sets exist and each one's rule falls short).
(C) THE SWAP (a restatement). Dropping the lowest label R holds on a
partner q, of posterior p, and serving r at size s costs
OPT - w_q + s w_r and covers cov(R) - w_q p + w_r P(r, s). So it
is an optimum if and only if s w_r = w_q and
w_q p <= w_r P(r, s) + D_R. Asking s w_r <= w_q instead, as the
engine does, changes nothing: under the coverage clause a strict
< would undercut OPT. This is the definition of an optimum read
at one rule; it has no step that could fail.
(D) THE FULL PARTNER (property). If R serves a partner q whole
(R_q = k) and d w_q = s w_r with 1 <= d, s <= k, dropping q's
lowest d labels loses at most w_q d/k of coverage (rows sum to
1, so the lowest d of k posteriors sum to at most d/k) and r's
top s gain at least s w_r/k: the trade is an optimum with no
coverage condition. Conversely a trade of that shape that is an
optimum balances, by its cost.
DESIGN. Two rows. An ATOM ROW reads one atom against the bounds: every
field 0 or 1, computed by bound_fields from four numbers and two bits
(its mass, its top posterior, t*, psi_max; whether a rule empty at it
covers T, read off the cell's table; whether an optimum abandons it),
so a row no real cell holds can be handed to it. A RESCUE ROW reads
one pair: its kind, and (C) and (D) each as three counts, the places
where the hypotheses hold, those among them whose trade is in the list
of optima, and the places where the list holds a trade of that shape.
The middle count is at most the first and at most the third at every
pair, so the three totals equal say the two sets are one at every
pair. A census is a sum of rows and a law is a count set against its
population's. Eight laws, of three sorts. Three read an argument with
a step in it: the equivalence of (A) at every atom (the table against
the mass), no atom wholly below t* with mass over the second bound,
and every trade the full partner's hypotheses name a listed optimum
((D)'s averaging). Four are arithmetic, of two rules' costs and coverages,
each side computed its own way: the dominated bit
from the drop-sets' coverage against the one read off the optima, at
every pair, rescued or not; (C)'s two; (D)'s converse. One is the
grid's: no atom attains the second bound strictly under the first.
On these cells psi_max is a tenth and at least 7/10, so
1 - 7/(10 psi_max) is
0, 1/8, 2/9 or 3/10, and the masses (twentieths, a third, a quarter,
the four-atom arm's tenths) hold 3/10 alone; TIGHT, off the grid,
attains it under.
The cells are fates.py's (sets.py's sweep and the four-atom arm, 4,900
cells from a fixed seed), read at the recorded seed and at two further
ones (--seeds a,b,... names others); the counts no law fixes are a
seed's own, pinned at the recorded seed, nine of them at the others.
THE HAND CELLS (k = 3, T = 7/10; every figure by hand, a rule written
as its sizes in atom order). SHORT's first row and the last of PAST,
GAIN and HALF are entered with their labels in another order, which a row read
unsorted misreads.
GAIN w (1/20, 1/2, 9/20), rows (4/5, 1/10, 1/10), (3/5, 2/5, 0),
(3/5, 1/5, 1/5); t* 2/5. (0, 2, 1) covers 77/100 and
(1, 1, 2) covers 7/10, both at 29/20; nothing cheaper
reaches 7/10 and the third rule of that cost, (2, 0, 3),
covers 99/200. Atom 0, its top above the level, is abandoned
by (0, 2, 1) and served
only by (1, 1, 2): one label of mass 1/2 dropped, one of 9/20
gained. The drop sums of (0, 2, 1) are 9/20, 1/2, 19/20, 1,
29/20, never 1/20, 1/10 or 3/20: ARITHMETIC.
SHORT w (3/5, 3/10, 1/10), rows (1/2, 2/5, 1/10), (4/5, 1/5, 0),
(7/10, 1/5, 1/10); t* 2/5, psi (9/10, 4/5, 7/10). Optima
(2, 1, 0), covering 39/50, and (1, 2, 3), covering 7/10, at
3/2. Atom 2 is abandoned by the first and rescued by the
second, which gains at atom 1. One drop-set balances (atom
1's label against atom 2 whole) and its rule (2, 0, 3) covers
16/25: COVERAGE. Atom 1 has mass 3/10 exactly: the others'
whole rows cover 7/10, and no optimum empties it.
PAST w (3/4, 3/20, 1/10), rows (2/5, 2/5, 1/5) twice and
(7/10, 3/10, 0); t* 2/5, psi_max 4/5, 1 - T/psi_max = 1/8.
One optimum (2, 0, 2) at 17/10, covering 7/10. Atom 1, its
top at the level, is abandoned at mass 3/20 > 1/8. Its pair
has no rescue and no drop-set.
FLAT four atoms of 1/4, rows (1/3, 1/3, 1/3) twice and (1, 0, 0)
twice; t* 1/3. Optima (0, 3, 1, 1), (1, 2, 1, 1),
(2, 1, 1, 1), (3, 0, 1, 1) at 5/4, each covering 3/4. Two
pairs, mirror images; in each the swap fires once (1/12 <=
1/12 + 1/20) and the full partner at d = s = 1, 2, 3.
FULL w (1/5, 2/5, 2/5), rows (1/2, 1/2, 0), (2/5, 3/10, 3/10),
(3/4, 1/4, 0). Optima (0, 3, 1) covering 7/10, (2, 2, 1) and
(2, 1, 2), at 8/5. One pair; the swap fires at s = 2 (3/25 <=
1/5; at s = 1, 3/25 > 1/10) and the full partner at d = 1,
s = 2, the same trade: the balance at d != s.
EB fates.py's: optima (1, 1, 2, 0), (1, 1, 1, 1), (1, 1, 0, 2).
Two pairs, each with one swap, to the middle optimum; the
other rescue of each drops two labels of a partner served in
part. (1, 1, 2, 0) has ten drop-sets at atom 3, two covering.
TIE w (3/10, 3/10, 2/5), three rows (1, 0, 0). Optima (1, 0, 1)
and (0, 1, 1) at 7/10, each covering 7/10 exactly. Two pairs,
mirror images; the swap fires once in each with its coverage
clause an equality (3/10 <= 3/10 + 0), and not at the heavy
partner (2/5 > 3/10).
HALF w (1/5, 1/10, 7/10), rows (1/3, 1/3, 1/3) twice and
(9/10, 1/10, 0). Optima (0, 3, 1) and (1, 1, 1) at 1, each
covering 73/100; (1, 0, 1) and (0, 2, 1) cover 209/300. One
pair. No swap can balance (the light partner is half atom
0's mass, the heavy one's top is worth 63/100); the full
partner fires at d = 2, s = 1.
TIGHT w (1/5, 4/5), rows (1/2, 1/2, 0), (7/8, 1/8, 0); t* 7/8,
psi_max 7/8. Atom 0 sits wholly below t* at mass 1/5 =
1 - (7/10)/(7/8): the second bound attained, under the first.
AT30 w (3/10, 7/10), rows (1, 0, 0) twice; t* 1. One optimum
(0, 1): atom 0 abandoned at mass 3/10 = 1 - T, its top at the
level.
CONTROLS (before any census is read; a failure stops the run).
K1 (the atom row) the rows of TIGHT, AT30, PAST, GAIN, SHORT and
FLAT, 17 atoms, summed: the equivalence at 17, 7 abandoned by an
optimum, 1 of them at 1 - T, 1 atom below the level, at its bound
and under the first, 1 past, 4 open, 2 rescued only by gain.
Six rows no cell holds: an atom below the level at mass 1/4 with
psi_max 9/10 is over its bound 2/9; with psi_max 14/15 it attains
1/4; one abandoned at 7/20 breaks the equivalence and is past;
one at 3/10 that no rule could empty breaks it too, attaining
both bounds at once; one over its bound and abandoned by no
optimum is not past; one at the level with mass 1/4 = 1 - T /
psi_max attains nothing. Four atoms on optima cut by hand, and
an atom of two rescue rows built by hand, a dominated one among them
or not.
K2 (the rescue row) the rows of GAIN, SHORT, PAST, FLAT, FULL, EB,
TIE and HALF, field by field, and the rules of the drop-sets of
EB, GAIN and SHORT.
Five rows on optima cut by hand: FLAT to (0, 3, 1, 1) and
(2, 1, 1, 1), where the swap's hypotheses hold and its trade is
not listed; to (0, 3, 1, 1) and (1, 3, 0, 1), where a listed
single drop does not satisfy them; to (0, 3, 1, 1) alone, where
the drop-sets say dominated and no rescue is listed; GAIN to
(0, 2, 1) and (2, 1, 1), a dominated rescue with no drop-set;
SHORT to (2, 1, 0) and (2, 0, 3), one whose rule falls short.
K3 (the law count) 8 on a census at its populations, 7 on each of
the 8 with one law field moved by one.
PREDICTIONS (K1 to P5 fixed before the first engine, its K1 that
engine's control; Pa to Pe before this one, for what no function
printed or no check read).
K1 CONTROL: the swap fires at some abandoning optimum and some
abandoning optimum has no drop-set.
P1 both bounds hold at every atom they read.
P2 an identity of any rule, between t* times its cost and its
coverage corrected by the excesses over the level of what it
drops and buys, holds at every optimum (not computed).
P3 the balance of (B) holds at every two optima it names (the two
costs equal: not computed); no optimum without a drop-set has a
dominated rescue.
P4 every rule the swap and the full partner build is an optimum
serving r.
P5 some atom abandoned by some optimum is rescued only by gain
exchanges, an ARITHMETIC case among them.
Pa the recorded seed reprints the first engine's counts: 1,047
pairs with a rescue, 908 dominated, 37 arithmetic, 102 coverage;
the swap at 991 places and the full partner at 123; 18 atoms
with a label at or above t* abandoned over the second bound.
Pb 2,559 atoms abandoned by some optimum and 943 open ones at the
recorded seed (fates.py's 1,616 forced-abandoned and 943 open).
Pc the eight laws at three seeds.
Pd on these cells some atom attains each bound, the second only
where it equals the first.
Pe a dominated pair where neither the swap nor the full partner
fires exists, between 20 and 120 of the 908 (a guess: two
partners dropped together, or two labels of a partner served in
part, with no single-label trade beside them).
KILL. A control off: nothing is read. A law off at any seed: its
argument is wrong, or the engine that reads it (for the grid's law,
its arithmetic). Pa off: the rewrite changed what it reads. Pe at
0: the swap and the full partner are the whole dominated rescue at
these sizes. P5 off: every open atom here has a dominated rescue, or
none rescued only by gain is arithmetic.
FINDINGS. No kill fired: every control held, every law count met its
population at the recorded seed and at two further ones, and every
count of the first engine's print reprints (1,047 = 908 + 37 + 102,
991, 123, 18). Three frozen clauses were off. (A)'s second bound was
called the stronger bound on the abandoned atoms; it covers the atoms
wholly below t*, and an optimum abandons atoms over it. P4's swap half
could not fail: the swap is the definition of an optimum at one rule
((C)), so what is read now is that its hypotheses fire exactly where
the enumeration lists a single-label trade. And P5 named an atom where
its count was of pairs; both are counted now. P1's first bound, frozen
as no abandoned atom over 1 - T, is read as (A)'s equivalence, which
implies it.
controls K1 11 of 11 summed fields, 29 of 29 planted, 10 of 10 on
cut optima, the built rows. K2 112 of 112 fields over
eight cells, the drop-sets' rules as by hand, 39 of 39 on
cut optima. K3 the law count 8, and 7 at each of 8 plants.
bounds the recorded seed: 16,300 atoms; a rule empty at the atom
covers T exactly at the atoms of mass at most 3/10, all
16,300 (Pc). Some optimum abandons 2,559 (Pb), 88 of them
at mass exactly 3/10. 635 sit wholly below t*, none over
1 - T/psi_max, 8 attaining it, none of those under 3/10
(Pd): on these cells the second bound is attained only
where it is the first, and TIGHT attains it under. 18
atoms with a label at or above t* are abandoned over it,
as PAST's is.
exchange 2,674 pairs, 1,047 with a rescue: 908 dominated, 37
arithmetic, 102
coverage. 1,188 pairs have no drop-set, the 37 arithmetic
ones among them and the rest at atoms no optimum serves,
as PAST's is. The dominated bit read two ways agrees at
all 2,674 (Pc). Of the 943 open atoms 128 are rescued only
by gain, as GAIN's and SHORT's are. GAIN's seven figures
as by hand.
trades the swap's hypotheses hold at 991 places, each a listed
optimum, and the optima list a single-label trade at 991
places; the full partner's at 123, each listed, 123 listed
(Pc). 91 of the 908 dominated pairs have neither (Pe):
every dominated rescue of theirs drops two labels or more,
and none is a trade with one partner served whole.
seeds at seeds 20260933 and 20260934 the eight laws met their
populations and the counts no law fixes moved (666 and 662
atoms below t*, 6 and 7 attaining the second bound; 73 and
96 abandoned at 3/10; 2,785 and
2,655 pairs; 57 and 43 arithmetic, 108 and 103 coverage;
the swap at 1,130 and 1,019 places, the full partner at
156 and 104; 114 and 106 dominated pairs beyond both).
pins entered from this engine's first print: 88, 8, 2,674,
1,188, 128, 91 and the further seeds' counts.
From a search made before the engine: 635,
and the cells SHORT and PAST, each figure then derived by
hand. From the first engine's print: 1,047, 908, 37, 102,
991, 123, 18, and the cell GAIN, that engine's first
arithmetic print, its figures then by hand.
From fates.py's record: 2,559 and 943. Every other pin is
a hand value.
mutants one token changed at each of 156 sites of the engine:
every run turns red. Four checks are failed by no mutant:
(A)'s equivalence, the dominated bit's agreement and
GAIN's figures, whose mutants stop at a control first, and
the count of check lines, which no engine token moves.
Each fails to an edit by hand with the stop lifted (the
equivalence's <= made <, or its bit read at size 1's
remainder; the drop-sets' bit true of any drop-set, or
its coverage strict; GAIN's cost moved; the count moved).
Of 33 edits by
hand, each with its FAIL lines named before its run, 31
turn red; 2 are green and equivalent, as named: the swap's
mass clause made an equality ((C)), and open read off a
rescue row (a rescue is the atom's, whichever optimum
abandons it).
RUN RECORD. python swaps.py: 21 of 21 checks, 5.6 s, peak commit
26.1 MB under a memory guard (512 MB).
"""
import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import sys
import time
from fractions import Fraction as F
from itertools import product
from fates import EB, Fates, figures, four_arm
from sets import FURTHER, SEED, T, Cell, census, sweep
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 tenths(*xs):
return [F(x, 10) for x in xs]
GAIN = Cell("GAIN", [F(1, 20), F(1, 2), F(9, 20)],
[tenths(8, 1, 1), tenths(6, 4, 0), tenths(2, 6, 2)])
SHORT = Cell("SHORT", [F(3, 5), F(3, 10), F(1, 10)],
[tenths(1, 5, 4), tenths(8, 2, 0), tenths(7, 2, 1)])
PAST = Cell("PAST", [F(3, 4), F(3, 20), F(1, 10)],
[tenths(4, 4, 2), tenths(4, 4, 2), tenths(3, 7, 0)])
FLAT = Cell("FLAT", [F(1, 4)] * 4,
[[F(1, 3)] * 3, [F(1, 3)] * 3, tenths(10, 0, 0),
tenths(10, 0, 0)])
FULL = Cell("FULL", [F(1, 5), F(2, 5), F(2, 5)],
[tenths(5, 5, 0), tenths(4, 3, 3), [F(3, 4), F(1, 4), F(0)]])
TIGHT = Cell("TIGHT", [F(1, 5), F(4, 5)],
[tenths(5, 5, 0), [F(7, 8), F(1, 8), F(0)]])
AT30 = Cell("AT30", [F(3, 10), F(7, 10)],
[tenths(10, 0, 0), tenths(10, 0, 0)])
TIE = Cell("TIE", [F(3, 10), F(3, 10), F(2, 5)], [tenths(10, 0, 0)] * 3)
HALF = Cell("HALF", [F(1, 5), F(1, 10), F(7, 10)],
[[F(1, 3)] * 3, [F(1, 3)] * 3, tenths(1, 9, 0)])
# ------------------------------------------------------- the engine
def bound_fields(w, top, t, pmax, can, dropped):
"""An atom against the two bounds of (A), every field 0 or 1: w its
mass, top its largest posterior, t the level, pmax psi_max, can
whether some rule empty at it covers T, dropped whether some
optimum abandons it."""
cap = 1 - T / pmax
low = top < t
return {
"atoms": 1,
"iff": can == (w <= 1 - T),
"dropped": dropped,
"drop_at": dropped and w == 1 - T,
"below": low,
"below_over": low and w > cap,
"below_at": low and w == cap,
"below_under": low and w == cap and w < 1 - T,
"past": dropped and top >= t and w > cap,
}
def drops(x, R, r):
"""The rule of every drop-set of R at r: R - d + s e_r over the d
with d_q <= R_q and the sizes 1 <= s <= k whose masses balance,
sum w_q d_q = s w_r. R is empty at r, so d is; each rule costs what
R costs."""
sc, M, k = x.an.sc, x.cell.M, x.cell.k
out = []
for d in product(*[range(R[q] + 1) for q in range(M)]):
shed = sum(d[q] * sc.W[q] for q in range(M))
out += [tuple(s if q == r else R[q] - d[q] for q in range(M))
for s in range(1, k + 1) if shed == s * sc.W[r]]
return out
def trade(R, r, q, d, s):
"""R with d labels dropped at q and r served at size s."""
return tuple(s if i == r else v - d if i == q else v
for i, v in enumerate(R))
def swap_fires(x, R, r, q, s):
"""(C)'s hypotheses at the lowest label R holds on q."""
sc = x.an.sc
lowest = sc.V[q][R[q]] - sc.V[q][R[q] - 1]
spare = x.table[R][1] - sc.TQ
return s * sc.W[r] <= sc.W[q] and lowest <= sc.V[r][s] + spare
def full_fires(x, R, r, q, d, s):
"""(D)'s hypotheses: q served whole, the masses balancing."""
sc = x.an.sc
return R[q] == x.cell.k and d * sc.W[q] == s * sc.W[r]
def rescue_row(x, r, R):
"""One (atom, abandoning optimum) pair: its kind, the dominated bit
two ways, and (C) and (D) each as three counts (the hypotheses
hold; and the trade is a listed optimum; the listed optima of the
trade's shape)."""
M, k = x.cell.M, x.cell.k
opts = set(x.opts)
serving = [o for o in x.opts if o[r] > 0]
partners = [q for q in range(M) if R[q] > 0]
sizes = range(1, k + 1)
rules = drops(x, R, r)
by_drops = any(x.table[o][1] >= x.an.sc.TQ for o in rules)
by_optima = any(all(o[q] <= R[q] for q in range(M) if q != r)
for o in serving)
swaps = [trade(R, r, q, 1, s) for q in partners for s in sizes
if swap_fires(x, R, r, q, s)]
fulls = [trade(R, r, q, d, s) for q in partners for d in sizes
for s in sizes if full_fires(x, R, r, q, d, s)]
singles = sum(trade(R, r, q, 1, s) in opts for q in partners
for s in sizes)
wholes = sum(trade(R, r, q, d, s) in opts for q in partners
if R[q] == k for d in sizes for s in sizes)
rescued = bool(serving)
return {
"pairs": 1,
"rescued": rescued,
"dominated": by_optima,
"arithmetic": rescued and not by_optima and not rules,
"coverage": rescued and not by_optima and bool(rules),
"nodrop": not rules,
"agree": by_drops == by_optima,
"swap": len(swaps),
"swap_opt": sum(o in opts for o in swaps),
"swap_enum": singles,
"full": len(fulls),
"full_opt": sum(o in opts for o in fulls),
"full_enum": wholes,
"beyond": by_optima and not swaps and not fulls,
}
RESCUE = ("pairs", "rescued", "dominated", "arithmetic", "coverage",
"nodrop", "agree", "swap", "swap_opt", "swap_enum", "full",
"full_opt", "full_enum", "beyond")
def atom_row(x, r, rows):
"""One atom: its bound fields, whether it is open, and from its
rescue rows whether none of its abandoning optima has a dominated
rescue."""
t = x.an.t
pmax = max(sum(p for p in row if p >= t) for row in x.cell.srt)
out = bound_fields(x.cell.w[r], x.cell.srt[r][0], t, pmax,
x.rest[r][0] is not None, bool(rows))
out["open"] = bool(rows) and any(o[r] > 0 for o in x.opts)
out["gain_only"] = (out["open"]
and not any(v["dominated"] for v in rows))
return out
def pair_rows(x, r):
"""Atom r's rescue rows, one an optimum abandoning it."""
return [rescue_row(x, r, R) for R in x.opts if R[r] == 0]
def read_cells(cells):
"""A census: the cells' atom rows and rescue rows, summed."""
atoms, pairs = [], []
for cell in cells:
x = Fates(cell)
for r in range(cell.M):
rows = pair_rows(x, r)
atoms.append(atom_row(x, r, rows))
pairs += rows
tot = census(pairs)
tot.update(census(atoms))
tot["cells"] = len(cells)
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 = (("iff", "atoms"), ("below_over", None), ("below_under", None),
("agree", "pairs"), ("swap_opt", "swap"), ("swap_enum", "swap"),
("full_opt", "full"), ("full_enum", "full"))
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)
# ----------------------------------------------------- what is pinned
ATOMS_HAND = {"atoms": 17, "iff": 17, "dropped": 7, "drop_at": 1,
"below": 1, "below_over": 0, "below_at": 1, "below_under": 1,
"past": 1, "open": 4, "gain_only": 2}
# (w, top, t, psi_max, can, dropped), then the fields by hand
BOUND_PLANTS = (
((F(1, 4), F(1, 5), F(1, 2), F(9, 10), True, True),
{"iff": 1, "dropped": 1, "drop_at": 0, "below": 1, "below_over": 1,
"below_at": 0, "below_under": 0, "past": 0}),
((F(1, 4), F(1, 5), F(1, 2), F(14, 15), True, True),
{"below_over": 0, "below_at": 1, "below_under": 1}),
((F(7, 20), F(1, 2), F(1, 2), F(1), True, True),
{"iff": 0, "drop_at": 0, "below": 0, "past": 1}),
((F(3, 10), F(1, 5), F(1, 2), F(1), False, True),
{"iff": 0, "drop_at": 1, "below": 1, "below_over": 0, "below_at": 1,
"below_under": 0, "past": 0}),
((F(1, 4), F(1, 2), F(1, 2), F(9, 10), True, False),
{"iff": 1, "dropped": 0, "drop_at": 0, "past": 0}),
((F(1, 4), F(1, 2), F(1, 2), F(14, 15), True, True),
{"below_at": 0, "below_under": 0, "past": 0}),
)
# (cell, the optima its list is cut to, atom, fields by hand)
ATOM_PLANTS = (
("GAIN", [(0, 2, 1)], 0, {"dropped": 1, "open": 0, "gain_only": 0}),
("GAIN", [(1, 1, 2)], 0, {"dropped": 0, "open": 0, "past": 0}),
("FLAT", [(0, 3, 1, 1), (1, 2, 2, 1)], 0, {"open": 1, "gain_only": 1}),
("SHORT", [(2, 1, 0), (2, 0, 3)], 2, {"open": 1, "gain_only": 0}),
)
# pairs, rescued, dominated, arithmetic, coverage, nodrop, agree, the
# swap's three counts, the full partner's three, beyond
PAIRS_HAND = {
"GAIN": (1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0),
"SHORT": (1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0),
"PAST": (1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0),
"FLAT": (2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 6, 6, 6, 0),
"FULL": (1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0),
"EB": (2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0),
"TIE": (2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0),
"HALF": (1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0),
}
# (cell, the optima its list is cut to, atom, its abandoning optimum,
# fields by hand)
PAIR_PLANTS = (
("FLAT", [(0, 3, 1, 1), (2, 1, 1, 1)], 0, (0, 3, 1, 1),
{"rescued": 1, "dominated": 1, "agree": 1, "swap": 1, "swap_opt": 0,
"swap_enum": 0, "full": 3, "full_opt": 1, "full_enum": 1,
"beyond": 0}),
("FLAT", [(0, 3, 1, 1), (1, 3, 0, 1)], 0, (0, 3, 1, 1),
{"rescued": 1, "dominated": 1, "agree": 1, "swap": 1, "swap_opt": 0,
"swap_enum": 1, "full": 3, "full_opt": 0, "full_enum": 0}),
("FLAT", [(0, 3, 1, 1)], 0, (0, 3, 1, 1),
{"rescued": 0, "dominated": 0, "arithmetic": 0, "coverage": 0,
"nodrop": 0, "agree": 0, "swap_opt": 0, "full_opt": 0}),
("GAIN", [(0, 2, 1), (2, 1, 1)], 0, (0, 2, 1),
{"rescued": 1, "dominated": 1, "arithmetic": 0, "nodrop": 1,
"agree": 0, "beyond": 1}),
("SHORT", [(2, 1, 0), (2, 0, 3)], 2, (2, 1, 0),
{"dominated": 1, "coverage": 0, "agree": 0, "swap": 0,
"swap_enum": 1, "beyond": 1}),
)
SIZES = {"cells": 4900, "atoms": 16300}
# The recorded seed's counts no law fixes.
PIN_BOUNDS = {"dropped": 2559, "drop_at": 88, "below": 635, "below_at": 8,
"past": 18}
PIN_KINDS = {"pairs": 2674, "rescued": 1047, "dominated": 908,
"arithmetic": 37, "coverage": 102, "nodrop": 1188, "open": 943,
"gain_only": 128}
PIN_TRADES = {"swap": 991, "full": 123, "beyond": 91}
OWN = ("below", "below_at", "drop_at", "pairs", "arithmetic", "coverage",
"swap", "full", "beyond")
SEED_PIN = {SEED + 5: (666, 6, 73, 2785, 57, 108, 1130, 156, 114),
SEED + 6: (662, 7, 96, 2655, 43, 103, 1019, 104, 106)}
LINES = 20
# --------------------------------------------------------- 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")
hand = {c.name: Fates(c) for c in (GAIN, SHORT, PAST, FLAT, FULL, EB,
TIE, HALF, TIGHT, AT30)}
six = [hand[name] for name in ("TIGHT", "AT30", "PAST", "GAIN",
"SHORT", "FLAT")]
check_hand("K1 the atom rows of TIGHT, AT30, PAST, GAIN, SHORT and "
"FLAT, summed: every field as by hand",
census(atom_row(x, r, pair_rows(x, r)) for x in six
for r in range(x.cell.M)), ATOMS_HAND, 11)
hits = n = 0
off = []
for i, (args, want) in enumerate(BOUND_PLANTS):
got = bound_fields(*args)
for key, v in want.items():
n += 1
hits += int(got[key]) == v
if int(got[key]) != v:
off.append(f"row {i}: {key}")
check("K1 six rows no cell holds: each named field of bound_fields "
"as by hand", hits == n == 29,
f"{hits} of {n}" + (f"; off: {off}" if off else ""))
hits = n = 0
off = []
for name, only, r, want in ATOM_PLANTS:
bent = Fates(hand[name].cell)
bent.opts = only
got = atom_row(bent, r, pair_rows(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("K1 four atoms on optima cut by hand: each named field of "
"atom_row as by hand", hits == n == 10,
f"{hits} of {n}" + (f"; off: {off}" if off else ""))
yes, no = {"rescued": 1, "dominated": 1}, {"rescued": 1, "dominated": 0}
built = [atom_row(hand["GAIN"], 0, rows)
for rows in ([yes, no], [no, yes], [no, no])]
got = [(v["open"], v["gain_only"]) for v in built]
check("K1 an atom of two built rescue rows: one of them dominated, "
"either one, and it is open and not rescued only by gain; "
"neither, and it is",
got == [(True, False), (True, False), (True, True)], f"{got}")
hits = n = 0
off = []
for name, want in PAIRS_HAND.items():
x = hand[name]
got = census(v for r in range(x.cell.M) for v in pair_rows(x, r))
for key, v in zip(RESCUE, want, strict=True):
n += 1
hits += got[key] == v
if got[key] != v:
off.append(f"{name}: {key} {got[key]}")
check("K2 the rescue rows of GAIN, SHORT, PAST, FLAT, FULL, EB, TIE "
"and HALF, a cell at a time: every field as by hand",
hits == n == 112,
f"{hits} of {n}" + (f"; off: {off}" if off else ""))
sets_ = (sorted(drops(hand["EB"], (1, 1, 2, 0), 3)),
drops(hand["GAIN"], (0, 2, 1), 0),
drops(hand["SHORT"], (2, 1, 0), 2))
eb = hand["EB"]
covering = [o for o in sets_[0]
if eb.table[o][1] >= eb.an.sc.TQ]
check("K2 the drop-sets' rules by hand: ten of EB's (1, 1, 2, 0) at its "
"last atom, the two covering T the other optima; none of "
"GAIN's (0, 2, 1); SHORT's one, (2, 0, 3)",
(len(sets_[0]), covering, sets_[1], sets_[2])
== (10, [(1, 1, 0, 2), (1, 1, 1, 1)], [], [(2, 0, 3)]),
f"{len(sets_[0])}, {covering}, {sets_[1]}, {sets_[2]}")
hits = n = 0
off = []
for name, only, r, R, want in PAIR_PLANTS:
bent = Fates(hand[name].cell)
bent.opts = only
got = rescue_row(bent, r, 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}: {key} {int(got[key])}")
check("K2 five pairs on optima cut by hand: each named field of "
"rescue_row as by hand", hits == n == 39,
f"{hits} of {n}" + (f"; off: {off}" if off else ""))
good = {"atoms": 9, "iff": 9, "below_over": 0, "below_under": 0,
"pairs": 5, "agree": 5, "swap": 4, "swap_opt": 4,
"swap_enum": 4, "full": 3, "full_opt": 3, "full_enum": 3}
bad = [dict(good, **{f: good[f] + (-1 if pop else 1)})
for f, pop in LAWS]
lost = sum(laws_held(d) == 7 for d in bad)
check("K3 the law count: 8 of 8 on a census at its populations, 7 on "
"each of the 8 with one law field moved by one",
(laws_held(good), lost, len(LAWS)) == (8, 8, 8),
f"{laws_held(good)}, {lost} of {len(bad)}")
return hand
def section_mass_bounds(tot):
section("TWO MASS BOUNDS (A)")
print(f" {tot['cells']} cells, {tot['atoms']} atoms; some optimum "
f"abandons {tot['dropped']}, {tot['below']} sit wholly below t*")
check_pins("the populations: 4,900 cells, 16,300 atoms", tot, SIZES, 2)
check("Pc (A) at every atom some rule empty at it covers T exactly "
"when its mass is at most 1 - T", tot["iff"] == tot["atoms"],
f"{tot['iff']} of {tot['atoms']} atoms")
check("Pc (A) no atom wholly below t* has mass over 1 - T/psi_max; "
"Pd (the grid's) none attains it under 1 - T",
(tot["below_over"], tot["below_under"]) == (0, 0),
f"{tot['below_over']} over and {tot['below_under']} under, of "
f"{tot['below']} atoms, {tot['below_at']} attaining it")
check_pins("the recorded seed's atoms as recorded: those some optimum "
"abandons, those of them at mass 1 - T, those wholly below "
"t*, those of them at 1 - T/psi_max, and those with a "
"label at or above t* abandoned past it", tot, PIN_BOUNDS,
5)
GAIN_HAND = {"t": F(2, 5), "OPT": F(29, 20),
"optima": [(0, 2, 1), (1, 1, 2)],
"covers": [F(77, 100), F(7, 10)], "fates": "OSS"}
def section_exchange(hand, tot):
section("THE EXCHANGE (B), THE SWAP (C), THE FULL PARTNER (D)")
gain = hand["GAIN"]
got = dict(figures(gain), top=gain.cell.srt[0][0],
rules=drops(gain, (0, 2, 1), 0))
check_hand("P5 GAIN: t* 2/5, OPT 29/20, the optima (0, 2, 1) covering "
"77/100 and (1, 1, 2) covering 7/10, fates O, S, S; atom "
"0's top 4/5; no drop-set of (0, 2, 1)", got,
dict(GAIN_HAND, top=F(4, 5), rules=[]), 7)
print(f" {tot['pairs']} (atom, abandoning optimum) pairs, "
f"{tot['rescued']} with a serving optimum: {tot['dominated']} "
f"dominated, {tot['arithmetic']} arithmetic, {tot['coverage']} "
f"coverage; {tot['nodrop']} pairs with no drop-set")
print(f" {tot['open']} open atoms, {tot['gain_only']} rescued only "
f"by gain")
check("Pc (B) the dominated bit from the drop-sets' coverage equals "
"the one read off the optima at every pair",
tot["agree"] == tot["pairs"],
f"{tot['agree']} of {tot['pairs']} pairs")
check_pins("the recorded seed's kinds as recorded: the pairs, those "
"with a rescue and their three kinds, the pairs with no "
"drop-set, the open atoms, those rescued only by gain",
tot, PIN_KINDS, 8)
print(f" the swap's hypotheses hold at {tot['swap']} places, the "
f"full partner's at {tot['full']}; {tot['beyond']} dominated "
f"pairs where neither holds")
check("Pc (C) the swap's hypotheses hold exactly at the single-label "
"trades the optima list",
tot["swap_opt"] == tot["swap"] == tot["swap_enum"],
f"{tot['swap']} places, {tot['swap_opt']} of them listed, "
f"{tot['swap_enum']} listed")
check("Pc (D) the full partner's hypotheses hold exactly at the "
"trades of a whole partner the optima list",
tot["full_opt"] == tot["full"] == tot["full_enum"],
f"{tot['full']} places, {tot['full_opt']} of them listed, "
f"{tot['full_enum']} listed")
check_pins("the recorded seed's trades as recorded: the swap's "
"places, the full partner's, the dominated pairs beyond "
"both", tot, PIN_TRADES, 3)
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 8 laws; "
+ ", ".join(f"{key} {v}" for key, v in zip(OWN, mine,
strict=True)))
check("Pc every law holds at every further seed, each census sized "
"as the recorded one",
(held, sized, len(seeds)) == (8 * n, n, n),
f"{held} of {8 * 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_mass_bounds(tot)
section_exchange(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()