goldclimb.py

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

Cited on: FLUSH.

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

"""goldclimb.py -- the golden climb above 1/phi: Gamma on pairs.

QUESTION. goldren.py's translate copies T_s(v) = phi^-2 v + s carry
G_delta's passes into G_(R delta), R delta = 1/phi + delta/phi^2, by a
delta-free game Gamma below 1/phi. Above 1/phi the delta-reader also
plays c = 0, e = 1 and c' = -1, and Gamma's full-window sets die. Does a
family of PAIRS (s, I), a translation with a v-interval whose ends are
affine in delta, close at every delta in [1/phi, 1), so that the copies
hold there too?

DESIGN (by hand before the engine). A pair (s, I) on A-states, (r, I)
on B-states, asks T_s(I) inside V_(R delta) = [-delta/phi^2, 1 +
delta/phi^3] (T'_r(I) inside U_(R delta) = [-2, delta/phi]). A family
is CLOSED when, for each pair and each digit, the image of I under the
delta-reader's move, cut to the window it must land in (V_delta ∩
phi(c - I), U_delta ∩ phi(e - I), V_delta ∩ phi(c' + delta - phi - I)),
lies inside the union of the intervals of the pairs whose translation
is a reply: s' = phi C - phi s - c/phi, r = phi E - phi s - e/phi, s' =
phi C' - phi r - (c' + 1)/phi, C, E in {0, 1}, C' in {-1, 0, 1}. Then
v in A_n(delta) and in I gives T_s v in A_n(R delta) at every n, the R
delta-reader replying pointwise. The candidate family, derived by hand:
Gamma's eleven full pairs (s, V_delta), s in tau_A, (r, U_delta), r in
tau_B, and five more, A: (1, J), (0, J), (-1/phi, K), B: (0, L), (1,
M), J = [1/phi - delta, phi delta - 1], K = [2phi - phi^2 delta, (1 +
delta)/phi], L = [phi - phi^2 delta, phi delta - 1], M = [-1 - delta,
phi^3 delta - 2phi^2]. THE HAND CLOSURE, d = delta in [1/phi, 1).
Where each digit plays: c = 0 on Z0 = [1/phi - d, d/phi - phi^-2],
image -phi Z0 = J; c = 1 on [1/phi - d/phi^2, (1 + d)/phi]; e = 0 on
all of V; e = 1 on [phi - d, (1 + d)/phi]; c' = -1 on [-2, phi d - 3],
image J again; c' = 0 on [-2 + d/phi, phi d - 2]; c' = 1 on [-1 +
d/phi, phi d - 1]. Gamma dies only at c = 0 from phi^-2 and c' = -1
from -1/phi and phi^-2, each reply 1 on J (from -1/phi, C' = -1 gives -1/phi, whose K misses J's foot,
and C' = 1 gives phi^2, outside W_A); every other tau digit has a reply in tau. Then:
(1, J): c = 0 -> J, C = 1, s' = 0; c = 1 (on [1/phi - d/phi^2, phi d -
1], d >= phi/2) -> K, C = 1, s' = -1/phi; e = 0 -> -phi J = L, E = 1,
r = 0; e = 1 never (phi d - 1 < phi - d). (0, J): c = 0 -> J, s' = 0;
c = 1 (d >= phi/2) -> K, C = 0, s' = -1/phi; e = 0 -> L, r = 0; e = 1
never. (-1/phi, K): c = 0
never (K above Z0); c = 1 -> C = 0, s' = phi^-2, full; e = 0 -> -phi K
= M, r = 1; e = 1 -> E = 0, r = phi^-2, full. B (0, L): c' = -1 never
(needs phi^3 d >= phi + 3); c' = 0 (d >= (phi + 2)/phi^3) -> inside
[1/phi - d, phi^2(sqrt5 d - 2)], inside J as phi^2 sqrt5 - phi =
phi^3, C' = 1, s' = 1; c' = 1 -> C' = 1, s' = phi^-2, full. B (1, M):
c' = -1 -> inside [1/phi - d, phi(2d - phi)], in J, C' = 1, s' = 0;
c' = 0 (d >= 2/sqrt5) -> inside [phi^3 + phi - 2phi^2 d, (1 + d)/phi],
in K as phi^2(1 - d) >= 0, C' = 1, s' = -1/phi; c' = 1 never (needs d
>= phi^2/sqrt5). Windows: T_1 J, T_(-1/phi) K and T'_1 M iff d <= 1;
T_0 J and T'_0 L at every d of the range. Every end is alpha + beta
delta, alpha, beta in Z[phi]; each comparison is read on goldsurv's
Cell, a sign change splitting the cell at its root. The images are
computed from the moves, never from the hand list.

PREDICTIONS (frozen before the engine):
Q1 every condition holds on every leaf of [1/phi, 1].
Q2 removing any one of the five new pairs breaks closure on some leaf.
Q3 goldren's survey on [delta_3, delta_4] at L = 8: every s and r holds
   at every n (a theorem's prediction at new cells, rehearsal scale).
KILL (one print): "closure fails at N leaves" over [1/phi, 1], N > 0.
Controls before the kill: (a) the same checker on [0, 1/phi) with
Gamma's eleven alone passes; (b) on [1/phi, 1) with the eleven alone it
fails, at c = 0 from phi^-2 and c' = -1 from -1/phi, phi^-2 (the
deaths named above); (c) a planted wrong reply (1, J)'s c = 0 to s' =
1 fails.

FINDINGS (copied from the print).
Controls held: (a) Gamma's eleven close on [0, 1/phi) (2 leaves, 0
   failing); (b) on [1/phi, 1) the eleven alone fail at both leaves,
   at c = 0 from phi^-2 and c' = -1 from -1/phi and phi^-2 alone, the
   three deaths the hand derivation names.
Q1 held, the KILL missed: "closure fails at 0 leaves" over [1/phi, 1),
   8 leaves (4 open), 3 splits, 43 to 51 plays a leaf, all checked; the
   cuts at phi/2, 3phi - 4 and (4phi - 2)/5 = 2/sqrt5 (0.80902,
   0.85410, 0.89443, the floats by hand; by hand phi/2 is K's birth, 3phi - 4 = (phi +
   2)/phi^3 where (0, L)'s c' = 0 starts to play, 2/sqrt5 where (1,
   M)'s c' = 0 does).
Q2 held: without (1, J), (0, J) or (0, L) closure fails at 8 of 8
   leaves, without (-1/phi, K) at 6 of 8, without (1, M) at 4 of 6,
   each count checked.
Q3 held, at rehearsal scale only: on [delta_3, delta_4], L = 8, 139
   leaves, no failing s or r, every leaf alive in both games at L = 8;
   the 417 "short" verdicts are lag reads (k >= 1, by argument: both games run alive to L = 8), which Q3 does not
   read. Q3 is weak as eight levels decide no leaf, and deeper is dear:
   at L = 12 the same survey ran past 300 s and was stopped. It checks
   the engine against the theorem at n < 8 on cells goldren's survey
   does not reach, and proves nothing.
So the sixteen pairs close at every delta in [1/phi, 1), with Gamma's
eleven below: T_s(A_n(delta)) in A_n(R delta) for s in tau_A at every
n and every delta in [0, 1), a theorem by THE HAND CLOSURE above,
which this run checks and does not prove.

RUN RECORD. 6 of 6, 11.9 s, peak 13.3 MB under a 2048 MB cap (Q3 11.9
s of it). --plant (the -c/phi and -(c' + 1)/phi terms dropped): 1 of
5, controls (a) and (b), Q1 (closure fails at 8 of 8 leaves) and Q2
fail, Q1's cells check passing as it reads no reply, exit 1. K's lower
end broken in a scratch copy, 2phi - phi^2 d to 2phi - (1 + 2phi) d: Q1's
cells (16 leaves, 7 splits), Q1 and Q2 fail, 3 of 6. First run's fault, fixed before any verdict: the B -> A move's
constant written c' - 1 - phi for c' - phi; and an empty K (delta <
phi/2) read through the window check; both by reading the code
against the DESIGN before the first print. Changes to what was
frozen: Q1 and the KILL were frozen over [1/phi, 1] and run over [1/phi,
1) (frac((s + 1) phi) is never 1); control (c) was frozen as (1, J)'s c
= 0 sent to s' = 1, which cannot fail ((1, J) covers its own image J),
and was run as the -c/phi and -(c' + 1)/phi terms dropped. After a
review: THE HAND CLOSURE moved into this DESIGN, its windows corrected
(two hold at every d, not iff d <= 1), Q3's weakness restated off a
print of the leaves' ends, now printed by Q3.

Run: python goldclimb.py [--plant]
"""
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, zfloat,  # noqa
                      dk_pt, V0, U0)
import goldren  # noqa

PLANT = "--plant" in sys.argv
CHECKS = []


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


PHI = (0, 1)
IPHI = (-1, 1)                       # 1/phi
Z0 = (0, 0)
VR = goldren.VR[0]
UR = goldren.UR[0]
V = V0[0]
U = U0[0]


def lin(a, b=Z0):
    return (a, b)


def fmul(k, f):
    """k f, k in Z[phi]."""
    return (zmul(k, f[0]), zmul(k, f[1]))


def fadd(f, g):
    return (zadd(f[0], g[0]), zadd(f[1], g[1]))


def phi_minus(c, I):
    """phi(c - I) as an interval, c a linear function."""
    lo, hi = I
    return (fadd(fmul(PHI, c), fmul((0, -1), hi)),
            fadd(fmul(PHI, c), fmul((0, -1), lo)))


def T(s, I):
    E2 = (2, -1)
    return tuple(fadd(fmul(E2, x), lin(s)) for x in I)


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)]
J = (((-1, 1), (-1, 0)), ((-1, 0), (0, 1)))          # [1/phi - d, phi d - 1]
K = (((0, 2), (-1, -1)), (((-1, 1)), ((-1, 1))))    # [2phi - phi^2 d, (1+d)/phi]
L = (((0, 1), (-1, -1)), ((-1, 0), (0, 1)))          # [phi - phi^2 d, phi d - 1]
M = (((-1, 0), (-1, 0)), ((-2, -2), (1, 2)))         # [-1 - d, phi^3 d - 2phi^2]
ELEVEN = ([(s, V) for s in TAU_A], [(r, U) for r in TAU_B])
NEW_A = [("(1, J)", ((1, 0), J)), ("(0, J)", (Z0, J)),
         ("(-1/phi, K)", ((1, -1), K))]
NEW_B = [("(0, L)", (Z0, L)), ("(1, M)", ((1, 0), M))]


def family(drop=None):
    A, B = list(ELEVEN[0]), list(ELEVEN[1])
    A += [p for n, p in NEW_A if n != drop]
    B += [p for n, p in NEW_B if n != drop]
    return A, B


def replies(kind, t, d):
    """Reply translations to the delta-reader's digit d from translation t."""
    phi_t = zmul(PHI, t)
    k = d if not PLANT else 0
    if kind == "c":            # s' = phi C - phi s - c/phi
        return [zsub(zsub((0, C), phi_t), zmul((k, 0), IPHI)) for C in (0, 1)]
    if kind == "e":            # r = phi E - phi s - e/phi
        return [zsub(zsub((0, E), phi_t), zmul((k, 0), IPHI)) for E in (0, 1)]
    # c': s' = phi C' - phi r - (c' + 1)/phi
    return [zsub(zsub((0, C), phi_t), zmul((k + 1 if not PLANT else 0, 0),
                                           IPHI)) for C in (-1, 0, 1)]


def subset(cell, X, Y):
    return goldren.subset(cell, X, Y)


def check_cell(cell, fam):
    """The failing (pair, digit) list on this cell, and the plays read."""
    A, B = fam
    fails, plays = [], 0
    A = [(s, I) for s, I in A if cell.norm([I])]
    B = [(r, I) for r, I in B if cell.norm([I])]
    for s, I in A:
        if not subset(cell, [T(s, I)], [VR]):
            fails.append(("window A", s, None))
    for r, I in B:
        if not subset(cell, [T(r, I)], [UR]):
            fails.append(("window B", r, None))
    moves = [("c", c, s, I, V, A) for s, I in A for c in (0, 1)]
    moves += [("e", e, s, I, U, B) for s, I in A for e in (0, 1)]
    moves += [("c'", cp, r, I, V, A) for r, I in B for cp in (-1, 0, 1)]
    for kind, d, t, I, W, targets in moves:
        if kind == "c'":
            img = phi_minus(((d, -1), (1, 0)), I)     # c' + delta - phi
        else:
            img = phi_minus(lin((d, 0)), I)
        img = cell.inter([W], cell.norm([img]))
        if not img:
            continue
        plays += 1
        rs = replies(kind, t, d)
        cover = cell.norm([iv for x, iv in targets if x in rs])
        if not cover or not subset(cell, img, cover):
            fails.append((kind + f" = {d}", t, I))
    return fails, plays


def survey(cuts, fam):
    stack = [(cuts[0], None)]
    for lo, hi in zip(cuts, cuts[1:]):
        stack += [(lo, hi)]
    leaves, roots = [], []
    while stack:
        a, b = stack.pop()
        try:
            f, p = check_cell(Cell(a, b), fam)
            leaves.append((a, b, f, p))
        except Split as sp:
            r = sp.r
            roots.append(r.exact())
            stack += [(a, r), (r, None), (r, b)]
    return leaves, roots


def tname(t):
    return f"{t[0]} + {t[1]} phi ({zfloat(t):.4f})"


def section_controls():
    print("== controls")
    ZERO, INV, ONE = Pt(Z0), Pt(IPHI), Pt((1, 0))
    lv, sp = survey([ZERO, INV], ELEVEN)
    bad = [x for x in lv if x[2]]
    print(f"    (a) [0, 1/phi), Gamma's eleven: {len(lv)} leaves, {len(sp)} "
          f"splits, {len(bad)} failing")
    check("(a) Gamma's eleven close on [0, 1/phi), 2 leaves",
          len(lv) == 2 and not bad)
    lv, sp = survey([INV, ONE], ELEVEN)
    kinds = Counter((k, t) for x in lv for k, t, _ in x[2])
    nfail = sum(bool(x[2]) for x in lv)
    print(f"    (b) [1/phi, 1), the eleven alone: {len(lv)} leaves, "
          f"failing at {nfail}; failures by digit and translation:")
    for (k, t), n in sorted(kinds.items()):
        print(f"      {k} from {tname(t)}: {n} leaves")
    want = {("c = 0", (2, -1)), ("c' = -1", (1, -1)), ("c' = -1", (2, -1))}
    check("(b) the eleven fail at 2 of 2 leaves above 1/phi, at c = 0 from "
          "phi^-2 and c' = -1 from -1/phi, phi^-2 alone",
          set(kinds) == want and len(lv) == 2 and nfail == 2)


def section_kill():
    INV, ONE = Pt(IPHI), Pt((1, 0))
    print("== Q1, the KILL: the sixteen on [1/phi, 1)")
    t0 = time.time()
    lv, sp = survey([INV, ONE], family())
    bad = [x for x in lv if x[2]]
    plays = Counter(x[3] for x in lv)
    nopen = sum(x[1] is not None for x in lv)
    print(f"    {len(lv)} leaves ({nopen} open), {len(sp)} splits at "
          f"{sorted(sp)} ((a, b, d): (a + b phi)/d), {time.time() - t0:.1f}"
          f" s; plays per leaf {sorted(plays.items())}")
    cuts = sorted([(0, 1, 2), (-4, 3, 1), (-2, 4, 5)])
    check("Q1's cells: 8 leaves, 4 open, cut at phi/2, 3phi - 4 and (4phi - "
          "2)/5 alone, 43 to 51 plays a leaf",
          len(lv) == 8 and nopen == 4 and sorted(sp) == cuts
          and min(plays) == 43 and max(plays) == 51)
    for a, b, f, p in bad[:8]:
        print(f"      {a!r}" + ("" if b is None else f" .. {b!r}")
              + f" ({float(a):.5f}): {f[:3]}")
    print(f"    KILL: closure fails at {len(bad)} leaves")
    check("Q1 the sixteen close on every leaf of [1/phi, 1)", not bad)
    print("== Q2, each new pair removed")
    q2 = []
    for name, _ in NEW_A + NEW_B:
        lv, _ = survey([INV, ONE], family(drop=name))
        nb = sum(bool(x[2]) for x in lv)
        q2.append((nb, len(lv)))
        print(f"    without {name}: closure fails at {nb} of {len(lv)} leaves")
    check("Q2 each of the five is needed: fails at 8/8, 8/8, 6/8, 8/8, 4/6",
          q2 == [(8, 8), (8, 8), (6, 8), (8, 8), (4, 6)])


def section_q3():
    print("== Q3, goldren's survey on [delta_3, delta_4] at L = 8")
    goldren.LMAX = 8
    t0 = time.time()
    leaves, splits = goldren.survey([Pt(dk_pt(3)), Pt(dk_pt(4))])
    fa = sum(not all(lv[2][2]) for lv in leaves)
    fb = sum(not all(lv[2][4]) for lv in leaves)
    short = sum(lv[2][6] for lv in leaves)
    print(f"    {len(leaves)} leaves, {splits} splits, {time.time() - t0:.1f}"
          f" s; a failing s at {fa}, a failing r at {fb}; short {short}; "
          f"ends {sorted(Counter(lv[2][7] for lv in leaves).items())}")
    ends = Counter(lv[2][7] for lv in leaves)
    check("Q3 every s and r holds at every n < 8 on [delta_3, delta_4]: "
          "139 leaves, every one alive in both games, 417 short",
          fa == 0 and fb == 0 and len(leaves) == 139 and short == 417
          and ends == {("alive", "alive"): 139})


def main():
    t0 = time.time()
    section_controls()
    if PLANT:
        print("    (c) the plant: replies without the -c/phi, -(c' + 1)/phi terms")
    if not all(CHECKS) and not PLANT:
        print("CONTROL FAILED: the kill is not read.")
        sys.exit(1)
    section_kill()
    if not PLANT:
        section_q3()
    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()