goldtile.py

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

Cited on: FLUSH.

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

"""goldtile.py -- delta_1's tile at every golden survivor, against a CPS null.

QUESTION. At R(phi^2/3) the scale-1 translates of delta_1's fixed set
(A = {0, phi^-2, phi^-1, 2phi^-2, 1}, B eleven points) close on 181 of
the 301 A states, which no nearest-point source of its sizes does, B
its 11 nearest points (goldcps.py). Does delta_1's tile close inside every survivor's fixed
game, and is that delta_1's shape or any five-point box CPS's?

DESIGN (frozen before this engine). The fixed game at x: A -> A by v ->
phi(c - v), A -> B by phi(e - v), B -> A by u -> phi(c' + x - phi - u).
A translate by t sends phi(c - v) to phi(c - v) - phi t, and on B adds
phi(x - delta_1): delta_1's closed game, translated, closes in x's when
the translations close under t -> -phi t + phi k (and the B shift), a
game of the same shape on translations; sufficient, not necessary.
Population: the survivors of [0, delta_4] at L = 40 with |A_inf| >= 18,
and delta' = R(phi^2/3) as the known case. Arms, all at scale +1:
(T) delta_1's whole source, A and B translates (goldcps's
closed_at_one); (TA) its A side alone, B
free (all of B_x); (N) the CPS null, B free: F_x, every five-point S in
A_x that is a box CPS of Z[phi] (its box holds five coset points) with
real width in [1/phi, phi], enumerated exactly (p real-least, q
real-greatest in one Z[phi]-coset, S a run of five conj-consecutive
coset points of the strip [p, q] holding both), 200 drawn uniformly,
seed 2170; (M) the nearest-point null on A (five A points nearest a
drawn one), B free, 200 draws, seed 2170, the CPS shape removed. A
draw's statistic is the closed part's |A| of its translates' union.
By hand: delta_1's A is a box CPS of Z[phi] (box [0, 1] x [-phi,
2phi^2], b = (v - v*)/sqrt5 in {-2, -1, 0, 1}: 0, 1, phi - 1, 2 - phi,
4 - 2phi), width 1; closure is monotone, so TA >= T.

PREDICTIONS (frozen before the engine).
Q1 (TRANSPLANT from delta' alone) TA closes (closed |A| > 0) at every
   survivor with |A_inf| >= 18 where delta_1's A has a translate.
Q2 (a guess) where TA closes it beats N: fewer than 10 of 200 null
   draws close at least as many A states.
Q3 (a guess) N closes more often than M (the box shape matters).
KILL of the translation law (one print): "delta_1's A tile closes at n
   of N survivors with a translate; beats its CPS null at m of n"; the
   law stands iff n = N and m = n.
Controls: (a) T at delta' reprints 85 t_A, 122 t_B, closed 181; (b)
delta_1's A read as a box CPS of Z[phi] of width 1, and every translate
of it into A_delta' found in F_delta'; (c) a plant: delta_1's A with
2phi^-2 replaced by 2phi^-2 + 1/phi... read not box CPS; (d) TA >= T at
every x. (Frozen over "the 22 survivors of [0, delta_4] at L = 40 with
|A_inf| >= 18", which are 20; (c)'s plant was left unfinished.)

Arms added after the first run: (e) a known answer, at each x = R(y),
y a survivor: delta_1's A is phi^-3 + tau_A, so the climb's five full
copies T_s(v) = phi^-2 v + s, s in tau_A, of each v in A_y are one
translate of the tile, at t = phi^-2 v - phi^-3, which must be found;
and the tile's closure read by kind, R-images against roots.

FINDINGS (copied from the print).
Controls held: (a) delta' 85 t_A x 122 t_B, closed 181 (B 450); (b)
   delta_1's A box 5, width 1, its 85 translates into A_delta' all in
   F_delta' (|F| 1404); (c) the plant (1 moved to 1 + phi^-2) box 6;
   (d) TA >= T at all 20; (e) delta_1's A - phi^-3 = tau_A, and the
   translates at all 8 R-images; (f) every member of every F_x has five
   coset points in its box, every tile translate a member; fast moves
   equal goldroot's at delta'; the strips' largest conj gap 4.2361 (=
   sqrt5 + 2, four of them inside WIN = 30).
Population: 20 survivors with |A_inf| >= 18 (delta' = (-2 + 3phi)/3
   among them), each with translates of the tile (2 at phi/2 to 467 at
   delta_4).
KILL FIRED, the translation law killed: "delta_1's A tile closes at 12
   of 20 survivors with a translate; beats its CPS null at 0 of 12".
   Q1 killed (12 of 20). Q2 as frozen killed (0 of 12), but N holds
   the tile's own translates (85 of 1404 at delta'), which tie it: a
   draw of 200 carries about a dozen ties against a bar of 10, so N
   could hardly lose. Against N' (the same family, tile translates
   excluded, the bar scaled to the draws) the tile beats it at 1 of
   12, (-2 + 4phi)/5, where 0 of 146 draws reach its 36; at delta' 15
   of 200 reach 181, at delta_4 65 of 200 reach 930.
Q3 killed: the nearest-point arm closes more draws than the CPS one,
   3134 of 4000 against 1393 of 3647 (B free in both), but it reaches
   the tile's value less often: the tile beats M (fewer than 10 of 200
   reach it) at 9 of 12, not at (-4 + 3phi), (-2 + 4phi)/5 and (-1 +
   3phi)/4, a set disjoint from N''s one; at delta' 8 of 200 M draws
   reach 181 (max 185), against N''s 15.
After the run, by kind: the tile closes at 8 of 8 R-images and at 4
   of 12 roots, (-2 + 4phi)/5, (-2 + 3phi)/3, (-1 + 3phi)/4 and (-9 +
   17phi)/19; it fails at phi/2, (2 + 5phi)/11, (-1 + 7phi)/11, (2 +
   10phi)/19, (7 + 13phi)/29, 3phi/5, (1 + 3phi)/6, (-4 + 20phi)/29,
   where it has 2 to 427 translates. At five of those eight no N draw
   closes either (phi/2, whose |F| is 5, (2 + 5phi)/11, (2 + 10phi)/19,
   (7 + 13phi)/29, (1 + 3phi)/6), while 119 to 186 nearest-point draws
   do. T closes exactly where TA does, its closed |A| within 8 of TA's.
So the tile closes at every R-image read (8 of 8), where it holds the
climb's five full copies of each v (e); with B free (TA) that follows at
every R-image whose preimage survives, the copies closing on themselves
(goldcopy.py) and closure being monotone. Against nearest points it
stands out at 9 of 12,
against five-point box CPS sets of real width in [1/phi, phi] at 1 of
12: what the tile closes, the 181 at delta' among it, is mostly what a
box CPS of that band closes, not delta_1's alone.

RUN RECORD. 15 of 15, the FINDINGS' counts checks, 134.8 s, 222.0 MB
(gate --run); printed only: the translate counts, |F|, M's max 185,
the five roots no N draw closes, M's 119 to 186 there, the strip
gap, N''s 0 of 146 at (-2 + 4phi)/5, the names of M's exceptions and
of the closing and failing roots, and (a)'s B 450. Changes to what was frozen: control (c)'s plant was frozen
unfinished ("2phi^-2 replaced by 2phi^-2 + 1/phi..."), first run as 2phi^-2 moved to 1 +
phi^-2, which is itself a box CPS (its box drops 2phi^-2's conj 5.236):
the first run failed there alone, 5 of 6, and the plant is now 1 moved
to 1 + phi^-2, whose box takes 1 back. (e) and the by-kind print came
after the first run; after a review, N' (tile translates excluded), M's
count reaching the tile's value and the tile-against-M count, the
closing roots' print, (f) and (e)'s tau_A identity, each run reprinting
the first run's figures. A first reading after the review, "with B
free neither shape is needed", read any reach of M as a match; against
the frozen bar M is beaten at 9 of 12. Q2's bar
was frozen as 10 of 200 and read unscaled where F_x has fewer members
(84 at -4 + 3phi, 158 at (-2 + 4phi)/5), changing no verdict.

Run: python goldtile.py
"""
from fractions import Fraction as Fr
from functools import cmp_to_key
from math import floor, ceil
import os
import random
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 goldcps as gc   # noqa

PHI = (1 + 5 ** .5) / 2
S5 = 5 ** .5
CHECKS = []
WIN = 30.0          # |conj p - conj q| allowed; four strip gaps at most
PAD = 60.0          # the strip's conj margin beyond p and q


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


def fast_moves(dp, A, B):
    """goldroot's moves by dictionary lookup (points are exact tuples)."""
    ixA = {w: i for i, w in enumerate(A)}
    ixB = {w: i for i, w in enumerate(B)}
    mA, mB = [], []
    for v in A:
        c = [(cc, ixA[w]) for cc in (0, 1)
             for w in [gr.mul(gr.PHI, gr.sub(gr.q(cc), v))] if w in ixA]
        e = [(ee, ixB[w]) for ee in (0, 1)
             for w in [gr.mul(gr.PHI, gr.sub(gr.q(ee), v))] if w in ixB]
        mA.append((c, e))
    sh = gr.sub(dp, gr.PHI)
    for u in B:
        mB.append([(cc, ixA[w]) for cc in (-1, 0, 1)
                   for w in [gr.mul(gr.PHI, gr.sub(gr.add(gr.q(cc), sh), u))]
                   if w in ixA])
    return mA, mB


def translates(src, S):
    """every t with src + t inside the set S (scale +1)."""
    return [t for t in (gr.sub(w, src[0]) for w in S)
            if all(gr.add(v, t) in S for v in src)]


def closed_part(src_A, src_B, A, B, mA, mB, ixA, ixB):
    """(t_A, t_B, closed |A|, closed |B|) of the union of src's translates;
    src_B None: B free."""
    SA = set(A)
    tA = translates(src_A, SA)
    if not tA:
        return 0, 0, 0, 0
    iA = {ixA[gr.add(v, t)] for t in tA for v in src_A}
    if src_B is None:
        tB, iB = None, set(range(len(B)))
    else:
        tB = translates(src_B, set(B))
        iB = {ixB[gr.add(u, t)] for t in tB for u in src_B}
    XA, XB = gr.closed(mA, mB, iA, iB)
    return len(tA), (len(tB) if tB is not None else -1), len(XA), len(XB)


# ------------------------------------------------------------ the family

def ints(S, d):
    return gc.to_int(S, d)


def real_f(p, d):
    return (p[0] + p[1] * PHI) / d


def conj_f(p, d):
    return (p[0] + p[1] - p[1] * PHI) / d


def family(P, d):
    """F: every five-point box CPS of Z[phi] inside P (ints over d), real
    width in [1/phi, phi]; returns (sets as sorted tuples, max strip gap)."""
    Ps = set(P)
    groups = {}
    for p in P:
        groups.setdefault((p[0] % d, p[1] % d), []).append(p)
    out, maxgap = set(), 0.0
    for G in groups.values():
        G.sort(key=lambda p: real_f(p, d))
        rs = [real_f(p, d) for p in G]
        for i, p in enumerate(G):
            rp, cp = rs[i], conj_f(p, d)
            for j in range(i + 1, len(G)):
                w = rs[j] - rp
                if w > PHI + 1e-9:
                    break
                if w < 1 / PHI - 1e-9:
                    continue
                qq = G[j]
                cq = conj_f(qq, d)
                if abs(cq - cp) > WIN:
                    continue
                strip = strip_points(p, qq, d, min(cp, cq) - PAD,
                                     max(cp, cq) + PAD)
                cs = [conj_f(s, d) for s in strip]
                maxgap = max([maxgap] + [b - a for a, b in zip(cs, cs[1:])])
                ip, iq = strip.index(p), strip.index(qq)
                lo, hi = min(ip, iq), max(ip, iq)
                if hi - lo > 4:
                    continue
                for s in range(max(0, hi - 4), lo + 1):
                    run = strip[s:s + 5]
                    if len(run) == 5 and all(x in Ps for x in run):
                        out.add(tuple(sorted(run)))
    return sorted(out), maxgap


def strip_points(p, qq, d, clo, chi):
    """coset points p + d(m + n phi) with real in [real p, real q] (exact)
    and conj in [clo, chi] (float window), sorted by conj (exact)."""
    rp, rq = real_f(p, d), real_f(qq, d)
    cp = conj_f(p, d)
    pts = []
    # w = p + d(m + n phi): real = rp + m + n phi, conj = cp + m - n/phi
    n_lo = floor((rp - chi - (rp - cp)) / S5) - 1
    n_hi = ceil((rq - clo - (rp - cp)) / S5) + 1
    for n in range(n_lo, n_hi + 1):
        m_lo = max(-n * PHI, clo - cp + n / PHI)
        m_hi = min(rq - rp - n * PHI, chi - cp + n / PHI)
        for m in range(ceil(m_lo) - 1, floor(m_hi) + 2):
            w = (p[0] + d * m, p[1] + d * n)
            if gc.zcmp(w, p) < 0 or gc.zcmp(w, qq) > 0:
                continue
            c = conj_f(w, d)
            if clo <= c <= chi:
                pts.append(w)
    pts.sort(key=cmp_to_key(lambda u, v: gc.zcmp(gc.co_(u), gc.co_(v))))
    return pts


def as_q(S, d):
    return [(Fr(a, d), Fr(b, d)) for a, b in S]


# ------------------------------------------------------------ main

def main():
    t0 = time.time()
    G = gr.run(gr.DP)["d"]
    runs = {x: gr.run(gr.spt(*x))["d"] for x in gr.SURV}
    s1 = tuple(gr.pts(S) for S in gr.fixed(runs[(-1, 1, 1)]))
    srcA, srcB = s1
    print(f"delta_1's source: |A| {len(srcA)}, |B| {len(srcB)}; A "
          f"{[gr.show(v) for v in srcA]}")

    print("== (b), (c) the family's instrument")
    P1 = ints(srcA, 1)
    lat = gc.Lat([(1, 0), (0, 1)])
    bx = len(gc.box_points(P1, lat))
    wid = max(real_f(p, 1) for p in P1) - min(real_f(p, 1) for p in P1)
    plant = [p for p in P1 if p != (1, 0)] + [(3, -1)]     # 1 -> 1 + phi^-2
    bxp = len(gc.box_points(plant, lat))
    print(f"    delta_1's A: box {bx}, real width {wid:.6f}; plant "
          f"{plant}: box {bxp}")
    check("(c) the plant, 1 moved to 1 + phi^-2, read not a box CPS",
          bxp > 5)

    targets = [("delta' = R(phi^2/3)", gr.DP, 3, G)]
    for x in gr.SURV:
        if len(runs[x]["A"][-1]) >= 18:
            targets.append((gr.show(gr.pt_q(gr.spt(*x))), gr.spt(*x), x[2],
                            runs[x]))
    print(f"    population: {len(targets) - 1} survivors with |A_inf| >= 18, "
          f"and delta'")

    sq = {x: gr.pt_q(gr.spt(*x)) for x in gr.SURV}
    rows = []
    okb = okd = okr = okf = True
    nimg = 0
    gapmax = 0.0
    for k, (name, pt, d, H) in enumerate(targets):
        tk = time.time()
        A, B = (gr.pts(S) for S in gr.fixed(H))
        dq = gr.pt_q(pt)
        latd = gc.Lat([(d, 0), (0, d)])
        mA, mB = fast_moves(dq, A, B)
        if k == 0:
            ref = gr.moves(dq, A, B)
            check("fast moves equal goldroot's at delta'", (mA, mB) == ref)
        ixA = {w: i for i, w in enumerate(A)}
        ixB = {w: i for i, w in enumerate(B)}
        T = closed_part(srcA, srcB, A, B, mA, mB, ixA, ixB)
        TA = closed_part(srcA, None, A, B, mA, mB, ixA, ixB)
        okd &= TA[2] >= T[2]
        F, mg = family(ints(A, d), d)
        gapmax = max(gapmax, mg)
        if k == 0:
            check("(a) T at delta' reprints 85 t_A, 122 t_B, closed 181",
                  T[:3] == (85, 122, 181), f"{T}")
            fam = set(F)
            tr = translates(srcA, set(A))
            mine = [tuple(sorted(ints([gr.add(v, t) for v in srcA], d)))
                    for t in tr]
            okb = (bx == 5 and abs(wid - 1) < 1e-12
                   and all(m in fam for m in mine))
            check("(b) delta_1's A a box CPS of Z[phi], width 1; its "
                  f"{len(mine)} translates into A_delta' all in F_delta'", okb)
        rng = random.Random(2170)
        draw = F if len(F) <= 200 else rng.sample(F, 200)
        nv = sorted(closed_part(as_q(S, d), None, A, B, mA, mB, ixA, ixB)[2]
                    for S in draw)
        rng2 = random.Random(2170)
        mv = sorted(closed_part(gc.nearest(A, rng2.randrange(len(A)), 5),
                                None, A, B, mA, mB, ixA, ixB)[2]
                    for _ in range(200))
        kN = sum(v >= TA[2] for v in nv)
        tiles = {tuple(sorted(ints([gr.add(v, t) for v in srcA], d)))
                 for t in translates(srcA, set(A))}
        F2 = [S2 for S2 in F if S2 not in tiles]
        rng3 = random.Random(2170)
        draw2 = F2 if len(F2) <= 200 else rng3.sample(F2, 200)
        nv2 = sorted(closed_part(as_q(S2, d), None, A, B, mA, mB, ixA,
                                 ixB)[2] for S2 in draw2)
        kN2 = sum(v >= TA[2] for v in nv2)
        kM = sum(v >= TA[2] for v in mv)
        okf &= all(len(gc.box_points(list(S2), latd)) == 5 for S2 in F)
        okf &= tiles <= set(F)
        pre = gr.sub(gr.mul(gr.P2, dq), gr.PHI)
        y = [z for z in gr.SURV if gr.cmp(sq[z], pre) == 0]
        if y:
            Ay = gr.pts(gr.fixed(runs[y[0]])[0])
            S = set(translates(srcA, set(A)))
            e3 = gr.phipow(-3)
            okr &= all(gr.sub(gr.mul(gr.E2, v), e3) in S for v in Ay)
            nimg += 1
        rows.append((name, len(A), len(B), T, TA, len(F), len(draw), nv, mv,
                     kN, bool(y), len(F2), len(draw2), nv2, kN2, kM))
        print(f"  {name:22s} |A| {len(A):5d} |B| {len(B):5d}  T: t {T[0]}x"
              f"{T[1]} closed {T[2]}/{T[3]}  TA: t {TA[0]} closed "
              f"{TA[2]}/{TA[3]}  |F| {len(F)}")
        print(f"      N ({len(draw)}): closing {sum(v > 0 for v in nv)}, "
              f"median {nv[len(nv) // 2] if nv else None}, max "
              f"{nv[-1] if nv else None}, >= TA {kN}; M: closing "
              f"{sum(v > 0 for v in mv)}, median {mv[100]}, max {mv[-1]}, "
              f">= TA {kM}  ({time.time() - tk:.1f} s)")
        print(f"      N' (tile translates excluded, {len(draw2)} of "
              f"{len(F2)}): closing {sum(v > 0 for v in nv2)}, max "
              f"{nv2[-1] if nv2 else None}, >= TA {kN2}")
    check("(d) TA >= T at every x (monotone closure)", okd)
    tauA = sorted(gr.q(*t) for t in gr.goldren.TAU_A[:5])
    okt = sorted(gr.sub(v, gr.phipow(-3)) for v in srcA) == tauA
    check(f"(e) delta_1's A - phi^-3 is tau_A, and at each of the {nimg} "
          "R-images x = R(y), phi^-2 v - phi^-3 is a translate for every v "
          "of A_y", okt and okr and nimg > 0)
    check("(f) every member of every F_x has five coset points in its box "
          "over Z[phi], and every tile translate is a member", okf)
    print(f"    largest conj gap in any strip: {gapmax:.4f} (four gaps "
          f"must fit in {WIN})")
    check("the strip window holds every run: 4 x largest gap <= WIN",
          4 * gapmax <= WIN)

    sv = rows[1:]
    withT = [r for r in sv if r[4][0] > 0]
    closes = [r for r in withT if r[4][2] > 0]
    beats = [r for r in closes if r[9] < 10]
    print(f"\nKILL: delta_1's A tile closes at {len(closes)} of {len(withT)}"
          f" survivors with a translate; beats its CPS null at {len(beats)}"
          f" of {len(closes)}")
    print(f"    survivors with no translate: "
          f"{[r[0] for r in sv if r[4][0] == 0]}")
    law = len(closes) == len(withT) and len(beats) == len(closes)
    print(f"    the translation law {'stands' if law else 'KILLED'}")
    for lab, grp in (("R-images", [r for r in withT if r[10]]),
                     ("roots", [r for r in withT if not r[10]])):
        print(f"    after the run, by kind: the tile closes at "
              f"{sum(r[4][2] > 0 for r in grp)} of {len(grp)} {lab}; "
              f"fails at {[r[0] for r in grp if r[4][2] == 0]}")
    print(f"    closing roots: "
          f"{[r[0] for r in withT if not r[10] and r[4][2] > 0]}")
    beats2 = [r for r in closes if r[14] < 10 * r[12] / 200]
    print("")
    print(f"N': against N' (tile translates excluded, the bar "
          f"10 of 200 scaled to the draws), the tile beats it at "
          f"{len(beats2)} of {len(closes)}: {[r[0] for r in beats2]}")
    print(f"    reaching TA's closed |A|: N' "
          f"{[(r[0], r[14], r[12]) for r in closes]}")
    print(f"    M (B free) reaching it: {[(r[0], r[15]) for r in closes]}")
    beatsM = [r for r in closes if r[15] < 10]
    print(f"    the tile beats M (fewer than 10 of 200 reach it) at "
          f"{len(beatsM)} of {len(closes)}; not at "
          f"{[r[0] for r in closes if r[15] >= 10]}")
    nN = sum(sum(v > 0 for v in r[7]) for r in sv)
    nM = sum(sum(v > 0 for v in r[8]) for r in sv)
    tN = sum(len(r[7]) for r in sv)
    print(f"    Q3: N draws closing {nN} of {tN}; M {nM} of {200 * len(sv)}")
    img = [r for r in withT if r[10]]
    roots = [r for r in withT if not r[10]]
    d4 = [r for r in closes if r[0] == gr.show(gr.pt_q(gr.spt(-33, 21, 1)))
          and r[4][2] == 930]
    print("== the FINDINGS' figures")
    check("20 survivors with |A_inf| >= 18, each with a translate",
          len(sv) == 20 and len(withT) == 20)
    check("the kill's print: closes at 12 of 20, beats N at 0 of 12",
          len(closes) == 12 and len(beats) == 0)
    check("N' beaten at 1 of 12; at delta' 15 of 200 N' draws reach 181, "
          "at delta_4 65 of 200 reach 930",
          len(beats2) == 1 and rows[0][4][2] == 181 and rows[0][14] == 15
          and rows[0][12] == 200 and len(d4) == 1 and d4[0][14] == 65
          and d4[0][12] == 200)
    check("M beaten at 9 of 12; at delta' 8 of 200 M draws reach 181",
          len(beatsM) == 9 and rows[0][15] == 8)
    check("by kind: closes at 8 of 8 R-images, 4 of 12 roots",
          len(img) == 8 and all(r[4][2] > 0 for r in img)
          and len(roots) == 12 and sum(r[4][2] > 0 for r in roots) == 4)
    check("Q3: N draws closing 1393 of 3647, M 3134 of 4000",
          (nN, tN, nM, 200 * len(sv)) == (1393, 3647, 3134, 4000))
    check("T closes exactly where TA does, its closed |A| within 8",
          all((r[3][2] > 0) == (r[4][2] > 0) and r[4][2] - r[3][2] <= 8
              for r in sv))
    print(f"\n{sum(CHECKS)} of {len(CHECKS)} checks, {time.time() - t0:.1f} s")
    return 0 if all(CHECKS) else 1


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