radius.py

Checks: REDUNDANT: The segment lemma criterion; rule.

Cited on: REDUNDANT.

To run it: save radius.py, with manystream.py, piecewise.py, redundant.py beside it; standard library only.

"""radius.py -- the robust radius from the other side: whether any
continuous map within mu of the reciprocal reads one digit below the
curve, decided depth by depth by a greatest fixpoint.

QUESTION. piecewise.py's robust radius MU_ROB(0) is the largest smaller
overhang over the killing boxes of f = 1/(s + x), s = 1 + M-, at L = 0:
no map within mu < MU_ROB(0) of f reads at 0. Eight hand designs (the
HAND of design.py) read at 0 within 1.003 to 1.053 MU_ROB(0). At the
other twelve cells, does any continuous map within 1.053 MU_ROB(0) read
at 0, or is there a second floor above the radius?

THE REDUCTION (by hand, from manystream.Cell.kills). At depth n, L = 0,
e = b^-n, a box with image [lo, hi] kills iff hi > phi_n(lo),
    phi_n(t) = (floor(t/e + M-) + M+) e,
nondecreasing. A continuous F maps a box onto an interval holding F at
every point of it, so F alive at 0 implies, at every counted box beta
(n >= 1 - o, o the lead) and every finite set S of points in beta:
    max_S F <= phi_n(min_S F).

THE BOUND. The points: every box end at depths n0..N, merged. Unknowns
x_p in [f(p) - mu, f(p) + mu]; constraints x_p <= phi_beta(min over
beta's points of x). Every constraint is an upper bound by a monotone
map, so T(x)_p = min(f(p) + mu, min over beta holding p of
phi_beta(min_beta x)) is monotone, falls from the top to the greatest
fixpoint x*, and some x is feasible iff x* >= f - mu. Infeasible means
no continuous map within mu reads at 0 (mu below the lead gap, so the
map's lead is at least f's, a larger lead only counting more depths).
The bound grows with N.

THE IFF (by hand, after the run). The depth-N points nest in the
depth-(N + 1) points, so the greatest fixpoints fall with N; if
feasible at every N their limit is a function on a dense set with
oscillation at most w b^-n on
any two points within (w - 1) b^-n, so it extends continuously, and
phi's right-continuity carries every box's max <= phi(min) to the
extension. Clipped at M+ b^o, x* stays a solution (where a box's min is
below the clip nothing moves, else every point sits at the clip <=
phi(clip)) and above f - mu (f <= 1 <= M+ b^o; mu below min f, so
f - mu > 0, which every mu read here meets: mu <= 1.053/12 < 1/3 <=
1/(1 + w) = min f at every cell), so the limit's range
lies in the tile of lead o (its least value above f - mu > 0, its top
at least 1 - mu above the next smaller tile, mu below the lead gap),
and the counted depths are the system's. So, mu below the lead gap and
below min f, a continuous map within mu reads at 0 IFF the fixpoint is
feasible at
every N.

PREDICTIONS (frozen before this code).
  P1 mu_2(N) >= MU_ROB(0) at all 20 once N >= 3, = MU_ROB(0) at N = 3 at
     most cells.
  P2 mu_2(N) above 1.053 MU_ROB(0) at a majority of the twelve by the
     deepest N run (a guess).
  P3 at the eight ZIGZAG cells mu_2(N) <= the design's mu (forced).

CONTROLS AND KILL, frozen.
  C1 every map the clauses and engine call alive at 0 (8 ZIGZAGS, the
     uniform 4-chord design at the four top cells) satisfies every
     constraint at its own values, at every N run: 0 violations at 12
     maps. And feasibility at each ZIGZAG's mu. A violation voids all.
     (ZIGZAGS were the eight hand designs, design.py's HAND; C1 now
     reads piecewise.py's RADIUS_DESIGNS in their place.)
  C2 the 56 chord designs WT kills at 0 violate a constraint at a depth
     at most the engine's kill depth: a count of 56; a miss is the
     reduction's slack, not a bug.
  C3 single boxes, each its own two unknowns: the least feasible mu is
     MU_ROB(0) at all 20 cells, exactly.
  VERDICT per cell at the deepest N: SECOND FLOOR if the fixpoint at
     mu = 1.053 MU_ROB(0), in Fractions, is infeasible; else OPEN, with
     mu_2(N) by float bisection printed.

FINDINGS (entered after the run; every number is a print).
  - C3 holds at 20 of 20; C1 held at the 12 maps of the frozen run (a
    record: the hand designs are no longer in C1's set), 0
    violations at the deepest N (a superset of every shallower N's
    constraints), feasible at each design's mu; C2 caught 56 of 56,
    missed 0.
  - P1 holds: mu_2(N) / MU_ROB(0) prints 1.0000 at every cell and every
    N from 3 to the deepest (12 at radix 2, 8 at 3, 6 at 4, 5 at 5).
  - P2 failed: no SECOND FLOOR. The fixpoint in Fractions is feasible at
    1.053 MU_ROB(0) and at MU_ROB(0) itself, and infeasible at
    (1 - 1e-6) MU_ROB(0), at all 20 cells, at the deepest N. The bound
    reads nothing above the radius at these depths. P3 is C1's
    feasibility line. The infeasibility below is forced (every single
    box's constraint is in the system, and C3 gives MU_ROB as theirs):
    it is a control on the solver's wiring, not a finding.
  - By the iff, at MU_ROB(0) the fixpoint is feasible to the depths
    above, which a continuous map within MU_ROB(0) reading at 0 needs.
    The designs of design.py's guided search, now piecewise.py's
    RADIUS_DESIGNS, supply the map at 15 cells (piecewise.py's WZ); C1
    reads all 19 of them and the four chord designs: 0 violations at 23
    maps, feasible at each design's mu. So the hand designs' 1.003 to
    1.053 was their own price, not the price of affine pieces.
  - One change after the first full run, before these findings: the
    float phi floored a cap (k + M+)/b^n read back one zone low and
    printed 2.5000 at (3,2,2), N = 7 and 8, against C1's alive design
    at 1.0033 and the exact OPEN there; a 1e-9 guard errs toward
    feasible (the bound only lower), and the exact check at MU_ROB
    itself was added. The verdict lines are Fractions throughout.
  - Changes after a review, named: C3 as coded is the closed form of
    single boxes (the box enumeration against overhangs()), not a run
    of the solver; the frozen "last infeasible mu checked in Fractions"
    is the exact infeasibility at (1 - 1e-6) MU_ROB(0). A break moving
    that probe to (1 + 1e-6) prints "FEASIBLE below MU_ROB" at 20 of 20
    at --quick. The exit status reads C3, C1, C2's count of 56 and, at
    every cell, feasibility at MU_ROB(0) and infeasibility below it; that
    break prints its FAIL at 0 of 20 and exits 1.

RUN RECORD: 29.1 s, peak commit 39.7 MB under a memory guard; after the
review's two prints, 31.5 s, 39.6 MB; after a second review, one of
them cut, 31.5 s, 39.2 MB; C1 at the 23 maps, 35.5 s, 40.3 MB.
"""

import math
import sys
import time
from fractions import Fraction as Fr

import manystream as ms
import piecewise as pw

NMAX = {2: 12, 3: 8, 4: 6, 5: 5}
FACTOR = Fr(1053, 1000)


def curve_lead(cell):
    fn = pw.recip(cell)
    return cell.lead((fn(cell.Mp), fn(-cell.Mm)))


class System:
    """The points and counted boxes of a cell to depth N."""

    def __init__(self, cell, N):
        self.cell, self.N = cell, N
        self.o = curve_lead(cell)
        self.n0 = max(0, 1 - self.o)
        ends = set()
        raw = []
        for n in range(self.n0, N + 1):
            umin, umax = pw.prefixes(cell, n)
            for u in range(umin, umax + 1):
                x1, x2 = cell.box(u, n)
                ends.add(x1)
                ends.add(x2)
                raw.append((n, x1, x2))
        self.P = sorted(ends)
        idx = {p: i for i, p in enumerate(self.P)}
        self.boxes = [(n, idx[x1], idx[x2]) for n, x1, x2 in raw]
        self.of = [[] for _ in self.P]
        for k, (n, i, j) in enumerate(self.boxes):
            for t in range(i, j + 1):
                self.of[t].append(k)
        fn = pw.recip(cell)
        self.f = [fn(p) for p in self.P]
        self.ff = [float(v) for v in self.f]

    def phi(self, n, m, exact):
        c = self.cell
        if exact:
            B = Fr(c.b) ** n
            return (math.floor(m * B + c.Mm) + c.Mp) / B
        B = float(c.b) ** n
        # a cap (k + M+)/B read back can floor one zone low in floats,
        # which over-constrains; the guard errs the other way
        return (math.floor(m * B + float(c.Mm) + 1e-9) + float(c.Mp)) / B

    def feasible(self, mu, exact=False):
        """Greatest fixpoint from the top; (feasible, x*)."""
        if exact:
            mu = Fr(mu)
            x = [v + mu for v in self.f]
            lo = [v - mu for v in self.f]
        else:
            mu = float(mu)
            x = [v + mu for v in self.ff]
            lo = [v - mu for v in self.ff]
        queue = list(range(len(self.boxes)))
        inq = [True] * len(self.boxes)
        while queue:
            k = queue.pop()
            inq[k] = False
            n, i, j = self.boxes[k]
            cap = self.phi(n, min(x[i:j + 1]), exact)
            for t in range(i, j + 1):
                if x[t] > cap:
                    x[t] = cap
                    if cap < lo[t]:
                        return False, x
                    for k2 in self.of[t]:
                        if not inq[k2]:
                            inq[k2] = True
                            queue.append(k2)
        return True, x

    def violations(self, vals, exact=True):
        """Boxes (n, i, j) where max > phi(min) at the given values."""
        out = []
        for n, i, j in self.boxes:
            seg = vals[i:j + 1]
            if max(seg) > self.phi(n, min(seg), exact):
                out.append((n, i, j))
        return out

    def least_mu(self, lo, hi, rel=1e-7):
        """Float bisection for the least feasible mu in [lo, hi]."""
        lo, hi = float(lo), float(hi)
        assert self.feasible(hi)[0]
        while hi - lo > rel * hi:
            mid = (lo + hi) / 2
            if self.feasible(mid)[0]:
                hi = mid
            else:
                lo = mid
        return hi


def single_box_mu(cell, N):
    """C3: each counted box its own two unknowns at its two ends; the
    least feasible mu is then, in closed form, the largest over boxes
    and contained zones of the smaller overhang. It checks the box
    enumeration against overhangs(), not the fixpoint solver."""
    sysm = System(cell, N)
    best = Fr(0)
    for n, i, j in sysm.boxes:
        hi, lo = sysm.f[i], sysm.f[j]
        e = Fr(1, cell.b ** n)
        # the box alone is infeasible at mu iff hi - mu > phi(lo + mu);
        # its threshold is the largest mu with that, over the zones q:
        # zone q's overhangs (q + 1 - M-)e - lo and hi - (q + M+)e.
        for q in range(math.floor(lo / e + cell.Mm) - 1,
                       math.ceil(hi / e - cell.Mp) + 1):
            zlo, zhi = (q + 1 - cell.Mm) * e, (q + cell.Mp) * e
            if lo < zlo and zhi < hi:
                best = max(best, min(zlo - lo, hi - zhi))
    return best


def design(key):
    mu, sl, th, ks = pw.RADIUS_DESIGNS[key]
    cell = ms.Cell(*key)
    return cell, mu, pw.PW("design", cell, ks, list(zip(th, sl)))


def main():
    t0 = time.time()
    quick = "--quick" in sys.argv
    nmax = {b: (min(v, 3 + (b < 4)) if quick else v)
            for b, v in NMAX.items()}
    cells = pw.cells()

    print("C3  single boxes give back MU_ROB(0)")
    off = []
    for cell in cells:
        a, r = single_box_mu(cell, 3), pw.mu_rob(cell)
        if a != r:
            off.append((pw.tag(cell), str(a), str(r)))
    print(f"  {'PASS' if not off else 'FAIL'}  C3 at {len(cells)} cells, "
          f"off {off}")
    ok3 = not off

    print("C1  the alive maps satisfy every constraint")
    alive = [design(k) for k in pw.RADIUS_DESIGNS]
    for cell in cells:
        if cell.am == cell.ap == cell.b - 1:
            f = pw.chords("uniform 4", cell, pw.designs(cell)[0][1],
                          pw.recip(cell))
            alive.append((cell, None, f))
    bad, feas = [], []
    for cell, mu, f in alive:
        sysm = System(cell, nmax[cell.b])
        v = sysm.violations([f.f(p) for p in sysm.P])
        if v:
            bad.append((pw.tag(cell), f.name, len(v), v[0]))
        if mu is not None:
            feas.append((pw.tag(cell), sysm.feasible(mu, exact=True)[0]))
    print(f"  {'PASS' if not bad and all(ok for _, ok in feas) else 'FAIL'}"
          f"  C1 violations {sum(x[2] for x in bad)} at {len(alive)} maps "
          f"{bad}; feasible at each design's mu: {feas}")
    if bad or not all(ok for _, ok in feas):
        print("C1 failed: nothing below is read")
        raise SystemExit(1)

    print("C2  the dead chord designs violate a constraint")
    caught, missed = 0, []
    for cell in cells:
        sysm = System(cell, nmax[cell.b])
        for label, xs in pw.designs(cell):
            f = pw.chords(label, cell, xs, pw.recip(cell))
            tab = pw.Clauses(f)
            k, _ = pw.scan(f, 0, tab.o)
            if k is None:
                continue
            v = sysm.violations([f.f(p) for p in sysm.P])
            if any(n <= k[1] for n, _, _ in v):
                caught += 1
            else:
                missed.append((pw.tag(cell), label, k[1],
                               min((n for n, _, _ in v), default=None)))
    print(f"  C2 caught {caught}, missed {len(missed)} {missed}")
    tight = []

    print("THE BOUND  mu_2(N) / MU_ROB(0), and the verdict at "
          "1.053 MU_ROB(0)")
    for cell in cells:
        key = (cell.b, cell.am, cell.ap)
        r = pw.mu_rob(cell)
        gap = pw.lead_gap(cell)
        top = (1 - pw.recip(cell)(cell.Mp)) / 2
        line = []
        for N in range(3, nmax[cell.b] + 1):
            t1 = time.time()
            sysm = System(cell, N)
            m2 = sysm.least_mu(r * Fr(99, 100), top * Fr(101, 100))
            line.append(f"N={N}:{m2 / float(r):.4f}"
                        f"({time.time() - t1:.0f}s)")
        t1 = time.time()
        ok, _ = sysm.feasible(FACTOR * r, exact=True)
        at_rob, _ = sysm.feasible(r, exact=True)
        below, _ = sysm.feasible(r * (1 - Fr(1, 10 ** 6)), exact=True)
        verdict = ("OPEN" if ok else "SECOND FLOOR") + (
            ", feasible at MU_ROB itself" if at_rob else
            ", infeasible at MU_ROB itself") + (
            ", infeasible at (1 - 1e-6) MU_ROB" if not below else
            ", FEASIBLE below MU_ROB")
        tight.append(at_rob and not below)
        dm = (f" design mu/MU_ROB {float(pw.RADIUS_DESIGNS[key][0] / r):.4f}"
              if key in pw.RADIUS_DESIGNS else "")
        print(f"  {pw.tag(cell)} MU_ROB {r} lead gap {float(gap):.3f} "
              f"{' '.join(line)}{dm}  at 1.053 (N={sysm.N}, exact, "
              f"{time.time() - t1:.0f}s): {verdict}", flush=True)
    ok = ok3 and caught == 56 and all(tight) and len(tight) == 20
    print(f"  {'PASS' if ok else 'FAIL'}  C3, C1, C2 at 56, and feasible "
          f"at MU_ROB(0), infeasible below, at {sum(tight)} of {len(tight)} "
          f"cells")
    print(f"{time.time() - t0:.1f} s")
    raise SystemExit(0 if ok else 1)


if __name__ == "__main__":
    main()