goldsurv.py

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

Cited on: FLUSH.

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

"""goldsurv.py -- the golden survivor set S_L of G_delta, exactly, as a
finite union of closed delta-intervals.

QUESTION. goldelta.py reads the golden c = 1 bar at m = M(s) as a game
G_delta in delta = frac((s + 1) phi) alone. Its survivor set S_L =
{delta in [0, delta_4] : A_(L-1)(delta) nonempty}, delta_k = 1 -
phi^-2k, is a finite union of closed intervals. Is S_40 the five chain
points delta_0 .. delta_4 alone, so that every s >= 1 with delta(s) in
[0, delta_4] and s + 1 no F_2k fails, by one finite computation?

DESIGN (derived by hand before the engine). Every endpoint of A_n and
B_n is alpha + beta delta, alpha and beta in Z[phi]: V's are (phi - 1)
- delta and (phi - 1)(1 + delta), U's -2 and phi delta - 1; v -> c -
v/phi sends (alpha, beta) to (c - alpha/phi, -beta/phi), v -> c' +
delta - phi - v/phi to (c' - phi - alpha/phi, 1 - beta/phi), and an
intersection or union keeps endpoints. Two endpoints cross only at
delta = -alpha/beta of their difference, a point p/q, p and q in Z[phi].
A cell is an open interval (lo, hi) or a point, its ends p/q: the sign of
alpha + beta delta at p/q is that of alpha q + beta p times q's, all in
Z[phi], the sign of a + b phi read off (2a + b) + b sqrt5 in integers.
A comparison in an open cell reads the difference's sign at both ends:
one sign (a zero at one end allowed) is the sign on the whole cell;
opposite signs split the cell at the root into (lo, r), {r}, (r, hi),
and the step restarts on each. So on every leaf cell the run is one
exact computation, its L* (the first L with A_(L-1) empty, as
goldelta's run) constant on the cell. A_(n+1) lies in A_n (the step is
monotone, A_1 in V = A_0 and B_1 in U = B_0), so S_(L+1) lies in S_L; the
graph of
A_n is closed, so S_L is compact.

PREDICTIONS (frozen before this engine).
P1 S_40 is {delta_0, delta_1, delta_2, delta_3, delta_4}, five points.
P2 the component of S_(2k+5) holding delta_k is {delta_k} alone, k = 2,
   3, 4.
P3 the pieces of S_L, printed at L <= 13 (endpoints exact and as
   floats), and their count at every L <= 40, finite (a property).
P4 (a TRANSPLANT from DEEP's two midpoints) the deepest L* off the
   chain on [0, delta_4] is 15, at the cell holding 1 - phi^-7. A read.
Control, read before the kill: (a) the point evaluator (exact Q(phi)
   game) against goldelta's Delta.run L* at delta(s), s = 1 .. 40, at
   DEEP's points delta_k +- phi^-j inside [0, delta_4] (k = 2, 3; delta_4
   - phi^-j), j = 2k + 2 .. 2k + 20, and fixed at delta_0, delta_1; (b)
   the cell engine's L* at the cell holding each of those points equal
   to (a)'s; (c) every open cell's L* equal to the point evaluator's at
   an interior point of it; (d) a break, the split skipped (the sign read
   at the cell's left end), must fail (b) or (c).
KILL (one print): some delta in [0, delta_4] off {delta_0 .. delta_4}
   in S_40, or a component of S_(2k+5) about delta_k (k = 2, 3, 4) of
   positive length. Read over every cell of [0, delta_4], none drawn.

FINDINGS (copied from the print).
Controls held: (a) L* and fixedness equal at 137 points, fixed at
   delta_0 (n = 1) and delta_1 (n = 4); (b) 0 of 137 differ; (c) 0 of the
   141 open cells differ; S_L closed. (d) the break: 3 leaves, 0 splits,
   (b) failing at 110 of 137.
P1 KILLED as frozen: S_40 on [0, delta_4] is 22 points, none of
   positive length, 17 off the chain, every one of the 22 an exact
   fixed point (n = 1 .. 11): phi/2 (n 6), (-2 + 4 phi)/5 = 2/sqrt5 and
   (2 + 5 phi)/11 (8), (-3 + 3 phi)/2 and (-1 + 7 phi)/11 (9), (-2 + 3
   phi)/3, (2 + 10 phi)/19, (-13 + 11 phi)/5, (-1 + 3 phi)/4 (10), (7 +
   13 phi)/29, (-12 + 14 phi)/11, 3 phi/5, (-11 + 8 phi)/2, (-9 + 17
   phi)/19, (1 + 3 phi)/6, (-20 + 19 phi)/11, (-4 + 20 phi)/29 (11).
   Its points of Z[phi] are the chain's five alone.
P2 held: S_9's, S_11's and S_13's pieces about delta_2, delta_3,
   delta_4 are the points, length 0.
P3: pieces 1, 1, 1, 2, 3, 4, 5, 8, 14, 22, 35, 27, 26 at L = 1 .. 13,
   23 points at L = 14, 22 from L = 15 to 40; S_L is a single interval
   to L = 3 and all points from L = 12.
P4 held: the deepest finite L* off the chain is 15, at 22 - 13 phi = 1
   - phi^-7, a point of Z[phi] with b < 0, no delta(s).
C on [0, delta_4]: the 141 open cells each hold delta(s) at infinitely
   many s, and every point of Z[phi] in S_40 is a chain point, so every
   s >= 1 with delta(s) <= delta_4 = 1 - phi^-8 and s + 1 no F_2k fails,
   by L = 12 ("by L = 12 (141 leaves holding some delta(s))"), given
   goldelta's reduction of the bar to G_delta (its DESIGN, by hand; R1
   its check at s = 1 .. 40).
--full, [0, delta_5] to L = 16 (175 points; 865 leaves, 432 open, 431
   splits; all points from L = 14):
   controls 0 differ; S_16 61 points, none of positive length, its
   points of Z[phi] the chain's six and 56 - 34 phi = 1 - phi^-9; the
   piece of S_15 about delta_5 a point; C on [0, delta_5], by L = 14;
   R: "22 of 22 images fixed, depth up by [2, 3]", every fixed point of
   [0, delta_4]'s image fixed.
R(delta) = 1 - phi^-2(1 - delta) sends delta_k to delta_(k+1): "9 of
   9 images fixed, depth up by [2, 3]", the fixed points with images in
   [0, delta_4], an observation; not back: "phi^2/3 = (1 + 1 phi)/3: L*
   10, fixed n None; its image (-2 + 3 phi)/3, fixed n 10".

RUN RECORD. 6 of 6, 20.5 s, peak 20.3 MB under a 2048 MB cap; --break
fails (b); [0, delta_5] to L = 16 6 of 6, 383.9 s (the survey's line
240.3 s), peak 88.2 MB. Changes to
what was frozen: the C check and the [0, delta_5] run were added after
the first run's
kill, the C check reading leaves the frozen kill already printed. P3
prints exact endpoints at S_lmax alone, floats at L <= 13. The break
leaves one open cell, its L* its midpoint's, so it fails (b) alone and
prints no piece about delta_2, delta_3; (c)'s plant, --late, skips the
split from step 6 on: "103 leaves (51 open)", (b) 19 of 137 differ,
(c) 8 of 51. A fixed point at n = lmax - 1 first read alive at the
cap (goldelta tests fixedness there first): at --lmax 10, "(a) L* and
fixedness equal at 137 points -- 1 differ" (s 7), 0 after the fix,
every default print unchanged. section_renorm was added after. The
checks against RECORD were added after, every print unchanged: the
default 15 of 15, 20.3 s; --full 13 of 13, 384.0 s, peak 89.1 MB under
a 2048 MB cap; --break fails 10 of 15. The C check itself passes under
both plants; its truth rests on (b), (c) and the RECORD checks.

Run: python goldsurv.py [--full] [--break | --late]
"""
import functools
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 = []
BREAK = "--break" in sys.argv
LATE = "--late" in sys.argv


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 zmul(x, y):
    a, b = x
    c, d = y
    return (a * c + b * d, a * d + b * c + b * d)


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


def zadd(x, y):
    return (x[0] + y[0], x[1] + y[1])


def zsign(x):
    """sign of a + b phi: 2(a + b phi) = (2a + b) + b sqrt5."""
    p, q = 2 * x[0] + x[1], x[1]
    if p >= 0 and q >= 0:
        return 1 if p or q else 0
    if p <= 0 and q <= 0:
        return -1
    s = p * p - 5 * q * q
    if p > 0:
        return 1 if s > 0 else -1
    return 1 if s < 0 else -1


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


def zpow(j):
    """phi^j as (a, b), j of either sign."""
    x = (1, 0)
    for _ in range(abs(j)):
        x = (x[1], x[0] + x[1]) if j > 0 else zdivphi(x)
    return x


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


# ------------------------------------------------------------ points p/q

class Pt:
    """delta = p/q, p and q in Z[phi], q != 0."""
    __slots__ = ("p", "q", "sq")

    def __init__(self, p, q=(1, 0)):
        self.p, self.q, self.sq = p, q, zsign(q)

    def sign_at(self, f):
        """sign of alpha + beta delta at this point."""
        a, b = f
        return zsign(zadd(zmul(a, self.q), zmul(b, self.p))) * self.sq

    def cmp(self, o):
        return zsign(zsub(zmul(self.p, o.q), zmul(o.p, self.q))) \
            * self.sq * o.sq

    def __float__(self):
        return zfloat(self.p) / zfloat(self.q)

    def exact(self):
        """(a, b, d): (a + b phi)/d, d > 0, by q's conjugate."""
        qc = (self.q[0] + self.q[1], -self.q[1])
        num, n = zmul(self.p, qc), zmul(self.q, qc)[0]
        a, b, d = num[0], num[1], n
        if d < 0:
            a, b, d = -a, -b, -d
        g = math.gcd(math.gcd(a, b), d)
        return a // g, b // g, d // g

    def __repr__(self):
        a, b, d = self.exact()
        s = f"{a} + {b} phi" if b >= 0 else f"{a} - {-b} phi"
        return f"({s})/{d}" if d != 1 else f"({s})"


def mid(lo, hi):
    return Pt(zadd(zmul(lo.p, hi.q), zmul(hi.p, lo.q)),
              zmul((2, 0), zmul(lo.q, hi.q)))


class Split(Exception):
    def __init__(self, r):
        self.r = r


# ------------------------------------------------------------ one cell

class Cell:
    """A cell, open (lo, hi) or the point lo = hi; endpoints are linear
    functions ((alpha), (beta)) of delta."""

    def __init__(self, lo, hi):
        self.lo, self.hi = lo, hi
        self.point = hi is None
        self.n = 0

    def cmp(self, f, g):
        d = (zsub(f[0], g[0]), zsub(f[1], g[1]))
        if d == ((0, 0), (0, 0)):
            return 0
        sl = self.lo.sign_at(d)
        if self.point:
            return sl
        sh = self.hi.sign_at(d)
        if sl >= 0 and sh >= 0:
            return 1
        if sl <= 0 and sh <= 0:
            return -1
        if BREAK or (LATE and self.n >= 6):
            return sl
        a, b = d
        raise Split(Pt((-a[0], -a[1]), b))

    # interval lists on the cell
    def norm(self, xs):
        key = functools.cmp_to_key(self.cmp)
        xs = sorted(xs, key=lambda iv: key(iv[0]))
        out = []
        for a, b in xs:
            if self.cmp(a, b) > 0:
                continue
            if out and self.cmp(a, out[-1][1]) <= 0:
                if self.cmp(b, out[-1][1]) > 0:
                    out[-1] = (out[-1][0], b)
            else:
                out.append((a, b))
        return out

    def inter(self, U, V):
        out, i, k = [], 0, 0
        while i < len(U) and k < len(V):
            a = U[i][0] if self.cmp(U[i][0], V[k][0]) >= 0 else V[k][0]
            b = U[i][1] if self.cmp(U[i][1], V[k][1]) <= 0 else V[k][1]
            if self.cmp(a, b) <= 0:
                out.append((a, b))
            if self.cmp(U[i][1], V[k][1]) < 0:
                i += 1
            else:
                k += 1
        return out

    def same(self, U, V):
        return len(U) == len(V) and all(
            self.cmp(x[0], y[0]) == 0 and self.cmp(x[1], y[1]) == 0
            for x, y in zip(U, V))


def fneg(f):
    """-f/phi."""
    return (zdivphi((-f[0][0], -f[0][1])), zdivphi((-f[1][0], -f[1][1])))


def fshift(f, a, b=(0, 0)):
    """f + a + b delta."""
    return (zadd(f[0], a), zadd(f[1], b))


def negscale(U):
    return [(fneg(y), fneg(x)) for x, y in reversed(U)]


def shifts(U, n):
    return [(fshift(x, (e, 0)), fshift(y, (e, 0)))
            for e in range(n + 1) for x, y in U]


V0 = [(((-1, 1), (-1, 0)), ((-1, 1), (-1, 1)))]
U0 = [(((-2, 0), (0, 0)), ((-1, 0), (0, 1)))]


def step(cell, A, B):
    nA = negscale(A)
    A2 = cell.inter(cell.inter(V0, cell.norm(shifts(nA, 1))),
                    cell.norm(shifts(negscale(B), 1)))
    B2 = cell.inter(U0, [(fshift(x, (-1, -1), (1, 0)),
                          fshift(y, (-1, -1), (1, 0)))
                         for x, y in cell.norm(shifts(nA, 2))])
    return A2, B2


def survey(lo, hi, lmax, stats=None):
    """Leaves (lo, hi or None, L*, fixed n) over [lo, hi]: L* the first L
    with A_(L-1) empty, None if alive at L = lmax or fixed (n)."""
    stack = [(lo, None, 0, V0, U0), (lo, hi, 0, V0, U0),
             (hi, None, 0, V0, U0)]
    leaves = []
    while stack:
        a, b, n, A, B = stack.pop()
        cell = Cell(a, b)
        try:
            while True:
                if not A:
                    leaves.append((a, b, n + 1, None))
                    break
                cell.n = n
                A2, B2 = step(cell, A, B)
                if cell.same(A2, A) and cell.same(B2, B):
                    leaves.append((a, b, None, n))
                    break
                if n >= lmax - 1:
                    leaves.append((a, b, None, None))
                    break
                A, B, n = A2, B2, n + 1
        except Split as sp:
            r = sp.r
            if stats is not None:
                stats["splits"] += 1
            stack += [(a, r, n, A, B), (r, None, n, A, B), (r, b, n, A, B)]
    return leaves


def point_run(pt, lmax):
    """(L*, fixed n) of G_delta at the point pt alone, exactly."""
    (_, _, L, n), = survey_point(pt, lmax)
    return L, n


def survey_point(pt, lmax):
    cell = Cell(pt, None)
    A, B, n = V0, U0, 0
    while True:
        if not A:
            return [(pt, None, n + 1, None)]
        A2, B2 = step(cell, A, B)
        if cell.same(A2, A) and cell.same(B2, B):
            return [(pt, None, None, n)]
        if n >= lmax - 1:
            return [(pt, None, None, None)]
        A, B, n = A2, B2, n + 1


def ordered(leaves):
    """Leaves sorted along delta, a point before an open cell at it."""
    def key(x, y):
        c = x[0].cmp(y[0])
        if c:
            return c
        return (x[1] is not None) - (y[1] is not None)
    return sorted(leaves, key=functools.cmp_to_key(key))


def alive(leaf, L):
    """delta in S_L at this leaf."""
    return leaf[2] is None or leaf[2] > L


def components(leaves, L):
    """S_L's components as (lo, hi) points, hi = lo for a point."""
    out = []
    for a, b, Ls, n in leaves:
        if not alive((a, b, Ls, n), L):
            continue
        right = b if b is not None else a
        if out and out[-1][1].cmp(a) == 0:
            out[-1] = (out[-1][0], right)
        else:
            out.append((a, right))
    return out


def holding(leaves, pt):
    """The leaf holding the point pt."""
    for a, b, Ls, n in leaves:
        if b is None:
            if a.cmp(pt) == 0:
                return (a, b, Ls, n)
        elif a.cmp(pt) < 0 < b.cmp(pt):
            return (a, b, Ls, n)
    return None


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

def dk_pt(k, j=None, sigma=0):
    e = zpow(-2 * k)
    x = (1 - e[0], -e[1])
    if j is not None:
        x = zadd(x, tuple(sigma * c for c in zpow(-j)))
    return x


FULL = "--full" in sys.argv
KTOP = 5 if FULL else 4
LMAX = 16 if FULL else 40
# copied from the prints, keyed on (KTOP, LMAX)
RECORD = {
    (4, 40): {
        "points": 137, "leaves": 283, "open": 141,
        "pieces": [1, 1, 1, 2, 3, 4, 5, 8, 14, 22, 35, 27, 26, 23]
        + [22] * 26,
        "fixed": [1, 4, 6, 7, 8, 8, 9, 9, 9, 10, 10, 10, 10] + [11] * 9,
        "lattice": [(0, 0), (-1, 1), (-4, 3), (-12, 8), (-33, 21)],
        "deepest": (15, (22, -13)), "C": (12, 141),
        "renorm": (9, 9, [2, 3]), "back": (10, None, 10)},
    (5, 16): {
        "points": 175, "leaves": 865, "open": 432, "last": (61, 14),
        "lattice": [(0, 0), (-1, 1), (-4, 3), (-12, 8), (-33, 21),
                    (56, -34), (-88, 55)],
        "C": (14, 432), "renorm": (22, 22, [2, 3]), "back": (10, None, 10)},
}.get((KTOP, LMAX))
D4 = Pt(dk_pt(KTOP))
CHAIN = [Pt(dk_pt(k)) for k in range(KTOP + 1)]


def test_points():
    """(label, (a, b)) inside [0, delta_4]: delta(s), DEEP's rays."""
    from goldfix import floor_phi
    pts = [(f"s {s}", (-floor_phi(s + 1), s + 1)) for s in range(1, 41)]
    for k in range(2, KTOP + 1):
        for sigma in ((-1, 1) if k < KTOP else (-1,)):
            for j in range(2 * k + 2, 2 * k + 21):
                pts.append((f"d{k}{'+' if sigma > 0 else '-'}{j}",
                            dk_pt(k, j, sigma)))
    pts += [("delta_0", (0, 0)), ("delta_1", (-1, 1))]
    return [(lab, x) for lab, x in pts
            if Pt(x).cmp(Pt((0, 0))) >= 0 and Pt(x).cmp(D4) <= 0]


def section_points(lmax):
    from goldelta import Delta
    print(f"== (a) the point evaluator against goldelta's Delta, L <= {lmax}")
    pts, off, rows = test_points(), [], {}
    for lab, x in pts:
        Lg, _, ng = Delta(*x).run(lmax)
        Lm, nm = point_run(Pt(x), lmax)
        rows[lab] = (Lm, nm)
        if Lg != Lm or (ng is None) != (nm is None):
            off.append((lab, (Lg, ng), (Lm, nm)))
    for r in off:
        print(f"    {r}")
    check(f"(a) L* and fixedness equal at {len(pts)} points", not off,
          f"{len(off)} differ")
    check("(a) fixed at delta_0, delta_1 (n = 1, 4)",
          rows["delta_0"][1] == 1 and rows["delta_1"][1] == 4)
    return pts, rows


def section_survey(lmax, pts, rows):
    print(f"== the survey of [0, delta_{KTOP}], L <= {lmax}")
    t0, stats = time.time(), {"splits": 0}
    leaves = ordered(survey(Pt((0, 0)), D4, lmax, stats))
    opens = [lv for lv in leaves if lv[1] is not None]
    print(f"    {len(leaves)} leaves ({len(opens)} open), {stats['splits']} "
          f"splits, {time.time() - t0:.1f} s", flush=True)
    if RECORD:
        check("the survey's leaves as recorded",
              (len(pts), len(leaves), len(opens)) == (
                  RECORD["points"], RECORD["leaves"], RECORD["open"]),
              f"{len(pts)} points, {len(leaves)} leaves, {len(opens)} open")
    bad = [lab for lab, x in pts
           if holding(leaves, Pt(x))[2] != rows[lab][0]]
    check(f"(b) the cell holding each of the {len(pts)} points has its L*",
          not bad, f"{len(bad)} differ {bad[:5]}")
    badc = [(float(a), float(b), L, point_run(mid(a, b), lmax)[0])
            for a, b, L, n in opens if point_run(mid(a, b), lmax)[0] != L]
    check(f"(c) every open cell's L* equals its midpoint's ({len(opens)})",
          not badc, f"{len(badc)} differ {badc[:3]}")
    # closure: an open cell alive at L has both ends alive at L
    unclosed = []
    for i, (a, b, L, n) in enumerate(leaves):
        if b is None:
            continue
        ends = [lv for lv in (leaves[i - 1], leaves[(i + 1) % len(leaves)])
                if lv[1] is None]
        for e in ends:
            if (e[2] is not None) and (L is None or e[2] < L):
                unclosed.append((float(a), float(b)))
    check("S_L closed: no open cell outlives an end", not unclosed,
          f"{len(unclosed)} {unclosed[:3]}")
    return leaves


def lattice(pt):
    """(a, b) if pt is a + b phi with integers a, b, else None."""
    a, b, d = pt.exact()
    return (a, b) if d == 1 else None


def section_pieces(leaves, lmax):
    print(f"== P3 the pieces of S_L on [0, delta_{KTOP}]")
    counts, first = [], None
    for L in range(1, lmax + 1):
        comps = components(leaves, L)
        counts.append(len(comps))
        if first is None and all(a.cmp(b) == 0 for a, b in comps):
            first = L
        if L <= 13:
            txt = ", ".join(f"[{float(a):.6f}, {float(b):.6f}]"
                            if a.cmp(b) else f"{{{float(a):.6f}}}"
                            for a, b in comps)
            print(f"    S_{L}: {len(comps)} pieces: {txt}")
        else:
            npt = sum(a.cmp(b) == 0 for a, b in comps)
            print(f"    S_{L}: {len(comps)} pieces, {npt} points")
    print(f"    S_L all points from L = {first}")
    comps = components(leaves, lmax)
    if RECORD and "pieces" in RECORD:
        check("P3 the piece counts at L = 1 .. 40 as recorded, all points "
              "from L = 12", counts == RECORD["pieces"] and first == 12)
    if RECORD and "last" in RECORD:
        check(f"S_{lmax} {RECORD['last'][0]} points, all points from L = "
              f"{RECORD['last'][1]}", (len(comps), first) == RECORD["last"])
    print(f"    S_{lmax} exactly:")
    for a, b in comps:
        lv = holding(leaves, a)
        print(f"      {a!r} = {float(a):.10f}"
              + ("" if a.cmp(b) == 0 else f" .. {b!r}")
              + (f", fixed at n = {lv[3]}" if lv[3] is not None else
                 ", alive at L" if lv[2] is None else ""))
    return comps


def section_kill(leaves, comps, lmax):
    print("== KILL")
    off = [(a, b) for a, b in comps
           if not (a.cmp(b) == 0 and any(a.cmp(c) == 0 for c in CHAIN))]
    print(f"    S_{lmax} off the chain: {len(off)} pieces, "
          f"{sum(a.cmp(b) != 0 for a, b in off)} of positive length")
    fixed = [holding(leaves, a)[3] for a, b in comps]
    if RECORD and "fixed" in RECORD:
        check(f"S_{lmax} is {len(RECORD['fixed'])} exact fixed points, "
              f"{len(off)} off the chain, n as recorded",
              fixed == RECORD["fixed"] and len(off) == 17
              and all(a.cmp(b) == 0 for a, b in comps))
    p2 = []
    for k in range(2, KTOP + 1):
        comp = [(a, b) for a, b in components(leaves, 2 * k + 5)
                if a.cmp(CHAIN[k]) <= 0 <= b.cmp(CHAIN[k])]
        if not comp:
            print(f"    S_{2 * k + 5} holds no piece about delta_{k}")
            continue
        (a, b), = comp
        p2.append(a.cmp(b) == 0)
        print(f"    S_{2 * k + 5}'s piece about delta_{k}: "
              f"[{float(a):.12f}, {float(b):.12f}], length "
              f"{float(b) - float(a):.3g}")
    deep = [(lv[2], lv) for lv in leaves if lv[2] is not None
            and not any(lv[1] is None and lv[0].cmp(c) == 0 for c in CHAIN)]
    check(f"P2 the piece about delta_k is a point, k = 2 .. {KTOP}",
          p2 == [True] * (KTOP - 1))
    Lmax, lv = max(deep, key=lambda t: t[0])
    print(f"    P4 deepest finite L* off the chain: {Lmax} at "
          f"{lv[0]!r}" + ("" if lv[1] is None else f" .. {lv[1]!r}"))
    if RECORD and "deepest" in RECORD:
        check("P4 the deepest finite L* off the chain as recorded",
              lv[1] is None and (Lmax, lattice(lv[0])) == RECORD["deepest"])
    lat = [(a, lattice(a)) for a, b in comps
           if a.cmp(b) == 0 and lattice(a) is not None]
    print(f"    S_{lmax}'s points of Z[phi]: "
          + ", ".join(f"{x[0]} + {x[1]} phi" for _, x in lat))
    if RECORD:
        check(f"S_{lmax}'s points of Z[phi] as recorded",
              [x for _, x in lat] == RECORD["lattice"])
    # C: an open cell holds delta(s) for infinitely many s (frac((s + 1)
    # phi) is dense); a point a + b phi with b >= 2 is delta(b - 1)
    def is_s(lv):
        if lv[1] is not None:
            return True
        x = lattice(lv[0])
        return x is not None and x[1] >= 2
    chain_b = {lattice(c)[1] for c in CHAIN}
    reach = [lv for lv in leaves if is_s(lv)
             and not (lv[1] is None and lattice(lv[0])[1] in chain_b)]
    worst = max(lv[2] or 10 ** 9 for lv in reach)
    check(f"C on [0, delta_{KTOP}]: every delta(s), s >= 1, s + 1 no F_2k, "
          f"empties", all(lv[2] is not None for lv in reach),
          f"by L = {worst} ({len(reach)} leaves holding some delta(s))")
    if RECORD:
        want, nr = RECORD["C"]
        check("C's depth as recorded", worst == want
              and (nr is None or len(reach) == nr))
    return off


def section_renorm(leaves):
    """R(delta) = 1 - phi^-2 (1 - delta) on the fixed points whose
    image lies in the survey."""
    print("== R on the fixed points, R(delta) = 1 - phi^-2 (1 - delta)")
    e, rows = zpow(-2), []

    def R(x):
        return Pt(zsub(x.q, zmul(e, zsub(x.q, x.p))), x.q)
    for a, b, L, n in leaves:
        if n is None or R(a).cmp(D4) > 0:
            continue
        h = holding(leaves, R(a))
        rows.append((a, n, R(a), h[3] if h[1] is None else None))
    for a, n, r, m in rows:
        print(f"    {a!r} (n {n}) -> {r!r} (fixed n {m})")
    ups = sorted({m - n for _, n, _, m in rows if m is not None})
    nfix = sum(m is not None for *_, m in rows)
    print(f"    {nfix} of {len(rows)} images fixed, depth up by {ups}")
    back = Pt((1, 1), (3, 0))
    hb, hr = holding(leaves, back), holding(leaves, R(back))
    print(f"    phi^2/3 = {back!r}: L* {hb[2]}, fixed n {hb[3]}; its image "
          f"{R(back)!r}, fixed n {hr[3]}")
    if RECORD and "renorm" in RECORD:
        check("R: the fixed points' images fixed, depth up as recorded",
              (nfix, len(rows), ups) == RECORD["renorm"])
        check("R: phi^2/3 dies, its image fixed, as recorded",
              (hb[2], hb[3], hr[3]) == RECORD["back"])


def main():
    t0 = time.time()
    lmax = LMAX
    pts, rows = section_points(lmax)
    leaves = section_survey(lmax, pts, rows)
    comps = section_pieces(leaves, lmax)
    section_kill(leaves, comps, lmax)
    section_renorm(leaves)
    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()