goldren.py

Checks: FLUSH: The cylinder bound theorem; rule; pattern; observation.

Cited on: FLUSH.

To run it: save goldren.py, with defer.py, flush.py, goldelta.py, goldfix.py, goldsurv.py, ostrowski.py, shifted.py beside it; standard library only.

"""goldren.py -- R(delta) = 1/phi + delta/phi^2 read in G_delta's
coordinates: the translate family T_s(v) = phi^-2 v + s.

QUESTION. goldsurv.py's survivor sets show R sending fixed points of
G_delta to fixed points of G_(R delta) 2 or 3 levels deeper. Is that
carried by copies: T_s(A_n(delta)) inside A_n(R delta) for a fixed set
of translations s, at every n, on every cell?

DESIGN (by hand before the engine). On A-states T_s(v) = phi^-2 v + s, on
B-states T'_r(u) = phi^-2 u + r. T_s(V_delta) lies in V_(R delta) iff s in
W_A = [-phi^-3, 1 - phi^-3], T'_r(U_delta) in U_(R delta) iff r in W_B =
[-2/phi, phi^-2], both delta-free. When the delta-reader plays a digit
and the R delta-reader answers, the new R delta-state is the image of
the new delta-state under a new translation, delta-free:
  (a) s' = phi C - phi s - c/phi    (A -> A, c, C in {0, 1})
  (b) r  = phi E - phi s - e/phi    (A -> B, e, E in {0, 1})
  (c) s' = phi C' - phi r - (c' + 1)/phi  (B -> A, c', C' in {-1, 0, 1})
So the translations play a game Gamma with the delta-reader's digits as
adversary; a safe set tau_A, tau_B of Gamma against the digits the
delta-reader uses gives T_s(A_n(delta)) in A_n(R delta) at every n, by
induction (base: the windows). It carries a pass up, never a fail.
Below 1/phi the delta-reader plays c = 1, e = 0, c' in {0, 1} only (c =
0, e = 1 and c' = -1 each need delta >= 1/phi). Gamma's closure there,
by hand, tau_A = {a, b, c, d, e} = {-phi^-3, phi^-4, phi^-2, 2phi^-2 -
phi^-3, 2phi^-2}: at c = 1, a -> a (C = 0), b -> e, c -> c, d -> b, e ->
a (C = 1); at e = 0 (E = 0), a -> phi^-2, b -> -phi^-3, c -> -1/phi, d
-> 4 - 3phi, e -> -2/phi; from tau_B at c' = 0, 1: -2/phi -> a (C' =
-1), e (0); 4 - 3phi -> e, b (0, 0); -1/phi -> c, a (0, 0); -phi^-3 ->
a, e (0, 1); phi^-4 -> e, b (1, 1); phi^-2 -> c, a (1, 1). The 22
identities close the sets, so the copies below 1/phi are a theorem
with no step a run; gamma() reprints the sets.

The engine runs G_delta and G_(R delta) on one cell of delta at once, the
R delta game's ends rewritten in delta (V_(R delta) = [-delta/phi^2, 1 +
delta/phi^3], U_(R delta) = [-2, delta/phi], its B -> A shift c'' - 2 +
delta/phi^2, c'' in {0, 1, 2}), every comparison by goldsurv's Cell (a
sign change splits the cell at the root, the histories carried). An
inclusion X in Y of sorted disjoint lists is read by a merge walk.

PREDICTIONS (frozen before this engine), every cell of [0, delta_3], L
<= 40:
P1 on cells in [0, 1/phi): every s in tau_A and r in tau_B hold at every
   n (proved once Gamma's sets are exact; a failure is an engine fault).
P2 (a TRANSPLANT from four fixed points' floats) on [1/phi, delta_3]:
   every s in tau_A holds at every n < L*(delta).
P3 (a TRANSPLANT from goldsurv's depth up 2 or 3) wherever L*(delta) is
   finite, L*(R delta) - L*(delta) >= 2; the lag (the largest k <= 3 with
   T_s(A_n(delta)) in A_(n+k)(R delta) at every n) printed.
KILL (one print): "pass-up fails at N cells": the cells with some n <
   L*(delta) at which no s in tau_A has T_s(A_n(delta)) in A_n(R delta).
   Read over every cell, none drawn; per-s, per-r counts beside it.
Controls, read before the kill: (a) Gamma's safe sets exact: five and
   six points at c = 1, e = 0, c' in {0, 1}; empty with c' = -1, c = 0
   or e = 1 added; (b) at delta = 0, T_s(A(0)) over tau_A is A(delta_1),
   one point each; (c) the planted break s = 0 fails at delta = 0; (d)
   every open cell's verdicts equal its midpoint's.

FINDINGS (copied from the print).
Controls held: (a) Gamma at c = 1, e = 0, c' in {0, 1} is fixed at n =
   3, tau_A the five frozen points, tau_B the six; empty with c' = -1 or
   with c = 0 added; with e = 1 added tau_A is unchanged (the frozen
   control said empty: a misreading of a float regime that also held c'
   = -1; corrected to the exact print, so e = 1 costs Gamma nothing); (b)
   T_s(A(0)) over tau_A is A(delta_1) = {0, phi^-2, 1/phi, 2phi^-2, 1},
   one point each, exactly; (c) s = 0 fails at delta = 0; (d) 0 of the
   143 open cells' verdicts differ from their midpoints'.
The survey: [0, delta_3], cut at 1/phi, 287 leaves (143 open), 141
   splits; every n decided (G_delta empty, or both games fixed) at 287
   of 287 leaves.
P1 held: [0, 1/phi), 16 leaves, 0 with a failing s or r.
P2 held: [1/phi, delta_3], 271 leaves, 0 with a failing s; each of the
   five s and six r fails at 0 leaves.
P3 KILLED: L*(R delta) - L*(delta) takes 1, 2, 3, 4, 5, 6; the lag is
   1 for s = -phi^-3, phi^-2, 2phi^-2 and 0 for phi^-4, 2phi^-2 -
   phi^-3 at 286 leaves, 3 (the cap) at the one leaf delta = 0; ends
   (G_delta, G_(R delta)): 266 (empty, empty), 12 (empty, fixed), 9
   (fixed, fixed); "short" verdicts 0.
KILL missed: "pass-up fails at 0 cells". So T_s(A_n(delta)) lies in
   A_n(R delta) for all five s, and T'_r(B_n(delta)) in B_n(R delta) for
   all six r, at every n on [0, delta_3] (a rule), though Gamma's
   delta-free argument covers only [0, 1/phi): above it c = 0 and c' =
   -1 occur, and the copies hold anyway.

RUN RECORD. 5 of 5, 24.0 s, peak 28.7 MB under a 2048 MB cap. --s0
(s = 0 added to tau_A): s = 0 fails at 287 of 287 leaves, the other
counts unchanged, so the inclusion read can fail on cells. --break
(goldsurv's split skipped): 5 leaves, (d) fails at 2 of 2 open cells.
Changes to what was frozen: control (a)'s e = 1 clause (above); the
check of n past G_delta's fixing up to G_(R delta)'s, and the "every n
decided" count, added after the first run (every verdict unchanged).
The kill as coded, no s holding at every n, holds the frozen one (some
n at which no s holds), so its 0 carries the frozen 0; no plant fires
the kill line itself. After a review: control (b) reads both ends, (a)'s
e = 1 arm tau_B too, the lags by leaf count, the ends and "short"
printed; 5 of 5, 24.3 s, peak 28.6 MB, every verdict unchanged. The
copies' rule, the KILL with P1 and P2, every n decided and no "short"
verdict, then made one check: 6 of 6; --s0 fails it alone.
That check first read r above 1/phi by print alone; it reads it now
(a break of okB above 1/phi alone fails it, and passed it before).

Run: python goldren.py [--s0 | --break]
"""
from collections import Counter
import os
import sys
import time

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from goldsurv import (Cell, Pt, Split, zmul, zadd, zsub, zpow, zfloat,  # noqa
                      fneg, fshift, negscale, shifts, dk_pt, mid, V0, U0)

S0 = "--s0" in sys.argv
LMAX = 40
KLAG = 3
CHECKS = []


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


E2 = (2, -1)                      # phi^-2
Z0 = (0, 0)
# G_(R delta) in delta: V = [-delta/phi^2, 1 + delta/phi^3], U = [-2,
# delta/phi]; B -> A shift c'' - 2 + delta/phi^2
VR = [((Z0, (-2, 1)), ((1, 0), (-3, 2)))]
UR = [(((-2, 0), Z0), (Z0, (-1, 1)))]
GAMES = {"d": (V0, U0, ((-1, -1), (1, 0))), "R": (VR, UR, ((-2, 0), E2))}

TAU_A = [(3, -2), (5, -3), (2, -1), (7, -4), (4, -2)]
TAU_B = [(2, -2), (4, -3), (1, -1), (3, -2), (5, -3), (2, -1)]
if S0:
    TAU_A = TAU_A + [(0, 0)]


def gstep(cell, A, B, game):
    V, U, (sa, sb) = GAMES[game]
    nA = negscale(A)
    A2 = cell.inter(cell.inter(V, cell.norm(shifts(nA, 1))),
                    cell.norm(shifts(negscale(B), 1)))
    B2 = cell.inter(U, [(fshift(x, sa, sb), fshift(y, sa, sb))
                        for x, y in cell.norm(shifts(nA, 2))])
    return A2, B2


def tmap(S, s):
    """phi^-2 S + s on a list of intervals of linear functions."""
    return [((zadd(zmul(E2, x[0]), s), zmul(E2, x[1])),
             (zadd(zmul(E2, y[0]), s), zmul(E2, y[1]))) for x, y in S]


def subset(cell, X, Y):
    k = 0
    for lo, hi in X:
        while k < len(Y) and cell.cmp(Y[k][1], lo) < 0:
            k += 1
        if k == len(Y) or cell.cmp(Y[k][0], lo) > 0 \
                or cell.cmp(hi, Y[k][1]) > 0:
            return False
    return True


# ------------------------------------------------------------ Gamma

def gamma(cs, es, cps, nmax=200):
    """Gamma's safe sets (tau_A, tau_B), exact, at the adversary digits
    cs (A -> A), es (A -> B), cps (B -> A)."""
    cell = Cell(Pt(Z0), None)
    WA = [(((3, -2), Z0), ((4, -2), Z0))]
    WB = [(((2, -2), Z0), ((2, -1), Z0))]

    def pre(S, ks, Cs):
        # {t : -phi t + phi C - k in S} = C - k/phi^2... as (C - K) - S/phi
        out = None
        for k in ks:
            u = cell.norm([(fshift(x, zsub((C, 0), zmul(k, E2))),
                            fshift(y, zsub((C, 0), zmul(k, E2))))
                           for C in Cs for x, y in negscale(S)])
            out = u if out is None else cell.inter(out, u)
        return out
    A, B = WA, WB
    for n in range(nmax):
        A2 = cell.inter(cell.inter(WA, pre(A, [(c, 0) for c in cs], (0, 1))),
                        pre(B, [(e, 0) for e in es], (0, 1)))
        B2 = cell.inter(WB, pre(A, [(cp + 1, 0) for cp in cps], (-1, 0, 1)))
        if cell.same(A2, A) and cell.same(B2, B):
            return A, B, n
        A, B = A2, B2
    return A, B, None


def pts_of(S):
    return [x[0] for x, y in S if x == y]


def section_gamma():
    print("== (a) Gamma's safe sets, exact")
    A, B, n = gamma((1,), (0,), (0, 1))
    pa, pb = pts_of(A), pts_of(B)
    print(f"    c = 1, e = 0, c' in {{0, 1}}: fixed at n = {n}; tau_A {pa}; "
          f"tau_B {pb}")
    check("(a) tau_A, tau_B: five and six points, as frozen",
          len(pa) == len(A) == 5 and len(pb) == len(B) == 6
          and sorted(pa) == sorted(TAU_A[:5]) and sorted(pb) == sorted(TAU_B))
    empt = []
    for lab, reg in [("c' = -1", ((1,), (0,), (-1, 0, 1))),
                     ("c = 0", ((0, 1), (0,), (0, 1))),
                     ("e = 1", ((1,), (0, 1), (0, 1)))]:
        A, B, n = gamma(*reg)
        print(f"    with {lab}: tau_A {len(A)} pieces, tau_B {len(B)} "
              f"(fixed at n = {n})")
        empt.append((not A, sorted(pts_of(A)) == sorted(TAU_A[:5])))
    check("(a) empty with c' = -1 or c = 0 added; with e = 1, tau_A "
          "and tau_B unchanged",
          empt == [(True, False), (True, False), (False, True)]
          and sorted(pts_of(B)) == sorted(TAU_B))


# ------------------------------------------------------------ two games

def run_cell(cell, st):
    """Advance the state st on this cell to the end; Split propagates."""
    for g in ("d", "R"):
        H = st[g]
        while H["end"] is None:
            A, B = H["A"][-1], H["B"][-1]
            n = len(H["A"]) - 1
            if not A:
                H["end"] = ("empty", n + 1)
                break
            A2, B2 = gstep(cell, A, B, g)
            if cell.same(A2, A) and cell.same(B2, B):
                H["end"] = ("fixed", n)
                break
            if n >= LMAX - 1:
                H["end"] = ("alive", None)
                break
            H["A"].append(A2)
            H["B"].append(B2)
    d, R = st["d"], st["R"]

    def get(H, key, k):
        if k < len(H[key]):
            return H[key][k]
        if H["end"][0] == "fixed":
            return H[key][-1]
        if H["end"][0] == "empty":
            return []
        return None
    jobs = [(("A", i, k), s, "A", k) for i, s in enumerate(TAU_A)
            for k in range(KLAG + 1)]
    jobs += [(("B", i, 0), r, "B", 0) for i, r in enumerate(TAU_B)]
    for key, s, side, k in jobs:
        top = len(d[side])
        if d["end"][0] == "fixed":
            top = max(top, len(R[side]))
        ns = [n for n in range(top) if get(d, side, n)]
        stt = st["v"].get(key, ("ok", 0, None))
        while stt[0] == "ok" and stt[1] < len(ns):
            n = ns[stt[1]]
            Y = get(R, side, n + k)
            if Y is None:
                stt = ("short", stt[1], n)
                break
            if subset(cell, tmap(get(d, side, n), s), Y):
                stt = ("ok", stt[1] + 1, None)
            else:
                stt = ("fail", stt[1], n)
            st["v"][key] = stt
        st["v"][key] = stt


def fresh():
    return {"d": {"A": [V0], "B": [U0], "end": None},
            "R": {"A": [VR], "B": [UR], "end": None}, "v": {}}


def copy(st):
    return {g: {"A": list(st[g]["A"]), "B": list(st[g]["B"]),
                "end": st[g]["end"]} for g in ("d", "R")} | {
        "v": dict(st["v"])}


def verdict(st):
    """(L*(delta), L*(R delta), okA per s (k = 0), lag per s, okB per r)."""
    def lstar(H):
        return H["end"][1] if H["end"][0] == "empty" else None
    def ok(key):  # "short" (R's history too short) counts as a pass
        return st["v"][key][0] != "fail"
    okA = tuple(ok(("A", i, 0)) for i in range(len(TAU_A)))
    lag = tuple(max([k for k in range(KLAG + 1) if ok(("A", i, k))],
                    default=-1) for i in range(len(TAU_A)))
    okB = tuple(ok(("B", i, 0)) for i in range(len(TAU_B)))
    every = st["d"]["end"][0] == "empty" or (
        st["d"]["end"][0] == "fixed" and st["R"]["end"][0] == "fixed")
    short = sum(v[0] == "short" for v in st["v"].values())
    ends = (st["d"]["end"][0], st["R"]["end"][0])
    return lstar(st["d"]), lstar(st["R"]), okA, lag, okB, every, short, ends


def survey(cuts):
    """Leaves over [cuts[0], cuts[-1]], every cut a leaf of its own."""
    stack = [(cuts[0], None, fresh())]
    for lo, hi in zip(cuts, cuts[1:]):
        stack += [(lo, hi, fresh()), (hi, None, fresh())]
    leaves, splits = [], 0
    while stack:
        a, b, st = stack.pop()
        cell = Cell(a, b)
        try:
            run_cell(cell, st)
            leaves.append((a, b, verdict(st)))
        except Split as sp:
            splits += 1
            r = sp.r
            stack += [(a, r, copy(st)), (r, None, copy(st)), (r, b, copy(st))]
    return leaves, splits


def point_verdict(pt):
    st = fresh()
    run_cell(Cell(pt, None), st)
    return verdict(st)


def fixed_points_of(pt):
    st = fresh()
    run_cell(Cell(pt, None), st)
    return st


def section_hand():
    print("== (b), (c) the hand control at delta = 0")
    st = fixed_points_of(Pt(Z0))
    d, R = st["d"], st["R"]
    print(f"    G_0 ends {d['end']}, G_(R 0) = G_(delta_1) ends {R['end']}")
    A0 = [zfloat(x[0]) for x, y in d["A"][-1]]
    A1 = sorted(round(zfloat(x[0]) + zfloat(x[1]) * 0, 9)
                for x, y in R["A"][-1])
    imgs = sorted(round(zfloat(s) + A0[0] * zfloat(E2), 9)
                  for s in TAU_A[:5])
    print(f"    A(0) = {[round(x, 6) for x in A0]}; images "
          f"{[round(x, 6) for x in imgs]}; A(delta_1) "
          f"{[round(x, 6) for x in A1]}")
    exact = sorted(zadd(zmul(E2, d["A"][-1][0][0][0]), s) for s in TAU_A[:5])
    a1 = sorted(x[0] for x, y in R["A"][-1])
    check("(b) T_s(A(0)) over tau_A is A(delta_1), one point each (exact)",
          len(d["A"][-1]) == 1 and exact == a1 and len(set(exact)) == 5
          and all(x[0] == y[0] for x, y in d["A"][-1] + R["A"][-1]))
    cell = Cell(Pt(Z0), None)
    brk = subset(cell, tmap(d["A"][-1], Z0), R["A"][-1])
    check("(c) the planted break s = 0 fails at delta = 0", not brk)


def section_survey():
    D3 = Pt(dk_pt(3))
    INV = Pt((-1, 1))                 # 1/phi = delta_1
    print(f"== the two games on [0, delta_3], L <= {LMAX}")
    t0 = time.time()
    leaves, splits = survey([Pt(Z0), INV, D3])
    opens = [lv for lv in leaves if lv[1] is not None]
    print(f"    {len(leaves)} leaves ({len(opens)} open), {splits} splits, "
          f"{time.time() - t0:.1f} s", flush=True)
    bad = [(float(a), float(b)) for a, b, v in opens
           if point_verdict(mid(a, b)) != v]
    check(f"(d) every open cell's verdicts equal its midpoint's "
          f"({len(opens)})", not bad, f"{len(bad)} differ {bad[:3]}")
    if not all(CHECKS):
        print("    CONTROL FAILED: the kill is not read.")
        return leaves

    def below(lv):
        a, b = lv[0], lv[1] if lv[1] is not None else lv[0]
        return b.cmp(INV) <= 0 and not (b.cmp(INV) == 0 and lv[1] is None)
    lowc = [lv for lv in leaves if below(lv)]
    p1 = [lv for lv in lowc if not (all(lv[2][2]) and all(lv[2][4]))]
    print(f"    P1: [0, 1/phi): {len(lowc)} leaves, {len(p1)} with a "
          f"failing s or r")
    up = [lv for lv in leaves if not below(lv)]
    p2 = [lv for lv in up if not all(lv[2][2])]
    print(f"    P2: [1/phi, delta_3]: {len(up)} leaves, {len(p2)} with a "
          f"failing s")
    for i, s in enumerate(TAU_A):
        nf = sum(not lv[2][2][i] for lv in leaves)
        lags = Counter(lv[2][3][i] for lv in leaves)
        print(f"      s = {s[0]} + {s[1]} phi ({zfloat(s):.6f}): fails at "
              f"{nf} leaves; leaves by lag {sorted(lags.items())}")
    for i, r in enumerate(TAU_B):
        nf = sum(not lv[2][4][i] for lv in leaves)
        print(f"      r = {r[0]} + {r[1]} phi ({zfloat(r):.6f}): fails at "
              f"{nf} leaves")
    dl = sorted({lv[2][1] - lv[2][0] for lv in leaves
                 if lv[2][0] is not None and lv[2][1] is not None})
    nfin = sum(lv[2][0] is not None and lv[2][1] is None for lv in leaves)
    print(f"    P3: L*(R delta) - L*(delta) over {dl}; {nfin} leaves with "
          f"L*(delta) finite and G_(R delta) not empty by {LMAX}")
    nev = sum(lv[2][5] for lv in leaves)
    print(f"    \"short\" verdicts: {sum(lv[2][6] for lv in leaves)}; "
          f"(G_delta, G_(R delta)) ends {sorted(Counter(lv[2][7] for lv in leaves).items())}")
    print(f"    every n decided (G_delta empty, or both games fixed) at "
          f"{nev} of {len(leaves)} leaves")
    kill = [lv for lv in leaves if not any(lv[2][2])]
    print(f"    KILL: pass-up fails at {len(kill)} cells")
    for a, b, v in kill[:12]:
        print(f"      {a!r}" + ("" if b is None else f" .. {b!r}")
              + f" ({float(a):.6f}): L* {v[0]}, L*(R) {v[1]}")
    short = sum(lv[2][6] for lv in leaves)
    check("the copies: every s in tau_A and r in tau_B holds at every n "
          "at every leaf, every n decided, none short",
          not p1 and not p2 and not [lv for lv in up if not all(lv[2][4])]
          and nev == len(leaves) and short == 0
          and not kill, f"{len(leaves)} leaves")
    return leaves


def main():
    t0 = time.time()
    section_gamma()
    section_hand()
    section_survey()
    print(f"\n{sum(CHECKS)} of {len(CHECKS)} checks passed "
          f"({time.time() - t0:.1f} s)")
    sys.exit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()