goldcover.py

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

Cited on: FLUSH.

To run it: save goldcover.py, with defer.py, flush.py, goldclimb.py, goldcopy.py, goldcps.py, goldelta.py, goldfix.py, goldren.py, goldroot.py, goldshift.py, goldsurv.py, goldtile.py, ostrowski.py, shifted.py beside it; standard library only.

"""goldcover.py -- do the copies and the six shifts cover A_inf(R y)?

Frozen before this engine (copied whole but BY HAND's (-1, K') line and
P3, corrected in the engine's commit before any run):
QUESTION. At x = R(y), y a survivor, C_A = {T_s(v) : v in A_inf(y), s in
tau_A} and C_B = {T'_r(u) : u in B_inf(y), r in tau_B} close on
themselves in G_x (the climb, the shift on [1/phi, 1), the reduction
below). x = 1/phi + y/phi^2 lies in [1/phi, 1), where the six pairs
hold on A_inf(x), B_inf(x): A: (1/phi, J), (-1, K'); B: (1/phi, Z1),
(1/phi, L_lo), (-1, L_hi), (phi, M'), at d = x. Is the closure S_A of
C_A under A's two pairs (S_B: C_B under B's four) all of A_inf(x)?

THE REDUCTION, re-derived (the shift => the copies close). A point w =
T_s(v) of C_A: v has a c move into A_y and an e move into B_y. By the
copy identity each lands at a copy at s' = phi C - phi s - c/phi (r = phi
E - phi s - e/phi), the window of G_x held since T_s' maps V_y into V_x.
Every e reply stays in tau_B; the only c leaving tau_A is c = 0 at s =
phi^-2. If v plays c = 1 too, use it. If c = 0 alone, v lies in Z0
inside J, so v + 1/phi in A_inf(y) (the shift at y in [1/phi, 1); for
y < 1/phi, Z0 is empty), and w = T_(phi^-4)(v + 1/phi) (phi^-3 + phi^-4
= phi^-2): from s = phi^-4 c = 0 goes to 1, c = 1 to 5, both in tau_A.
B alike: c' = -1 leaves tau only from r = -1/phi and phi^-2; a u playing
c' = -1 alone lies in Z1, u + 1/phi in B_inf(y), and T'_(-1/phi)(u) =
T'_(4 - 3phi)(u + 1/phi) (phi^-3 + 4 - 3phi = -1/phi), T'_(phi^-2)(u) =
T'_(phi^-4)(u + 1/phi); from 4 - 3phi and phi^-4 every c' stays in tau.
So every point of C_A, C_B has its moves inside (C_A, C_B): closed,
hence inside A_inf(x), B_inf(x), at every y in [0, 1). Held.

BY HAND, the labels. (1/phi, J) sends a copy at s = -phi^-3 to s =
phi^-2 and at phi^-4 to 2 phi^-2 (phi^-1 + phi^-4 = 2 phi^-2), same v;
(-1, K') sends s = 2phi^-2 to -phi^-3 alone (2phi^-2 - 1 = -phi^-3).
A step adds a point only from a copy each of whose labels leaves
tau_A: by 1/phi from s in {phi^-2, 2phi^-2 - phi^-3, 2phi^-2}, by -1
from s other than 2phi^-2.
Control (a) by hand: at x = delta_1, A_inf = {0, phi^-2, 1/phi, 2phi^-2,
1}, J = {0}, K' = {1}; the A closure of {1} is {1, 0, 1/phi}.

PREDICTIONS.
P1 (a guess) the shifts add points: |S_A| > |C_A| at some of the 8.
P2 (a guess) no cover is whole: S_A is A_inf(x) at 0 of 8.
P3 (by hand, the labels) every point S_A adds at its first step from
   C_A comes from a copy whose labels all leave tau_A under that step
   (above), and none from a label the step keeps in tau_A. (Corrected
   in the engine's commit, before any run: the frozen P3 had (-1, K')
   reverse 1/phi.)
KILL (one print): "copies and shifts cover A_inf(x) at n of 8
   R-images; S_A above C_A at m of 8"; it fires iff n = 0 and m = 0
   (the copies already closed under the six, adding nothing): the
   golden fixed sets close as a direction (reopen: a second
   generator). n = 8: A_inf(R y) is generated by the copies and the
   shifts, a proof owed. Else the residual A_x - S_A is named.
Controls, read before the kill: (a) the hand closure at delta_1 above;
   (b) S_A inside A_x, S_B inside B_x at all 8 (a theorem); (c) a plant,
   1/phi replaced by 1/phi + phi^-12 in (1/phi, J): (b) refuses at some
   x (caught by construction, read only that the inclusion can fail).
Statistic per x: |C_A|, |S_A|, |A_x| and their shares; B likewise.

FINDINGS (copied from the print; shares derived from its rows).
Controls held: (a) at delta_1 the A closure of {1} is {1, 0, 1/phi};
   (b) S_A in A_x, S_B in B_x at all 8; (c) the plant leaves A_x at 8 of
   8.
KILL MISSED: "copies and shifts cover A_inf(x) at 0 of 8 R-images; S_A
   above C_A at 8 of 8". P1 and P2 held. The kill's bar, any added
   point, was priced only at its two ends, never at a middle: the run
   sits near the null it was frozen against. S_A less C_A is 1, 6, 20,
   4, 9, 12, 14, 18 points (delta_2, delta_3, delta_4, then x = R y at y
   = phi/2, (-2 + 4phi)/5, (2 + 5phi)/11, (-3 + 3phi)/2, (-1 + 7phi)/11),
   each one shift from a copy (chain depth 1), every recorded first
   step by (-1, K') from copies labelled 2phi^-2 - phi^-3 alone (close()
   keeps the first parent found, 1/phi's tried first). That
   gain is 0.013 to 0.033 of A_x, S_A's share 0.424 to 0.581 (from the
   copies' 0.409 to 0.549). On B the four pairs add nothing (S_B = C_B
   at 8 of 8). P3 as first frozen held by its letter (every parent's
   label in {phi^-2, 2phi^-2 - phi^-3, 2phi^-2}), not by its mechanism, a
   shift by 1/phi, which no recorded step is; as corrected, its labels kept in tau_A
   (by 1/phi from -phi^-3 and phi^-4, by -1 from 2phi^-2) match the hand
   list, its first-step count (0 of 84) forced.
The residual A_x - S_A, 0.41 to 0.58 of A_x, is not named. phi^-2
   copies of A_y at labels a + b phi (|a|, |b| <= 8, in [-1.5, 2.5])
   reach 0 of its 13 points at delta_2, 16 of 108 at delta_3 and 38 of
   816 at delta_4, at most 27 of 63 to 690 at the other five; -phi^-1
   copies 0, 4, 34 and at most 19: such copies hold a few residual
   points and generate no large part of it at those labels.
   |A_inf| along the chain runs 5, 31, 211, 1437, ratios 6.2, 6.81,
   6.81 against phi^4 = 6.854 (an observation), while the copies give at
   most 5 points a point.

RUN RECORD. 3 of 3, 41.9 s, peak 219.1 MB under a 2048 MB cap. P3 was
corrected in the engine's commit, before any run: the frozen P3 read
every added point's chain back to a copy at s in {phi^-2, 2phi^-2 -
phi^-3, 2phi^-2}, the correction its first step alone, with the hand
label list redone (the frozen block had (-1, K') reverse 1/phi). The
two arms after the run (P3 as first frozen; the residual against
copies at other labels) were added after the first run, which printed
the kill as above, and reproduce its scratch read's counts.

Run: python goldcover.py
"""
from collections import Counter
import os
import sys
import time

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

import goldroot as gr  # noqa
import goldcopy as gc  # noqa
from goldshift import SIX  # noqa

CHECKS = []


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


def pairs_at(side, d, tweak=None):
    """[(name, t, interval list)] of the six pairs at d = d."""
    out = []
    for name, t, I in SIX[side]:
        tq = gr.q(*t)
        if tweak is not None and name == "(1/phi, J)":
            tq = gr.add(tq, tweak)
        out.append((name, tq, gr.ivs([I], d)))
    return out


def within(w, Iv):
    return any(gr.cmp(a, w) <= 0 and gr.cmp(w, b) <= 0 for a, b in Iv)


def close(seed, prs):
    """closure of seed under the pairs; parent[w] = (w0, pair name)."""
    S = set(seed)
    parent = {}
    todo = list(seed)
    while todo:
        w = todo.pop()
        for name, t, Iv in prs:
            if within(w, Iv):
                w2 = gr.add(w, t)
                if w2 not in S:
                    S.add(w2)
                    parent[w2] = (w, name)
                    todo.append(w2)
    return S, parent


def main():
    t0 = time.time()
    runs = {x: gr.run(gr.spt(*x))["d"] for x in gr.SURV}
    sq = {x: gr.pt_q(gr.spt(*x)) for x in gr.SURV}
    print(f"runs: {len(runs)} survivors ({time.time() - t0:.1f} s)")
    pairs = []
    for x in gr.SURV:
        pre = gr.sub(gr.mul(gr.P2, sq[x]), gr.PHI)
        ys = [z for z in gr.SURV if gr.cmp(sq[z], pre) == 0]
        if ys:
            pairs.append((ys[0], x))

    print("== controls")
    d1 = sq[(-1, 1, 1)]
    A1 = set(gr.pts(gr.fixed(runs[(-1, 1, 1)])[0]))
    S1, _ = close([gr.q(1)], pairs_at("A", d1))
    want = {gr.q(1), gr.q(0), gr.IPHI}
    check("(a) at delta_1 the A closure of {1} is {1, 0, 1/phi}",
          S1 == want and want <= A1,
          f"{sorted(gr.show(w) for w in S1)}; |A| {len(A1)}")

    rows = []
    for y, x in pairs:
        A_y, B_y = (gr.pts(S) for S in gr.fixed(runs[y]))
        A_x, B_x = (set(gr.pts(S)) for S in gr.fixed(runs[x]))
        labA, labB = gc.labels(A_y, gc.TAU_A), gc.labels(B_y, gc.TAU_B)
        CA, CB = set(labA), set(labB)
        SA, parA = close(CA, pairs_at("A", sq[x]))
        SB, parB = close(CB, pairs_at("B", sq[x]))
        # P3: the first step's labels
        p3 = 0
        for w2, (w, name) in parA.items():
            if w not in CA:
                continue
            t = gr.IPHI if name == "(1/phi, J)" else gr.q(-1)
            if any(gr.add(s, t) in gc.TAU_A for s, _ in labA[w]):
                p3 += 1
        plant = close(CA, pairs_at("A", sq[x], tweak=gr.phipow(-12)))[0]
        rows.append(dict(y=y, x=x, nCA=len(CA), nSA=len(SA), nAx=len(A_x),
                         nCB=len(CB), nSB=len(SB), nBx=len(B_x),
                         inc=SA <= A_x and SB <= B_x, p3=p3,
                         new1=sum(w in CA for w, _ in parA.values()),
                         plant_out=len(plant - A_x),
                         depth=max([depth(w, parA) for w in parA] or [0]),
                         firsts=[(nm, frozenset(gr.show(s) for s, _ in labA[w]))
                                 for w2, (w, nm) in parA.items() if w in CA],
                         res=A_x - SA, A_y=set(A_y)))
        r = rows[-1]
        print(f"  x = {gr.show(sq[x]):20s} |C_A| {r['nCA']:4d} |S_A| "
              f"{r['nSA']:4d} |A_x| {r['nAx']:4d} ({r['nSA'] / r['nAx']:.3f}"
              f" from {r['nCA'] / r['nAx']:.3f});  |C_B| {r['nCB']:4d} |S_B|"
              f" {r['nSB']:4d} |B_x| {r['nBx']:4d}; chain depth {r['depth']}")
    big = [r for r in rows if r["nAx"] >= 18]
    check(f"(b) S_A in A_x and S_B in B_x at all {len(big)} R-images past "
          "delta_1", len(big) == 8 and all(r["inc"] for r in big))
    nout = sum(r["plant_out"] > 0 for r in big)
    check("(c) the plant 1/phi + phi^-12 leaves A_x somewhere", nout > 0,
          f"at {nout} of {len(big)}")
    ctrl = all(CHECKS)

    print("== the kill")
    n = sum(r["nSA"] == r["nAx"] for r in big)
    m = sum(r["nSA"] > r["nCA"] for r in big)
    print(f"KILL: copies and shifts cover A_inf(x) at {n} of {len(big)} "
          f"R-images; S_A above C_A at {m} of {len(big)}")
    print(f"    {'FIRES' if n == 0 and m == 0 else 'missed'}")
    print(f"    P1 {'held' if m > 0 else 'failed'}; P2 "
          f"{'held' if n == 0 else 'failed'} ({n} whole); B: S_B whole at "
          f"{sum(r['nSB'] == r['nBx'] for r in big)} of {len(big)}")
    print(f"    P3: first steps from a kept label {sum(r['p3'] for r in big)}"
          f" of {sum(r['new1'] for r in big)} (forced 0)")
    keep = {nm: {gr.show(s) for s in gc.TAU_A if gr.add(s, t) in gc.TAU_A}
            for nm, t in (("1/phi", gr.IPHI), ("-1", gr.q(-1)))}
    hand = {"1/phi": {gr.show(gr.q(3, -2)), gr.show(gr.phipow(-4))},
            "-1": {gr.show(gr.q(4, -2))}}
    print(f"    P3, the labels kept in tau_A: {keep}; by hand {hand}: "
          f"{'held' if keep == hand else 'FAILED'}")

    print("== after the run: P3 as first frozen, the parents' labels")
    first = Counter(f for r in big for f in r["firsts"])
    for (nm, labs), k in sorted(first.items(), key=lambda z: -z[1]):
        print(f"    by {nm}: {k} points from copies labelled {sorted(labs)}")
    print("== after the run: the residual against copies at other labels")
    grid = [gr.q(a, b) for a in range(-8, 9) for b in range(-8, 9)
            if -1.5 <= gr.fl(gr.q(a, b)) <= 2.5]
    for r in big:
        c2 = {w for w in r["res"] for s in grid
              if gr.mul(gr.P2, gr.sub(w, s)) in r["A_y"]}
        c1 = {w for w in r["res"] for s in grid
              if gr.mul(gr.q(0, -1), gr.sub(w, s)) in r["A_y"]}
        print(f"    x = {gr.show(gr.pt_q(gr.spt(*r['x']))):20s} residual "
              f"{len(r['res']):4d}: phi^-2 copies at labels |a|, |b| <= 8 "
              f"reach {len(c2)}, -phi^-1 copies {len(c1)}")
    if not ctrl:
        print("CONTROL FAILED: no verdict")
    print(f"\n{sum(CHECKS)} of {len(CHECKS)} checks, "
          f"{time.time() - t0:.1f} s")
    return 0 if all(CHECKS) else 1


def depth(w, par):
    k = 0
    while w in par:
        w = par[w][0]
        k += 1
    return k


if __name__ == "__main__":
    sys.exit(main())