goldfix.py

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

Cited on: FLUSH.

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

"""goldfix.py -- the free shifted bar at golden, c = 1, read as an exact
set recursion in Z[phi], and its fixed points at s + 1 = F_2k.

QUESTION. At golden, s0 = 1, c = 1 and m = M(s) = floor((s + 1) phi),
the largest m with c_lo = 1, does the free bar pass where s + 1 = F_2k
(s = 2, 7, 20, ...) and fail at the other s (X3 reads s <= 12)? A
pass at every L is a nonempty greatest fixed point of the bar's
recursion. Is it reached exactly at a finite depth, so that
the pass is proved at that cell, and is it proved at every k?

DESIGN. Golden is self-similar: at c = 1, level i reads lv = t + i and
K = lv + 1; in units x = y / theta_lv, theta_K = -1/phi, theta_(K+1) =
phi^-2, the window T_(lv+1) is [-(1 + s), (1 + s)/phi] and the next
level's x is -phi x. So, A the set after a 0 (the opponent's digit d in
{0, 1}) and B after a 1 (d = 0 only), each at distance n from the
bottom (A_0 = B_0 = R):
  G0 = [-(1 + s) + m phi^-2, (1 + s - m)/phi]
  G1 = [-(1 + s) + m phi^-2, (1 + s)/phi - m phi^-3]
  C0 = G0 cap (-A/phi), C1 = (G1 cap (-B/phi)) + m/phi
  U(C) = cup_(e = 0 .. 1 + s) (C + e)
  A' = U(C0) cap U(C1), B' = U(C0); W(t, 1, L) = G0 cap (-A_(L-1)/phi).
As a game: from x the opponent plays d, the reader e in 0 .. 1 + s,
and x' = phi(e - x) + m d must lie in J_d: J_0 = -phi G0 = [m - 1 - s,
(1 + s)phi - m/phi], J_1 = -phi G1 = [-(1 + s) + m phi^-2, (1 +
s)phi - m/phi]. At s + 1 = F_2k, m = F_(2k+1) - 1, J_0 = [F_(2k-1) - 1,
F_(2k-1) + 1/phi - phi^(1-2k)] (by F_n phi = F_(n+1) - (-1/phi)^n), its
length below phi, so the reader's answer to d = 0 is forced.
Every endpoint is a + b phi, a and b integers, held exactly; order is
read off an integer key, floor(2^200 (a + b phi)), exact at these
coefficients. The windows are the exact closed T, so a pass here is a
pass of the widened bar.

PREDICTIONS (frozen before the engine).
X1 at s = 2 (m 4) and 7 (m 12) the iteration reaches a fixed point,
   (A_(n+1), B_(n+1)) = (A_n, B_n) exactly, at some n <= 40, its root
   nonempty.
X2 likewise at s = 20 (m 33), n <= 60.
X3 at s = 3 .. 12 with s + 1 not F_2k, m = M(s), A_n empties at
   the interval engine's L* (L* = n + 1).
Control X0: |W(t, 1, L)| per L equals shifted.py's Bar's at the first
pin, s = 1 .. 12, m = floor(s phi) + 1, + 2, L <= 12; a plant (the d = 1
shift's sign flipped) must differ.
KILL: X1 or X2 printing "none by" at a cell; X3 off at any cell.

FINDINGS (copied from the print).
X0 held: 0 of 24 differ; the plant differs at 20 of 24; the sets
   themselves, Bar's endpoints over theta_t at L <= 8: "128 reads,
   0 count mismatches, worst endpoint difference 4.592e-13".
X1 and X2 held, and the next chain cell with them: at s = 2, 7, 20, 54
   (m = 4, 12, 33, 88) the iteration is fixed at n = 7, 9, 11, 13, with
   |A| = 31, 211, 1437, 9815, so W(t, 1, L) is nonempty at every L
   there: the pass is verified at these four cells (s = 54 under
   --full). At each, every interval of
   A and B is a single point, so the pass is an exact tie, and A spans
   the window -phi G0 = [F_(2k-1) - 1, F_(2k-1) + 1/phi - phi^(1-2k)]
   ([1.0000, 2.3820] .. [33.0000, 34.6049]); |B| = (s + 2)|A|.
   The fixed point is no cut-and-project set over one conjugate
   interval: at s = 2, 7, 20 the box of real and conjugate ranges holds
   53, 422, 3074 points of Z[phi] against |A| = 31, 211, 1437.
X3 held: L* 4 or 6 at the nine failing cells, equal to Bar's.
The game: c_saf = 1 at s = 2 (m 4) and s = 7 (m 12), so at those two
   the bar's silence at c = 1 is the truth, not slack.

RUN RECORD. 5 of 5, 56.3 s, peak 1719.8 MB under a 2048 MB cap (the
point sets B at s = 54, 549640 points). Changes to what was frozen:
the first run's X0 read 4 of 24 differing at L = 1 (s 2 m 5, 5 m 10, 7
m 13, 10 m 18), where G0 is inverted and the engine passed it through
as an interval; an inverted window is now empty, and the other prints
reprinted unchanged. The point and game prints were added after the
first run; X1 runs to n <= 60, not the frozen 40 (every cell is fixed
by n = 13). The X0 set check was added later and run alone
(section_control, 3 of 3); a plant, the d = 1 shift's sign flipped in
it, reads "56 reads, 29 count mismatches". The interval engine X0 and
X3 read against was first a faster one, its union taken by halving;
shifted.py's Bar reprints every X0 and X3 line unchanged. The checks
against RECORD, the game's check and X3's emptying check were added
after: a break, the reader's digit cap at d = 0 lowered by one, fails
10 of 18, X0 through X3 and W2.
The default run (s <= 20, W2 at k <= 4): 18 of 18, 10.7 s, peak 124.5
MB under a 512 MB cap. --full adds s = 54 and K_5 inside A: 20 of 20,
117.4 s, peak 1737.5 MB under a 2048 MB cap.

WINDOW (--window alone): the pass at every k, by a closed subset.
A nonempty K inside J_0 such that each x in K has an e with phi(e - x)
in K, and an e, e' with y = phi(e - x) + m in J_1 and phi(e' - y) in K,
lies in every A_n (by induction, with {y : some e', phi(e' - y) in K}
inside B_n), so W(t, 1, L) holds -K/phi at every L. At s + 1 = F_2k,
m = F_(2k+1) - 1, k >= 2, write x = s/phi + v, eps = phi^-2k, N =
phi^2k = eps*, * the conjugate (phi* = -1/phi), and
  K_k = {s/phi + v : v in Z[phi], v in I, v* in I*},
  I = [-phi^-2 + eps, 2/phi - phi eps], I* = [0, N - phi^2].
Proof that K_k is closed. By F_n phi = F_(n+1) - (-1/phi)^n, J_0 -
s/phi = [-phi^-2 + eps, 2/phi - eps/phi], which holds I, and phi^2 s -
phi m = -1 - phi eps. d = 0 with e = s + c: v' = phi(c - v), v'* = (v*
- c)/phi; c = 0 or 1 puts v' in I (its real part) except for v in the
gap (phi^-3 - eps/phi, phi^-3 + eps), and a v of K there makes u = v -
phi^-3 nonzero (u = 0 has v* < 0) with |u| < eps and u* = v* + phi^3 <=
N + phi: |N(u)| < 2, so u = +-phi^-j, j > 2k, |u*| = phi^j > N + phi,
none. At c = 1, v'* >= 0 needs v* >= 1: v - v* = b sqrt5 in (-1, 1.24]
gives b = 0 and v an integer in [0.236, 1), none; and (v* - c)/phi <=
v* <= N - phi^2. d = 1 with e = 0: y = F_(2k-1) - phi v, inside J_1 for
v in I; e' = s + c', c' in {-1, 0, 1}: v'' = phi^2 v + phi c' - 1 - phi
eps, v''* = v*/phi^2 - c'/phi - 1 + N/phi. The real part leaves two
gaps of length phi^2 eps, at u = phi^2 v - 1/phi and u = phi^2 v -
sqrt5 in (0, phi^2 eps), where u* <= N/phi^2 + sqrt5: |N(u)| < 2, u =
phi^-j with j even (u* > 0), j >= 2k, u* >= N > N/phi^2 + sqrt5 (k >=
2), none. The conjugate holds at c' = 1 always, at c' = 0 iff v* <= N -
phi^3, at c' = -1 iff v* <= N - sqrt5 phi^2; a v breaking either makes
u = v - eps a point of Z[phi] in [phi^-3, sqrt5/phi^2) x (-phi^3,
-phi^2] or [sqrt5/phi^2, 2/phi) x (-sqrt5 phi^2, -phi^2], where u - u*
= b sqrt5 leaves only phi^-3, 2/phi and sqrt5/phi^2, each on an
excluded end. v = 0 is in K_k. So the bar passes at every L at every k
>= 2: the pass at s + 1 = F_2k is a theorem of this recursion.
PREDICTIONS (frozen before the check's code). W1 K_k, built exactly,
is closed with the proof's witnesses (e in {s, s + 1} at d = 0; e = 0,
e' in s - 1 .. s + 1 at d = 1) at k = 2 .. 12. W2 K_k inside A at k =
2 .. 4 (5 under --full), point for point. W3 |K_k| = F_(2k+1) - 1 = m at
k = 2 .. 12, a pattern. Control: I's top raised by phi^2 eps must break
W1. KILL: W1 off at any k; W2 off at any point.
FINDINGS (copied from the print). W1 held at k = 2 .. 12; W3 held,
|K_k| = 4, 12, 33, 88, .., 75024; W2 held at k = 2 .. 5, K_k against
|A| = 31, 211, 1437, 9815, 0 outside. Three plants break W1 at k = 2 ..
12, each check reading its own branch: I's top raised adds one point, v
= 2/phi + eps, failing all three tests and read at K inside J_0 (by
construction, J_0's top being 2/phi - eps/phi); the d = 1 witness
without e' = s - 1 fails the d = 1 test alone; the d = 0 witness
without e = s + 1 fails the d = 0 test alone. I*'s top raised by 1
admits one point, v* = N - phi, and the m + 1 points stay closed at k =
2 .. 12: K_k is not the largest closed window.
RUN RECORD. --window with K_5: 8 of 8, 59.1 s, peak 1740.5 MB under a
2048 MB cap (A at k = 5); --window alone 3.9 s, 113.9 MB (5.4 s with
the third plant). Changes to what was frozen: a second plant, I*'s top
raised by 1, was frozen as a defect and admitted a point the proof
never excludes (the raise moves the target window with the domain), so
it read nothing and is now a print; in its place the d = 1 witness
without e' = s - 1, the proof's c' = -1 branch, breaks W1 at every k.
The d = 0 plant was added later, the first plant reading only K
inside J_0.

Run: python goldfix.py [--window] [--full]
"""
import math
import os
import sys
import time

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

CHECKS = []
PREC = 199


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


# ------------------------------------------------------------ Z[phi]

def num(a, b):
    """a + b phi as (key, a, b), key = floor(2^(PREC+1) (a + b phi))."""
    r = math.isqrt((5 * b * b) << (2 * PREC))
    return (((2 * a + b) << PREC) + (r if b >= 0 else -r - 1), a, b)


def ndiv(x):
    """-x / phi: -(a + b phi)(phi - 1) = (a - b) - a phi."""
    return num(x[1] - x[2], -x[1])


def add(x, a, b):
    return num(x[1] + a, x[2] + b)


def fl(x):
    return x[1] + x[2] * (1 + math.sqrt(5)) / 2


# ------------------------------------------------------------ intervals

def norm(xs):
    xs = sorted(xs)
    out = []
    for a, b in xs:
        if a > b:
            continue
        if out and a <= out[-1][1]:
            if b > out[-1][1]:
                out[-1] = (out[-1][0], b)
        else:
            out.append((a, b))
    return out


def inter(U, V):
    """U cap V; None is the whole line."""
    if U is None:
        return V
    if V is None:
        return U
    out, i, k = [], 0, 0
    while i < len(U) and k < len(V):
        a, b = max(U[i][0], V[k][0]), min(U[i][1], V[k][1])
        if a <= b:
            out.append((a, b))
        if U[i][1] < V[k][1]:
            i += 1
        else:
            k += 1
    return out


def shift(U, a, b):
    return [(add(x, a, b), add(y, a, b)) for x, y in U]


def negscale(U):
    """-U/phi; None stays the whole line."""
    if U is None:
        return None
    return [(ndiv(y), ndiv(x)) for x, y in reversed(U)]


def sweep(C, n):
    """cup_(e = 0 .. n) (C + e), by halving."""
    if n == 0 or not C:
        return norm(C)
    h = n // 2
    half = sweep(C, h)
    return norm(half + shift(half, n - h, 0))


# ------------------------------------------------------------ the bar

class Gold:
    """The normalized recursion at (s, m); sign = -1 plants the d = 1
    shift's sign flipped."""

    def __init__(self, s, m, sign=1):
        self.s, self.m = s, m
        S = 1 + s
        g0 = (num(-S + 2 * m, -m), num(-(S - m), S - m))
        g1 = (g0[0], num(-S + 3 * m, S - 2 * m))
        self.G0 = [g0] if g0[0] <= g0[1] else []
        self.G1 = [g1] if g1[0] <= g1[1] else []
        self.sh = (-m * sign, m * sign)  # m / phi = m(phi - 1)

    def step(self, A, B):
        C0 = inter(self.G0, negscale(A))
        C1 = shift(inter(self.G1, negscale(B)), *self.sh)
        U0 = sweep(C0, 1 + self.s)
        return inter(U0, sweep(C1, 1 + self.s)), U0

    def root(self, A):
        return inter(self.G0, negscale(A))

    def run(self, nmax):
        """(n, A, B, counts): n the first n with (A_(n+1), B_(n+1)) =
        (A_n, B_n), or 'empty' at A_n empty, or None by nmax; counts
        the root's |W| at L = 1 .. ."""
        A = B = None
        counts = []
        for n in range(nmax + 1):
            W = self.root(A)
            counts.append(len(W))
            if not W:
                return "empty", A, B, counts
            A2, B2 = self.step(A, B)
            if A2 == A and B2 == B:
                return n, A, B, counts
            A, B = A2, B2
        return None, A, B, counts


def floor_phi(s):
    return (s + math.isqrt(5 * s * s)) // 2


def fib_chain(smax):
    out, f = [], (1, 2)
    while f[0] <= smax + 1:
        out.append(f[0] - 1)
        f = (f[0] + f[1], f[1] + f[0] + f[1])
    return out


# ------------------------------------------------------------ sections

def counts_upto(g, L):
    A = B = None
    out = []
    for _ in range(L):
        W = g.root(A)
        out.append(len(W))
        if not W:
            break
        A, B = g.step(A, B)
    return out


def bar_read(s, m, lmax):
    """(L*, |W| per L at the first pin level): shifted.py's Bar at
    golden, s0 = 1, L* the least L <= lmax with W(t, 1, L) empty, or
    None."""
    from flush import Metric, numeration
    from shifted import Bar, pin_ts
    met = Metric(numeration("[1]", (1,)), s, 1, 72)
    bar, t = Bar(met, m), pin_ts(met, 24)[0]
    counts = []
    for L in range(1, lmax + 1):
        counts.append(len(bar.W(t, 1, L)))
        if not counts[-1]:
            return L, counts
    return None, counts


def section_control():
    print("== X0 the normalized engine against shifted.py's Bar, s = 1 .. "
          "12, L <= 12")
    off, plant = [], 0
    for s in range(1, 13):
        for k in (1, 2):
            m = floor_phi(s) + k
            L, fast = bar_read(s, m, 12)
            mine = counts_upto(Gold(s, m), 12)
            if mine != fast:
                off.append((s, m, fast, mine))
            plant += counts_upto(Gold(s, m, -1), 12) != fast
    for s, m, fast, mine in off:
        print(f"    s {s} m {m}: Bar {fast}, exact {mine}")
    check("X0 |W| per L equal at 24 cells", not off,
          f"{len(off)} of 24 differ")
    check("X0 plant (d = 1 shift's sign flipped) differs",
          plant == RECORD["plant"],
          f"{plant} of 24 differ")
    # the sets themselves: Bar's endpoints over theta_t, L <= 8
    from flush import Metric, numeration
    from shifted import Bar, pin_ts
    worst, bad, nr = 0.0, 0, 0
    for s in range(1, 13):
        for k in (1, 2):
            m = floor_phi(s) + k
            met = Metric(numeration("[1]", (1,)), s, 1, 72)
            bar, t = Bar(met, m), pin_ts(met, 24)[0]
            g, A, B = Gold(s, m), None, None
            for L in range(1, 9):
                W, X = bar.W(t, 1, L), g.root(A)
                ends = sorted(v / met.theta(t) for iv in W for v in iv)
                mine = sorted(fl(v) for iv in X for v in iv)
                nr += 1
                if len(ends) != len(mine):
                    bad += 1
                else:
                    worst = max([worst] + [abs(a - b)
                                           for a, b in zip(ends, mine)])
                if not X:
                    break
                A, B = g.step(A, B)
    check("X0 the sets: every endpoint within 1e-9 of Bar's",
          bad == 0 and worst < 1e-9 and nr == RECORD["reads"],
          f"{nr} reads, {bad} count mismatches, worst endpoint "
          f"difference {worst:.3e}")


# FINDINGS' numbers: (n, |A|, |B|, the box's points of Z[phi]) on the
# chain, L* at the failing cells, X0's plant count and set reads
RECORD = {"chain": {2: (7, 31, 124, 53), 7: (9, 211, 1899, 422),
                    20: (11, 1437, 31614, 3074), 54: (13, 9815, 549640)},
          "fails": {3: 4, 4: 4, 5: 6, 6: 4, 8: 4, 9: 4, 10: 6, 11: 4,
                    12: 4},
          "plant": 20, "reads": 128}


def box_points(A):
    """The points of Z[phi] in the box of A's real and conjugate ranges."""
    pts = [(x[1], x[2]) for x, _ in A]
    conj = [a - b * (5 ** .5 - 1) / 2 for a, b in pts]
    lo, hi = min(fl(x) for x, _ in A), max(fl(x) for x, _ in A)
    clo, chi = min(conj), max(conj)
    n, r5 = 0, 5 ** .5
    for b in range(math.floor((lo - chi) / r5) - 1,
                   math.ceil((hi - clo) / r5) + 2):
        for a in range(math.floor(clo + b * (r5 - 1) / 2) - 1,
                       math.ceil(chi + b * (r5 - 1) / 2) + 2):
            v, w = fl((None, a, b)), a - b * (r5 - 1) / 2
            n += lo - 1e-9 <= v <= hi + 1e-9 and clo - 1e-9 <= w <= chi + 1e-9
    return n


def section_chain(nmax, smax):
    print(f"== X1 X2 the chain s + 1 = F_2k, s <= {smax}, n <= {nmax}")
    got, rec = {}, []
    for s in fib_chain(smax):
        if s < 2:
            continue
        m = floor_phi(s + 1)
        t0 = time.time()
        n, A, B, counts = Gold(s, m).run(nmax)
        got[s] = n
        pts = isinstance(n, int) and all(x == y for x, y in A + B)
        if isinstance(n, int):
            j0 = (num(m - 1 - s, 0), num(m, 1 + s - m))
            box = box_points(A) if s <= 20 else None
            want = RECORD["chain"].get(s)
            rec.append(want is not None and pts
                       and (n, len(A), len(B)) == want[:3]
                       and len(B) == (s + 2) * len(A)
                       and (A[0][0], A[-1][1]) == j0
                       and (box is None or box == want[3]))
            if box is not None:
                print(f"    s {s}: box of A's ranges {box} points of Z[phi]")
        print(f"    s {s} m {m}: "
              + (f"fixed at n = {n}, |A| {len(A)}, |B| {len(B)}, root "
                 f"{counts[-1]}, A in [{fl(A[0][0]):.4f}, "
                 f"{fl(A[-1][1]):.4f}], "
                 f"{'every interval a point' if pts else 'not all points'}"
                 if isinstance(n, int) else
                 "empties" if n == "empty" else f"none by {nmax}")
              + f"; |W| by L {counts[:12]}{'..' if len(counts) > 12 else ''}"
              f" ({time.time() - t0:.1f} s)", flush=True)
    check("X1 s = 2 and 7 fixed, root nonempty",
          all(isinstance(got.get(s), int) for s in (2, 7)),
          f"{[got.get(s) for s in (2, 7)]}")
    check("X2 s = 20 fixed", isinstance(got.get(20), int),
          f"{got.get(20)}")
    if smax >= 54:
        check("X2 s = 54 fixed", isinstance(got.get(54), int),
              f"{got.get(54)}")
    check("X1 X2 the record: n, |A|, |B| = (s + 2)|A|, every interval a "
          "point, A spanning J_0, the box's points",
          len(rec) == len([s for s in fib_chain(smax) if s >= 2])
          and all(rec), f"{sum(rec)} of {len(rec)} cells")


def section_fails():
    print("== X3 the failing cells s = 3 .. 12 at M(s)")
    chain = set(fib_chain(60))
    off, dead, got = [], [], {}
    for s in range(3, 13):
        if s in chain:
            continue
        m = floor_phi(s + 1)
        n, A, B, counts = Gold(s, m).run(40)
        Lx = len(counts) if n == "empty" else None
        Lf = bar_read(s, m, 12)[0]
        print(f"    s {s} m {m}: exact L* {Lx}, Bar L* {Lf}")
        if Lx != Lf:
            off.append(s)
        if Lx is None:
            dead.append(s)
        got[s] = Lx
    check("X3 exact L* = Bar's at every failing cell", not off,
          f"off: {off}")
    check("X3 every failing cell empties", not dead, f"passing: {dead}")
    check("X3 L* as recorded", got == RECORD["fails"], f"{got}")


def section_game():
    print("== the safety game at lookahead 1, s0 = 1, the first two cells")
    from flush import Game, Source
    wins = []
    for s, m in ((2, 4), (7, 12)):
        win = Game(Source(period=(1,)), m, s, 1, 1).solve(False)
        wins.append(win)
        print(f"    s {s} m {m}: the game {'wins' if win else 'loses'} at "
              f"c = 1, so c_saf {'= 1' if win else '>= 2'}")
    check("the game wins at c = 1 at both cells", all(wins))


# ------------------------------------------------------------ the window

def zsign(a, b):
    """The sign of a + b phi, exactly: 2(a + b phi) = (2a + b) + b sqrt5."""
    p, q = 2 * a + b, b
    if p >= 0 and q >= 0:
        return 0 if p == q == 0 else 1
    if p <= 0 and q <= 0:
        return -1
    d = p * p - 5 * q * q          # never 0: sqrt5 is irrational
    return (1 if d > 0 else -1) * (1 if p > 0 else -1)


def zle(x, y):
    return zsign(y[0] - x[0], y[1] - x[1]) >= 0


def zconj(x):
    return (x[0] + x[1], -x[1])


def zmul_phi(x):
    """phi (a + b phi) = b + (a + b) phi."""
    return (x[1], x[0] + x[1])


def zpow(j):
    """phi^j = F_(j-1) + F_j phi, any integer j."""
    def fib(n):
        if n < 0:
            return fib(-n) * (1 if (-n) % 2 else -1)
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return a
    return (fib(j - 1), fib(j))


def zfl(x):
    return x[0] + x[1] * (1 + 5 ** .5) / 2


def zadd(*xs):
    return (sum(x[0] for x in xs), sum(x[1] for x in xs))


def zneg(x):
    return (-x[0], -x[1])


def window(k, top=(0, 0), ctop=(0, 0)):
    """K_k in x = s/phi + v: v in [-phi^-2 + eps, 2/phi - phi eps] + top's
    raise, v* in [0, N - phi^2] + ctop's raise, eps = phi^-2k, N = eps*."""
    eps, N = zpow(-2 * k), zpow(2 * k)
    lo = zadd(zneg(zpow(-2)), eps)
    hi = zadd((-2, 2), zneg(zpow(1 - 2 * k)), top)     # 2/phi = 2phi - 2
    chi = zadd(N, zneg(zpow(2)), ctop)
    out = []
    for b in range(-int((zfl(chi) + 2) / 5 ** .5) - 2, 3):
        a0 = math.floor(zfl(lo) - b * (1 + 5 ** .5) / 2)
        for a in range(a0 - 1, a0 + 3):
            v = (a, b)
            if zle(lo, v) and zle(v, hi) and zle((0, 0), zconj(v)) \
                    and zle(zconj(v), chi):
                out.append(v)
    return out


def window_closed(k, K, cs=(-1, 0, 1), c0s=(0, 1)):
    """Each x of K: some e in {s, s + 1} with phi(e - x) in K; and with e
    = 0, y = m - phi x in J_1 and some e' in s - 1 .. s + 1 with phi(e' -
    y) in K; K inside J_0. Returns the points failing."""
    s, m = fibn(2 * k) - 1, fibn(2 * k + 1) - 1
    S = 1 + s
    X = {zadd((-s, s), v) for v in K}                  # s/phi = (-s, s)
    J0 = ((m - 1 - s, 0), (m, S - m))
    J1 = ((-S + 2 * m, -m), (m, S - m))
    bad = []
    for x in X:
        ok0 = any(zmul_phi(zadd((e, 0), zneg(x))) in X for e in (s + c for c in c0s))
        y = zadd((m, 0), zneg(zmul_phi(x)))
        ok1 = zle(J1[0], y) and zle(y, J1[1]) and any(
            zmul_phi(zadd((e, 0), zneg(y))) in X for e in (s + c for c in cs))
        inj = zle(J0[0], x) and zle(x, J0[1])
        if not (ok0 and ok1 and inj):
            bad.append("".join(t for t, ok in (("0", ok0), ("1", ok1),
                                                ("J", inj)) if not ok))
    return X, bad


def fibn(n):
    return zpow(n)[1]


def section_window(kmax, kA):
    print(f"== W the model set K_k closed under one step, k = 2 .. {kmax}")
    off, sizes = [], []
    for k in range(2, kmax + 1):
        K = window(k)
        X, bad = window_closed(k, K)
        sizes.append((k, len(K), fibn(2 * k + 1) - 1))
        if bad or not K:
            off.append((k, len(bad)))
    print(f"    (k, |K_k|, m): {sizes}")
    check(f"W1 closed at k = 2 .. {kmax}", not off, f"off: {off}")
    check("W3 |K_k| = m", all(a == b for _, a, b in sizes))
    for name, top, cs, c0s, want in (
            ("I's top + phi^2 eps", True, (-1, 0, 1), (0, 1), "J"),
            ("no e' = s - 1 at d = 1", False, (0, 1), (0, 1), "1"),
            ("no e = s + 1 at d = 0", False, (-1, 0, 1), (0,), "0")):
        hit, how = [], set()
        for k in range(2, kmax + 1):
            K = window(k, top=zpow(2 - 2 * k) if top else (0, 0))
            _, bad = window_closed(k, K, cs, c0s)
            if bad:
                hit.append(k)
                how |= set(bad)
        check(f"W plant ({name}) breaks W1 through its branch {want}",
              hit and any(want in h for h in how),
              f"breaks at k = {hit}, failing branches {sorted(how)}")
    # I*'s top raised: one more point, v* = N - phi, and still closed
    wide = []
    for k in range(2, kmax + 1):
        K2 = window(k, ctop=(1, 0))
        new = sorted(set(K2) - set(window(k)))
        wide.append((k, len(K2), len(window_closed(k, K2)[1]),
                     [zadd(zconj(v), zneg(zpow(2 * k))) for v in new]))
    print("    I*'s top + 1 (k, |K|, failing, v* - N of the new points): "
          f"{wide}")
    for k in range(2, kA + 1):
        s, m = fibn(2 * k) - 1, fibn(2 * k + 1) - 1
        n, A, B, _ = Gold(s, m).run(60)
        Apts = {(x[1], x[2]) for x, y in A}
        X, _ = window_closed(k, window(k))
        miss = X - Apts
        check(f"W2 K_{k} inside A (s {s}, m {m})", not miss,
              f"|K| {len(X)}, |A| {len(Apts)}, outside {len(miss)}")


def main():
    t0 = time.time()
    full = "--full" in sys.argv
    section_window(12, 5 if full else 4)
    if "--window" not in sys.argv:
        section_control()
        section_chain(60, 54 if full else 20)
        section_fails()
        section_game()
    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()