fatecensus.py

Checks: SETS: At three atoms on the twentieths every mass vector fails rule.

Cited on: SETS.

To run it: save fatecensus.py, with fates.py, sets.py beside it; standard library only.

"""fatecensus.py -- which three-atom mass vectors keep every above-level atom?

QUESTION. Three atoms, masses (m_0, m_1, m_2)/20, positive integers
summing to 20 (171 ordered vectors, 33 up to order), each row a sorted
posterior on the tenths (14 rows, 14^3 = 2744 row triples), T = 7/10.
A mass vector QUALIFIES when at no row triple is an atom with top > t*
forced-abandoned (every optimum, size vectors with labels bought whole,
gives it size 0). Which qualify? (The slack
1 - w_min - T is >= 0 at all 171, w_min <= 6/20.)

BY HAND (frozen before engine code). Masses in twentieths, coverage in
two-hundredths (T = 140).
An atom of mass m > 6 is never abandoned by a covering rule (the rest
covers 10(20 - m) < 140), so only atoms with m <= 6 are at risk.
TEMPLATE (a sufficient condition for failure). Roles (r, b, c) a
permutation, masses m, b, c; rows r = (10, 0, 0), b = (10, 0, 0), c =
(Y, 10 - Y, 0), Y in 5..9 (sorted). If
  (i) m + b < 14, (ii) b > m, (iii) 140 - 10b <= cY < 140 - 10m,
then r is forced-abandoned and above the level: pairs at 1 cover 10(m +
b) < 140, so t* <= Y/10 < 1 = r's top; (0, 1, 1) covers 10b + cY >= 140
at cost b + c; a vector serving r costs m plus its rest, and every rest
costing at most b + c - m fails to reach 140 - 10m: {b} (cost b <=
b + c - m, as m + b < 14 gives c > 6 >= m) covers 10m + 10b < 140,
{c-top} (cost c <= b + c - m as b > m) covers 10m + cY < 140,
{c-top, c-second} (2c <= b + c - m only if c <= b - m) covers 10m +
10c <= 10b < 140; every other rest costs more.
So every serving vector costs more than b + c >= OPT.

PREDICTIONS. (1) The census is symmetric: permuting a vector's masses
keeps its verdict (strongly; the definitions are). (2) ABOVE (2, 9, 9),
DA (11, 7, 2) and FA (1, 1, 18) fail, their hand atoms read A (strongly;
fates.py's witnesses). (3) Every vector the TEMPLATE marks fails
(strongly; the derivation). (4) (6, 7, 7) and (6, 6, 8) qualify
(weakly: the template misses both, and at (6, 7, 7) abandoning the 6
needs both others' whole rows, forcing t* = 1 at the rows I tried).
(5) The template is also necessary: the qualifiers are exactly its
survivors (weakly; no argument).

KILL (frozen; what the script PRINTS): "KILL template: marked vectors
read qualifying n" fires iff n >= 1, over the 171: the derivation is
wrong.

CONTROLS (before any verdict). POSITIVE: the engine's fates equal
fates.Fates's at ABOVE, BELOW, DA, DS, FA, FS (their hand fates) and at
2,000 census cells drawn at seed 1 (every atom). PLANT: forced read as
"some optimum gives size 0" (the open fate merged into A) must differ
from fates.Fates at some drawn cell, and must raise the failing count;
a plant missed by construction reads nothing.

FINDINGS. The kill misses: "KILL template: marked vectors read
qualifying 0". (1), (2), (3) held; (4) half: (6, 7, 7) qualifies and
(6, 6, 8) fails; (5) failed: 9 vectors up to order survive the
template, one qualifies.
  CONTROLS: the six hand cells read as fates.Fates reads them (ABOVE
  ASS, BELOW SAS, DA SSA, DS SAS, FA AAS, FS SSS); the engine equals
  fates.Fates at 2000 drawn cells ("0 differ"; S 4980, A 881, O 139
  atoms); the plant differs at 92 and raises the failing cells from
  95757 to 110565.
  THE ANSWER: "qualifying, up to order (1 of 33): [(6, 7, 7)]". ABOVE,
  DA, FA fail at 827, 511, 1466 row triples. The template's survivors
  (1, 1, 18), (1, 2, 17), (2, 2, 16), (2, 3, 15), (3, 3, 14), (4, 4, 12),
  (5, 5, 10), (6, 6, 8) fail off it, e.g. (6, 6, 8) at rows (10, 0, 0),
  (6, 4, 0), (5, 5, 0): t* 5/10, and by hand the one optimum is (1, 0,
  2) at cost 22 (coverage 140), every vector serving atom 1 at cost 22
  or less missing 140 ((1, 1, 1) covers 136 at 20), so atom 1, top 6/10,
  is forced-abandoned.
  WHY (6, 7, 7) QUALIFIES (by hand, after the run): only the atom of
  mass 6 can be abandoned, and a rule abandoning it covers 140 = the
  others' whole mass, so it buys both rows' supports. If both are
  single labels, pairs at 1 cover 140 and t* = 1, nothing above. Else
  let P be the least positive label of the two rows, in a row of
  support >= 2: swapping that label for the atom's top Top saves 7 - 6
  = 1 and covers iff 6 Top >= 7 P, so an optimum that abandons it has
  6 Top < 7 P, so Top <= P (P <= 5, on the tenths), so every bought
  label is >= Top, the pairs at Top cover 140 and t* >= Top: the atom
  is not above the level. At (6, 6, 8) the swap saves 2 against the
  heavier row but covers only when 6 Top >= 8 P, which Top 6, P 5
  misses.
  The plant's A-set holds the true one, so its raise is forced and its
  difference reads only that open fates exist (O 139 drawn): it controls
  nothing past the positive control, and the strict > of "above" has no
  plant. The frozen blocks above were first retyped shorter here
  (prediction (2)'s "their hand atoms read A", the KILL's clause, the
  plant's gloss, the template's t* <= Y/10 and {b}'s cost); restored
  verbatim from the frozen commit, (2)'s check then reading the hand
  atoms' A, and level() given a control against sets.Anatomy's t*.
  Run: 8/10 checks with the t* control (the two weak predictions' FAILs),
  11.3 s, peak commit 8.5 MB; first, 7/9, 12.8 s, peak
  commit 8.3 MB.

ON THE TWENTIETHS (frozen before its engine code). The swap closes
because 6 Top < 7 P forces Top <= P when P <= 5, which the tenths give;
on the twentieths P runs to 10 and Top = P + 1 is admitted for P >= 6.
Does (6, 7, 7) fail at rows on the twentieths (coverage in four-
hundredths, the bar 280)? BY HAND, cell H: rows (8, 6, 6), (13, 7, 0),
(20, 0, 0). (1, 1, 1) costs 20 and covers 48 + 91 + 140 = 279 < 280;
(0, 2, 1) costs 21 and covers 280. Every vector serving atom 0 at cost
<= 21 misses: s0 = 1 with s1 + s2 <= 2 covers at most 279, s0 = 2 with
s1 + s2 <= 1 at most 224, s0 = 3 alone 120; below cost 21 every
abandoning vector covers at most 231, and at 21 (0, 3, 0), (0, 1, 2),
(0, 0, 3) cover 140, 231, 140. So OPT = 21 at the one optimum (0, 2,
1), atom 0 forced-abandoned; t* = 7/20 (at 8, 279 < 280), below its top
8/20. By inclusion (rows on the tenths are rows on the twentieths), no
three-atom vector of masses on the twentieths then qualifies at rows on
the twentieths.
  PREDICTIONS. (6) H reads atom 0 A and t* = 7/20 (strongly; by hand).
  (7) (6, 7, 7) fails at n >= 1 of the 44^3 row triples on the
  twentieths (strongly; H).
  KILL (frozen; what the script PRINTS): "KILL twentieths: (6, 7, 7)
  failing row triples n, H fails B" fires iff n = 0 or B is False.
  CONTROL: the engine, its row grid a parameter, equals fates.Fates and
  sets.Anatomy's t* at 2,000 cells drawn at seed 2 with rows on the
  twentieths.
  FINDINGS. The kill misses: "KILL twentieths: (6, 7, 7) failing row
  triples 82, H fails True". (6) and (7) held: H reads fates ASS at t*
  7/20. CONTROL: 0 fates and 0 levels differ at the 2000 drawn cells
  (S 5071, A 785, O 144 atoms). So (6, 7, 7)'s qualifying is the tenths'
  grid's, and no three-atom vector of masses on the twentieths qualifies
  at rows on the twentieths. The frozen text's "P >= 6" is P >= 7:
  6(P + 1) < 7P iff P > 6, and H's P is 7. Run: 12/12 checks, 13.1 s, peak commit
  8.6 MB.

RUN: python fatecensus.py. The weak predictions (4) and (5) are read as
prints since the script moved beside the doc it serves; the tenths
census's answer, (6, 7, 7) alone, is a check.
"""
import random
import sys
import time
from fractions import Fraction as F
from itertools import permutations, product

from fates import ABOVE, BELOW, DA, DS, FA, FS, Fates
from sets import Cell

CHECKS = []


def grid(d):
    """The sorted three-label rows on the 1/d."""
    return [(a, b, d - a - b) for a in range(d, -1, -1)
            for b in range(a, -1, -1) if 0 <= d - a - b <= b]


ROWS = grid(10)
ROWS20 = grid(20)
MASSES = [(a, b, 20 - a - b) for a in range(1, 19) for b in range(1, 20 - a)]


def check(name, ok, detail=""):
    CHECKS.append(bool(ok))
    tail = f"  ({detail})" if detail else ""
    print(f"  {'PASS' if ok else 'FAIL'}  {name}{tail}", flush=True)


def level(ms, rows, d=10):
    """t*, in 1/d: the largest t whose pairs {p >= t} cover T, the bar
    14 d in units of 1/(20 d)."""
    for t in range(d, 0, -1):
        if sum(m * sum(y for y in row if y >= t)
               for m, row in zip(ms, rows)) >= 14 * d:
            return t
    raise AssertionError("no level")


def fates(ms, rows, plant=False, d=10):
    """Each atom's fate, A, S or O, over the optima of the 64 size
    vectors (cost in twentieths, coverage in units of 1/(20 d))."""
    opts = [[(m * s, m * sum(row[:s])) for s in range(4)]
            for m, row in zip(ms, rows)]
    best, arg = None, []
    for sz in product(range(4), repeat=3):
        c = opts[0][sz[0]][0] + opts[1][sz[1]][0] + opts[2][sz[2]][0]
        if best is not None and c > best:
            continue
        v = opts[0][sz[0]][1] + opts[1][sz[1]][1] + opts[2][sz[2]][1]
        if v < 14 * d:
            continue
        if best is None or c < best:
            best, arg = c, [sz]
        else:
            arg.append(sz)
    out = []
    for r in range(3):
        zero = [o[r] == 0 for o in arg]
        if plant:
            out.append("A" if any(zero) else "S")
        else:
            out.append("A" if all(zero) else "S" if not any(zero) else "O")
    return out


def bad_atoms(ms, rows, plant=False, d=10):
    """The above-level atoms forced-abandoned."""
    t = level(ms, rows, d)
    f = fates(ms, rows, plant, d)
    return [r for r in range(3) if rows[r][0] > t and f[r] == "A"]


def cell_of(ms, rows, d=10):
    return Cell("x", [F(m, 20) for m in ms],
                [[F(y, d) for y in row] for row in rows])


def scaled(cell):
    """A hand cell on the twentieths and tenths, as integers."""
    ms = tuple(int(w * 20) for w in cell.w)
    rows = tuple(tuple(int(y * 10) for y in row) for row in cell.srt)
    assert all(F(m, 20) == w for m, w in zip(ms, cell.w))
    return ms, rows


def template(ms):
    """True when some role assignment meets (i)-(iii) at some Y."""
    for r, b, c in permutations(range(3)):
        m, B, C = ms[r], ms[b], ms[c]
        if m + B < 14 and B > m and any(
                140 - 10 * B <= C * Y < 140 - 10 * m for Y in range(5, 10)):
            return True
    return False


def canon(ms):
    return tuple(sorted(ms))


def twentieths():
    """(6, 7, 7) at every row triple on the twentieths, after a control
    of the engine there against fates.Fates and sets.Anatomy."""
    print("ON THE TWENTIETHS")
    rng = random.Random(2)
    miss, tmiss, kinds = 0, 0, {}
    for _ in range(2000):
        ms = rng.choice(MASSES)
        rows = tuple(rng.choice(ROWS20) for _ in range(3))
        x = Fates(cell_of(ms, rows, 20))
        tmiss += F(level(ms, rows, 20), 20) != x.an.t
        ref = [x.fate_of(r) for r in range(3)]
        miss += fates(ms, rows, d=20) != ref
        for f in ref:
            kinds[f] = kinds.get(f, 0) + 1
    print(f"  2000 drawn cells: fates read {kinds}")
    ok = miss == 0 and tmiss == 0
    check("CONTROL: fates and t* as fates.Fates reads them, on the "
          "twentieths", ok, f"{miss} fates, {tmiss} levels differ")
    if not ok:
        print("CONTROL FAILED: nothing below is read.")
        return
    ms, h = (6, 7, 7), ((8, 6, 6), (13, 7, 0), (20, 0, 0))
    hf, ht = fates(ms, h, d=20), level(ms, h, 20)
    print(f"  H: rows {h}, fates {''.join(hf)}, t* {ht}/20")
    hb = bad_atoms(ms, h, d=20) == [0]
    check("(6) H reads atom 0 A and t* = 7/20", hf[0] == "A" and ht == 7)
    n = sum(1 for rows in product(ROWS20, repeat=3)
            if bad_atoms(ms, rows, d=20))
    print(f"  {len(ROWS20)} sorted rows, {len(ROWS20) ** 3} row triples")
    print(f"KILL twentieths: (6, 7, 7) failing row triples {n}, H fails {hb}")
    print(f"KILL fires: {n == 0 or not hb}")
    check("(7) (6, 7, 7) fails on the twentieths", n >= 1 and hb)


if __name__ == "__main__":
    t0 = time.time()
    assert len(ROWS) == 14 and len(MASSES) == 171
    print("CONTROLS")
    hand = {"ABOVE": ABOVE, "BELOW": BELOW, "DA": DA, "DS": DS, "FA": FA,
            "FS": FS}
    agree = []
    for name, cell in hand.items():
        ms, rows = scaled(cell)
        ref = [Fates(cell).fate_of(r) for r in range(3)]
        got = fates(ms, rows)
        agree.append(got == ref)
        print(f"  {name}: masses {ms}, fates engine {''.join(got)}, "
              f"fates.Fates {''.join(ref)}")
    check("POSITIVE: the six hand cells' fates as fates.Fates reads them",
          all(agree))
    rng = random.Random(1)
    drawn = [(rng.choice(MASSES), tuple(rng.choice(ROWS) for _ in range(3)))
             for _ in range(2000)]
    miss, pmiss, tmiss, kinds = 0, 0, 0, {}
    for ms, rows in drawn:
        x = Fates(cell_of(ms, rows))
        tmiss += F(level(ms, rows), 10) != x.an.t
        ref = [x.fate_of(r) for r in range(3)]
        miss += fates(ms, rows) != ref
        pmiss += fates(ms, rows, plant=True) != ref
        for f in ref:
            kinds[f] = kinds.get(f, 0) + 1
    print(f"  2000 drawn cells: fates read {kinds}")
    check("POSITIVE: the engine equals fates.Fates at 2000 drawn cells",
          miss == 0, f"{miss} differ")
    check("POSITIVE: level() is sets.Anatomy's t* at the 2000 cells",
          tmiss == 0, f"{tmiss} differ")
    check("PLANT: 'some optimum empties it' differs at a drawn cell",
          pmiss > 0, f"{pmiss} differ")
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)

    print("THE CENSUS")
    fail, wit, ncells, pcells = {}, {}, 0, 0
    for ms in MASSES:
        n = 0
        for rows in product(ROWS, repeat=3):
            b = bad_atoms(ms, rows)
            if b:
                n += 1
                wit.setdefault(ms, (rows, b))
        pn = sum(1 for rows in product(ROWS, repeat=3)
                 if bad_atoms(ms, rows, plant=True))
        fail[ms] = n
        ncells += n
        pcells += pn
    print(f"  failing (vector, rows) cells {ncells}; under the plant {pcells}")
    check("PLANT: the plant raises the failing cells", pcells > ncells)
    qual = sorted({canon(ms) for ms in MASSES if fail[ms] == 0})
    sym = all((fail[ms] == 0) == (fail[tuple(p)] == 0)
              for ms in MASSES for p in permutations(ms))
    check("(1) the verdict is symmetric under permuting the masses", sym)
    for name in ("ABOVE", "DA", "FA"):
        ms = scaled(hand[name])[0]
        print(f"  {name} {ms}: failing row triples {fail[ms]}")
    atom_a = {"ABOVE": 0, "DA": 2, "FA": 0}
    check("(2) ABOVE, DA and FA fail, their hand atoms read A",
          all(fail[scaled(hand[x])[0]] > 0
              and fates(*scaled(hand[x]))[atom_a[x]] == "A" for x in atom_a))
    marked = {ms for ms in MASSES if template(ms)}
    bad = [ms for ms in marked if fail[ms] == 0]
    print("THE KILL")
    print(f"KILL template: marked vectors read qualifying {len(bad)}")
    print(f"KILL fires: {len(bad) >= 1}")
    check("(3) every vector the template marks fails", not bad)
    print(f"  qualifying, up to order ({len(qual)} of 33): {qual}")
    surv = sorted({canon(ms) for ms in MASSES if ms not in marked})
    print(f"  template survivors, up to order ({len(surv)}): {surv}")
    check("THE ANSWER: on the tenths (6, 7, 7) alone qualifies",
          qual == [(6, 7, 7)])
    print(f"  (4), weak, read: (6, 7, 7) qualifies {(6, 7, 7) in qual}, "
          f"(6, 6, 8) qualifies {(6, 6, 8) in qual}")
    extra = sorted(set(surv) - set(qual))
    print(f"  (5), weak, read: template survivors failing off it {extra}")
    for ms in extra:
        for p in permutations(ms):
            if p in wit:
                rows, b = wit[p]
                print(f"  {p}: rows {rows}, t* {level(p, rows)}/10, "
                      f"forced-abandoned above the level: atoms {b}")
                break
    twentieths()
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")
    sys.exit(0 if all(CHECKS) else 1)