#!/usr/bin/env python3 """Verify the upper bound for the measure of hyperbolic logistic parameters. python3 verify_regions.py # full Appendix A certificate python3 verify_regions.py --quick # smaller search, with its own bound python3 verify_regions.py --example # the tile with return times 4 and 14 This single file implements the calculations in the two accompanying proofs, "A parameter Cantor construction for the logistic family" and the multiple- regions supplement. Python 3.9+ suffices. All tables and all itineraries are generated from the map. NumPy, when installed, can accelerate two integer calculations. Use --jobs 1 for a serial run and --stdlib to use only the standard library. Floating-point values propose centers and paths. The proof checks them using integer inequalities and outward-rounded Decimal bounds. """ import argparse from array import array from bisect import bisect_right import cmath from collections import defaultdict from decimal import Context, Decimal, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_EVEN from fractions import Fraction from functools import lru_cache from heapq import heappop, heappush from itertools import islice import math import multiprocessing import os import sys from typing import NamedTuple D = Decimal S = 1 << 55 # ticks per unit in the real tile calculation MASS = 10**8 # units per probability in the Bellman table TOP = 112 # log moduli in eighths, capped at 14 SIDE = TOP + 1 BANDS = (0, 6, 14, 24, 45, 65, 85, 107, 145, 185, 230, 305, 345, 390, 455) CUTS = (0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 20, 28, 40, 64, 96, 128, 192) CTX = Context(prec=78, rounding=ROUND_HALF_EVEN) # The moving boundary of the initial puzzle. Distances here are in units 2^-40. U = 1 << 40 ctx = Context(prec=72, rounding=ROUND_HALF_EVEN) def ceildiv(a,b): return -((-a)//b) def isqrt_up(n): s = math.isqrt(n) return s + (s*s != n) def norm_down(z): return math.isqrt(z[0]**2+z[1]**2) def norm_up(z): return isqrt_up(z[0]**2+z[1]**2) def point(z): return round(z.real*U),round(z.imag*U) def complex_value(z): return complex(z[0]/U,z[1]/U) def plus(a,b): return a[0]+b[0],a[1]+b[1] def product(a,b): # Product in units U^2. return a[0]*b[0]-a[1]*b[1], a[0]*b[1]+a[1]*b[0] def imul(x,y): prod=[a*b for a in x for b in y] return min(prod)//U,ceildiv(max(prod),U) def rooted(x): return (math.isqrt(max(0,x[0])*U),isqrt_up(x[1]*U)) def disk(x,y): a=(x[0]+x[1])//2 b=(y[0]+y[1])//2 return (a,b),norm_up((x[1]-a,y[1]-b)) @lru_cache(None) def hyp_at(s): # s is a nonnegative dyadic. The division is exact at this precision. if s==0: return (U,U),(0,0) arg=ctx.divide(D(s),D(U)) def scaled_exp(x): mid=ctx.exp(x) lo=ctx.next_minus(mid).as_integer_ratio() hi=ctx.next_plus(mid).as_integer_ratio() return (lo[0]*U//lo[1],ceildiv(hi[0]*U,hi[1])) pos,neg=scaled_exp(arg),scaled_exp(arg.copy_negate()) return ((pos[0]+neg[0])//2,ceildiv(pos[1]+neg[1],2)), ((pos[0]-neg[1])//2,ceildiv(pos[1]-neg[0],2)) def paths(resolution=48): # The cap is a subdivision count, independent of the integer lattice. root3=rooted((3*U,3*U)) curves=[] for j in range(resolution): l=j*U//(2*resolution); h=ceildiv((j+1)*U,2*resolution) ray=[];sl,sh=l,h for k in range(17): cl,hl=hyp_at(sl);ch,hh=hyp_at(sh) x=(cl[0],ch[1]);y=imul((hl[0],hh[1]),root3) if k: x=(-x[1],-x[0]) if k%2==0:y=(-y[1],-y[0]) ray.append(disk(x,y)) if sh>=3*U:break sl*=2;sh*=2 curves.append(ray) C=(l,h) si=(U-imul(C,C)[1],U-imul(C,C)[0]) sn=rooted(si) arc=[] for k in range(4): cc,ss=hyp_at((U//2)*(2**k)) x=imul(C,(2*cc[0],2*cc[1])); y=imul(sn,(2*ss[0],2*ss[1])) arc.append(disk(x,y)) C2=imul(C,C);cs=imul(C,sn) C=(2*C2[0]-U,2*C2[1]-U);sn=(2*cs[0],2*cs[1]) curves.append(arc) return curves def displaced(curve,t,spread,E): z,d=curve[-1] lower=max(U,norm_down(z)-d) error=min(E,ceildiv((E+t+spread)*U,2*lower-E)) next_center=(0,0) for z,size in reversed(curve[:-1]): zz=complex_value(z) square=cmath.sqrt(zz*zz+complex_value(next_center)-t/U) if abs(-square-zz)=E: guess=(0,0);error=E else: error=refined next_center=guess z,size=curve[0] return plus(z,next_center),size+error def quadratic_step(z,r,t,spread): cand=point(cmath.sqrt(2-t/U+complex_value(z))) realpart=2*U-t+z[0]-r-spread if realpart<=0:return None den=cand[0]+math.isqrt(U*realpart) if den<=0:return None a,b=product(cand,cand) residual=ceildiv(norm_up(((2*U-t+z[0])*U-a,z[1]*U-b)),U) return cand,ceildiv((r+spread+residual)*U,den) def enclosure(curves,t,spread,max_p): T=t+spread if T*100>=46*U:return None b=ceildiv(53*T,100) E=(U-math.isqrt(U*(U-4*b)))//2+2 assert E*20:branch[k]=[round(U*math.sqrt(w)),0] for curve in curves: z,r=displaced(curve,t,spread,E) a0=min(a0,norm_down(z)-r) for sign in [-1,1]: center=(sign*z[0],sign*z[1]);rad=r for n in range(1,max_p): new=quadratic_step(center,rad,t,spread) if new is None: for p in range(n+1,max_p+1): bounds[p]=[0,8*U];branch[p]=None break center,rad=new b=(2*U-t-center[0],-center[1]) low=max(0,norm_down(b)-rad-spread) high=norm_up(b)+rad+spread if branch[n+1] is not None: gap=b[0]-rad-spread if gap<=0: branch[n+1]=None else: center_z=point(cmath.sqrt(complex_value(b))) wx,wy=product(center_z,center_z) residual=ceildiv(norm_up((b[0]*U-wx,b[1]*U-wy)),U) rz=ceildiv((rad+spread+residual)*U, center_z[0]+math.isqrt(U*gap)) bx=branch[n+1][0] rw=rz+norm_up((center_z[0]-bx,center_z[1])) branch[n+1][1]=max(branch[n+1][1],rw) v=bounds[n+1] v[0]=min(v[0],math.isqrt(U*low));v[1]=max(v[1],isqrt_up(U*high)) return a0,bounds,branch def boundary_table(example=False): """Compute the moving collars, converting the 2^-40 lattice to 2^-55.""" curves = paths() grid = {} for level in range(4, 13): step = U >> level first, last = 0, ceildiv(455*U, 1000*step) if example: # Only disks meeting the example's parameter range can be used. first = max(first, 66*U//(1000*step)-2) last = min(last, 67*U//(1000*step)+2) for j in range(first, last+1): if level > 10 and 1000*j*step > 36*U: break result = enclosure(curves, j*step, 2*step, 10) if result is None: continue a0, bounds, branches = result assert 0 < a0 <= 2*U assert all(0 <= lo and 0 < hi <= 8*U for lo, hi in bounds[3:]) assert all(v is None or (v[0] >= 0 and 0 <= v[1] <= 8*U) for v in branches[2:10]) child = tuple((lo << 15, hi << 15) for lo, hi in bounds) branch_disks = tuple((v[0] << 15, v[1] << 15) if v else (0, 0) for v in branches) grid[level, j] = a0 << 15, child, branch_disks if not grid: raise ArithmeticError('Empty table of moving boundaries') return grid # Conditional survival on the principal nest (multiple-regions proof, Section 2). def upper_exp(x): return CTX.next_plus(CTX.exp(x)) def ratio_bound(k): """Upper bound on the inverse Grötzsch modulus, in MASS units.""" if k == 0: return MASS u = min(D(1), CTX.next_plus(CTX.multiply(D(4), upper_exp(D(-2*k))))) for _ in range(4): num = CTX.next_plus(CTX.multiply(D(2), CTX.next_plus(CTX.sqrt(u)))) den = CTX.next_minus(CTX.add(D(1), u)) u = min(D(1), CTX.next_plus(CTX.divide(num, den))) num, den = CTX.next_plus(CTX.multiply(D(MASS), u)).as_integer_ratio() return min(MASS, ceildiv(num, den)) def geometric_tables(): ratios = [ratio_bound(k) for k in range(SIDE)] probabilities = [] thresholds = [] for k, ratio in enumerate(ratios): remaining = Fraction(MASS-ratio, MASS) tails = [remaining**cut for cut in CUTS] + [0] row = [int(MASS*(a-b)) for a, b in zip(tails, tails[1:])] assert min(row) >= 0 and sum(row) <= MASS probabilities.append(row) x = CTX.next_minus(CTX.exp(CTX.divide(D(-k), D(8)))) num, den = x.as_integer_ratio() thresholds.append(S*num//den) assert Fraction(4)*Fraction(upper_exp(D(-8))) < Fraction(1, 19) term = Fraction(upper_exp(D('-10.8'))) assert 64*term/(1-term) < Fraction(2, 1000) return ratios, probabilities, thresholds def survival_numpy(np, ratios, probabilities): """20 lower Bellman iterates. All int64 sums are at most MASS squared.""" ar = np.arange(SIDE, dtype=np.int64) ratio = np.asarray(ratios, dtype=np.int64) b, p = ar[None, :], ar[:, None] q = b*(MASS-ratio[p])//(MASS+ratio[p]) probs = np.asarray(probabilities, dtype=np.int64) # The array axes are (old phase, parameter, new phase). old = np.zeros((SIDE, SIDE, SIDE), dtype=np.int64) old[96:, 64:, 96:] = 99800000 transitions = [np.minimum(TOP, (2*b+cut*ar[:, None])//4) for cut in CUTS] for _ in range(20): total = np.zeros_like(old) for j, d in enumerate(transitions): total += probs[q, j] * old[b, q, d[:, None, :]] nxt = np.maximum(old, total//MASS) for axis in range(3): np.maximum.accumulate(nxt, axis=axis, out=nxt) old = nxt return array('I', old.ravel().tolist()) def survival_python(ratios, probabilities): """Same recurrence with arbitrary-precision integers and list indexing.""" # Factor through (b,q). All p giving the same q use the same child row. next_q = [[b*(MASS-r)//(MASS+r) for b in range(SIDE)] for r in ratios] reachable = [sorted({row[b] for row in next_q}) for b in range(SIDE)] choices = [[tuple(min(TOP, (2*b+cut*a)//4) for cut in CUTS) for a in range(SIDE)] for b in range(SIDE)] old = [[([0]*96 + [99800000]*(SIDE-96) if a >= 96 and p >= 64 else [0]*SIDE) for p in range(SIDE)] for a in range(SIDE)] for _ in range(20): nxt = [[row.copy() for row in ap] for ap in old] for b in range(SIDE): columns = {0: [0]*SIDE} for q in reachable[b]: child = old[b][q] if not child[-1]: columns[q] = columns[0] continue weights = probabilities[q] columns[q] = [sum(w*child[d] for w, d in zip(weights, indices))//MASS for indices in choices[b]] for p, qr in enumerate(next_q): column = columns[qr[b]] for a, val in enumerate(column): if val > nxt[a][p][b]: nxt[a][p][b] = val for a, ap in enumerate(nxt): for p, row in enumerate(ap): previous_a = nxt[a-1][p] if a else row previous_p = ap[p-1] if p else row prev = 0 for b, val in enumerate(row): prev = max(prev, previous_a[b], previous_p[b], val) row[b] = prev old = nxt return array('I', (x for ap in old for row in ap for x in row)) # Finite marked returns. A word records the signs of x[1], ..., x[n-1]. class Parent(NamedTuple): collar: int # P in the proof local: int # smaller parameter disk on which radii are combined outer_inner: int # inner radius of the enclosing puzzle piece inner: int # inner radius of its critical child outer: int # outer radius of the same child modulus: int # lower log modulus, in eighths class Orbit(NamedTuple): t: int x: list absolute: list error: list square_margin: list class Tile(NamedTuple): prefix: bool left: int low: int high: int band: int d0: int d1: int p1: int width: int bits: int times: tuple def dyadic(value): """Nearest tick, with exact halfway cases rounded away from zero.""" scaled = value*S n = int(scaled) fraction = scaled-n return n + (fraction >= 0.5) - (fraction <= -0.5) def sqrt_low(x): return math.isqrt(x << 55) def sqrt_high(x): return isqrt_up(x << 55) def alpha_interval(t): # Truncate the negative half towards zero, then add one tick on either side. radicand = 9*S-4*t return -((sqrt_high(radicand)-S)//2)-1, -((sqrt_low(radicand)-S)//2)+1 def inverse_guess(t, signs, n, target, centers=None): """Floating-point inverse and its parameter derivative, for proposals only.""" x, derivative = target, 0.0 const = 2-t for j in range(n-1, 0, -1): z = const+x if not 0 < z < 6: return None x = signs[j]*math.sqrt(z) derivative = (derivative-1)/(2*x) if centers is not None: centers[j] = dyadic(x) if math.isfinite(derivative): return x, derivative return None def solve_mark(t, signs, n, target): for _ in range(14): value = inverse_guess(t, signs, n, target) if value is None: return None x, derivative = value if derivative == 1: return None delta = (x+2-t)/(1-derivative) if not math.isfinite(delta) or abs(delta) > 0.04: return None t += delta if abs(delta) < 3e-16: break return t if 0 < t < 0.46 else None def marked_inverse(t, signs, n): x = [0]*(n+1) if inverse_guess(t/S, signs, n, 0.0, x) is None: return None errors, margins = [0]*(n+1), [0]*(n+1) c = t-2*S for j in range(1, n): square = x[j]*x[j] residual = abs(square+((c-x[j+1]) << 55)) errors[j] = (residual+S-1) >> 55 margins[j] = (square >> 55)-errors[j] return Orbit(t, x, list(map(abs, x)), errors, margins) def set_tile_tables(grid, thresholds): global BOUNDARY_GRID, NEGATIVE_LOG_THRESHOLDS BOUNDARY_GRID = grid NEGATIVE_LOG_THRESHOLDS = tuple(-x for x in thresholds) nearby_disks.cache_clear() parent_disks.cache_clear() branch_disks.cache_clear() def log_bin(num, den): """Greatest admissible log threshold: num * exp(-k/8) >= den.""" if num <= den or den <= 0: return 0 limit = ceildiv(den << 55, num) return max(0, bisect_right(NEGATIVE_LOG_THRESHOLDS, -limit)-1) @lru_cache(maxsize=None) def nearby_disks(cell): # Cell is on the finest (2^-12) boundary grid. The coarser grid indices # are constant throughout this interval. Preserve increasing (level,j). found = [] for level in range(4, 13): step = S >> level j0 = cell >> (12-level) for j in range(max(0, j0-2), j0+3): row = BOUNDARY_GRID.get((level, j)) if row is not None: found.append((2*step, j*step, row)) return found @lru_cache(maxsize=None) def parent_disks(cell, p): return [(spread, center, a0, child[p][0], child[p][1]) for spread, center, (a0, child, _) in nearby_disks(cell) if child[p][0]] @lru_cache(maxsize=None) def branch_disks(cell, k): return [(spread, center, br[k][0], br[k][1]) for spread, center, (_, _, br) in nearby_disks(cell) if br[k][1]] def initial_parent(t, p): if not 3 <= p <= 10: return None lo = hi = 0 al, ah = alpha_interval(t) c = t-2*S for j in range(1, p+1): near = max(0, lo, -hi) far = max(-lo, hi) lo, hi = (near*near >> 55)+c, ((far*far+S-1) >> 55)+c if (j == 1 and hi >= al) or (1 < j < p and lo <= -al): return None if lo <= ah or hi >= -ah: return None good = [] collar = 0 for spread, center, a0, inner, outer in parent_disks(t >> 43, p): room = spread-abs(t-center) if room > 0: good.append((room, a0, inner, outer)) if room > collar: collar = room if not collar: return None local = min(collar//8, S//1024) outer_inner = inner = 0 outer = 8*S for room, a0, a, big_a in good: if room >= local: outer_inner = max(outer_inner, a0) inner = max(inner, a) outer = min(outer, big_a) if not 0 < inner < outer: return None return Parent(collar, local, outer_inner, inner, outer, log_bin(outer_inner, outer)) def inverse_tube(orbit, n, target, spread, radii=None): """Enclose a chain of inverse disks and bound its spatial derivative.""" radius, derivative = target, S centers, errors, margins = orbit.absolute, orbit.error, orbit.square_margin isqrt = math.isqrt for j in range(n-1, 0, -1): gap = margins[j]-radius-spread if gap <= 0: return None center = centers[j] den = center+isqrt(gap << 55) radius = (((radius+spread+errors[j]) << 55)+den-1)//den den = 2*(center-radius) if den <= 0 or derivative > 12*den: return None if radii is not None: radii[j] = radius derivative = ((derivative << 55)+den-1)//den return radius, derivative def exact_inverse(t, signs, n, target): lo = hi = target constant = 2*S-t for j in range(n-1, 0, -1): if constant+lo <= 0: return None a, b = sqrt_low(constant+lo), sqrt_high(constant+hi) lo, hi = (a, b) if signs[j] > 0 else (-b, -a) return lo, hi def core_contains(t, signs, n, radius): a = exact_inverse(t, signs, n, -radius) b = exact_inverse(t, signs, n, radius) c = t-2*S return a is not None and b is not None and (a[1] < c < b[0] or b[1] < c < a[0]) def certified_core(t, signs, n, spread, radius): x = solve_mark(t/S, signs, n, radius/S) y = solve_mark(t/S, signs, n, -radius/S) if x is None or y is None: return None left, right = sorted((dyadic(x), dyadic(y))) width = right-left if width <= 16: return None middle = left+width//2 for j in range(12): inset = max(4, width >> max(1, 16-j)) lo, hi = left+inset, right-inset if not lo < middle < hi: return None if (abs(lo-t) < spread and abs(hi-t) < spread and core_contains(lo, signs, n, radius) and core_contains(hi, signs, n, radius)): return lo, hi-lo return None def next_piece(t, spread, signs, n, piece): orientation = math.prod(signs[1:n]) lo, hi = piece if orientation > 0 else (-piece[1], -piece[0]) a, b = 2*S-t-spread, 2*S-t+spread for j in range(n-1, 0, -1): if a+lo <= 0: return None l, h = sqrt_low(a+lo), sqrt_high(b+hi) lo, hi = (l, h) if signs[j] > 0 else (-h, -l) if a+lo <= 0: return None lo, hi = sqrt_low(a+lo), sqrt_high(b+hi) return (lo, hi) if lo > 0 else None def forward_error(orbit, n, spread, z): r = spread+((z*z+S-1) >> 55)+abs(orbit.x[1]-(orbit.t-2*S)) for j in range(1, n): if r >= 2*S: return 4*S r = ((r*(2*orbit.absolute[j]+r)+S-1) >> 55)+spread+orbit.error[j] return r def deeper_parent(orbit, signs, n, parent): collar = parent.local center = orbit.absolute[n] while collar >= 32 and center+forward_error(orbit, n, collar, 0) >= parent.inner: collar //= 2 if collar < 32: return None marked = marked_inverse(orbit.t, signs, n) if marked is None: return None local = collar//8 tube = inverse_tube(marked, n, parent.outer, local) if tube is None: return None radius, deriv = tube offset = abs(marked.x[1]-(orbit.t-2*S))+local image = center+forward_error(orbit, n, local, 0) sq = min(offset+radius, ((parent.outer+image)*deriv+S-1) >> 55) lo, hi = 0, parent.inner for _ in range(28): mid = lo+(hi-lo)//2 if center+forward_error(orbit, n, local, mid) < parent.inner: lo = mid else: hi = mid outer = sqrt_high(sq) if not 0 < lo < outer: return None return Parent(collar, local, parent.inner, lo, outer, log_bin(parent.inner, outer)) def enclosing_spread(orbit, n, target, limit): tube = inverse_tube(orbit, n, target, 0) if tube is None: return None shift = abs(orbit.x[1]-(orbit.t-2*S)) spread = max(16, tube[0]+shift+4) for _ in range(18): if spread > limit: return None tube = inverse_tube(orbit, n, target, spread) if tube is None: return None radius, derivative = tube if radius+shift < spread: return spread, radius+shift, derivative spread = max(spread+spread//4+4, radius+shift+8) return None def closed_tile(orbit, signs, times, parent): for n in times[1:-1]: parent = deeper_parent(orbit, signs, n, parent) if parent is None: return None t, n = orbit.t, times[-1] enclosed = enclosing_spread(orbit, n, parent.outer, parent.local) if enclosed is None: return None spread, offset, derivative = enclosed radii = [0]*(n+1) if inverse_tube(orbit, n, 0, spread, radii) is None: return None piece = -alpha_interval(t+spread)[1], -alpha_interval(t-spread)[0] for k, time in enumerate(times): if any(orbit.absolute[j]-radii[j] <= piece[1] for j in range(1, time)): return None if orbit.absolute[time]+radii[time] >= piece[0]: return None if k+1 < len(times): piece = next_piece(t, spread, signs, time, piece) if piece is None: return None sq = min(offset+spread, ((parent.outer+piece[1])*derivative+S-1) >> 55) radius = sqrt_high(sq) if not 0 < radius < parent.inner: return None return spread, piece[0], parent.modulus, log_bin(parent.inner, radius), log_bin(parent.collar, spread) def unfinished_tile(orbit, signs, times, parent): t = orbit.t p, n = times a = -alpha_interval(t)[1]/S k = 1 while k < p and n-k >= p and orbit.absolute[n-k]/S >= a: k += 1 early = n-k if k < 2 or k >= p or early < p: return None target, branch_radius = 9*S, 0 for spread, center, disk_center, disk_radius in branch_disks(t >> 43, k): if spread-abs(t-center) >= parent.local: trial = disk_radius+abs(orbit.x[early]-signs[early]*disk_center) if trial < target: target, branch_radius = trial, disk_radius if not branch_radius: return None enclosed = enclosing_spread(orbit, early, target, parent.local) if enclosed is None: return None spread, offset, derivative = enclosed radii = [0]*(n+1) if inverse_tube(orbit, n, 0, spread, radii) is None: return None base = -alpha_interval(t+spread)[1], -alpha_interval(t-spread)[0] central = next_piece(t, spread, signs, p, base) if central is None or any(orbit.absolute[j]-radii[j] <= central[1] for j in range(1, n)): return None if orbit.absolute[early]+radii[early] >= base[0]: return None if any(orbit.absolute[j]-radii[j] <= base[1] for j in range(early+1, n)): return None if signs[early+1] != -1 or any(sign < 0 for sign in signs[early+2:n]): return None radius = sqrt_high(min(offset+spread, (2*branch_radius*derivative+S-1) >> 55)) if not radius: return None sigma = ((parent.collar-spread) << 55)//(parent.collar+spread) d1 = min(TOP, log_bin(parent.inner, radius)+parent.modulus//2) p1 = min(TOP, log_bin(parent.collar, spread)+((parent.modulus*sigma*sigma) >> 110)) return spread, parent.outer_inner, parent.modulus, d1, p1 def certified_tiles(bits, times, hint): n = times[-1] signs = [0]+[1 if bits & (1 << j) else -1 for j in range(n-1)] proposed = solve_mark(hint, signs, n, 0.0) if proposed is None: return t = dyadic(proposed) orbit = marked_inverse(t, signs, n) if orbit is None: return parent = initial_parent(t, times[0]) if parent is None: return tests = (closed_tile, unfinished_tile) if len(times) == 2 else (closed_tile,) for test in tests: data = test(orbit, signs, times, parent) if data is None: continue spread, radius, d0, d1, p1 = data lo, hi = t-spread, t+spread band = bisect_right(BANDS, 1000*lo//S)-1 if not 0 <= band < len(BANDS)-1 or 1000*hi > S*BANDS[band+1]: continue core = certified_core(t, signs, n, spread, radius) if core is not None: left, width = core yield Tile(test is unfinished_tile, left, lo, hi, band, d0, d1, p1, width, bits, times) # Candidate search. Discovery only proposes words; certification is independent. # A key stores 61 sign bits and a sequence of return times in base 64. # All the times are positive and at most 62, so this encoding is one-to-one. SIGN_MASK = (1 << 62)-1 def unpack(key): code = key >> 62 times = [] while code: times.append(code & 63) code >>= 6 return key & SIGN_MASK, tuple(reversed(times)) def search_chunk(spec): resolution, start, stop, prefix = spec samples = 1 << resolution found = {} for s in range(start, stop): t = 0.455*(s+0.5)/samples c = t-2 a = (math.sqrt(9-4*t)-1)/2 if prefix: x, radius, p, threshold, bits = 0.0, 0.0, 0, 12, 0 for n in range(1, 49): x = x*x+c if abs(x) < a: if p == 0: p = n if not 3 <= p <= 10: break b = -a for _ in range(1, p): b = math.sqrt(2-t+b) if 2-t-b <= 0: break radius = math.sqrt(2-t-b) elif n >= threshold: key = (((p << 6) | n) << 62) | bits found.setdefault(key, t) threshold += 7 if abs(x) < radius: break if x > 0: bits |= 1 << (n-1) continue orbit, signs = [0.0]*63, [0]*63 x, bits = c, 0 for j in range(1, 63): orbit[j] = x if x > 0: signs[j] = 1 bits |= 1 << (j-1) else: signs[j] = -1 x = x*x+c radius, n, code = a, 0, 0 for depth in range(4): last, n = n, max(1, n) while n <= 62 and abs(orbit[n]) >= radius: n += 1 if n > 62 or (depth == 0 and not 3 <= n <= 10): break code = (code << 6) | n if depth and n > last: key = (code << 62) | (bits & ((1 << (n-1))-1)) found.setdefault(key, t) if depth == 3: break orientation = math.prod(signs[1:n]) # As in inverse_guess, only the marked inverse value is used here. y = orientation*radius const = 2-t for j in range(n-1, 0, -1): z = const+y if not 0 < z < 6: break y = signs[j]*math.sqrt(z) else: if y > c: radius = math.sqrt(y-c) continue break return found def worker_setup(grid, thresholds, weights): global SURVIVAL SURVIVAL = weights set_tile_tables(grid, thresholds) def positive_records(batch): records = [] for key, hint in batch: bits, times = unpack(key) for tile in certified_tiles(bits, times, hint): val = SURVIVAL[(tile.d0*SIDE+tile.p1)*SIDE+tile.d1] if val: records.append((tile.band, times[0], len(times), tile.prefix, tree_node(tile.low, tile.high, tile.band), tile.left, tile.width, val)) return len(batch), records def batches(items, size): it = iter(items) while True: group = list(islice(it, size)) if not group: return yield group def candidate_words(resolution, pool): # First occurrence on the closing grid takes precedence over the prefix # grid. Ordered chunk results give the same choice at every worker count. words = {} for prefix, power in ((False, resolution), (True, min(resolution, 20))): samples = 1 << power stride = 8192 tasks = ((power, s, min(s+stride, samples), prefix) for s in range(0, samples, stride)) chunks = pool.imap(search_chunk, tasks) if pool is not None else map(search_chunk, tasks) for chunk in chunks: for key, hint in chunk.items(): words.setdefault(key, hint) return words # Whole-tile lower bounds and the dyadic overlap calculation. TREE_HEIGHT = 6 LEAVES = 1 << TREE_HEIGHT VALUE_MASK = (1 << 27)-1 def leaf_index(x, band): lo, hi = BANDS[band:band+2] numerator = 1000*x-lo*S denominator = (hi-lo)*S if not 0 <= numerator <= denominator: raise ArithmeticError('Tile extends outside its parameter band') return min(LEAVES-1, (numerator << TREE_HEIGHT)//denominator) def tree_node(lo, hi, band): left, right = leaf_index(lo, band), leaf_index(hi, band) shift = (left ^ right).bit_length() return (LEAVES+left) >> shift class ActiveWeights: """Maximum of a multiset of interval weights at the current sweep point.""" def __init__(self): self.counts = {} self.heap = [] self.largest = 0 def change(self, val, start): count = self.counts.get(val, 0) if start: if not count: heappush(self.heap, -val) self.counts[val] = count+1 elif count == 1: del self.counts[val] elif count > 1: self.counts[val] = count-1 else: raise ArithmeticError('Unmatched interval endpoint') while self.heap and -self.heap[0] not in self.counts: heappop(self.heap) self.largest = -self.heap[0] if self.heap else 0 class Group: def __init__(self): self.events = [] self.deep = {depth: [0]*(2*LEAVES) for depth in (3, 4)} self.counts = [0]*4 def add(self, depth, prefix, node, left, width, val): assert 0 < val <= MASS <= VALUE_MASK and 1 <= node < 2*LEAVES and width > 0 self.counts[0 if prefix else depth-1] += 1 if depth > 2: self.deep[depth][node] += width*val return # Packed events keep millions of endpoints in bounded space. The # high bits are the coordinate, so an ordinary integer sort suffices. level = node.bit_length()-1 tag = (level << 29) | (int(prefix) << 28) | val self.events.append((left << 32) | (1 << 27) | tag) self.events.append(((left+width) << 32) | tag) def scores(self, band): full, closed = [0]*(2*LEAVES), [0]*(2*LEAVES) self.events.sort() band_lo, band_hi = BANDS[band:band+2] origin, denominator = S*band_lo, S*(band_hi-band_lo) # At level h use only events whose ENTIRE tile fits a level-h node. for h in range(TREE_HEIGHT+1): active = (ActiveWeights(), ActiveWeights()) last = 0 for event in self.events: if ((event >> 29) & 7) < h: continue x = event >> 32 if x > last: completed = active[0].largest upper_envelope = max(completed, active[1].largest) if upper_envelope: mid = (last+x)//2 pos = min(LEAVES-1, ((1000*mid-origin)*LEAVES)//denominator) node = (LEAVES+pos) >> (TREE_HEIGHT-h) full[node] += (x-last)*upper_envelope closed[node] += (x-last)*completed active[(event >> 28) & 1].change(event & VALUE_MASK, (event >> 27) & 1) last = x assert not any(s.counts for s in active) deep_rows = [row.copy() for row in self.deep.values()] for row in deep_rows: for node in range(LEAVES-1, 0, -1): row[node] += row[2*node]+row[2*node+1] for node in range(2*LEAVES-1, 0, -1): deep = max(row[node] for row in deep_rows) full[node] = max(full[node], deep) closed[node] = max(closed[node], deep) if node < LEAVES: full[node] = max(full[node], full[2*node]+full[2*node+1]) closed[node] = max(closed[node], closed[2*node]+closed[2*node+1]) return full[1], closed[1] def jacobian(low): rad = Fraction(9)-Fraction(4*low, 1000) upper_sqrt = CTX.next_plus(CTX.sqrt(CTX.divide(D(rad.numerator), D(rad.denominator)))) return Fraction(10**12//(2*Fraction(upper_sqrt)), 10**12) def decimal_lower(x, places=12): scale = 10**places units = int(x*scale) return f'{units//scale}.{units%scale:0{places}d}' def summarize(groups): bands, orders, counts = defaultdict(Fraction), defaultdict(Fraction), [0]*4 raw = completed = Fraction() for (band, order), group in sorted(groups.items()): full, closed = group.scores(band) assert 0 <= closed <= full t_length = Fraction(full, S*MASS) factor = jacobian(BANDS[band]) raw += t_length bands[band] += t_length*factor orders[order] += t_length*factor completed += Fraction(closed, S*MASS)*factor for j, count in enumerate(group.counts): counts[j] += count group.events.clear() print('t interval guaranteed logistic length (rounded down)') for j, (lo, hi) in enumerate(zip(BANDS, BANDS[1:])): print(f'{lo/1000:5.3f} to {hi/1000:5.3f} {decimal_lower(bands[j])}') print('Breakdown by initial ordinary return time:') for p in sorted(orders): print(f'{p:2d} {decimal_lower(orders[p])}') print('Positive-weight certificates (prefix / closing depth 2, 3, 4):', *counts) print('Nonhyperbolic length in c, rounded down:', decimal_lower(raw)) total = sum(orders.values(), Fraction()) print('Nonhyperbolic length in lambda, rounded down:', decimal_lower(total)) print('Exact rational lower bound in lambda:', total) return total, orders, completed down = Context(prec=70, rounding=ROUND_FLOOR) up = Context(prec=70, rounding=ROUND_CEILING) nearest = Context(prec=70, rounding=ROUND_HALF_EVEN) J, M = 4096, 10**12 # integer units of modulus and probability CAP, PARAMETER_CAP, PRECISION = 80, 32, 22 BRANCHES = range(3, 16) def sqrt_lo(x): return nearest.next_minus(nearest.sqrt(x)) def sqrt_hi(x): return nearest.next_plus(nearest.sqrt(x)) def ln_lo(x): return nearest.next_minus(nearest.ln(x)) def exp_hi(x): return nearest.next_plus(nearest.exp(x)) def integer_lo(x): return int(x.to_integral_value(rounding=ROUND_FLOOR)) def integer_hi(x): return int(x.to_integral_value(rounding=ROUND_CEILING)) def branch(m): # Bounds for B_t(w)=sqrt(2-t+w) along the positive inverse orbit. L, prod = D('-1.18'), D(1) for _ in range(m): L = sqrt_lo(down.add(D('1.96'), L)) prod = down.multiply(prod, down.add(D('1.98'), L)) R = up.divide(D('3.40'), down.multiply(D('2.6'), prod)) assert R < D('.04') a = down.subtract(D(1),up.multiply(D('1.05'),R)) L, ymin, zero, zero_upper = D('-1.18'), D(-1), D(0), D(0) den = diameter_den = difference_den = base_den = base_den_upper = D(1) credit = [] obstruction_denominator = D(1) for n in range(1,m+1): L = sqrt_lo(down.add(down.subtract(D(2), R), L)) ymin = sqrt_lo(down.add(down.subtract(D(2), R), ymin)) zero = sqrt_lo(down.add(down.subtract(D(2), R), zero)) zero_upper = sqrt_hi(up.add(D(2),zero_upper)) den = down.multiply(den, down.add(D('1.98'), L)) diameter_den = down.multiply(diameter_den,down.add(L,ymin)) difference_den = down.multiply(difference_den,down.add(L,zero)) base_den = down.multiply(base_den,down.add(D('1.98'),zero)) base_den_upper = up.multiply(base_den_upper,up.add(D(2),zero_upper)) shift = up.multiply(D('.68'),R) radius = sqrt_hi(up.add(shift, up.divide(D('3.40'), den))) modulus = ln_lo(down.divide(a, radius)) # Each sign of a simple branch has a smaller disk about a real center. H = down.subtract(down.divide(D('.48'),D(4**n)),shift) center2 = down.subtract(down.divide(D('1.98'),base_den_upper),shift) if H > 0 and center2 > 0: outside = down.subtract(a,sqrt_hi(up.divide(D('2.02'),base_den))) inner = up.divide(up.divide(D('1.5'),difference_den), down.add(sqrt_lo(center2),sqrt_lo(H))) if outside > inner: modulus = max(modulus, ln_lo(down.divide(outside,inner))) phase_units = max(0, integer_lo(down.multiply(D(4), modulus))) obstruction_denominator = up.multiply(obstruction_denominator, D('4.04')) T = min(D('.04'), down.divide(D('1.16'), obstruction_denominator)) parameter_units = 0 if T > R and phase_units and n >= 2: # The marked boundaries of both signs move over |t|= 30*J: return 1 # 4 exp(-30) < 10^-12 if p <= J//8: return M # Bound r(16p/J) by 4 exp(-16p/J), then undo four Landen transformations. exponent = up.divide(D(-16*p), D(J)) u = min(D(1), up.multiply(D(4), exp_hi(exponent))) for _ in range(4): u = min(D(1), up.divide(up.multiply(D(2), sqrt_hi(u)), down.add(D(1), u))) return min(M, integer_hi(up.multiply(D(M), u))) def schedule_weight(d_previous, d, p, first): weight = M for i in range(32): if i >= 6 and min(d_previous,d) >= 80*J and p >= 40*J: # Beyond this point eight returns are required at every level. # The infinite remaining loss is less than 10^-12. return weight*(M-1)//M L = first[i] if i < 3 else (5 if i < 6 else 8) r = inner_ratio(p) next_p = d*(M-r)//(M+r) hazard = inner_ratio(next_p) if hazard == M: return 0 weight = weight*(M-hazard)**L//M**L if weight == 0: return 0 d_previous, d, p = d, (2*d+L*d_previous)//4, next_p # Even a branch which missed the tail test contributes a safe zero. return 0 # Geometric lower bounds for the distribution of the first induced return. THRESHOLDS = (0,1,2,3,4,5,6,8,10,14,20,28,40,64) SCHEDULES = ((2,3,5),(3,3,5),(4,4,5),(6,3,5),(8,2,5),(3,4,5),(5,3,5), (10,2,5),(4,3,5),(3,2,5),(14,2,5)) def weight(d0, p1, phase_units, parameter_units): d1 = (d0 + phase_units*(J//4))//2 p1 += parameter_units*(J//4) r = inner_ratio(p1) p2 = d1*(M-r)//(M+r) hazard = inner_ratio(p2) previous, total = 0, 0 for j in THRESHOLDS: d2 = (2*d1+j*d0)//4 value = max(previous, *(schedule_weight(d1,d2,p2,s) for s in SCHEDULES)) # For any child with at least j excursions the same value is valid. total += (M-hazard)**j*(value-previous)//M**j previous = value return total def short_example(): """Independently locate an entire short interval with first return time 11.""" m, scale = 9, 1 << 58 lo, hi = 3*scale//(4*4**m), scale//4**m x = y = 0 for n in range(1,m+3): lower = min(abs(x),abs(y)) if x*y > 0 else 0 upper = max(abs(x),abs(y)) x,y = (lower**2//scale-2*scale+lo, (upper**2+scale-1)//scale-2*scale+hi) if n == 1: assert y < -scale elif n < m+2: assert x > scale else: assert -scale//2 < x and y < 3*scale//5 assert (3*scale//5+1)*(3*scale//5+1+scale) < (2*scale-hi)*scale d0,p1,_ = branch(m) assert min(d0,p1) >= 6*J # Use only r(p) <= 4 exp(-p) for this illustration. d_prev,d,p = 6*J,3*J,6*J retained = M def upper_r(a): exponent = up.divide(D(-a),D(J)) return min(M, integer_hi(up.multiply(D(4*M),exp_hi(exponent)))) for i,L in enumerate((4,4,4,5,5,5,8,8,8,8,8,8)): if i >= 6 and min(d_prev,d) >= 80*J and p >= 40*J: break r = upper_r(p) pn = d*(M-r)//(M+r) retained = retained*(M-upper_r(pn))**L//M**L d_prev,d,p = d,(2*d+L*d_prev)//4,pn else: raise ArithmeticError('Example did not enter the infinite-tail regime') assert retained*(M-1)//M > 33*M//100 sharp = schedule_weight(6*J,3*J,6*J,(4,4,4)) assert 3*sharp > M and sharp > 3376*M//10000 def endpoint_tail_checks(): # Both boundaries of the initial image annulus move over |t| < .2. # On this disk V^0 contains D(0,.7) and lies in D(0,1.75). # The following four inverse steps suffice for every m >= 3. L, den = D('-1.75'), D(1) for _ in range(4): L = sqrt_lo(down.add(D('1.8'), L)) den = down.multiply(den, down.add(D('1.9'), L)) assert up.add(D('.28'), up.divide(D('3.85'), den)) < D('.49') assert up.divide(up.multiply(D(64), exp_hi(D(-40))), down.subtract(D(1), exp_hi(D(-40)))) < D('1e-12') L1 = sqrt_lo(D('.46')) L2 = sqrt_lo(down.add(D('1.96'),L1)) den = down.multiply(down.add(D('1.98'),L1),down.add(D('1.98'),L2)) assert up.add(D('.04'),up.divide(D('3.52'),den)) < D('.9025') assert up.multiply(D(4),exp_hi(D(-30))) < D('1e-12') # Independent endpoint certificate. Its fixed parameter cells use scale 2^-58. E_UNIT = 1 << 58 def boundary_cut(t, strict): """Largest integer x >= 0 with x(x+unit) < (2*unit-t)*unit, or <=. Both sides are integers. Strict inequality subtracts one from the right side before the quadratic inequality is solved by an integer square root. """ return (math.isqrt(((9*E_UNIT-4*t) << 58)-4*strict)-E_UNIT)//2 def cell_score(tl, th, m, credits): """The score of one closed mesh cell. A negative score rejects the cell.""" unit = E_UNIT lower_c, upper_c = tl-2*unit, th-2*unit in_cut, out_cut = boundary_cut(th, True), boundary_cut(tl, False) lo = hi = elapsed = phase_score = param_score = 0 for n in range(1, m+3+64): if lo >= 0: near, far = lo, hi elif hi <= 0: near, far = -hi, -lo else: near, far = 0, max(-lo, hi) lo = (near*near >> 58)+lower_c hi = min(2*unit, ((far*far+unit-1) >> 58)+upper_c) inside = lo >= -in_cut and hi <= in_cut outside = lo > out_cut or hi < -out_cut if n < m+2: if not outside or (n >= 2 and lo <= 0): return -1 elif n == m+2: if not inside: return -1 else: elapsed += 1 if elapsed > m+1 or not (outside or inside): break if inside: assert elapsed >= 2 phase, param = credits[elapsed-2] phase_score = min(CAP, phase_score+phase) param_score = min(PARAMETER_CAP, param_score+param) elapsed = 0 if phase_score == CAP and param_score == PARAMETER_CAP: break return phase_score*(PARAMETER_CAP+1)+param_score def block_score(first, stop, width, m, credits): """Prove identical scalar decisions for a block, or request subdivision. ll,lu bound the *lower* endpoint of every individual orbit enclosure in the block; hl,hu bound its *upper* endpoint. Bounding each separately also permits proving that every cell stops at an uncertain comparison. """ tl, tr = first*width, (stop-1)*width unit = E_UNIT cl, cr = tl-2*unit, tr-2*unit in_min, in_max = boundary_cut(tr+width, True), boundary_cut(tl+width, True) out_min, out_max = boundary_cut(tr, False), boundary_cut(tl, False) ll = lu = hl = hu = elapsed = score = param_score = 0 for n in range(1, m+3+64): if ll >= 0: near_min, near_max, far_min, far_max = ll, lu, hl, hu elif hu <= 0: near_min, near_max, far_min, far_max = -hu, -hl, -lu, -ll else: near_min, near_max = max(0, ll, -hu), max(0, lu, -hl) far_min, far_max = max(0, hl, -lu), max(0, hu, -ll) ll = (near_min*near_min >> 58)+cl lu = (near_max*near_max >> 58)+cr hl = min(2*unit, ((far_min*far_min+unit-1) >> 58)+cl+width) hu = min(2*unit, ((far_max*far_max+unit-1) >> 58)+cr+width) all_in = ll >= -in_min and hu <= in_min all_out = ll > out_max or hu < -out_max no_in = lu < -in_max or hl > in_max no_out = lu <= out_min and hl >= -out_min if n < m+2: if no_out or (n >= 2 and lu <= 0): return -1 if not all_out or (n >= 2 and ll <= 0): return None elif n == m+2: if no_in: return -1 if not all_in: return None else: elapsed += 1 if elapsed > m+1 or (no_in and no_out): break if not (all_in or all_out): return None if all_in: assert elapsed >= 2 phase, par = credits[elapsed-2] score, param_score = min(CAP, score+phase), min(PARAMETER_CAP, param_score+par) elapsed = 0 if score == CAP and param_score == PARAMETER_CAP: break return score*(PARAMETER_CAP+1)+param_score def endpoint_python(m, width, credits, first, stop, counts): pending = [(first, stop)] while pending: l, h = pending.pop() if h-l <= 4: for j in range(l, h): s = cell_score(j*width, (j+1)*width, m, credits) if s >= 0: counts[s] += 1 continue s = block_score(l, h, width, m, credits) if s is None: mid = (l+h)//2 pending.extend(((l, mid), (mid, h))) elif s >= 0: counts[s] += h-l def endpoint_numpy(np, m, width, credits, first, stop, counts): """Exactly the scalar lattice recurrence in signed 64-bit vector lanes. Write x=h*2^29+l. Then floor(x^2/2^58) is h^2 + floor((2*h*l + floor(l^2/2^29))/2^29). The ceiling adds one exactly when l is nonzero. For x <= 2^59 all intermediates fit in 61 bits. This avoids a floating-point square. """ unit = E_UNIT mask = (1 << 29)-1 def square(x): h, l = x >> 29, x & mask return h*h+((2*h*l+((l*l) >> 29)) >> 29) phase = np.asarray([0, 0]+[x for x, _ in credits], dtype=np.int64) param = np.asarray([0, 0]+[x for _, x in credits], dtype=np.int64) t = np.arange(first, stop, dtype=np.int64)*width low_sq = high_sq = np.zeros(t.size, dtype=np.int64) status_count = (CAP+1)*(PARAMETER_CAP+1) def finish(scores): if scores.size: counts[:] += np.bincount(scores, minlength=status_count) for n in range(1, m+3+64): lo = np.maximum(-2*unit, low_sq-2*unit+t) hi = np.minimum(2*unit, high_sq-2*unit+t+width) near = np.maximum(0, np.maximum(lo, -hi)) far = np.maximum(-lo, hi) low_sq, far_floor = square(near), square(far) high_sq = far_floor+((far & mask) != 0) inside = far_floor+far < 2*unit-t-width outside = low_sq+((near & mask) != 0)+near > 2*unit-t if n <= m+2: keep = inside if n == m+2 else (outside & (lo > 0) if n >= 2 else outside) if not np.all(keep): t, low_sq, high_sq = t[keep], low_sq[keep], high_sq[keep] if not t.size: return if n == m+2: elapsed = np.zeros(t.size, dtype=np.int64) a = np.zeros_like(elapsed) b = np.zeros_like(elapsed) continue elapsed += 1 returning = inside & (elapsed <= m+1) if np.any(returning): times = elapsed[returning] assert np.all(times >= 2) a[returning] = np.minimum(CAP, a[returning]+phase[times]) b[returning] = np.minimum(PARAMETER_CAP, b[returning]+param[times]) elapsed[returning] = 0 keep = ((inside | outside) & (elapsed <= m+1) & ((a < CAP) | (b < PARAMETER_CAP))) if not np.all(keep): finish(a[~keep]*(PARAMETER_CAP+1)+b[~keep]) t, low_sq, high_sq = t[keep], low_sq[keep], high_sq[keep] a, b, elapsed = a[keep], b[keep], elapsed[keep] if not t.size: return finish(a*(PARAMETER_CAP+1)+b) def endpoint_chunk(task): m, start, stop, credits, use_numpy = task width = 1 << (58-2*m-PRECISION) size = (CAP+1)*(PARAMETER_CAP+1) if use_numpy: import numpy as np counts = np.zeros(size, dtype=np.int64) for first in range(start, stop, 32768): last = min(first+32768, stop) uniform = block_score(first, last, width, m, credits) if uniform is None: endpoint_numpy(np, m, width, credits, first, last, counts) elif uniform >= 0: counts[uniform] += last-first return m, counts.tolist() counts = [0]*size endpoint_python(m, width, credits, start, stop, counts) return m, counts def endpoint_contributions(pool, use_numpy): endpoint_tail_checks() short_example() data = {m: branch(m) for m in BRANCHES} counts = {m: [0]*((CAP+1)*(PARAMETER_CAP+1)) for m in data} start, stop, stride = 1 << (PRECISION-2), 2 << PRECISION, 1 << 18 tasks = ((m, j, min(j+stride, stop), v[2], use_numpy) for m, v in data.items() for j in range(start, stop, stride)) results = pool.imap_unordered(endpoint_chunk, tasks) if pool is not None else map(endpoint_chunk, tasks) for m, partial in results: for i, count in enumerate(partial): counts[m][i] += count endpoint = {} exact_sum = Fraction() for m, row in counts.items(): assert min(row) >= 0 and 0 < sum(row) <= stop-start d0, p1, _ = data[m] weighted = sum(count*weight(d0, p1, *divmod(i, PARAMETER_CAP+1)) for i, count in enumerate(row) if count) contribution = Fraction(weighted, 6*M*(1 << (2*m+PRECISION))) exact_sum += contribution # Match the downward per-order rounding used in the appendix. endpoint[m+2] = Fraction(int(M*contribution), M) assert exact_sum > Fraction(101324849, 10**12) return endpoint def verify_example(grid, thresholds, weights): itinerary = '-++--++-----+' bits = sum(1 << j for j, sign in enumerate(itinerary) if sign == '+') set_tile_tables(grid, thresholds) verified = [r for r in certified_tiles(bits, (4, 14), 0.066112) if not r.prefix] if len(verified) != 1: raise ArithmeticError('Expected one completed return for the example') tile = verified[0] core_l, core_h = Fraction('0.066100'), Fraction('0.066124') assert Fraction('0.066082') < Fraction(tile.low, S) assert Fraction(tile.high, S) < Fraction('0.066142') assert Fraction(tile.left, S) <= core_l < core_h <= Fraction(tile.left+tile.width, S) assert tile.d0 >= 12 and tile.d1 >= 27 and tile.p1 >= 48 val = weights[(tile.d0*SIDE+tile.p1)*SIDE+tile.d1] g = Group() g.add(2, False, tree_node(tile.low, tile.high, tile.band), tile.left, tile.width, val) assert g.scores(tile.band) == (tile.width*val, tile.width*val) fraction = Fraction(val, MASS) assert Fraction('0.26993889') <= fraction <= 1 length = fraction*(core_h-core_l)/6 assert length >= Fraction('0.00000107975556') print('First return times to successive critical pieces: 4, 14') print('Whole real tile lies in t = (0.066082, 0.066142).') print('Verified inner interval in t: [0.066100, 0.066124]') print('Phase, phase and parameter modulus lower bounds:', Fraction(tile.d0, 8), Fraction(tile.d1, 8), Fraction(tile.p1, 8)) print('Nonhyperbolic fraction of the whole tile, rounded down:', decimal_lower(fraction, 8)) print('Contribution in lambda, rounded down:', decimal_lower(length, 14)) return length def stage(message): print(message, file=sys.stderr, flush=True) def verify(quick=False, example=False, jobs=1, stdlib=False): if not __debug__: raise RuntimeError('Run without -O: the verifier uses assertions.') if jobs < 1 or (quick and example): raise ValueError('Invalid mode or worker count') np = None if not stdlib: try: import numpy as np except ImportError: pass stage('Computing the moving boundaries and the survival table.') grid = boundary_table(example) ratios, probs, thresholds = geometric_tables() weights = survival_python(ratios, probs) if np is None else survival_numpy(np, ratios, probs) if example: return verify_example(grid, thresholds, weights) worker_setup(grid, thresholds, weights) pool = None if jobs > 1: try: pool = multiprocessing.Pool(jobs, initializer=worker_setup, initargs=(grid, thresholds, weights)) except (OSError, RuntimeError): stage('Using the serial verifier because worker processes are unavailable.') try: stage('Searching the parameter grid for marked return itineraries.') words = candidate_words(17 if quick else 24, pool) stage(f'Checking {len(words):,} distinct itineraries with integer enclosures.') num_words = len(words) tasks = batches(words.items(), 256) results = pool.imap_unordered(positive_records, tasks) if pool is not None else map(positive_records, tasks) groups = defaultdict(Group) checked, next_percent = 0, 10 for batch_size, records in results: for band, order, depth, prefix, node, left, width, val in records: groups[band, order].add(depth, prefix, node, left, width, val) checked += batch_size if not quick and checked*100 >= num_words*next_percent: stage(f'Checked {next_percent}% of the marked itineraries.') next_percent += 10 assert checked == num_words del words stage('Combining whole-tile estimates and accounting for overlaps.') total, by_order, completed = summarize(groups) if quick: return total assert Fraction(4129469908, 10**12) < completed <= total print('New length from completed returns alone, rounded down:', decimal_lower(completed), flush=True) stage('Verifying the dyadic endpoint cells and their disjoint contributions.') earlier = endpoint_contributions(pool, np is not None) finally: if pool is not None: pool.terminate() pool.join() combined = sum(max(by_order.get(p, 0), earlier.get(p, 0)) for p in by_order.keys() | earlier.keys()) print('Additional disjoint endpoint contribution:', decimal_lower(combined-total)) print('Combined exact rational lower bound in lambda:', combined) print('Combined nonhyperbolic length, rounded down:', decimal_lower(combined)) upper_int = ceildiv((combined.denominator-combined.numerator)*10**12, combined.denominator) print('Combined hyperbolic length, rounded up:', decimal_lower(Fraction(upper_int, 10**12))) if combined <= Fraction(8384470711, 10**12): raise ArithmeticError('The recomputed result does not reach the published bound.') return combined if __name__ == '__main__': if not __debug__: raise SystemExit('Run Python without -O so that certificate assertions are checked.') parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) mode = parser.add_mutually_exclusive_group() mode.add_argument('--quick', action='store_true', help='use a smaller discovery grid') mode.add_argument('--example', action='store_true', help='verify the 4, 14 example') usable = len(os.sched_getaffinity(0)) if hasattr(os, 'sched_getaffinity') else (os.cpu_count() or 1) parser.add_argument('--jobs', type=int, default=min(8, usable), help='worker processes (1 runs serially)') parser.add_argument('--stdlib', action='store_true', help='use only the standard library') args = parser.parse_args() if args.jobs < 1: parser.error('--jobs must be positive') verify(args.quick, args.example, args.jobs, args.stdlib)