fixedt.py

Checks: SETS: Deciding a fate encodes subset sum theorem.

Cited on: SETS.

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

"""fixedt.py -- is an atom's fate as hard at a FIXED coverage level?

QUESTION. fatehard.py's reduction from SUBSET SUM sets the level
T = (1 - e) B u from the instance, so it shows nothing at a level fixed
beforehand, the sweep's 7/10 say. Does the hardness survive at every
fixed rational tau in (0, 1)? The objects: a cell's atoms, each a mass
and a posterior row; a rule's cost and coverage; an atom forced-served
or forced-abandoned by the optima.

THE DERIVATION (by hand, before any code). Given positive integers b,
a target B and a level tau, take e = 1/4, W = B + 3/4 and atoms
  the rest   mass b_i u, row (3/4, 1/4)
  a FILLER   mass D u,   row (3/4, 1/4)
  a PAD      mass P u,   row (1, 0)
  a (last)   mass W u,   row (3/4, 1/4)
with u = 1/(sum b + D + P + W) and T = (P + (1 - e) B) u, which is tau
exactly when P (1 - tau) = tau (sum b + W + D) - (1 - e) B. D is the
least integer >= B + 1 making P >= 3.
Every atom but the pad covers at most 1 - e per unit of cost.
  (i)   A covering rule without the pad costs at least
        (P + (1 - e) B)/(1 - e) = P + B + P e/(1 - e) >= P + B + 1 (u).
  (ii)  A rule that uses the filler beside the pad costs at least
        P + D >= P + B + 1.
  (iii) With the pad, no filler and no a, the rest must cover
        (1 - e) B: at cost B exactly when a subset of b sums to B,
        else at B + 1 or more (its costs are whole numbers of u).
  (iv)  A rule serving a costs at least P + W: beside the pad it costs
        that or more, and the pad with a at size 1 covers; without the
        pad, (i) gives P + B + 1 > P + W.
YES: OPT = (P + B) u and the least cost serving a is (P + W) u: a is
forced-abandoned, by 3u/4. NO: every rule without a costs at least
(P + B + 1) u > (P + W) u = OPT: a is forced-served, by at least u/4.
So at every fixed rational tau the fate is NP-hard one way and
coNP-hard the other, masses in binary, on the two rows (1, 0) and
(3/4, 1/4) alone. Here a's row is the rest's, which fatehard.py's cell
does not read: nothing above uses more of it than its top, 3/4.

BY HAND, at tau = 7/10 (atoms in the order rest, filler, pad, a).
  F1 b (1, 3), B 2: W 11/4, D 3, P = (0.7 * 9.75 - 1.5)/0.3 = 71/4,
     u 2/55; masses 2/55, 6/55, 6/55, 71/110, 1/10; T 7/10. NO, tight:
     OPT (P + W) u = 41/55 (the pad and a), the least cost without a
     (P + 3) u = 83/110, fate S, margin 1/110 = u/4.
  F2 b (1, 3), B 3: W 15/4, D 4, P = (0.7 * 11.75 - 2.25)/0.3 =
     239/12, u 3/95; T 7/10. YES: OPT (P + 3) u, the least cost
     serving a (P + W) u, fate A, margin 3u/4.
And at tau = 1/5, where the filler's size binds.
  F3 b (1,), B 1: W 7/4, and P = (D - 1)/4, so P >= 3 first at D 13:
     P 3, u 4/75, T 1/5. YES: OPT (P + 1) u = 16/75 at the pad and the
     part, the least cost serving a (P + W) u = 19/75, fates SASA. At
     D 12 the pad is 11/4, under 3: a cell at the level all the same,
     and the row's valid field 0.
The law fields are fatehard.law_fields, read on the three costs less
the pad's P u.

PREDICTIONS, frozen before the engine.
  P1 at tau = 7/10, 1/5 and 19/20, over every multiset of at most four
     parts from 1 to 4 with every B from 1 to its sum (4 + 10 + 20 +
     35 = 69 multisets, 10 + 50 + 150 + 350 = 560 instances): every
     cell valid with T = tau, the fate A on yes and S on no, OPT
     (P + B) u on yes and (P + W) u on no, the margin 3u/4 on yes, at
     least u/4 on no and u/4 where B + 1 is a subset sum.
  P2 at tau = 7/10 fates.py's engine, which reads a cell at 7/10
     alone, gives a the same fate at every instance: agreements
     counted, 560 of 560.
  KILL, as printed: "fate mismatches m of 560" with m >= 1 at any tau,
     or an agreement count under 560: the derivation has a hole.
  CONTROL, read first (the plant), at tau = 7/10: D = 1, P recomputed
     (there P = (0.7 sum b - 0.05 B + 1.225)/0.3 > 6). The filler is
     then one more part of 1, so the fate must be wrong at exactly the
     NO instances with B - 1 a subset sum, a set fatehard.sums names
     without a cell; by hand wrong at b (1, 3), B 2 (the pad, the part
     1 and the filler cost P + 2) and right at b (3,), B 2. A plant
     that fails nowhere, or everywhere, reads nothing.

FINDINGS (copied from the printed output; the engine was written after
the lines above were committed, F3 and the law-fields line aside: they
came with a later repair of the engine, F3 by hand before its run).
  F0 CONTROLS. F1 and F2 as by hand (D 3, P 71/4, u 2/55, OPT 41/55,
     empty 83/110, fates AAASS; D 4, P 239/12, u 3/95, OPT 55/76,
     served 71/95, fates ASASA) and F3 (D 13, P 3, u 4/75, OPT 16/75,
     served 19/75, fates SASA; valid 0 at D 12). The plant: fate
     mismatches 125 of 560; decoyed no 125 of 176; split 560; valid
     560.
  F1 KILL MISSED, P1 HELD. At tau = 7/10, 1/5 and 19/20 alike: 560
     instances (384 yes, 176 no, 125 tight); fate mismatches 0 of 560;
     OPT off at 0; margin 3/4 at 384 yes, at least 1/4 at 176 no, 1/4
     at 125 tight; 6 of 6 laws.
  F2 P2 HELD. fates.py's engine at 7/10: the fate of a agrees at 560 of
     560, OPT at 560 of 560.
  TIERS. The hardness at a fixed level is the derivation's, a proof by
  hand; F1 checks its construction on a toy family (at most four parts
  from 1 to 4) at three levels and one e, a's row the rest's. D enters
  through (ii) alone, where more than B + 3/4 would do. Unread: whether
  P >= 3 is needed or only sufficient; any e but 1/4.
  MUTANTS. One token changed at each of 67 sites of build and row_at:
  65 runs turn red. The two that stay green each drop a clause of
  valid that the build's algebra makes true of every cell (the masses
  sum to 1; T is tau); the third clause, P >= 3, is F3's at D 12.

RUN RECORD. python fixedt.py: 11 of 11 checks, 2.3 s, peak commit
11.2 MB under a memory guard (512 MB).
"""

import sys
import time
from fractions import Fraction as F
from math import ceil

import fatehard as FH
from fates import Fates
from sets import Cell
from sets import T as SWEEP_T

E = F(1, 4)
TAUS = (F(7, 10), F(1, 5), F(19, 20))
CHECKS = []
LINES = 10


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


def build(b, B, tau, D=None):
    """The cell, atoms in the order rest, filler, pad, a; then u, P, D.
    D None: the least integer >= B + 1 making P >= 3."""
    W = B + F(3, 4)

    def pad(D):
        return (tau * (sum(b) + W + D) - (1 - E) * B) / (1 - tau)

    if D is None:
        need = (3 * (1 - tau) + (1 - E) * B) / tau - sum(b) - W
        D = max(B + 1, ceil(need))
    P = pad(D)
    u = 1 / (sum(b) + D + P + W)
    row = (1 - E, E)
    w = [x * u for x in b] + [D * u, P * u, W * u]
    rows = [row] * (len(b) + 1) + [(F(1), F(0)), row]
    return w, rows, (P + (1 - E) * B) * u, u, P, D


def row_at(b, B, tau, D=None, weld=False):
    """One instance at one level: every field 0 or 1."""
    S = FH.sums(b)
    yes = B in S
    tight = not yes and B + 1 in S
    w, rows, T, u, P, D = build(b, B, tau, D)
    x = FH.read(w, rows, T, len(w) - 1)
    fate = x["fates"][-1]
    out = {
        "instances": 1,
        "yes": yes,
        "no": not yes,
        "tight": tight,
        "decoy_no": not yes and B - 1 in S,
        "valid": FH.is_cell(w, rows, T) and T == tau and P >= 3,
    }
    pad = P * u
    out.update(FH.law_fields(yes, tight, fate, x["opt"] - pad,
                             x["served"] - pad, x["empty"] - pad, B, u))
    out["split"] = out["fate"] != out["decoy_no"]
    if weld:
        other = Fates(Cell("X", w, [list(r) for r in rows]))
        out["weld"] = other.fate_of(len(w) - 1) == fate
        out["weld_opt"] = other.value(other.opt) == x["opt"]
    return out


LAWS = (("valid", "instances"), ("fate", "instances"),
        ("opt", "instances"), ("m_yes", "yes"), ("m_no", "no"),
        ("m_tight", "tight"))


def main():
    t0 = time.time()
    fam = FH.family(4, 4)
    tau = F(7, 10)
    print("CONTROLS")
    w, rows, T, u, P, D = build((1, 3), 2, tau)
    x = FH.read(w, rows, T, len(w) - 1)
    check("F1 by hand: D 3, P 71/4, u 2/55, the masses, T 7/10; OPT "
          "41/55, empty 83/110, fate S",
          (D, P, u, T) == (3, F(71, 4), F(2, 55), tau)
          and w == [F(2, 55), F(6, 55), F(6, 55), F(71, 110), F(1, 10)]
          and (x["opt"], x["empty"], x["fates"][-1])
          == (F(41, 55), F(83, 110), "S"),
          f"D {D}, P {P}, u {u}, OPT {x['opt']}, empty {x['empty']}, "
          f"fates {x['fates']}")
    w, rows, T, u, P, D = build((1, 3), 3, tau)
    x = FH.read(w, rows, T, len(w) - 1)
    check("F2 by hand: D 4, P 239/12, u 3/95, T 7/10; OPT 55/76, served "
          "71/95, fate A",
          (D, P, u, T) == (4, F(239, 12), F(3, 95), tau)
          and (x["opt"], x["served"], x["fates"][-1])
          == (F(55, 76), F(71, 95), "A"),
          f"D {D}, P {P}, u {u}, OPT {x['opt']}, served {x['served']}, "
          f"fates {x['fates']}")
    low = F(1, 5)
    w, rows, T, u, P, D = build((1,), 1, low)
    x = FH.read(w, rows, T, len(w) - 1)
    short = row_at((1,), 1, low, D=12)
    check("F3 by hand, at 1/5: D 13, P 3, u 4/75, T 1/5; OPT 16/75, "
          "served 19/75, fates SASA; at D 12 the row is not valid",
          (D, P, u, T) == (13, 3, F(4, 75), low)
          and (x["opt"], x["served"], x["fates"])
          == (F(16, 75), F(19, 75), "SASA")
          and (row_at((1,), 1, low)["valid"], short["valid"])
          == (True, False),
          f"D {D}, P {P}, u {u}, OPT {x['opt']}, served {x['served']}, "
          f"fates {x['fates']}, valid at D 12 {short['valid']:d}")
    hand = (row_at((1, 3), 2, tau, D=1), row_at((3,), 2, tau, D=1))
    check("the plant by hand: with a filler of 1 the fate is wrong at "
          "b (1, 3), B 2 and right at b (3,), B 2",
          (hand[0]["fate"], hand[1]["fate"]) == (False, True),
          f"fate fields {hand[0]['fate']:d}, {hand[1]['fate']:d}")
    tot = FH.census(row_at(b, B, tau, D=1) for b, B in fam)
    n, d = tot["instances"], tot["decoy_no"]
    print(f"  the plant, a filler of 1 at tau = 7/10: fate mismatches "
          f"{n - tot['fate']} of {n}; decoyed no {d} of {tot['no']}; "
          f"split {tot['split']}; valid {tot['valid']}")
    check("the plant: the fate is wrong exactly at the no instances "
          "with B - 1 a subset sum, some and not all",
          tot["split"] == n == 560 and n - tot["fate"] == d
          and 0 < d < tot["no"] and tot["valid"] == n,
          f"split {tot['split']} of {n}, wrong {n - tot['fate']}")
    check("the level fates.py reads is 7/10", SWEEP_T == tau)
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    print("\nTHE FAMILY AT EACH FIXED LEVEL")
    kill = 0
    for tau in TAUS:
        tot = FH.census(row_at(b, B, tau, weld=tau == SWEEP_T)
                        for b, B in fam)
        n = tot["instances"]
        held = sum(tot[f] == tot[pop] for f, pop in LAWS)
        kill += n - tot["fate"]
        print(f"  tau = {tau}: {n} instances ({tot['yes']} yes, "
              f"{tot['no']} no, {tot['tight']} tight); fate mismatches "
              f"{n - tot['fate']} of {n}; OPT off at {n - tot['opt']}; "
              f"margin 3/4 at {tot['m_yes']} yes, at least 1/4 at "
              f"{tot['m_no']} no, 1/4 at {tot['m_tight']} tight; "
              f"{held} of {len(LAWS)} laws")
        check(f"P1 at tau = {tau}: 560 instances, every law at its "
              "population", n == 560 and held == len(LAWS),
              f"{held} of {len(LAWS)}")
        if "weld" in tot:
            print(f"  fates.py's engine at 7/10: the fate of a agrees at "
                  f"{tot['weld']} of {n}, OPT at {tot['weld_opt']} of {n}")
            check("P2 fates.py's engine gives a the same fate, and the "
                  "cell the same OPT, at every instance",
                  tot["weld"] == n == tot["weld_opt"],
                  f"{tot['weld']} and {tot['weld_opt']} of {n}")
    print(f"  KILL (a fate mismatch at a level): "
          f"{'FIRED' if kill else 'MISSED'}")
    ran = len(CHECKS)
    check("every check line of the run printed, this one aside",
          ran == LINES, f"{ran} of {LINES}")
    print(f"\n{sum(CHECKS)} of {len(CHECKS)} checks, "
          f"{time.time() - t0:.1f} s")
    sys.exit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()