"""design.py -- a guided search for continuous maps of finitely many affine pieces near the reciprocal that read one digit below the curve, and what it found: at 15 of the 20 cells a design within the robust radius MU_ROB(0) itself. python design.py # the control at three hand cells, four # rows returned exactly (about 45 s) python design.py --all # the control at all eight, all 19 rows python design.py --ladder # the frozen verdict and the ladder, # about 15 minutes; cells by name split it python design.py --arm A1 "(4,3,1)" # one setting widened, A0..A4 QUESTION. f = 1/(s + x), s = 1 + M-, on the root box [-M-, M+]. At each cell of piecewise.cells() with no hand design (HAND below, eight designs reading at 0 within 1.003 to 1.053 MU_ROB(0)), is there a continuous map F of finitely many affine pieces with sup |F - f| <= mu = 1.053 MU_ROB(0) that reads at L = 0? A design FOUND is checked exactly as piecewise.section_wz checks one: within(cell, F, mu), Clauses(F).dead(0) false, scan(F, 0, o) finding no kill, o = Clauses(F).o, F's own lead. BY HAND (frozen with the design, before this code). H1 THE GUIDE IS NECESSARY. radius.System(cell, N) at mu has the greatest fixpoint x*(N); a continuous F within mu alive at 0 satisfies every constraint of the system at its own values on P_N, so F <= x*(N) there. The tube a piece may use is [f - mu, f + mu] cut at the points of P_N to x*(N): pruning by it loses no design. x* is read at the search's own mu. H2 THE OFFSET MENU. A piece s x + d, s = -u/v in lowest terms or 0, has at depth n the phase lattice {d b^n + const + k/v}, and its clause at depth n is empty iff d b^n mod 1/v lies in the slope's good set (every offset when its excess xi <= 0). If d b^K v (b - 1) = m is an integer, g = d b^K is a grid point m/(v(b - 1)) and g b^j - g = m R_j / v with R_j = (b^j - 1)/(b - 1) an integer, so d b^n = g mod 1/v at every n >= K: the clause at every depth >= K is one test, m mod (b - 1) among the good residues, read off piecewise.line_empty at r/(v(b - 1)), r = 0..v(b - 1) - 1 (checked periodic in r mod b - 1). The depths below K are read at the prefixes the piece actually holds, as Clauses.phases(full=False). H3 CONTINUITY fixes the kink: the next line s' x + d' meets s x + d at kappa = (d' - d)/(s - s'). H4 Only slope 0 and the alive-able -u/v at L = 0 (the segment lemma: u|I| - v rho <= b - 1), v <= VMAX, are offered; a slope that is not alive-able is dead at 0 at every offset once its piece holds a period. THE SEARCH (the frozen family). Left to right: a state is a line on [a, reach), reach the float supremum of where it stays in the H1 tube; its children are the lines of every menu slope s' != s and menu offset d' whose kink lies in (a, reach] (open at reach where x* cuts it, a point of P_N above x*). On fixing a kink the closed piece's depths below its anchor are read exactly, and so is every box of depth up to NSTR that straddles an earlier kink and ends in the piece just closed (cell.kills). A line reaching M+ closes the design, which then gets the exact check. At most PMAX pieces and BUDGET states a cell. Frozen: VMAX 12, KMAX 5 at b = 3, 4 at b = 4, 3 at b = 5, CAP 40 offsets a slope, depth first with the best BEAM = 4 children, PMAX 16, NSTR 6, BUDGET 20,000, the guide at N = 5 at b = 3, 4 at b = 4, 5. Not frozen and in the code from the first run: at most two children a slope, and the lazy cut (the tube's reach computed only while the band's bound can beat the 4 * BEAM-th, later 4 * CHILD-th, kept). CHANGED AFTER THE CONTROL MISSED (4,3,3), before any verdict, each named: (a) KMAX one higher at every radix (2: 8, 3: 6, 4: 5, 5: 4), the hand design there using anchor 5 at radix 4 (479/1536, 27/512); radix 2's KMAX and GUIDE_N (7) had not been frozen, radix 2 a control cell only. That alone still missed. (b) The offsets thinned to CAP at each anchor K apart, those of least anchor K, not CAP over all anchors. (c) Depth first replaced by a layered beam: layer j holds partial designs of j + 1 pieces, at most WIDTH = 200, one a current line, the farthest reach first, each expanding to its CHILD = 12 farthest children (PER_SLOPE = 3); BUDGET counts the states expanded. (d) A state's reach capped, exactly, at the right end of the first box below its anchor that the piece would hold and that kills (shallow_cap; its phases have period v in the prefix, so v prefixes a depth decide it): the tube's reach alone led the beam to long lines that died at their own shallow depths (1,738 of 2,151 states at (4,3,3), the beam's first run). The cap is the rejection test read ahead: a state keeps every child the rejection kept, but the cap moves reach, the beam's ranking key, so which states survive WIDTH changes. The control was the tuning set: (a) to (d) were made until (4,3,3) passed, (a) read off that hand design's own anchor, so its 8 of 8 is not independent of the repairs. POSITIVE CONTROL (read before any verdict). The search at each of the eight HAND cells at that design's own mu finds a design passing the exact check, at 8 of 8; a miss voids the method. KILL AND VERDICT. Per cell of the twelve, "FOUND p pieces, mu/MU_ROB r" or "BUDGET n nodes". A BUDGET is the frozen family's verdict at these parameters, never a floor (radius.py reads no floor above MU_ROB(0) to its depths). PREDICTIONS (guesses, frozen before this code). D1 FOUND at a majority (>= 7) of the twelve. D2 the found designs use more pieces than the hand design of the same radix (read: more than every hand design of that radix; the frozen text said "the neighbouring cell of the same radix", undefined, and this reading was fixed before the run). D3 where x*(N) has a long flat run, the design has a slope-0 piece over most of it. Extra print, not a verdict: at each FOUND cell the search rerun at mu = r MU_ROB(0), r in 1.003, 1.01, 1.02, 1.03, 1.04, the least r found. FINDINGS (entered after the run; every number is a print). - CONTROL PASS, 8 of 8: the search finds a design at each HAND cell at that design's mu, each passing the exact check, with 1 to 6 pieces against the hand design's 2 to 10 (one line, -2/5, at (4,2,2); three, -1 -2/5 0, at (4,1,3), whose hand design has ten). - THE VERDICT at mu = 1.053 MU_ROB(0): FOUND at 9 of 12, each passing the exact check: (3,2,1) 3 pieces, (4,2,3) 5, (4,3,2) 2, (5,2,3) 2, (5,3,2) 3, (5,3,3) 2, (5,4,1) 5, (5,4,3) 2, (5,4,4) 5, its lead 0 at (4,2,3) and (5,4,4) and 1 at the other seven. BUDGET at (4,3,1) (1568 states), (5,3,4) (1938) and (5,4,2) (1617), each stopping far below BUDGET (that run printed no reason; reruns since print the same counts and "emptied", every kept state's children rejected or cut: (4,3,1) alone, and all three at A0 of THE BEAM'S SETTINGS), straddler rejections 1086, 1091 and 1818 against piece rejections 44, 31 and 34. The counts do not say which variable would free them: the cap and the residue filter hide piece failures before they are counted. The label BUDGET names every stop short of FOUND, as frozen; the printed stop says which. - D1 held: 9 >= 7. D2 failed: more pieces than every hand design of its radix at 2 of 9, (5,4,1) and (5,4,4) (5 against 3 and 3). D3 failed: where x*(N) has long flat runs (at 8 of the 9), no flat piece of the design lies over them (share 0.000 at every one); the designs that have a flat piece, (5,2,3) and (5,3,3), place it elsewhere. x*'s flats are where the greatest solution is capped, not where a design must be flat. - The extra print: the least r found is 1.003, the lowest offered, at all 9 FOUND cells (536.7 s, peak commit 31.6 MB under a memory guard), read below 1.003 by THE LADDER. THE LADDER BELOW 1.003 (frozen before its code). QUESTION: at each of the 17 cells with a design (the eight HAND, the nine FOUND), the least rung of 1, 1.00003, 1.0003, 1.003, 1.01, ..., 1.04 (rungs read lowest first, stopping at the first FOUND; at a HAND cell only the rungs below that design's own ratio) at which the search finds a design passing the exact check. A design within r MU_ROB(0) is within every larger radius, so the least rung found is an upper bound on the cell's least ratio, never a floor. Rung 1 is MU_ROB(0) itself: the robust radius forbids only mu < MU_ROB(0) (a box kills F when both overhangs EXCEED mu), so a design there is allowed, and one found makes MU_ROB(0) the exact least radius at that cell. BY HAND: the guide's tube at mu = MU_ROB(0) is nonempty (radius.py's fixpoint is feasible there to its depths); the exact check is closed (within() fails only past mu), so equality at the critical box passes it. PREDICTIONS (guesses): L1 the least rung is at most 1.0003 at a majority (>= 9) of the 17; L2 rung 1 is found at fewer than half (<= 8) of the 17. KILL of "the designs approach MU_ROB(0)": the least rung is 1.003 or higher at a majority (>= 9) of the 17. CONTROL: the frozen CONTROL above (8 of 8 at each hand design's own mu), and the rows printed at each least rung pass section_wz's exact check when entered into piecewise.py (a second edit, read there). FINDINGS (entered after the run, copied from its prints). Run as four processes over the 20 cells by name with `--rows` (the bare run then, `--ladder --rows` now), each under a 2 GB memory guard: walls 400.6, 180.8, 181.1, 148.1 s, peak commit 29.7 MB. Summed over the four processes' prints, the CONTROL passed 8 of 8 and the verdict reprinted the frozen one (FOUND 9, BUDGET at (4,3,1), (5,3,4), (5,4,2), the same piece counts). - THE LEAST RUNG, every row passing the exact check inside the search: 1 (MU_ROB(0) itself) at 12 of the 17: (2,1,1), (3,2,1), (3,2,2), (4,2,2), (4,2,3), (4,3,3), (5,2,3), (5,2,4), (5,3,2), (5,3,3), (5,4,3), (5,4,4); 1.00003 at (3,1,2), (5,1,4), (5,4,1); 1.0003 at (4,1,3), (4,3,2). Each lower rung missed by "emptied". - L1 held (at most 1.0003 at 17 of 17). L2 failed (rung 1 at 12). The kill missed (1.003 or higher at 0 of 17). - THE ROWS printed at each least rung are piecewise.py's RADIUS_DESIGNS at those 17 cells, each at its rung's mu, and its section_wz read them, the frozen control: exact at all of them. A row's claim is its own ratio, never its rung (alive at 0 is free of mu), so the three rows found at rung 1.00003 are within MU_ROB(0) too: within MU_ROB(0) itself at 15 cells, (4,1,3) and (4,3,2) within 1.0000347 and 1.0000482 (section_wz's brackets). With the robust radius, MU_ROB(0) is there the exact least radius of a continuous map reading at 0, attained by 1 to 7 pieces. Whether MU_ROB(0) is attained at (4,1,3) and (4,3,2) is unread: the rung-1 and rung-1.00003 beams emptied, a verdict of the family. THE BEAM'S SETTINGS (frozen before its code). QUESTION: is the stop at (4,3,1), (5,3,4) and (5,4,2) the search's settings or the cells? One setting widened at a time (`--arm`), at mu = 1.053 MU_ROB(0): A0 the frozen settings; A1 WIDTH 200 -> 800; A2 CHILD 12 -> 36 and PER_SLOPE 3 -> 9; A3 VMAX 12 -> 20; A4 KMAX one higher and CAP 40 -> 120; A5 the children chosen after the straddler and piece tests, from 4 CHILD candidates (its code since removed: it freed nothing); A6 all at once (`--arm` runs A0 to A4). CONTROL: each arm at (5,2,3), which the frozen search finds in two pieces, must FOUND, or its verdict is not read. PREDICTIONS (guesses): F1 A5 frees at least two of the three; F2 A1 alone frees at most one; F3 A6 frees all three. KILL of "the three are the search's settings, not the cells": no arm frees any of the three. FINDINGS (entered after the run, copied from its prints). A0 alone 72.8 s, 27.3 MB; then A1 with A3 603.2 s, A2 with A4 775.2 s and A5 88.1 s, one process each, peak commit 35.6 MB under a memory guard, against an estimate of 10 to 20 minutes for the four. A6 was stopped unread: it had not printed its control line after about 19 minutes, and its parent shell was gone. - The control FOUND at every arm read, A0 to A5, the same row. - A0 reprints the verdict: BUDGET at all three, each emptied. - A1 (WIDTH 800) frees two: (4,3,1) FOUND, 5 pieces, 2925 nodes; (5,4,2) FOUND, 4 pieces, 2294 nodes; their rows, at 1.053 MU_ROB(0), are piecewise.py's RADIUS_DESIGNS there, own ratios within 1.0046594 and 1.0077520 (section_wz). (5,3,4) BUDGET 8609 nodes, stopped by PMAX (16 pieces), a setting no arm widened. - A2 frees (5,4,2) alone, another row (a slope -3/7 in place of -1/2, two offsets and the first kink moved), the same own ratio, (4,3,1) and (5,3,4) emptied; A3, A4 and A5 free none, A3 stopping (4,3,1) by PMAX, every other stop "emptied", and A5 multiplying the straddler rejections (5360, 4748, 25829). - F1 failed (A5 frees 0), F2 failed (A1 frees 2), F3 unread. The kill missed: the beam's width frees two of the three. (5,3,4) holds against every arm read. - The frozen BY HAND's "every arm only enlarges what the search may try" is false for this beam: the per-layer dedup, the WIDTH cut and CAP's thinning are not monotone. What a FOUND buys stands on the exact check alone, whatever the arm. THE BARE RUN (added when the rows moved into piecewise.py): the control at its three cheapest hand cells, and the search at four rows' cells and mu returning that row exactly, slopes, offsets and kinks; `--all` reads all eight controls and all 19 rows, (4,3,1) and (5,4,2) at WIDTH 800. The comparator and the search were each read failing in a scratch copy: (5,3,3)'s row moved in piecewise.py prints "FOUND another" and FAIL at 0 of 1; the beam's layers ranked nearest first return the row at 2 of the four (another design at (5,2,3), none at (5,4,1)). PER_SLOPE cut to 1, and the lazy cut's order reversed, move none of the four, so they read nothing. RUN RECORD, under a memory guard: the bare run 43.0 s, peak commit 28.3 MB, CONTROL 3 of 3 and ROWS at 4 of 4; `--all` 508.1 s, 38.3 MB, CONTROL 8 of 8 and ROWS returned at 19 of 19, (4,3,1) and (5,4,2) at WIDTH 800 in 40.9 and 65.2 s. """ import os import sys import time os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") import bisect # noqa: E402 import math # noqa: E402 from fractions import Fraction as Fr # noqa: E402 import numpy as np # noqa: E402 import manystream as ms # noqa: E402 import piecewise as pw # noqa: E402 import radius as rd # noqa: E402 VMAX = 12 KMAX = {2: 8, 3: 6, 4: 5, 5: 4} CAP = 40 CHILD = 12 PER_SLOPE = 3 WIDTH = 200 PMAX = 16 NSTR = 6 BUDGET = 20_000 GUIDE_N = {2: 7, 3: 5, 4: 4, 5: 4} BAR = Fr(1053, 1000) LADDER = [Fr(1), Fr(100003, 100000), Fr(10003, 10000), Fr(1003, 1000), Fr(101, 100), Fr(102, 100), Fr(103, 100), Fr(104, 100)] TOL = 1e-12 QUICK_CONTROL = [(4, 2, 2), (2, 1, 1), (5, 1, 4)] QUICK_ROWS = [(5, 3, 3), (5, 4, 3), (5, 2, 3), (5, 4, 1)] WIDE = {(4, 3, 1): 800, (5, 4, 2): 800} # the rows A1 found def F(*vs): return [Fr(v) for v in vs] # The control's keys: the eight hand designs (mu, slopes, offsets, # kinks), each reading at 0 within 1.003 to 1.053 MU_ROB(0). HAND = { (2, 1, 1): (Fr(5329, 366071), F(-1, "-4/7", "-2/7", "-1/7"), F(0, "3/8", "113/224", "13/28"), F("-7/8", "-29/64", "9/32")), (3, 1, 2): (Fr(7859, 704985), F(-1, "-1/3", -1, "-1/3", -1, "-1/2", "-1/4", "-1/6"), F("1/2", "41/54", "259/486", "365/486", "29/54", "2/3", "103/162", "5/9"), F("-7/18", "-55/162", "-53/162", "-26/81", "-7/27", "10/81", "26/27")), (3, 2, 2): (Fr(7859, 704985), F(-1, "-3/5", "-1/3", "-1/6", "-1/8"), F(0, "16/45", "596/1215", "1187/2430", "1087/2430"), F("-8/9", "-41/81", "1/81", "80/81")), (4, 1, 3): (Fr(26519, 729007), F(-1, "-1/4", "-1/2", "-1/2", "-2/7", "-2/7", "-2/7", "-1/3", "-1/2", "-1/5"), F("2/3", "73/96", "301/384", "301/384", "1135/1536", "1135/1536", "1135/1536", "24217/32256", "25603/32256", "24113/40320"), F("-1/8", "3/32", "131/768", "161/768", "59/256", "31/128", "191/768", "33/128", "167/256")), (4, 2, 2): (Fr(83763, 971233), F("-1/2", "-1/5"), F("2/3", "457/960"), F("61/96")), (4, 3, 3): (Fr(1225, 97319), F(-1, "-1/2", -1, "-1/2", "-2/3", "-1/2", "-2/3", "-1/3", "-1/7"), F(0, "113/256", "27/512", "225/512", "479/1536", "7/16", "5/16", "379/768", "2585/5376"), F("-113/128", "-199/256", "-99/128", "-49/64", "-193/256", "-3/4", "-139/256", "17/256")), (5, 1, 4): (Fr(28221, 841820), F(-1, "-1/2", "-1/4"), F("3/4", "1937/2500", "1677/2500"), F("-31/625", "52/125")), (5, 2, 4): (Fr(7997, 227918), F(-1, "-2/5", "-1/6"), F("1/2", "4229/6250", "1357/2500"), F("-184/625", "717/1250")), } # ---- the menu (H2, H4) ---- def menu(cell): """[(slope, v, good residues mod b - 1 or None for every offset)].""" b, I, rho = cell.b, cell.I, cell.rho out = [(Fr(0), 1, None)] for v in range(1, VMAX + 1): for u in range(1, v + 1): if math.gcd(u, v) != 1: continue ell = u * I - v * rho if ell > b - 1: continue s = -Fr(u, v) if ell <= 0: out.append((s, v, None)) continue em = [pw.line_empty(cell, s, Fr(r, v * (b - 1))) for r in range(v * (b - 1))] good = {r % (b - 1) for r in range(len(em)) if em[r]} per = all(em[r] == (r % (b - 1) in good) for r in range(len(em))) assert per, (pw.tag(cell), str(s), "good set not periodic") if good: out.append((s, v, frozenset(good))) return out def anchor(cell, v, d): """The least K with d b^K v (b - 1) an integer, and that integer.""" b = cell.b x = d * v * (b - 1) K = 0 while x.denominator != 1: x *= b K += 1 if K > 60: return None, None return K, x.numerator # ---- the tube (H1), floats ---- class Tube: def __init__(self, cell, mu, N): self.cell, self.mu = cell, float(mu) self.s0 = float(1 + cell.Mm) self.lo, self.hi = float(-cell.Mm), float(cell.Mp) sysm = rd.System(cell, N) ok, x = sysm.feasible(Fr(mu), exact=True) assert ok, (pw.tag(cell), "guide infeasible") self.sys, self.xs = sysm, x self.P = np.array([float(p) for p in sysm.P]) self.X = np.array([float(v) for v in x]) def band(self, lam, d, a): """The right end of the band [f - mu, f + mu] from a for lam x + d.""" mu, s0 = self.mu, self.s0 roots = [] for c in (d + mu, d - mu): # (lam x + c)(s0 + x) - 1 = lam x^2 + (lam s0 + c) x + c s0 - 1 A, B, C = lam, lam * s0 + c, c * s0 - 1 if A == 0: if B != 0: roots.append(-C / B) else: disc = B * B - 4 * A * C if disc >= 0: r = math.sqrt(disc) roots += [(-B - r) / (2 * A), (-B + r) / (2 * A)] pts = sorted(r for r in roots if a + 1e-15 < r < self.hi) prev = a for r in pts + [self.hi]: m = (prev + r) / 2 g = lam * m + d - 1 / (s0 + m) if g < -mu - TOL or g > mu + TOL: return prev prev = r return self.hi def reach(self, lam, d, a, cap=None): """(reach, open): the line stays in the tube on [a, reach), or on [a, reach] when not open.""" rb = self.band(lam, d, a) if cap is not None: rb = min(rb, cap) i0 = bisect.bisect_left(self.P, a - 1e-15) i1 = bisect.bisect_right(self.P, rb + 1e-15) if i1 > i0: seg = lam * self.P[i0:i1] + d - self.X[i0:i1] bad = np.nonzero(seg > TOL)[0] if len(bad): return float(self.P[i0 + bad[0]]), True return rb, False # ---- the exact reads ---- def n0_of(o): return max(0, 1 - o) def piece_shallow_ok(cell, s, d, K, a, c, n0): """H2's depths below the anchor, at the prefixes [a, c] holds.""" xi = abs(s) * cell.w - (cell.w - 1) if xi <= 0: return True end = -cell.Mm if s > 0 else cell.Mp for n in range(n0, K): bn = pw.pw(cell.b, n) umin, umax = pw.prefixes(cell, n) lo = max(math.ceil(a * bn + cell.Mm), umin) hi = min(math.floor(c * bn - cell.Mp), umax) for u in range(lo, hi + 1): z = pw.frac(s * (u + end) + d * bn + cell.Mm) if z > 1 - xi: return False return True def shallow_cap(cell, s, v, d, K, a, n0): """The right end x2 of the first box at a depth n0..K-1, lying right of a, whose phase kills: a piece from a holds it iff it reaches x2, so it must end before. None when there is none. The phases are periodic in u with period v, so v prefixes a depth decide it.""" xi = abs(s) * cell.w - (cell.w - 1) if xi <= 0: return None end = -cell.Mm if s > 0 else cell.Mp best = None for n in range(n0, K): bn = pw.pw(cell.b, n) umin, umax = pw.prefixes(cell, n) u0 = max(math.ceil(a * bn + cell.Mm), umin) for u in range(u0, min(u0 + v, umax + 1)): if pw.frac(s * (u + end) + d * bn + cell.Mm) > 1 - xi: x2 = (u + cell.Mp) / bn if best is None or x2 < best: best = x2 break return best class Partial: """The map fixed so far: lines and kinks, the last line open-ended.""" def __init__(self, lines, kinks): self.lines, self.kinks = lines, kinks def f(self, x): j = bisect.bisect_left(self.kinks, x) s, d = self.lines[j][:2] return s * x + d def image(self, x1, x2): vals = [self.f(x1), self.f(x2)] i = bisect.bisect_right(self.kinks, x1) while i < len(self.kinks) and self.kinks[i] < x2: vals.append(self.f(self.kinks[i])) i += 1 return min(vals), max(vals) def straddlers_ok(cell, part, left, right, n0): """Every box of depth n0..NSTR with x1 < left < x2 <= right, left a kink: its image strictly contains no zone.""" for n in range(n0, NSTR + 1): bn = pw.pw(cell.b, n) umin, umax = pw.prefixes(cell, n) lo = max(math.floor(left * bn - cell.Mp) + 1, umin) hi = min(math.floor(right * bn - cell.Mp), math.ceil(left * bn + cell.Mm) - 1, umax) for u in range(lo, hi + 1): x1, x2 = cell.box(u, n) if cell.kills(part.image(x1, x2), n, 0): return False return True def exact_check(cell, lines, kinks, mu): f = pw.PW("design", cell, kinks, [(d, s) for s, d, _ in lines]) if not pw.within(cell, f, mu): return False, "not within mu" tab = pw.Clauses(f) if tab.dead(0): return False, "clauses dead" k, _ = pw.scan(f, 0, tab.o) if k is not None: return False, "engine kill" return True, f # ---- the search ---- class Search: def __init__(self, cell, mu, N): self.cell, self.mu = cell, Fr(mu) self.tube = Tube(cell, mu, N) self.menu = menu(cell) self.o = rd.curve_lead(cell) self.n0 = n0_of(self.o) self.nodes = 0 self.found = None self.rejects = {} self.kmax = KMAX[cell.b] self.stop = None def offsets(self, v, good, dlo, dhi): """Menu offsets in [dlo, dhi]: at each anchor K = 0..KMAX those of least anchor K, evenly thinned to at most CAP.""" b = self.cell.b got = [] for K in range(self.kmax + 1): den = v * (b - 1) * b ** K m0, m1 = math.ceil(dlo * den), math.floor(dhi * den) new = [m for m in range(m0, m1 + 1) if (good is None or m % (b - 1) in good) and (K == 0 or m % b != 0)] if len(new) > CAP: step = len(new) / CAP new = [new[int(i * step)] for i in range(CAP)] got += [Fr(m, den) for m in new] return got def children(self, s, d, a, reach, opn): """[(reach', open', s', d', K', kappa)], best first.""" pool = [] fa, fr = float(a), reach for s2, v2, good in self.menu: if s2 == s: continue ds = s - s2 ends = sorted([d + ds * Fr(fa), d + ds * Fr(fr)]) for d2 in self.offsets(v2, good, *ends): kap = (d2 - d) / ds if not a < kap or (kap >= Fr(fr) if opn else kap > Fr(fr)): continue pool.append((float(s2), float(d2), float(kap), s2, v2, d2, kap)) # lazy: the band reach bounds the tube's reach scored = [] for fs, fd, fk, s2, v2, d2, kap in pool: scored.append((self.tube.band(fs, fd, fk), fs, fd, fk, s2, v2, d2, kap)) scored.sort(key=lambda t: -t[0]) kept, per = [], {} for rb, fs, fd, fk, s2, v2, d2, kap in scored: if len(kept) >= 4 * CHILD and rb <= kept[-1][0]: break K2, _ = anchor(self.cell, v2, d2) r, op = self.full_reach(s2, v2, d2, K2, kap, fs, fd, fk) if r <= fk + 1e-14: continue kept.append((r, op, s2, v2, d2, kap)) kept.sort(key=lambda t: -t[0]) out = [] for r, op, s2, v2, d2, kap in kept: if per.get(s2, 0) >= PER_SLOPE: continue per[s2] = per.get(s2, 0) + 1 out.append((r, op, s2, v2, d2, kap)) if len(out) >= CHILD: break return out def full_reach(self, s2, v2, d2, K2, kap, fs, fd, fk): """The tube's reach from the kink, capped at the first killing box the piece would hold below its anchor.""" r, op = self.tube.reach(fs, fd, fk) cap = shallow_cap(self.cell, s2, v2, d2, K2, kap, self.n0) if cap is not None and float(cap) <= r: return float(cap), True return r, op def reject(self, why): self.rejects[why] = self.rejects.get(why, 0) + 1 def close(self, st): """The exact reads of a state whose line reaches M+.""" lines, kinks, a, reach, opn = st cell = self.cell s, d, K = lines[-1] if not (reach >= float(cell.Mp) - 1e-15 and not opn): return False ok = piece_shallow_ok(cell, s, d, K, a, cell.Mp, self.n0) if ok and kinks: ok = straddlers_ok(cell, Partial(lines, kinks), kinks[-1], cell.Mp, self.n0) if not ok: self.reject("close shallow") return False good, f = exact_check(cell, lines, kinks, self.mu) if good: self.found = (lines, kinks, f) return True self.reject(f) return False def expand(self, st): lines, kinks, a, reach, opn = st cell = self.cell s, d, K = lines[-1] out = [] for r, op, s2, v2, d2, kap in self.children(s, d, a, reach, opn): if not piece_shallow_ok(cell, s, d, K, a, kap, self.n0): self.reject("piece shallow") continue K2, _ = anchor(cell, v2, d2) lines2 = lines + [(s2, d2, K2)] kinks2 = kinks + [kap] if kinks and not straddlers_ok(cell, Partial(lines2, kinks2), kinks[-1], kap, self.n0): self.reject("straddler") continue out.append((lines2, kinks2, kap, r, op)) return out def run(self): """The layered beam: layer j holds partial designs of j + 1 pieces, at most WIDTH, one a current line, the farthest reach first.""" cell, t = self.cell, self.tube a = -cell.Mm y0 = 1 / (1 + cell.Mm + a) ylo = y0 - self.mu yhi = min(y0 + self.mu, t.xs[0]) layer = [] for s, v, good in self.menu: for d in self.offsets(v, good, ylo + s * cell.Mm, yhi + s * cell.Mm): K, _ = anchor(cell, v, d) r, op = self.full_reach(s, v, d, K, a, float(s), float(d), float(a)) if r > float(a) + 1e-14: layer.append(([(s, d, K)], [], a, r, op)) for _ in range(PMAX): layer.sort(key=lambda z: -z[3]) seen, kept = set(), [] for st in layer: key = st[0][-1][:2] if key not in seen: seen.add(key) kept.append(st) if len(kept) >= WIDTH: break nxt = [] for st in kept: if self.nodes >= BUDGET: self.stop = "budget" return None self.nodes += 1 if self.close(st): return self.found nxt += self.expand(st) if not nxt: self.stop = "emptied" return None layer = nxt self.stop = "PMAX" return None def flat_cover(cell, tube, lines, kinks): """D3: the long flat runs of x*(N) (over 4w b^-N, slope 0 between consecutive points) and the share of their width under a slope-0 piece of the design.""" P, x = tube.sys.P, tube.xs e = Fr(1, cell.b ** tube.sys.N) runs, cur = [], None for i in range(len(P) - 1): if x[i + 1] == x[i]: if cur and cur[1] == P[i]: cur[1] = P[i + 1] else: cur = [P[i], P[i + 1]] runs.append(cur) long_ = [(lo, hi) for lo, hi in runs if hi - lo > 4 * cell.w * e] cuts = [-cell.Mm] + list(kinks) + [cell.Mp] flats = [(cuts[j], cuts[j + 1]) for j, (s, _, _) in enumerate(lines) if s == 0] tot = sum(hi - lo for lo, hi in long_) cov = sum(max(Fr(0), min(hi, fh) - max(lo, fl)) for lo, hi in long_ for fl, fh in flats) return len(long_), tot, cov def describe(lines, kinks): return ("slopes " + " ".join(str(s) for s, _, _ in lines) + " | anchors " + " ".join(str(K) for _, _, K in lines)) def rows(mu, lines, kinks): """A print only: the design as a row of piecewise.RADIUS_DESIGNS.""" return (f"({mu!r}, slopes {[str(s) for s, _, _ in lines]}, offsets " f"{[str(d) for _, d, _ in lines]}, kinks {[str(k) for k in kinks]})") def settings(arm): """THE BEAM'S SETTINGS: one arm's widened settings (A0 the frozen).""" g = globals() if arm == "A1": g["WIDTH"] = 800 elif arm == "A2": g["CHILD"], g["PER_SLOPE"] = 36, 9 elif arm == "A3": g["VMAX"] = 20 elif arm == "A4": g["KMAX"] = {b: k + 1 for b, k in KMAX.items()} g["CAP"] = 120 else: assert arm == "A0", arm def search(cell, mu): se = Search(cell, mu, GUIDE_N[cell.b]) t1 = time.time() return se, se.run(), time.time() - t1 def control(keys): """The positive control: a design found at each hand cell at that design's own mu.""" print("CONTROL the search at the hand cells, each at its design's mu") hits = [] for key in keys: mu, sl = HAND[key][:2] cell = ms.Cell(*key) se, got, dt = search(cell, mu) hits.append(got is not None) print(f" {pw.tag(cell)} mu/MU_ROB {float(mu / pw.mu_rob(cell)):.4f}" f" (hand design {len(sl)} pieces): " + (f"FOUND {len(got[0])} pieces, {describe(*got[:2])}" if got else f"MISS {se.nodes} nodes, stopped: " f"{se.stop}, {se.rejects}") + f" ({dt:.1f} s)", flush=True) ok = all(hits) and len(hits) == len(keys) and hits print(f" {'PASS' if ok else 'FAIL'} CONTROL {sum(hits)} of {len(hits)}") return ok def returns_rows(keys): """The search at each row's cell and mu returns that row exactly.""" global WIDTH print("ROWS the search at each row's cell and mu returns the row") same = [] for key in keys: mu, sl, th, ks = pw.RADIUS_DESIGNS[key] cell = ms.Cell(*key) WIDTH, w0 = WIDE.get(key, WIDTH), WIDTH try: se, got, dt = search(cell, mu) finally: WIDTH = w0 ok = bool(got) and ([s for s, _, _ in got[0]] == sl and [d for _, d, _ in got[0]] == th and got[1] == ks) same.append(ok) print(f" {pw.tag(cell)} WIDTH {WIDE.get(key, WIDTH)}: " + ("the row" if ok else "FOUND another" if got else f"none, stopped: {se.stop}") + f", {se.nodes} nodes ({dt:.1f} s)", flush=True) ok = all(same) and len(same) == len(keys) print(f" {'PASS' if ok else 'FAIL'} ROWS returned at {sum(same)} of " f"{len(same)}") return ok def arm(name, keys): """THE BEAM'S SETTINGS: one arm at its control and the named cells.""" settings(name) print(f"ARM {name} WIDTH {WIDTH}, CHILD {CHILD}, PER_SLOPE {PER_SLOPE}," f" VMAX {VMAX}, KMAX {KMAX}, CAP {CAP}") for key, tail in [((5, 2, 3), " <- control")] + [(k, "") for k in keys]: cell = ms.Cell(*key) se, got, dt = search(cell, BAR * pw.mu_rob(cell)) if got: lines, kinks, f = got lo, hi = pw.own_ratio(cell, f) print(f" {pw.tag(cell)} FOUND {len(lines)} pieces, " f"{describe(lines, kinks)}, own ratio in " f"{pw.ratio7(lo, hi)}, {se.nodes} nodes ({dt:.1f} s)" f"{tail}\n {rows(se.mu, lines, kinks)}", flush=True) else: print(f" {pw.tag(cell)} BUDGET {se.nodes} nodes, stopped: " f"{se.stop}, {se.rejects} ({dt:.1f} s){tail}", flush=True) def ladder(only): """The frozen experiment: the control, the verdict at 1.053 MU_ROB(0) at the twelve, and the ladder of rungs below it.""" cells = pw.cells() hand_pieces = {} for key, (_, sl, _, _) in HAND.items(): hand_pieces.setdefault(key[0], []).append(len(sl)) keys = [k for k in HAND if not only or pw.tag(ms.Cell(*k)) in only] if not control(keys): print("the control failed: the method is void, nothing below is " "read") raise SystemExit(1) ctrl = {k: HAND[k][0] / pw.mu_rob(ms.Cell(*k)) for k in keys} print("VERDICT the twelve cells at mu = 1.053 MU_ROB(0)") found = {} for cell in cells: key = (cell.b, cell.am, cell.ap) if key in HAND or (only and pw.tag(cell) not in only): continue r0 = pw.mu_rob(cell) se, got, dt = search(cell, BAR * r0) if got: lines, kinks, f = got found[key] = got nl, tot, cov = flat_cover(cell, se.tube, lines, kinks) print(f" {pw.tag(cell)} FOUND {len(lines)} pieces, mu/MU_ROB " f"{float(BAR):.4f}, lead {pw.Clauses(f).o}; " f"{describe(lines, kinks)}; hand pieces at radix " f"{cell.b}: {hand_pieces.get(cell.b)}; x* long flats {nl}, " f"width {float(tot):.4f}, under a flat piece " f"{float(cov / tot) if tot else 0:.3f} ({dt:.1f} s)", flush=True) if "--rows" in sys.argv: print(f" {rows(BAR * r0, lines, kinks)}") else: print(f" {pw.tag(cell)} BUDGET {se.nodes} nodes, " f"stopped: {se.stop}, {se.rejects} ({dt:.1f} s)", flush=True) print(f" FOUND at {len(found)} of " f"{sum((c.b, c.am, c.ap) not in HAND for c in cells)}") print("LADDER the least rung found at each HAND and FOUND cell") for key in list(ctrl) + list(found): cell = ms.Cell(*key) r0 = pw.mu_rob(cell) top = ctrl.get(key, BAR) least = None for r in LADDER: if r >= top: break se, got, dt = search(cell, r * r0) print(f" rung {r}: " + (f"FOUND {len(got[0])} pieces" if got else "none") + f", {se.nodes} nodes, stopped: {se.stop} ({dt:.1f} s)", flush=True) if got: least = r if "--rows" in sys.argv: print(f" {rows(r * r0, got[0], got[1])}") break print(f" {pw.tag(cell)} least rung " f"{least if least else f'none below {float(top):.5f}'}", flush=True) def main(): t0 = time.time() only = [a for a in sys.argv[1:] if a.startswith("(")] if "--ladder" in sys.argv: ladder(only) print(f"{time.time() - t0:.1f} s") return if "--arm" in sys.argv: name = sys.argv[sys.argv.index("--arm") + 1] arm(name, [tuple(int(c) for c in a.strip("()").split(",")) for a in only] or [(4, 3, 1), (5, 3, 4), (5, 4, 2)]) print(f"{time.time() - t0:.1f} s") return full = "--all" in sys.argv ok = control(list(HAND) if full else QUICK_CONTROL) ok = returns_rows(list(pw.RADIUS_DESIGNS) if full else QUICK_ROWS) and ok print(f"{time.time() - t0:.1f} s") raise SystemExit(0 if ok else 1) if __name__ == "__main__": main()