csbound.py
Checks: FLATTEN: The takeover depth grows as r^(3/2) theorem; property; rule; pattern; observation.
Cited on: FLATTEN.
To run it: save csbound.py, with bandend.py, bandscale.py, cstar_closed.py, dualtail.py, flatten.py, prunerr.py, rho_closed.py beside it; needs mpmath, numpy, sympy.
"""csbound.py -- the weighted Cauchy-Schwarz bound on N = ||Q_s c*||_1.
QUESTION. P = Q_s c*, coefficients p_k, k = 0..n, n = J + r - 1, centre
c = n/2; m = sum p_k^2, M2 = sum (k - c)^2 p_k^2, N = sum |p_k|. With
weight 1 + (k - c)^2/tau^2, Cauchy-Schwarz and sum 1/(1 + (k -
c)^2/tau^2) <= pi tau + 1 (the integral plus the peak) give, at tau^2 =
M2/m, N <= B = sqrt(2 m (pi tau + 1)), every ingredient in closed form.
Is B/N flat in r at every order, J at J*_s, 2 J*_s, 8 J*_s, r = 21..161?
BY HAND (before any engine code). (a) M2 in closed form. Pi(b) = (1 +
x)^(n - b) (1 - x)^b; D = x d/dx - c carries it to -(b/2) Pi(b - 1) -
((n - b)/2) Pi(b + 1), and on the circle <Pi(b), Pi(b')> = (-1)^(b + q)
4^n (1/2)_(n - q) (1/2)_q / n!, q = (b + b')/2. P = sum_k lam_k Pi(s +
2k), lam the closed weights of c*, so m and M2 = ||DP||^2 are quadratic
forms in lam over these values. (b) In the Gaussian limit M2/m ->
(J/4) rho^2, rho^2 = 2e + 1 + (2s + 4e + 3)/((4s - 2)(2s + 3)), e =
floor(d/2), the Gaussian int y^2 f^2 / int f^2 (the ARM below), and
B/N -> sqrt(2 pi rho int f^2)/int |f| at fixed (s, d). (c) N exactly: P = (1 + x)^M T / den,
deg T = D, n = M + D, so p_k = C(n, k) T~(k) / (n^(D) den), T~(k) =
sum_j
T_j k^(j) (n - k)^(D - j) in falling powers, an exact integer; N sums
C(n, k)|T~(k)| in floats over |k - c| <= sigma (2 sqrt r + 12), sigma =
sqrt(J)/2, the edge term of each side the window cuts printed against
the sum.
PREDICTIONS (frozen). (1) B/N at d = 2, J = J*_s: 1.43..1.45 over r =
21..161, flat. (2) At fixed (r, s) B/N falls toward its limit as J
grows,
d = 2 within 3% of 1.45 at 8 J*_s. (3) The largest ratio^(2/d) J*_s over
orders and T is d = 2's, about 1.45 J*; each d >= 3 under 1.3 J*.
KILL (frozen; what the script PRINTS). "KILL slope: d = 2 log-slope of
B/N in r over r = 21..161 at T = 1, 2, 8: a, b, c": KILLED iff the
largest is above 0.05. "KILL reach: largest ratio^(2/d) J*_s / max_s
J*_s over every order and T at r = 21..161: q (r, s, d, T)": KILLED iff
q > 2. Families: r = 21, 41, 61, 81, 101, 121, 161, every s <= r - 2,
J the even nearest T J*_s (at least r - 1), T = 1, 2, 8.
CONTROLS, read first. FORM: J*_s = 4 (max |He_(r-1) phi| / kappa_s)^(2/d),
kappa_s = int f^2 / int |f|, f = F phi the Gaussian limit of P's
coefficients, F = sum_k C(e, k) He_(s+2k) / (s + 3/2)_k, int |f| summed
over F's real zeros. By hand: at (s, d) = (1, 1) F = y, int |y| phi = 2,
int y^2 exp(-y^2) = sqrt(pi)/2, max |He_2 phi| = 1, J*_s = 64/pi; at
(0, 2) F = (2 y^2 + 1)/3 > 0, the integrals sqrt(2 pi) and 2
sqrt(pi)/3, J*_s = 6 sqrt 2; at (3, 1) F = y^3 - 3y, int |F| phi = 2 (1
+ 4 exp(-3/2)) by the antiderivative -He_2 phi, int F^2 exp(-y^2) = 15
sqrt(pi)/8, max |He_4 phi| = 3, J*_s = 1024 (1 + 4 exp(-3/2))^2 / (25
pi); at (1, 3), the one that reads beta_1 beside zeros, gamma at e = 1
and the exponent 2/d past 2, F = (2 y^3 - y)/5, zeros 0 and +-1/sqrt 2,
antiderivative -((2 y^2 + 3)/5) phi, int |F| phi = (16 exp(-1/4) -
6)/5, int F^2 exp(-y^2) = sqrt(pi)/5, J*_s = 4 (3 (16 exp(-1/4) -
6)/sqrt(pi))^(2/3): the four within 1e-40; and int |f| by the zeros
within 1e-7 of a plain grid that reads no zero, every order at r = 21
(the bar sits under the outermost zero's share at s = 19, d = 1).
ARM: rho^2's closed form against the exact
ratio on the Fourier side, int |G'|^2 / int |G|^2, G = w^s chi(w^2)
exp(-w^2/2) with chi f's Laguerre factor, every s + 2e up to the top
rank's s + 2e. POSITIVE: m and M2's closed forms against the
exact sums, the windowed N against the exact convolution, at r = 21,
every s, J the even nearest J*_s: m and M2 equal, N within 1e-12.
INSTRUMENT: B >= N at every cell. PLANT: M2 / 16 at one cell (r = 21,
d = 2, T = 1) quarters tau and puts B below N (halving it would not),
which the instrument must catch: plumbing, caught by construction.
Changed from the freeze: m is checked within 1e-9 in log (A by
lgamma), M2/m exactly; the plant tests the instrument at one cell, not
the slope at r = 61 (a slope moved by a plant reads nothing
of the kill's bar); the family is every order whose J*_s Form (below)
reaches: its float Hermite seeds fail to converge at many low orders
from r = 81 on (the unread orders printed), whose J*_s and reach are
unread; J at least r - 1; the edge check reads only a side the window
cuts, fixed after a first run that read an uncut end coefficient.
FINDINGS. "KILL slope: d = 2 log-slope of B/N in r over r = 21..161 at
T = 1, 2, 8: +0.0050, +0.0053, +0.0063: HOLDS". "KILL reach: largest
ratio^(2/d) J*_s / max_s J*_s over every order and T at r = 21..161:
1.4497 (r=121, s=118, d=2, T=1): HOLDS".
CONTROLS: FORM's four hand values within 8.55e-50, its zeros' int
|F| phi within 1.24e-08 of the grid's; with one zero dropped where F
has more than two, with gamma doubled, with max |He_(r-1) phi| read
at r - 3 and with beta_k's (s + 3/2)_k made (s + 5/2)_k it fails,
each in turn, the last by the (1, 3) value alone (the other three
pass it); the outermost zero dropped at s = 19, d = 1 alone moves
the grid's read to 1.75e-07, over the bar. M2/m's closed form equals the
exact sums' at every s, r =
21, m within 1e-9 in log (A by lgamma); the windowed N within
1.42e-13 in log of the convolution; the
plant reads B/N 0.7315, caught. INSTRUMENT: B >= N at all 813 cells,
the cut edges' largest share 6.85e-83. Orders read: every order at r =
21, 41, 61; 44, 39, 34, 34 of 80, 100, 120, 160 at r = 81, 101, 121,
161 (Form's seeds fail at 36, 61, 86, 126 orders, none above s = 36,
60, 86, 126; not an interval: s = 35 reads at r = 81).
(1) held: d = 2's B/N at J*_s is 1.4341, 1.4419, 1.4450, 1.4468,
1.4475, 1.4497, 1.4479 at r = 21..161. (2) half held: at fixed (r,
s) it
is lower at T = 8 than at T = 1 at d = 1, 2 (d = 2: 1.4286..1.4474 at
8 J*_s), not monotonically (d = 2 at r = 161 reads 1.4479, 1.4480,
1.4474; d = 3 at r = 21 1.4659, 1.4695, 1.4647), and higher at T = 8
at d = 8, r = 81 (1.6022, 1.6039), d = 8, r = 101 (1.5962, 1.5966)
and d = 39, r = 101 (1.7255, 1.7266); M2/(m J/4) at 8 J*_s, d = 2,
reads 3.0263 against
rho^2 3.0158 at r = 21 and 3.0053 against 3.0016 at r = 161. (3)
unread but for its top: the global reach's largest is d = 2's (per
rank and
per d the reach is not printed); B/N's largest per rank among the
orders read sits at large d, at r >= 81 the largest d read (1.7958
at r = 61, s = 1, d = 59, the largest over the
family read), where ratio^(2/d) is near 1. d = 1 reads 1.2471..1.2712,
d = 4 1.4880..1.5466.
So the weighted Cauchy-Schwarz loses at most 1.80 on N over the cells
read, flat in r at d = 2, and the reach ratio^(2/d) J*_s, a proxy
for the certifying depth (TRANSPLANT: the scaling of E, the dual
bound over H_ch over its limit, (J/J*_s)^(d/2) with B/N
read at T J*_s), is at most 1.4497 max_s J*_s: a pattern, seven
ranks, three depths an order.
Wall 170.2 s (four workers; J*_s by Form the bulk), peak 265.3 MB.
RUN RECORD. The bare run (BARE: r = 21, 41 in one process, the ARM to
s + 2e <= 39): 7/7 checks, "BARE KILL slope: ... over r = 21, 41 at T =
1, 2, 8: +0.0081, +0.0083, +0.0112: HOLDS", "BARE KILL reach: ... at r =
21, 41: 1.4419 (r=41, s=38, d=2, T=1): HOLDS"; 2.3 s, 37.1 MB. The
full family (the ARM to s + 2e <= 159, disagreements none) reprints
FINDINGS' two KILL values, 7/7 checks, 175.0 s (peak 264.8 MB at the
run before FORM's check entered). The
ARM fails at all 420 bare cells with rho^2's 4e + 3 made 4e + 5.
RUN: python csbound.py (the bare run). The full family, r = 21..161 on
four worker processes (about 180 s): python csbound.py full.
"""
import os
import sys
import time
from concurrent.futures import ProcessPoolExecutor
from fractions import Fraction
from math import ceil, comb, exp, lcm, lgamma, log, pi, sqrt
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import mpmath as mp # noqa: E402
import numpy as np # noqa: E402
from numpy.polynomial import hermite_e as HE # noqa: E402
from cstar_closed import weights # noqa: E402
mp.mp.dps = 50
FULL = (21, 41, 61, 81, 101, 121, 161)
BARE = (21, 41)
TS = (1, 2, 8)
CHECKS = []
class Serial:
"""The bare run's pool: one process, as a gate runs a suite."""
@staticmethod
def map(fn, items, chunksize=1):
return map(fn, items)
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def check(name, ok, detail=""):
CHECKS.append(bool(ok))
tail = f" ({detail})" if detail else ""
print(f" {'PASS' if ok else 'FAIL'} {name}{tail}", flush=True)
def even_near(x, lo):
return max(2 * round(x / 2), lo + (lo % 2))
def times_minus(a):
"""a (1 - x)."""
return [x - y for x, y in zip(a + [0], [0] + a)]
def times_plus(a):
"""a (1 + x)."""
return [x + y for x, y in zip(a + [0], [0] + a)]
def cofactor(r, s, J):
"""(integer R, den): Q_s c* = (1 + x)^(J+eps) (1 - x)^s R / den."""
d = r - 1 - s
e = d // 2
ws = weights(r, s, J)
den = lcm(*(w.denominator for w in ws))
R = [0] * (2 * e + 1)
for k, w in enumerate(ws):
p = [1]
for _ in range(2 * e - 2 * k):
p = times_plus(p)
for _ in range(2 * k):
p = times_minus(p)
iw = int(w * den)
for i, c in enumerate(p):
R[i] += iw * c
return R, den
def dfact(n):
"""(n - 1)!! at even n."""
out = mp.mpf(1)
for i in range(n - 1, 0, -2):
out *= i
return out
def he_list(n, x):
"""[He_0(x), ..., He_n(x)]."""
out = [mp.mpf(1), x]
for k in range(1, n):
out.append(x * out[k] - k * out[k - 1])
return out[:n + 1]
def he_eval(coef, h):
"""sum_m coef[m] He_m(x) from the list h of He_m(x)."""
return mp.fsum(c * h[m] for m, c in coef.items())
def lower(coef, h):
"""sum_m coef[m] He_(m-1)(x): the antiderivative's, -(He_(m-1) phi)'
= He_m phi."""
if coef.get(0, 0):
raise ValueError("He_(-1) is not a polynomial: m = 0 in the sum")
return mp.fsum(c * h[m - 1] for m, c in coef.items() if m)
class Form:
"""F = sum_k beta_k He_(s+2k), beta_k = C(e, k) / (s + 3/2)_k, at
(s, d), phi = exp(-y^2/2): its real zeros, I = int |F| phi, f2 = int
F^2 exp(-y^2), kappa_s = f2 / I and J*_s, at odd r = s + d + 1, where
max |He_(r-1) phi| is (r - 2)!!, at 0."""
def __init__(self, s, d):
self.s, self.d = s, d
e = d // 2
self.e = e
self.r = s + d + 1
h32 = mp.mpf(s) + mp.mpf(3) / 2
self.beta = [mp.binomial(e, k) / mp.rf(h32, k) for k in range(e + 1)]
self.F = {s + 2 * k: b for k, b in enumerate(self.beta)}
self.z = self.zeros()
gam = (2 ** s * dfact(2 * s) * mp.factorial(e) / mp.rf(h32, e))
self.f2 = mp.sqrt(mp.pi) * gam / 4 ** s
if not self.z:
if s != 0:
raise RuntimeError(f"no real zeros at s = {s}, d = {d}")
# F > 0: int F phi = sqrt(2 pi) beta_0, int He_m phi = 0, m >= 1
self.I = mp.sqrt(2 * mp.pi) * self.beta[0]
else:
tot = []
for z in self.z:
h = he_list(s + 2 * e, z)
ph = mp.exp(-z * z / 2)
dF = mp.fsum(c * m * h[m - 1] for m, c in self.F.items())
ep = 2 * mp.sign(dF) * ph
tot.append(ep * lower(self.F, h))
self.I = mp.fsum(tot)
self.kappa_s = self.f2 / self.I
def zeros(self):
s, deg = self.s, self.s + 2 * self.e
c = np.zeros(deg + 1)
for m, b in self.F.items():
c[m] = float(b)
roots = HE.hermeroots(c) if deg else np.array([])
seeds = [x.real for x in roots if abs(x.imag) < 1e-6]
out = []
for z0 in sorted(seeds):
# where Newton stalls short of 1e-40 it reruns 30 digits
# deeper: the sum cancels up to 15 digits at e near 30, and
# at 40 working digits the bar is the precision itself
for extra in (0, 30):
with mp.workdps(mp.mp.dps + extra):
z = mp.mpf(z0)
for _ in range(200):
h = he_list(deg, z)
f = he_eval(self.F, h)
g = mp.fsum(b * m * h[m - 1]
for m, b in self.F.items() if m)
dz = f / g
z -= dz
if abs(dz) < mp.mpf(10) ** -40:
break
else:
continue
break
else:
raise RuntimeError(f"no convergence at s = {s}")
out.append(+z)
gaps = [out[i + 1] - out[i] for i in range(len(out) - 1)]
if gaps and min(gaps) < mp.mpf(10) ** -10:
raise RuntimeError(f"two seeds met one zero at s = {s}")
return out
def grid_I(self, h=2e-4):
"""int |F| phi by the trapezoid on a plain grid (no zero read)."""
L = 2 * (self.s + 2 * self.e + 1) ** 0.5 + 12
y = np.arange(-L, L + h / 2, h)
coef = np.zeros(self.s + 2 * self.e + 1)
for m, b in self.F.items():
coef[m] = float(b)
v = np.abs(HE.hermeval(y, coef)) * np.exp(-y * y / 2)
return h * (np.sum(v) - (v[0] + v[-1]) / 2)
def jstar(self):
return 4 * (dfact(self.r - 1) / self.kappa_s) ** (mp.mpf(2) / self.d)
def forms(r, s, J):
"""(m / A, M2 / A) as Fractions, A = 4^n (1/2)_(n - s + 1)
(1/2)_(s - 1) / n! up to sign: the closed quadratic forms of (a)."""
d = r - 1 - s
e = d // 2
n = J + r - 1
lam = weights(r, s, J)
q0 = s - 1 if s >= 1 else 0
amp = {q0: Fraction(1)} # (1/2)_(n-q) (1/2)_q / A
for q in range(q0, s + 2 * e + 2):
amp[q + 1] = amp[q] * Fraction(2 * q + 1, 2 * n - 2 * q - 1)
def H(b, bp):
q = (b + bp) // 2
return (-1) ** ((b + q) % 2) * amp[q]
bs = [s + 2 * k for k in range(e + 1)]
m = sum(lam[j] * lam[k] * H(bs[j], bs[k])
for j in range(e + 1) for k in range(e + 1))
mu = {}
for k, b in enumerate(bs):
if b >= 1:
mu[b - 1] = mu.get(b - 1, 0) - lam[k] * Fraction(b, 2)
mu[b + 1] = mu.get(b + 1, 0) - lam[k] * Fraction(n - b, 2)
M2 = sum(mu[a] * mu[b] * H(a, b) for a in mu for b in mu)
return m, M2
def poly_T(r, s, J):
"""(T, den, M): P = (1 + x)^M T / den, T integer."""
d = r - 1 - s
R, den = cofactor(r, s, J)
for _ in range(s):
R = times_minus(R)
return R, den, J + d % 2
def l1_window(r, s, J):
"""(log N, edge share): N summed over the window of (c)."""
T, den, M = poly_T(r, s, J)
D = len(T) - 1
n = M + D
c = n / 2
W = ceil(sqrt(J) / 2 * (2 * sqrt(r) + 12))
lo, hi = max(0, int(c - W)), min(n, int(c + W) + 1)
lgn = lgamma(n + 1)
terms = []
for k in range(lo, hi + 1):
fk = [1] * (D + 1) # k^(j)
for j in range(1, D + 1):
fk[j] = fk[j - 1] * (k - j + 1)
gk = [1] * (D + 1) # (n - k)^(i)
for i in range(1, D + 1):
gk[i] = gk[i - 1] * (n - k - i + 1)
t = sum(T[j] * fk[j] * gk[D - j] for j in range(D + 1) if T[j])
if t:
terms.append(lgn - lgamma(k + 1) - lgamma(n - k + 1)
+ log(abs(t)))
else:
terms.append(None)
top = max(v for v in terms if v is not None)
tot = sum(exp(v - top) for v in terms if v is not None)
cut = [v for v, side in ((terms[0], lo > 0), (terms[-1], hi < n))
if side and v is not None] # only a side the window cut
edge = max((exp(v - top) for v in cut), default=0.0)
falling = 0.0
for i in range(D):
falling += log(n - i)
logN = top + log(tot) - falling - log(den)
return logN, edge / tot
def exact_m(r, s, J):
"""log m exactly: sum p_k^2 by the convolution (controls only)."""
T, den, M = poly_T(r, s, J)
base = [comb(M, i) for i in range(M + 1)]
p = [0] * (len(base) + len(T) - 1)
for i, x in enumerate(base):
for j, y in enumerate(T):
p[i + j] += x * y
n = len(p) - 1
m = Fraction(sum(x * x for x in p), den * den)
M2 = Fraction(sum((2 * k - n) ** 2 * x * x for k, x in enumerate(p)),
4 * den * den)
N = Fraction(sum(abs(x) for x in p), den)
return m, M2, N
def lgf(q):
q = Fraction(q)
return log(q.numerator) - log(q.denominator)
def cell(args):
"""(r, s, T, J, ratio B/N, edge, M2 / (m J / 4), wall)."""
r, s, T, js, plant = args
t0 = time.time()
J = even_near(T * js, r - 1)
mt, M2t = forms(r, s, J)
if plant:
M2t = M2t / 16
tau = sqrt(M2t / mt)
logN, edge = l1_window(r, s, J)
# log m from the exact closed m_s: m = mt * A, A from lgamma
n = J + r - 1
q0 = s - 1 if s >= 1 else 0
logA = (n * log(4) + lgamma(n - q0 + 0.5) + lgamma(q0 + 0.5)
- 2 * lgamma(0.5) - lgamma(n + 1))
logm = logA + lgf(mt)
logB = 0.5 * (log(2) + logm + log(pi * tau + 1))
return (r, s, T, J, exp(logB - logN), edge, float(M2t / mt) * 4 / J,
time.time() - t0)
def jstar_of(args):
"""(r, s, J*_s or None where Form's seeds do not converge)."""
r, s = args
try:
return r, s, float(Form(s, r - 1 - s).jstar())
except RuntimeError:
return r, s, None
def rho2(s, d):
e = d // 2
return 2 * e + 1 + Fraction(2 * s + 4 * e + 3, (4 * s - 2) * (2 * s + 3))
def rho2_fourier(s, e):
"""int y^2 f^2 / int f^2 exactly, on the Fourier side: G = h(w)
exp(-w^2/2), h = sum_n C(e, n) (-1)^n w^(s+2n) / (s + 3/2)_n, the
ratio int |G'|^2 / int |G|^2, int w^(2j) exp(-w^2) = Gamma(1/2)
(1/2)_j. In integers: h scaled by 2^e (s + 3/2)_e, (1/2)_j by
2^top, so h_n = C(e, n) (-1)^n 2^n prod_(n<=i<e) (2s + 3 + 2i)."""
h = {}
for n in range(e + 1):
c = comb(e, n) * (-1) ** n * 2 ** n
for i in range(n, e):
c *= 2 * s + 3 + 2 * i
h[s + 2 * n] = c
g = {} # h' - w h
for k, v in h.items():
if k:
g[k - 1] = g.get(k - 1, 0) + k * v
g[k + 1] = g.get(k + 1, 0) - v
top = s + 2 * e + 1
mom = [2 ** top] # 2^top (1/2)_j
for j in range(top):
mom.append(mom[-1] * (2 * j + 1) // 2)
def norm(poly):
return sum(x * y * mom[(a + b) // 2] for a, x in poly.items()
for b, y in poly.items())
return Fraction(norm(g), norm(h))
def slope(xs, ys):
lx = [log(x) for x in xs]
ly = [log(y) for y in ys]
mx, my = sum(lx) / len(lx), sum(ly) / len(ly)
return (sum((a - mx) * (b - my) for a, b in zip(lx, ly))
/ sum((a - mx) ** 2 for a in lx))
def main(ranks, tag):
t0 = time.time()
print("CONTROLS", flush=True)
top = max(ranks) - 2
bad = [(s, e) for s in range(top + 1) for e in range((top - s) // 2 + 1)
if rho2_fourier(s, e) != rho2(s, 2 * e)]
check(f"ARM: rho^2's closed form equals the Fourier side's exact ratio "
f"at every s + 2e <= {top}", not bad, f"disagreements {bad[:5]}")
r = 21
fr = {s: Form(s, r - 1 - s) for s in range(r - 1)}
pin = max(abs(Form(1, 1).jstar() - 64 / mp.pi),
abs(Form(0, 2).jstar() - 6 * mp.sqrt(2)),
abs(Form(3, 1).jstar() - 1024 * (1 + 4 * mp.exp(mp.mpf(-3) / 2))
** 2 / (25 * mp.pi)),
abs(Form(1, 3).jstar() - 4 * (3 * (16 * mp.exp(mp.mpf(-1) / 4)
- 6) / mp.sqrt(mp.pi))
** (mp.mpf(2) / 3)))
gap = max(abs(float(f.I) / f.grid_I() - 1) for f in fr.values())
check("FORM: J*_s by hand at (s, d) = (1, 1), (0, 2), (3, 1), (1, 3) "
"within 1e-40; int |F| phi by the zeros within 1e-7 of a plain "
"grid, every s at r = 21", pin < mp.mpf(10) ** -40 and gap < 1e-7,
f"pins within {float(pin):.2e}, grid within {gap:.2e}")
js = {s: float(fr[s].jstar()) for s in range(r - 1)}
bad_m, worst_n = [], 0.0
for s in range(r - 1):
J = even_near(js[s], r - 1)
mt, M2t = forms(r, s, J)
m, M2, N = exact_m(r, s, J)
if M2 / m != M2t / mt:
bad_m.append(s)
n = J + r - 1
q0 = s - 1 if s >= 1 else 0
logA = (n * log(4) + lgamma(n - q0 + 0.5) + lgamma(q0 + 0.5)
- 2 * lgamma(0.5) - lgamma(n + 1))
if abs(logA + lgf(mt) - lgf(m)) > 1e-9:
bad_m.append(("m", s))
logN, _ = l1_window(r, s, J)
worst_n = max(worst_n, abs(logN - lgf(N)))
check("POSITIVE: closed M2/m exact, m within 1e-9 in log, every s at r = 21",
not bad_m, f"disagreements {bad_m}")
check("POSITIVE: windowed N against the exact convolution, every s at "
"r = 21, within 1e-12 in log", worst_n < 1e-12,
f"largest |log N - log N_exact| {worst_n:.2e}")
pl = cell((21, 18, 1, js[18], True))
check("PLANT: M2 / 16 at r = 21, d = 2, T = 1 puts B below N",
pl[4] < 1, f"B/N {pl[4]:.4f}")
if not all(CHECKS):
print("CONTROL FAILED: nothing below is read.")
sys.exit(1)
tasks, jmax = [], {}
with (ProcessPoolExecutor(max_workers=4) if ranks == FULL
else Serial()) as pool:
got = list(pool.map(jstar_of, [(r, s) for r in ranks
for s in range(r - 1)], chunksize=1))
for r in ranks:
jsr = {s: v for rr, s, v in got if rr == r and v is not None}
unread = [s for rr, s, v in got if rr == r and v is None]
jmax[r] = (max(jsr.values()), jsr)
print(f" r = {r}: {len(jsr)} of {r - 1} orders read"
+ (f", unread s = {min(unread)}..{max(unread)} "
f"({len(unread)})" if unread else ""), flush=True)
for s in jsr:
for T in TS:
tasks.append((r, s, T, jsr[s], False))
tasks.sort(key=lambda t: -t[3] * t[2] * t[0])
rows = []
for row in pool.map(cell, tasks, chunksize=1):
rows.append(row)
print(f" {len(rows)} cells, {time.time() - t0:.1f} s", flush=True)
under = [(r, s, T, q) for r, s, T, J, q, *_ in rows if q < 1]
check("INSTRUMENT: B >= N at every cell", not under,
f"{len(rows)} cells, below at {under[:5]}")
edge = max(rw[5] for rw in rows)
check("INSTRUMENT: the window's edge terms below 1e-15 of N",
edge < 1e-15, f"largest share {edge:.2e}")
print("THE READ")
by = {(r, s, T): rw for rw in rows for r, s, T in [rw[:3]]}
for r in ranks:
s = r - 3
print(f" r = {r:3d}, d = 2: B/N " + ", ".join(
f"T={T}: {by[(r, s, T)][4]:.4f}" for T in TS)
+ f"; M2/(m J/4) at T=8 {by[(r, s, 8)][6]:.4f} against rho^2 "
f"{float(rho2(s, 2)):.4f}")
for d in (1, 3, 4, 8, r - 1 - min(jmax[r][1])):
s = r - 1 - d
print(f" d = {d:3d}: B/N " + ", ".join(
f"T={T}: {by[(r, s, T)][4]:.4f}" for T in TS))
hi = max((by[(r, s, T)][4], s, T) for s in jmax[r][1] for T in TS)
print(f" largest B/N {hi[0]:.4f} (s={hi[1]}, d={r - 1 - hi[1]}, "
f"T={hi[2]})")
named = ", ".join(str(r) for r in ranks)
sl = [slope(ranks, [by[(r, r - 3, T)][4] for r in ranks]) for T in TS]
print(f"{tag}KILL slope: d = 2 log-slope of B/N in r over r = {named} "
"at T = 1, 2, 8: " + ", ".join(f"{v:+.4f}" for v in sl)
+ f": {'KILLED' if max(sl) > 0.05 else 'HOLDS'}")
reach = max((by[(r, s, T)][4] ** (2 / (r - 1 - s)) * jmax[r][1][s]
/ jmax[r][0], r, s, r - 1 - s, T)
for r in ranks for s in jmax[r][1] for T in TS)
q, r, s, d, T = reach
print(f"{tag}KILL reach: largest ratio^(2/d) J*_s / max_s J*_s over "
f"every order read and T at r = {named}: {q:.4f} (r={r}, s={s}, "
f"d={d}, T={T})"
f": {'KILLED' if q > 2 else 'HOLDS'}")
walls = sorted(rw[7] for rw in rows)
print(f" cell walls: largest {walls[-1]:.1f} s, total {sum(walls):.1f} s")
print(f"{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")
sys.exit(0 if all(CHECKS) else 1)
if __name__ == "__main__":
arg = sys.argv[1:]
if not arg:
main(BARE, "BARE ")
elif arg == ["full"]:
main(FULL, "")
else:
sys.exit(__doc__)