goldelta.py

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

Cited on: FLUSH.

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

"""goldelta.py -- the golden c = 1 bar at m = M(s) as a game in delta
alone, delta = (s + 1) phi - M(s).

QUESTION. goldfix.py's recursion, read in v = w - s/phi with its sets
restricted to the windows, should depend on s only through delta
(the DESIGN's derivation): V_delta = [1/phi - delta, (1 + delta)/phi] after
an input 0, U_delta = [-2, delta phi - 1] in u = y - (m - s) after a 1,
the reader's digits forced into c, e in {0, 1}, c' in {-1, 0, 1}:
  A' = V cap (cup_c (c - A/phi)) cap (cup_e (e - B/phi))
  B' = U cap (cup_c' (c' + delta - phi - A/phi)).
Does it, cell for cell against Gold, and how does the emptying depth L*
behave as delta nears the passes delta_k = 1 - phi^-2k?

DESIGN (derived by hand before the engine). With m = (s + 1)phi -
delta: J_0 - s/phi = V_delta (m - 1 - s - s/phi = 1/phi - delta, the
top (1 + delta)/phi). d = 0, e = s + c: v' = phi(c - v), and v' in
V_delta forces c in {0, 1} at every delta in [0, 1) (c >= 1 - delta phi
> -1; c = 2 needs delta >= 1). d = 1, reader e: y = m - s - phi(v - e),
in J_1 iff v - e in [1/phi - delta, m/phi^2 + 1/phi], the top never
binding at m >= 2, the bottom forcing e in {0, 1} (e = 1 only at delta
>= 1/phi). The forced 0, e' = s + c': v'' = phi^2(v - e) + phi c' -
phi^2 + phi delta (2s phi - s/phi - phi m = -phi^2 + phi delta), in
V_delta only at c' in {-1, 0, 1}, so s >= 1. In u = y - (m - s) =
-phi(v - e), J_1 - (m - s) = [-1 - m/phi, delta phi - 1], its bottom
below every u met (u >= -(1 + delta) > -2), hence U_delta. At the chain
delta = 1 - eps the constants are WINDOW's: [-phi^-2 + eps, 2/phi -
eps/phi] and -1 - phi eps.

PREDICTIONS (frozen before this engine).
R1 at s = 1 .. 40, |W| per L at delta(s) equals Gold(s, M(s))'s at every
   L <= 24 (or to its emptying), cell for cell, L* equal.
R2 at delta_k = 1 - phi^-2k, k = 2 .. 5, fixed by n <= 2k + 5.
R3 (a TRANSPLANT from expansion by phi a level) at delta_k + sigma
   phi^-j, sigma = +-1, k = 2, 3, j = 2k + 1 .. 2k + 10: a finite L*,
   nondecreasing in j on each side, L* - j spread at most 4.
Control: goldfix's RECORD L* at s = 3 .. 12 off the chain, its fixed
   points at s = 2, 7, 20; a plant (phi delta's sign flipped in v'')
   differs at some cell.
KILL: R1 off at any cell or L; R2 off at any k. R3 a read: a delta off
   the chain alive to L = 40 kills "G_delta empties unless delta =
   delta_k" on that side.

FINDINGS (copied from the print).
Controls held: RECORD's L* at the failing cells, fixed at s = 2, 7, 20;
   the plant differs at 19 of 40.
R1 held: 0 of 40 differ, so the bar at golden, c = 1, m = M(s) is a
   game in delta alone at s = 1 .. 40. L* off the chain: 4 at 25 cells,
   5, 6, 7, 8, 9 at the others (s 28's 9 the deepest).
R2 held: fixed at n = 7, 9, 11, 13 (n = 2k + 3), |A| = 31, 211, 1437,
   9815, as goldfix's chain.
R3 KILLED as frozen: L* does not grow with j. At k = 2 it is 7 below
   (6 at j = 6) and 8 above (from j = 7); at k = 3, 9 to 11 below (11
   at j = 7), 10 to 11 above (15 at j = 8). delta_2 + phi^-5 = delta_3
   and delta_3 + phi^-7 = delta_4 read fixed, the chain's next points, not a
   counterexample; every other delta read empties.
DEEP (read after R3, j = 2k + 2 .. 2k + 30, L <= 60): L*
   settles at 7, 10, 12 below delta_k and 8, 11, 13 above at k = 2, 3,
   4, at most two levels past the fixed depth 2k + 3, from j = 2k + 3
   on: every sampled delta_k +- phi^-j empties by L = 2k + 5, an
   observation on two rays at these k and j (whether delta_k is
   isolated in a survivor set is the parametric engine's question).
   At delta_k + phi^-(2k+2) = 1 - phi^-(2k+1), L* = 11, 15, 19 at k =
   2, 3, 4 (4k + 3), deeper than either side's limit; 1 - phi^-5 is
   also delta_3 - phi^-7 (R3's j = 7), 11 again.

RUN RECORD. 5 of 5, 12.5 s, peak 104.5 MB under a 2048 MB cap; DEEP
alone 4.2 s, 25.6 MB. The R3 and DEEP checks against RECORD were added
after, DEEP joining the default run: R3's rows, DEEP's last values, the settle
by L = 2k + 5 from j = 2k + 3, and L* = 4k + 3 at 1 - phi^-(2k+1):
9 of 9, 18.1 s, peak 103.4 MB.

Run: python goldelta.py
"""
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 goldfix import (Gold, RECORD, counts_upto, floor_phi,  # noqa
                     inter, negscale, num, shift, sweep, zpow)

CHECKS = []


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


class Delta:
    """G_delta's restricted recursion; delta = a + b phi; sign = -1
    plants phi delta's sign flipped in v''."""

    def __init__(self, a, b, sign=1):
        self.V = [(num(-1 - a, 1 - b), num(b - 1 - a, 1 + a))]
        self.U = [(num(-2, 0), num(b - 1, a + b))]
        # c' + delta - phi over c' = -1 .. 1: sweep 0 .. 2 from delta - phi - 1
        self.q = (sign * a - 1, sign * b - 1)

    def step(self, A, B):
        nA = negscale(A)
        A2 = inter(inter(self.V, sweep(nA, 1)), sweep(negscale(B), 1))
        B2 = inter(self.U, shift(sweep(nA, 2), *self.q))
        return A2, B2

    def run(self, lmax):
        """(L*, counts, n): counts |A_n| for n = 0 .. ; L* the first L with
        A_(L-1) empty (counts' length at emptying), n the first fixed n."""
        A, B, counts = self.V, self.U, []
        for n in range(lmax):
            counts.append(len(A))
            if not A:
                return len(counts), counts, None
            A2, B2 = self.step(A, B)
            if A2 == A and B2 == B:
                return None, counts, n
            A, B = A2, B2
        return None, counts, None


def delta_of(s):
    return -floor_phi(s + 1), s + 1


def counts_fixed(d, lmax):
    """counts to lmax, a fixed point's count repeated past it."""
    L, counts, n = d.run(lmax)
    while L is None and n is not None and len(counts) < lmax:
        counts.append(counts[-1])
    return L, counts, n


def section_r1(smax, lmax):
    print(f"== R1 the delta engine against Gold, s = 1 .. {smax}, L <= {lmax}")
    off, plant, rows = [], 0, []
    for s in range(1, smax + 1):
        m = floor_phi(s + 1)
        gold = counts_upto(Gold(s, m), lmax)
        L, mine, n = counts_fixed(Delta(*delta_of(s)), lmax)
        mine = mine[:len(gold)]
        if mine != gold:
            off.append((s, gold, mine))
        _, pl, _ = counts_fixed(Delta(*delta_of(s), sign=-1), lmax)
        plant += pl[:len(gold)] != gold
        rows.append((s, L, n))
    for s, g, x in off:
        print(f"    s {s}: Gold {g}, delta {x}")
    print(f"    (s, L*, fixed n): {rows}")
    check(f"R1 |W| per L equal at s = 1 .. {smax}", not off,
          f"{len(off)} of {smax} differ")
    check("control: L* at the failing cells s <= 12 as goldfix's RECORD",
          all(L == RECORD["fails"][s] for s, L, _ in rows
              if s in RECORD["fails"]))
    check("control: fixed at s = 2, 7, 20",
          all(n is not None for s, _, n in rows if s in (2, 7, 20)))
    check("control: the plant (phi delta's sign flipped) differs",
          plant > 0, f"{plant} of {smax} differ")
    return rows


def dk(k, j=None, sigma=0):
    e = zpow(-2 * k)
    a, b = 1 - e[0], -e[1]
    if j is not None:
        p = zpow(-j)
        a, b = a + sigma * p[0], b + sigma * p[1]
    return a, b


def section_r2():
    print("== R2 delta_k = 1 - phi^-2k, k = 2 .. 5")
    out = []
    for k in range(2, 6):
        L, counts, n = Delta(*dk(k)).run(2 * k + 8)
        out.append((k, n, counts[-1]))
    print(f"    (k, fixed n, |A|): {out}")
    check("R2 fixed by n <= 2k + 5 at k = 2 .. 5",
          all(n is not None and n <= 2 * k + 5 for k, n, _ in out))


# R3's L* (or "fixed n") at j = 2k + 1 .. 2k + 10, and DEEP's settled
# L* (the row's last) below and above delta_k, copied from the print
RECORD3 = {(2, -1): [7, 6, 7, 7, 7, 7, 7, 7, 7, 7],
           (2, 1): ["fixed 9", 11, 8, 8, 8, 8, 8, 8, 8, 8],
           (3, -1): [11, 9, 9, 9, 9, 9, 10, 10, 10, 10],
           (3, 1): ["fixed 11", 15, 10, 10, 10, 10, 10, 10, 11, 11]}
SETTLE = {(2, -1): 7, (2, 1): 8, (3, -1): 10, (3, 1): 11, (4, -1): 12,
          (4, 1): 13}


def section_r3(lmax):
    print(f"== R3 delta_k + sigma phi^-j, k = 2, 3, j = 2k + 1 .. 2k + 10, "
          f"L <= {lmax}")
    got = {}
    for k in (2, 3):
        for sigma in (-1, 1):
            row = []
            for j in range(2 * k + 1, 2 * k + 11):
                L, counts, n = Delta(*dk(k, j, sigma)).run(lmax)
                row.append((j, L if L is not None else
                            ("fixed %d" % n if n is not None else "alive"),
                            max(counts)))
            got[(k, sigma)] = [r[1] for r in row]
            print(f"    k {k} sigma {sigma:+d} (j, L*, max |A|): {row}",
                  flush=True)
    check("R3's L* rows as recorded", got == RECORD3)


def section_deep(lmax):
    print(f"== DEEP L* at delta_k + sigma phi^-j, k = 2 .. 4, j to 2k + 30, "
          f"L <= {lmax}")
    rows = {}
    for k in (2, 3, 4):
        for sigma in (-1, 1):
            row = [Delta(*dk(k, j, sigma)).run(lmax)[0]
                   for j in range(2 * k + 2, 2 * k + 31)]
            rows[(k, sigma)] = row
            print(f"    k {k} sigma {sigma:+d} L* at j = 2k + 2 ..: {row}",
                  flush=True)
    check("DEEP: every row empties, settling at 7, 10, 12 below and 8, 11, "
          "13 above", all(None not in r and r[-1] == SETTLE[key]
                          for key, r in rows.items()))
    check("DEEP: from j = 2k + 3 on, every L* <= 2k + 5",
          all(max(r[1:]) <= 2 * k + 5 for (k, _), r in rows.items()))
    check("DEEP: L* = 4k + 3 at delta_k + phi^-(2k+2) = 1 - phi^-(2k+1)",
          all(rows[(k, 1)][0] == 4 * k + 3 for k in (2, 3, 4)),
          f"{[rows[(k, 1)][0] for k in (2, 3, 4)]}")


def main():
    t0 = time.time()
    section_r1(40, 24)
    section_r2()
    section_r3(40)
    section_deep(60)
    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()