defer.py

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

Cited on: FLUSH.

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

"""defer.py -- the deferring reader: where the 10^8 family's gap sits.

QUESTION. At alpha = [0; 1 x (N + 1), H, H, ...], H = 10^8, s the least
slack with |T_N| >= 1 and s0 = 1, the cylinder bound c_lo is 1 and the
overlap reader's c_ov is N + 1 at the gap's m, the first power of 2 to
reach the largest gap (flush.py::section_cylinder), and at every larger
m read. Where does the completion reader's least lookahead c_comp sit
between?

DESIGN. The deferring reader writes 0 at every position below a level L,
picks its lift at L and then runs the overlap reader from L. The star
still owed at L, J_L = M + m(sum_(k <= L+c) d_k theta_k + I_(L+c+1)), has
width w_L; the members e theta_L + T_(L+1) cover T_L with consecutive
overlaps ov_L, so a J of width at most ov_L inside T_L + j lies in one
member, and some integer j puts J_L inside T_L + j at every placement if
w_L <= |T_L| - 1. So c_def(L) is the least c with w_L <= |T_L| - 1 and
w_t <= ov_t at every t >= L, c_def the least over L, c_def(0) = c_ov, and
c_comp <= c_def.

PROOF that c_def <= c_lo + 2 wherever E > 0 (by hand). If t_1 <= 2,
c_ov <= c_lo + 2 (the gap bound). If t_1 >= 2 take L = t_1 - 1 >= 1.
Levels: for t >= t_1 - 2, w_t(c_lo + 2) = w_(t+2)(c_lo) <= |T_(t+3)| <=
ov_t (c_lo's bar at t + 2 >= t_1; |T_(t+3)| <= ov_t as in the gap
bound). Seam: w_L(c_lo + 2) = w_(t_1+1)(c_lo) <= |T_(t_1+2)| <= (1 + s)
(|th_(t_1+1)| + |th_(t_1+2)|) <= (1 + s)|th_(t_1)| < (1 + s)|th_(t_1-1)|
<= (a_(t_1) + s)|th_(t_1-1)| = |T_(t_1-1)| - |T_(t_1)| <= |T_(t_1-1)| - 1,
by S_t <= |th_(t-1)| + |th_t|, the telescoping |T_L| - |T_(L+1)| =
|th_(L-1)| - |th_(L+1)| + s|th_L| at L >= 1, and |T_(t_1)| >= 1. So c_lo
<= c_comp <= c_lo + 2 at every irrational alpha with E > 0.

PREDICTIONS (frozen before the engine).
P1 c_def - c_lo <= 2 at every cell read (family and grid).
P2 c_def in {1, 2} at all 72 family cells, 2 at the six gap m's.
P3 the deferring reader, run at c_def on random inputs to depth N + 40,
   exact, never fails to find a member.
P4 control at the grid's 120 E > 0 cells: c_saf <= c_def <= c_ov, c_saf
   read as the safety game winning at c_def. Plant A (the lax bar
   |T_(t+1)| for ov_t) must put c_def below c_saf at some cell; plant B
   (the seam dropped) is read, not checked.
P5 the Q-alpha (H -> Q, eventually periodic; Eventual below): c_saf =
   c_def at the cells read. KILL of P5: c_saf < c_def at any. Engine
   control first: a purely periodic alpha fed as preperiod + period
   gives the periodic engine's verdicts. At an eventually periodic alpha
   c_comp = c_saf by the completion reader's proof, which uses only a
   finite source and bounded quotients (Koenig's lemma and the box).

FINDINGS (copied from the print; P5's last two cells from --game).
P1 held: c_def - c_lo <= 2 at the 72 family cells and the 120 grid
   cells; c_def(0) = c_ov at every family cell.
P2 held: c_def is 1 or 2 at every family cell, 2 at the six gap m's
   (x4, x16, x64, x256, x512, x2048 at N = 2 .. 7), each reached at
   L = N - 1 = t_1 - 1, where c_ov is N + 1. From m = 2^N on, c_def is
   2 while c_ov runs from 3 to N + 1 (from 4 to 8 at N = 7).
P3 held: 0 of 2880 runs fail at c_def; the control at c_def - 1, same
   L, fails 2820 of 2880.
P4 held: the game wins at c_def at all 120 grid cells, and c_def =
   c_saf (the game loses at c_def - 1) at 90. c_def < c_ov at 5, all
   at (s, s0) = (1, 0) with L = 1: golden x2 (2 to 1), x3 (3 to 2), x5
   (4 to 3), sqrt(3) - 1 x3 and [1, 1, 1, 2] x3 (3 to 2). Plant A put
   c_def below c_saf at 43 cells; plant B moved c_def at 4 cells, the
   game losing at 1 of them, so the seam bar binds at a grid cell.
P5 held, the kill missed: c_saf = c_def = 2 at N 2 Q 4 x3 (c_ov 2),
   N 2 Q 8 x4, N 3 Q 8 x8 and N 2 Q 16 x4 (c_ov 3), c_lo 1 at each;
   the engine controls held. The Q-alpha's tail bar is tight: the
   overshoot c_ov - c_saf is the overlap reader's lift taken at level 0.
   Three cells exercise the deferral (L = 1, 2, 1 at Q 8 x4, Q 8 x8
   and Q 16 x4); at Q 4 x3 c_def is
   reached at L = 0, so it is c_ov. The game loses at c = 1 at all four,
   m dividing Q (x4 at Q = 8, 16, x8 at Q = 8) or not (x3 at Q = 4).
   At H = 10^8 the game is unread; shifted.py's tail law puts c_comp
   at 2 or more there, so c_comp = c_def = 2 at every m = 2^e read
   from s + 2 on.

RUN RECORD. The bare run reads the family, the grid and the Q cells (2,
4, 3) and (2, 8, 4); --game adds (3, 8, 8) and (2, 16, 4), whose peaks,
each cell run alone under a 2048 MB watch, are 497.3 and 903.1 MB (the
first two 21.9 and 125.6 MB); the last two have 410815 and 809960
states and take 14 and 38 s.
The bare run: 13/13, 22.0 s, peak 125.1 MB under a 512 MB watch;
--game: 13/13, 73.9 s, peak 906.8 MB under 2048 MB. Changes to what
was frozen: P5 froze N = 2 at the gap m; x4 is the gap m at Q = 8 and 16 (the first m
with c_ov - c_lo = 2, read at m = 2 .. 16, unprinted here), and the
cells (2, 4, 3), not at the gap m, (3, 8, 8), at N = 3, and (2, 16, 4)
were added. The frozen engine control read c_saf at the grid's cells;
it reads verdicts at c_def - 1 and c_def at 12 cells, (2, 0, 1) and (3,
1, 1) at each period. The grid's maps were widened from (2, 3) to (2,
3, 4, 5), and the prints of c_def = c_saf, the five c_def < c_ov cells
and plant B's game reads were added after the first run. The quotient
walk was added with its plant (the wrap sent to 0), caught at the four
Q cells and the three periods of length above 1; the walk is what sees
a wrap, the verdicts not (a verdict-level plant moved 0 of 12), and the
rotated period repeats the old arm at a period of length 1.

Run: python defer.py [--game]
"""
import os
import random
import sys
import time

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")

from flush import (Game, Metric, Numeration, PERIODIC, SLACKS,  # noqa: E402
                   Source, c_floor, c_overlap, legal_random,
                   numeration)

CHECKS = []


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


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

def c_def_at(met, m, L, depth, cmax=40, seam=True, lax=False):
    """The least c with w_L <= |T_L| - 1 (unless seam is False) and
    w_t <= ov_t at every L <= t < depth; None if |T_L| < 1 or no c <=
    cmax. lax: the bar |T_(t+1)| in place of ov_t (plant A)."""
    room = met.Tlen(L) - met.Q
    if room < 0:
        return None
    bars = [met.Tlen(t + 1) if lax else met.ov(t) for t in range(L, depth)]
    for c in range(cmax + 1):
        if seam and met.width(L, c, m) > room:
            continue
        if all(met.width(t, c, m) <= b
               for t, b in zip(range(L, depth), bars)):
            return c
    return None


def c_def(met, m, depth, **kw):
    """(c_def, the least L reaching it)."""
    best = None
    for L in range(depth):
        if met.Tlen(L) < met.Q:
            break
        c = c_def_at(met, m, L, depth, **kw)
        if c is not None and (best is None or c < best[0]):
            best = (c, L)
    return best if best else (None, None)


# ------------------------------------------------------------ the run

def interval_I(met, j):
    """I_j, between -theta_j and -theta_(j-1), as numerators."""
    a, b = -met.theta(j), -met.theta(j - 1)
    return min(a, b), max(a, b)


def run_reader(met, m, c, L, d, depth):
    """The deferring reader on digits d (d[0] .. past depth + c): None
    if it finds a member at every level L .. depth - 1, else the level
    where it fails."""
    Q = met.Q
    th = met.theta
    base = sum(d[k] * th(k) for k in range(L + c + 1))
    M = None
    P = 0
    for t in range(L, depth):
        if t > L:
            base += d[t + c] * th(t + c)
        ilo, ihi = interval_I(met, t + c + 1)
        jlo, jhi = m * (base + ilo) - P, m * (base + ihi) - P
        lo1, hi1 = met.T(t + 1)
        if M is None:      # level L: the lift, then the member
            tlo, thi = met.T(L)
            lifts = range(-((jlo - tlo) // Q), (thi - jhi) // Q + 1)
        else:
            lifts = (M,)
        found = None
        for M2 in lifts:
            a, b = jlo + M2 * Q, jhi + M2 * Q
            # e th(t) + lo1 <= a and b <= e th(t) + hi1
            for e in _members(th(t), a - lo1, b - hi1, met.cap(t)):
                found = (M2, e)
                break
            if found:
                break
        if found is None:
            return t
        M, e = found
        P += e * th(t)
    return None


def _members(theta, up, down, cap):
    """The e in 0..cap with down <= e theta <= up."""
    if theta > 0:
        lo, hi = -((-down) // theta), up // theta
    else:               # dividing by theta < 0 flips both sides
        lo, hi = -((-up) // theta), down // theta
    return range(max(lo, 0), min(hi, cap) + 1)


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

H = 10 ** 8


def family(N, Hq=H):
    """The family's alpha at the tail quotient Hq, and its s."""
    tail = 60 if Hq >= 10 ** 4 else 200
    w = Numeration(f"fam{N}", [1] * (N + 1) + [Hq] * tail)
    s = next(s for s in range(1, 10 ** 4)
             if Metric(w, s, 0, N + 50).Tlen(N) >= w.Q)
    return w, s


def section_family():
    print("== P1 P2 P3 the 10^8 family, s0 = 1, m = 2 .. 4096")
    over = bad = runs = fails = low_runs = low_fails = 0
    gap_cdef = []
    rnd = random.Random(1964)
    for N in range(2, 8):
        w, s = family(N)
        met = Metric(w, s, 1, N + 50)
        depth = N + 40
        row, best = [], None
        for e in range(1, 13):
            m = 2 ** e
            lo = c_floor(met, m, depth)
            ov = c_overlap(met, m, depth, 40)
            cd, L = c_def(met, m, depth)
            cd0 = c_def_at(met, m, 0, depth)
            bad += cd0 != ov
            over += cd - lo > 2
            row.append(f"x{m} {lo}/{cd}@{L}/{ov}")
            if best is None or ov - lo > best[0]:
                best = (ov - lo, m, cd)
            quots = w.a[1:]
            for _ in range(40):
                d = legal_random(rnd, quots, depth + cd + 3)
                runs += 1
                fails += run_reader(met, m, cd, L, d, depth) is not None
                if cd >= 1:     # the control: one digit less, same L
                    low_runs += 1
                    low_fails += run_reader(met, m, cd - 1, L, d,
                                            depth) is not None
        gap_cdef.append(best[2])
        print(f"  N {N} s {s}: c_lo/c_def@L/c_ov  " + "  ".join(row))
        print(f"    the gap's m x{best[1]}: c_ov - c_lo {best[0]}, "
              f"c_def {best[2]}")
    check("instrument: c_def(0) = c_ov at every family cell", bad == 0,
          f"{bad} off")
    check("P1 c_def - c_lo <= 2 at every family cell", over == 0,
          f"{over} over")
    check("P2 c_def = 2 at the six gap m's", gap_cdef == [2] * 6,
          f"{gap_cdef}")
    check("P3 the deferring reader finds a member at every level",
          fails == 0, f"{fails} of {runs} runs fail")
    check("control: the same reader at c_def - 1 fails somewhere",
          low_fails > 0, f"{low_fails} of {low_runs} runs fail")


def section_grid():
    print("== P1 P4 the grid's E > 0 cells: c_saf <= c_def <= c_ov")
    over = above_ov = lose = 0
    lax_below = seam_moved = seam_lose = tight = 0
    gaps, cells, won = [], 0, []
    t0 = time.time()
    for name, per in PERIODIC:
        w = numeration(name, per)
        src = Source(period=per)
        for m in (2, 3, 4, 5):    # the grid's maps (flush.py --full)
            for s, s0 in SLACKS[1:]:
                met = Metric(w, s, s0, 120)
                lo = c_floor(met, m, 60)
                ov = c_overlap(met, m, 60)
                cd, L = c_def(met, m, 60)
                lax, _ = c_def(met, m, 60, lax=True)
                ns, _ = c_def(met, m, 60, seam=False)
                cells += 1
                over += cd - lo > 2
                above_ov += cd > ov
                gaps.append(ov - cd)
                seam_moved += ns != cd
                if not Game(src, m, s, s0, cd).solve(False):
                    lose += 1
                tight += cd == 0 or not Game(src, m, s, s0,
                                             cd - 1).solve(False)
                if ns != cd:
                    seam_lose += not Game(src, m, s, s0, ns).solve(False)
                if cd < ov:
                    won.append(f"{name.split()[0]} x{m} ({s}, {s0}) "
                               f"c_ov {ov} c_def {cd}@{L}")
                if lax < cd and not Game(src, m, s, s0, lax).solve(False):
                    lax_below += 1
    print(f"    {cells} cells, {time.time() - t0:.0f} s; c_ov - c_def: "
          + ", ".join(f"{g}: {gaps.count(g)}" for g in sorted(set(gaps))))
    print(f"    plant B, the seam dropped, moves c_def at {seam_moved} cells, "
          f"the game losing there at {seam_lose}")
    print(f"    c_def = c_saf (the game loses at c_def - 1) at {tight} of "
          f"{cells}; c_def < c_ov at: " + "; ".join(won))
    check("P1 c_def - c_lo <= 2 at every grid cell", over == 0)
    check("instrument: c_def <= c_ov at every grid cell", above_ov == 0)
    check("P4 the safety game wins at c_def at every grid cell", lose == 0,
          f"{lose} lose")
    check("P4 plant A, the lax bar, puts c_def below c_saf somewhere",
          lax_below > 0, f"at {lax_below} cells")


class Eventual(Source):
    """An eventually periodic alpha: the quotients pre, then per
    repeated; the state is the index of the next quotient."""

    def __init__(self, pre, per):
        self.seq, self.p0 = tuple(pre) + tuple(per), len(pre)
        self.period, self.alphabet = None, None
        self.A = max(self.seq)

    def nxt(self, st):
        n = st + 1 if st + 1 < len(self.seq) else self.p0
        return [(self.seq[st], n)]


class WrongWrap(Eventual):
    """A plant: the wrap returns to the preperiod's start."""

    def nxt(self, st):
        return [(self.seq[st], (st + 1) % len(self.seq))]


def walk(src, n):
    """The first n quotients a source hands the game."""
    out, st = [], src.start()
    for _ in range(n):
        a, st = src.nxt(st)[0]
        out.append(a)
    return out


def section_q(cells):
    print("== P5 the Q-alpha [0; 1 x (N + 1), Q, Q, ...]: c_saf beside c_def")
    off = 0
    for name, per in PERIODIC:
        for m, s, s0 in ((2, 0, 1), (3, 1, 1)):
            w = numeration(name, per)
            cd, _ = c_def(Metric(w, s, s0, 120), m, 60)
            for c in (cd - 1, cd):
                if c < 0:
                    continue
                a = Game(Source(period=per), m, s, s0, c).solve(False)
                for pre, rest in ((per, per), (per[:1], per[1:] + per[:1])):
                    b = Game(Eventual(pre, rest), m, s, s0, c).solve(False)
                    off += a != b
    check("engine control: preperiod + period, and the period rotated "
          "after one quotient, read as the period at c_def - 1 and c_def",
          off == 0, f"{off} off")
    seq_off = wrong_q = wrong_p = 0
    for N, Q, _m in cells:
        want = [1] * (N + 1) + [Q] * 40
        seq_off += walk(Eventual([1] * (N + 1), (Q,)), 40) != want[:40]
        wrong_q += walk(WrongWrap([1] * (N + 1), (Q,)), 40) != want[:40]
    for name, per in PERIODIC:
        want = list(per) * 40
        pre, rest = per[:1], per[1:] + per[:1]
        seq_off += walk(Eventual(pre, rest), 40) != want[:40]
        wrong_p += walk(WrongWrap(pre, rest), 40) != want[:40]
    check("engine control: Eventual's quotients are the alpha's, 40 deep, "
          "at every Q cell and rotated period", seq_off == 0,
          f"{seq_off} off")
    check("engine control: the plant wrapping to 0 is caught at every Q "
          "cell and some period", wrong_q == len(cells) and wrong_p >= 1,
          f"{wrong_q} of {len(cells)} Q cells, {wrong_p} of "
          f"{len(PERIODIC)} periods")
    kills = 0
    for N, Q, m in cells:
        w, s = family(N, Q)
        met = Metric(w, s, 1, N + 60)
        lo = c_floor(met, m, N + 50)
        ov = c_overlap(met, m, N + 50, 40)
        cd, L = c_def(met, m, N + 50)
        src = Eventual([1] * (N + 1), (Q,))
        t0 = time.time()
        saf = None
        for c in range(lo, cd + 1):
            g = Game(src, m, s, 1, c)
            if g.solve(False):
                saf = c
                break
        kills += saf is None or saf < cd     # a loss at c_def fails too
        print(f"    N {N} Q {Q} x{m} s {s}: c_lo {lo}, c_def {cd}@{L}, "
              f"c_ov {ov}, c_saf {saf} ({len(g.states)} states, "
              f"{time.time() - t0:.0f} s)")
    check("P5 c_saf = c_def at every Q-alpha cell read", kills == 0,
          f"{kills} below")


# the first two fit a 512 MB suite; the last two run under --game
QCELLS = [(2, 4, 3), (2, 8, 4), (3, 8, 8), (2, 16, 4)]


def main():
    t0 = time.time()
    section_family()
    section_grid()
    section_q(QCELLS if "--game" in sys.argv else QCELLS[:2])
    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()