""" phi.py -- is the continuum error of a slowly varying width profile the local functional Phi, a cell's error priced by its two widths against the width at its sum? QUESTION. The power cut sets P_n(p), cuts (i/n)^(1/(1-p)), i = 0..n, p < 1, give the interval near t a width proportional to t^p. Their continuum error E(n) (erring_zones.py's cont_error, overflow [1, 2)) settles as n grows at p = 0.25, 0.5 and 0.75, below the zone bound 1/(4(p+1)), the integral of (w(x) + w(y))/(4 w(x + y)) at w(t) = t^p. The zone bound charges a cell (a, b) the chance (w_a + w_b)/(4 w_d) that a cut splits a pair from the label of the cell's midpoint sum. Is the limit the cell's own expected error instead, cell by cell, the widths read locally? THE MODEL (derived by hand before any code). Near a point (x, y) of the triangle x, y > 0, x + y < 1 the cells have widths w(x), w(y) and the labels near x + y width w(x + y); on P_n(p), w(t) is proportional to t^p (dc/di = c^p/(n(1-p))). In units of w(x + y) put alpha = w(x)/w(x+y), beta = w(y)/w(x+y). The cell's sum S = U + V, U ~ U[0, alpha], V ~ U[0, beta], has the trapezoid law; the labels are the unit windows [u + k, u + k + 1), u the cell's offset. TRANSPLANT, to re-derive by the run: u uniform on [0, 1) as the cells vary (it fails at p = 0, where the grid's apex sits on a cut and the limit is 1/4). The cell errs its area times phi = 1 - E_u max_k P(S in the k-th window). phi in closed form. G(s) = P(s <= S < s + 1) is the trapezoid convolved with a unit box, symmetric and unimodal about c = (L - 1)/2, L = alpha + beta (a convolution of symmetric unimodal laws, Wintner). Over the lattice u + Z its largest value is at the point nearest c, so E_u max_k G(u + k) = Int_{c-1/2}^{c+1/2} G(s) ds, and for fixed S the s in [c - 1/2, c + 1/2] with s <= S < s + 1 fill a length (1 - |S - L/2|)_+. So phi(alpha, beta) = E min(1, |X + Y|), X ~ U[-alpha/2, alpha/2], Y ~ U[-beta/2, beta/2] independent. Where alpha + beta <= 2 the min is moot, and for alpha >= beta (a = alpha/2, b = beta/2, Z = X + Y flat 1/(2a) on |z| <= a - b, linear to 0 at a + b) E|Z| = 2[(a - b)^2/(4a) + b/2 - b^2/(6a)] = a/2 + b^2/(6a): phi(alpha, beta) = alpha/4 + beta^2/(12 alpha), alpha >= beta, alpha + beta <= 2. Checks by hand: phi(1, 1) = 1/3 (the triangle against cuts u, u + 1 errs 1/2 - u + u^2, mean 1/3); beta -> 0 gives alpha/4, one uniform against the grid; phi <= (alpha + beta)/4, the zone bound's integrand, equal only at beta = 0 (E min(1, |Z|) <= E|Z| <= E|X| + E|Y|). Phi_p. On P_n(p), alpha = (x/(x+y))^p, beta = (y/(x+y))^p, functions of u = x/(x + y) alone, and alpha + beta = u^p + (1-u)^p <= 2^(1-p) < 2. With x = su, y = s(1 - u) (Jacobian s, Int_0^1 s ds = 1/2) and the symmetry u <-> 1 - u: Phi_p = Int_{1/2}^1 [u^p/4 + (1 - u)^(2p)/(12 u^p)] du, its first term (1 - 2^(-(p+1)))/(4(p+1)). By hand: p -> 0+ gives 1/8 + 1/24 = 1/6, beside the grid's 1/4 at p = 0; at p = 1/2 the second term is (1/12)(4/3 - 5 sqrt2/6), so Phi_{1/2} = (5 - 2 sqrt2)/18 = 0.1206429; by series at p = 0.25, 0.115910 + 0.021590 = 0.137500, and at p = 0.75, 0.100385 + 0.008347 = 0.108732. The cells within O(1/n) of x + y = 1 (overflow), of the axes, or whose sum's grid is not one width across the trapezoid cost O(1/n) in all: the model's limit is Phi_p. Not blind: the limits were first read by the drop fit below, and a quadrature of Phi_p sat within 1e-5 of them before this freeze; the hand values above sit within 5e-6 of them. The run re-derives them; it does not copy. DESIGN. CTRL-phi phi's own control: a Monte Carlo of the trapezoid against 2*10^6 random offsets, each offset's window masses exact from the trapezoid's CDF, at (alpha, beta) = (1, 1), (0.8, 0.5), (0.3, 0.9), (1, 0.05), (0.6, 0.6), and past alpha + beta = 2, where E min(1, |X + Y|) is read by quadrature: (1.5, 1.2), (3, 0.5). Agreement within 4 standard errors at all seven. The PLANT: phi with 1/6 for 1/12 must miss at (1, 1), (0.8, 0.5), (0.3, 0.9) and (0.6, 0.6) (its excess beta^2/(12 alpha) is 0.083, 0.026, 0.0083 and 0.05 against standard errors under 3e-4). CTRL-Phi the quadrature of Phi_p at p = 1/2 against (5 - 2 sqrt2)/18 within 1e-9, and its first term against the closed form at the three p within 1e-9. C0 the reference, the drop fit (limit E(n3) - d2 rho/(1 - rho), d1 = E(n1) - E(n2), d2 = E(n2) - E(n3), rho = d2/d1, n doubling), is an instrument: on the grid p = 0 through cont_error, where E is 1/4 + 1/(4n), it must give 0.25 within 1e-6, and E its closed form within 1e-9 (the float sum). A p = 0.25, 0.5, 0.75: E(n) of P_n(p) at n = 1000, 2000, 4000, 8000, the fit's limit L from 2000..8000, and L' from 1000..4000: |L - L'| is the fit's spread, the kill's readability, owed below 2e-4 (a fifth of the bar). LOCAL print only, no verdict: p = 0.5, n = 1000, cell_errs binned in ten bins of u = x/(x + y) (cell corners), each bin's sum of cell errors over its sum of w_a w_b phi(w_a/w_d, w_b/w_d), w_d the width of the label holding the cell's midpoint sum (overflow cells, w_d = 1, kept out). OFFSETS p = 1/2: the corner offset (i^2 + j^2 - k^2)/(2k + 1), k^2 the cut below the corner sum, binned in tenths over the u-bins [0.3, 0.4) and [0.4, 0.5), at n = 1000 and 4000. HALF p = 1/2 past arm A, D(n) = n (E - Phi_{1/2}) at n = 1000 to 16000 doubling (32000 behind its flag), its steps and their ratios: a term c n^(-1/2) steps at ratio sqrt2, a limit below Phi_{1/2} at 2, a mix between, so the arm states no limit. Its controls: D(2000) at each p, and D(4000), D(8000) at p = 1/2, within 5e-5 of arm A's and B's prints; C0 the grid at 16000, D within 1e-3 of 1/4 (the instrument at the arm's size); HOLD p = 0.25 at 16000, D in [0.17, 0.19], the p said to hold. The float sum (C0's 2.3e-11 at 4e6 cells, linear in the cells at worst) leaves D within 2.4e-5 at 16000 and 1.9e-4 at 32000. KILL (frozen before the run): |Phi_p - L| above 1e-3 at any of the three p, L readable. A miss at one p alone names the offsets (the TRANSPLANT); a miss at all three names phi. PREDICTIONS. The kill misses: |Phi_p - L| under 5e-5 at all three, the script's Phi_p within 2e-5 of the hand values above. LOCAL's ratios within 0.03 of 1 in every bin but perhaps the two at the axes. A change from the first freeze: the limit is recomputed here, not read off an earlier run's record, and its spread L - L' is new. RUN. Bare: CTRL-phi, CTRL-Phi, C0 at n = 250 to 2000, the three p at n = 1000 and 2000 (B: Phi_p < E(n) < Phi_p + 1/(2n), checked), LOCAL. --full P [n1 n2 n3 n4]: arm A at one p, n to 8000 by default (P = 0 the grid, C0's fit at those n). --offsets: OFFSETS, its rows a block at a time. --half P [32000]: HALF at P = 0, 0.25 or 0.5, n to 16000, or to 32000. FINDINGS (entered after the run; every number is a print). CTRL-phi PASS: the Monte Carlo within 1 standard error of phi at all seven pairs (z from -0.99 to +0.16; (3, 0.5) errs 2/3 at every offset, se 0, so z is read as the difference, below 1e-12, a repair made after the first run printed z -1582); the quadrature of E min(1, |X + Y|) equals the closed form at the five pairs below alpha + beta = 2; the plant 1/6 is caught at all four pairs named (z -81 to -1581). CTRL-Phi PASS: Phi_{1/2} - (5 - 2 sqrt2)/18 = 1.4e-17; the first terms equal their closed form; Phi_p 0.1375007, 0.1206429, 0.1087323, off the hand values by 6.8e-7, 3.8e-8, 3.0e-7; Phi at p = 1e-9 0.166666667. C0 PASS: on the grid at n = 1000 to 8000 the fit read L - 1/4 = 1.4e-9 (spread 1.7e-9); the bare run's n = 250 to 2000 reads E off 1/4 + 1/(4n) by 2.3e-11 at most, L - 1/4 = +9.2e-11 (its first bar, 1e-12 on E, failed on the float sum; 1e-9 since). B PASS: n (E - Phi_p) 0.1863, 0.1874 (p = 0.25), 0.1889, 0.1638 (0.5), 0.4426, 0.4334 (0.75) at n = 1000, 2000, the digits arm A printed. KILL missed at all three p, readable: p L L' spread Phi_p - L 0.25 0.1375043 0.1374909 +1.3e-5 -3.63e-6 0.5 0.1206359 0.1206341 +1.7e-6 +7.08e-6 0.75 0.1087288 0.1087439 -1.5e-5 +3.45e-6 E(8000) sits above Phi_p by 2.25e-5, 1.08e-5, 5.42e-5: the cut sets near Phi_p from above. n (E - Phi_p) at n = 1000 to 8000 reads 0.1863, 0.1874, 0.1792, 0.1797 at p = 0.25 and 0.4426, 0.4334, 0.4368, 0.4336 at p = 0.75, flat: E = Phi_p + a/n there. At p = 0.5 it reads 0.1889, 0.1638, 0.1312, 0.0864, not flat, and Phi_p - L is four spreads, though the drops of E are near geometric (ratios 0.459, 0.448). By hand off these prints, n (E - Phi_p) steps -0.0251, -0.0326, -0.0448, step ratios 1.30 and 1.37: a term c n^(-1/2) steps at sqrt2, a limit below Phi_p plus a/n at 2, and a mix of the two between, so step ratios alone do not separate a limit at Phi_p from one below it; HALF reads past 8000. LOCAL every u-bin within 0.0020 of 1 (0.9980 to 1.0001), all kept cells 0.9996, no cell past alpha + beta = 2, overflow cells' error 2.33e-4. The two low bins, [0.3, 0.4) and [0.6, 0.7), are symmetric and hold u = 9/25 and 16/25, the (3, 4, 5) direction. OFFSETS over the bin [0.3, 0.4), in tenths: 1.276, 0.726, 1.276, 0.765, ... at n = 1000 and 1.140, 0.863, 1.138, 0.873, ... at n = 4000: the bin's pooled histogram is 5-periodic, its swing 0.554 then 0.280 (two n). By hand, v = m(3, 4) + t(1, 1) has |v| = 5m + 7t/5 + t^2/(250m) + ..., so offsets bunch near fifths while t^2 is below about 25m: a band of angular width near n^(-1/2) about the (3, 4, 5) direction, whose share of the bin is what shrinks (a print split by t is owed). [0.4, 0.5) reads 0.967 to 1.020 and 0.983 to 1.011, ten bins resolving period 1/5 only (its triples' periods 1/29 and finer are invisible), its top tenth drifting. Cells are kept by corner sum below 1 here, by midpoint sum in LOCAL (O(n) cells apart). HALF C0 PASS, D(16000) 0.24998 (E 0.250015623998 against 1/4 + 1/64000, the float sum 1.0e-9 off); HOLD PASS, D(16000) 0.18443; the records met within 4.1e-6. At p = 1/2, D reads 0.18889, 0.16378, 0.13124, 0.08644, 0.02273, -0.06864 at n = 1000 to 32000, steps -0.02511 to -0.09138, step ratios 1.296, 1.376, 1.422, 1.434: past sqrt2 and rising. E(32000) = 0.120640792362 sits below Phi_{1/2} = 0.120642937514 (CTRL-Phi's (5 - 2 sqrt2)/18), so Phi_{1/2} is no lower bound of E(n), and the limit is open: E fell at every n run, and a limit at Phi_{1/2} needs it to turn and rise past 32000. A first read (a lab run) froze a band, step ratio at most 1.55 for the n^(-1/2) term and at least 1.75 for a limit below, and printed the first; a mix of the two passes either, and no fit through three points fixes the limit (a + c sqrt n - delta n and a + c sqrt n + e n^(1/4) both meet 8000 to 32000). So at p = 0.25 and 0.75 the drop fit's limit is within 4e-6 of Phi_p, the cell's own expected error at a uniform offset, inside the fit's spread (1.3e-5, 1.5e-5); at p = 1/2 it sits four spreads below, the limit open. The zone bound's (alpha + beta)/4 overcharges by beta/4 - beta^2/(12 alpha). Peaks: the bare run 13.9 s, 192.3 MB; each --full p 59 to 77 s, 162 MB, four processes; --offsets 0.9 s, 108.5 MB (938 MB before its rows were blocked, the same prints); --half 0 and 0.25 241 s, 272 MB; --half 0.5 32000 855 s (570 s at 32000), 492 MB. """ import math import os import sys import time os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") import numpy as np # noqa: E402 from scipy.integrate import quad # noqa: E402 from erring_zones import cont_error, cell_errs # noqa: E402 CHECKS = [] NS = (1000, 2000, 4000, 8000) BARE = (1000, 2000) KILL, SPREAD = 1e-3, 2e-4 HAND = {0.25: 0.137500, 0.5: 0.1206429, 0.75: 0.108732} PAIRS = [(1, 1), (0.8, 0.5), (0.3, 0.9), (1, 0.05), (0.6, 0.6), (1.5, 1.2), (3, 0.5)] # HALF's rehearsal records: D(n) = n (E - ref), five places, as a first # (lab) run of this arm printed them; arm A and B print four D_REC = {0.0: {2000: 0.25}, 0.25: {2000: 0.18736}, 0.5: {2000: 0.16378, 4000: 0.13124, 8000: 0.08644}} 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 power_cuts(p, n): """P_n(p): cuts (i/n)^(1/(1-p)), i = 0..n, p < 1.""" e = 1 / (1 - p) return [(i / n) ** e for i in range(n + 1)] def phi_closed(a, b, twelve=12.0): """alpha/4 + beta^2/(12 alpha), alpha the larger; alpha + beta <= 2.""" hi, lo = max(a, b), min(a, b) return hi / 4 + lo * lo / (twelve * hi) def phi_general(a, b): """E min(1, |X + Y|), X ~ U[-a/2, a/2], Y ~ U[-b/2, b/2], by quad.""" A, B = max(a, b) / 2, min(a, b) / 2 def dens(z): return 1 / (2 * A) if z <= A - B else (A + B - z) / (4 * A * B) pts = [x for x in (A - B, 1.0) if x < A + B] val, _ = quad(lambda z: min(1.0, z) * dens(z), 0, A + B, points=pts or None, limit=200, epsabs=1e-13) return 2 * val def phi(a, b): return phi_closed(a, b) if a + b <= 2 else phi_general(a, b) def trap_cdf(s, a, b): """CDF of U[0, a] + U[0, b] at s (array).""" hi, lo = max(a, b), min(a, b) L = hi + lo s = np.clip(s, 0.0, L) return np.where(s <= lo, s * s / (2 * hi * lo), np.where(s <= hi, (2 * s - lo) / (2 * hi), 1 - (L - s) ** 2 / (2 * hi * lo))) def mc_phi(a, b, N, rng): """1 - the largest window's mass, over N uniform offsets: mean, se.""" u = rng.uniform(0, 1, N) best = np.zeros(N) for k in range(-1, int(math.ceil(a + b)) + 1): lo = u + k best = np.maximum(best, trap_cdf(lo + 1, a, b) - trap_cdf(lo, a, b)) e = 1 - best return float(e.mean()), float(e.std() / math.sqrt(N)) def Phi(p): """Int_{1/2}^1 u^p/4 + (1 - u)^(2p)/(12 u^p) du, and its first term.""" t1, _ = quad(lambda u: u ** p / 4, 0.5, 1, epsabs=1e-14) t2, _ = quad(lambda u: 1 / (12 * u ** p), 0.5, 1, weight="alg", wvar=(0, 2 * p), epsabs=1e-14) return t1 + t2, t1 def fit(E, n1, n2, n3): """The drop fit: E(n3) - d2 rho/(1 - rho), rho = d2/d1.""" d1, d2 = E[n1] - E[n2], E[n2] - E[n3] rho = d2 / d1 return E[n3] - d2 * rho / (1 - rho), rho def section_controls(): print("CTRL-phi: Monte Carlo over 2e6 offsets, exact window masses") rng = np.random.default_rng(2036) zs = [] for a, b in PAIRS: m, se = mc_phi(a, b, 2_000_000, rng) f = phi(a, b) # a pair whose every offset errs alike, (3, 0.5), has se 0 z = (m - f) / se if se > 1e-12 else (0.0 if abs(m - f) < 1e-12 else math.inf) zs.append(z) line = (f" ({a}, {b}): MC {m:.6f} +- {se:.1e} phi {f:.6f} " f"z {z:+.2f}") if a + b <= 2: g = phi_general(a, b) zp = (m - phi_closed(a, b, twelve=6.0)) / se line += f" (quad {g:.6f}; PLANT 1/6: z {zp:+.1f})" print(line) check("CTRL-phi: the Monte Carlo within 4 se of phi at all seven pairs", all(abs(z) < 4 for z in zs), f"largest |z| {max(abs(z) for z in zs):.2f}") quads = [abs(phi_general(a, b) - phi_closed(a, b)) for a, b in PAIRS if a + b <= 2] check("CTRL-phi: the quadrature equals the closed form below " "alpha + beta = 2", max(quads) < 1e-9, f"largest difference {max(quads):.1e}") caught = 0 for a, b in [(1, 1), (0.8, 0.5), (0.3, 0.9), (0.6, 0.6)]: m, se = mc_phi(a, b, 2_000_000, rng) caught += abs(m - phi_closed(a, b, twelve=6.0)) / se >= 4 check("PLANT: phi with 1/6 for 1/12 caught at the four pairs", caught == 4, f"{caught} of 4") print("CTRL-Phi: quadrature") v, _ = Phi(0.5) exact = (5 - 2 * math.sqrt(2)) / 18 print(f" Phi_1/2 {v:.12f} (5 - 2 sqrt2)/18 {exact:.12f} " f"diff {v - exact:.1e}") firsts = [] for p in HAND: v, t1 = Phi(p) closed = (1 - 2 ** (-(p + 1))) / (4 * (p + 1)) firsts.append(abs(t1 - closed)) print(f" p {p}: first term {t1:.12f} closed {closed:.12f}; " f"Phi_p {v:.7f} hand {HAND[p]:.7f} diff {v - HAND[p]:+.1e}") check("CTRL-Phi: Phi_1/2 is (5 - 2 sqrt2)/18 and the first terms their " "closed form, within 1e-9", abs(Phi(0.5)[0] - exact) < 1e-9 and max(firsts) < 1e-9) v0, _ = Phi(1e-9) print(f" Phi at p = 1e-9: {v0:.9f} (1/6 = {1 / 6:.9f})") print("C0: the drop fit on the grid p = 0") E = {n: cont_error(power_cuts(0, n)) for n in (250, 500, 1000, 2000)} off = max(abs(E[n] - (0.25 + 0.25 / n)) for n in E) L, _ = fit(E, 500, 1000, 2000) L1, _ = fit(E, 250, 500, 1000) check("C0: the grid errs 1/4 + 1/(4n) within 1e-9 and the fit reads 1/4 " "within 1e-6", off < 1e-9 and abs(L - 0.25) < 1e-6, f"E off 1/4 + 1/(4n) by {off:.1e} at most; L - 1/4 = " f"{L - 0.25:+.1e}, spread {L - L1:+.1e}") def family(p, ns): E = {} for n in ns: t = time.time() E[n] = cont_error(power_cuts(p, n)) print(f" p {p} n {n}: E {E[n]:.9f} ({time.time() - t:.1f} s)", flush=True) return E def section_bare(): """B: E(n) - Phi_p at n = 1000 and 2000, the three p.""" print("B: the power cut sets against Phi_p at n = 1000, 2000") D = [] for p in HAND: v, _ = Phi(p) E = family(p, BARE) d = [n * (E[n] - v) for n in BARE] D += d print(f" p {p}: Phi_p {v:.7f}; n (E - Phi_p) " + ", ".join(f"{x:.4f}" for x in d)) check("B: Phi_p < E(n) < Phi_p + 1/(2n) at the three p, n = 1000, 2000", all(0 < x < 0.5 for x in D), f"n (E - Phi_p) from {min(D):.4f} to {max(D):.4f}") def section_full(p, ns=NS): """A: the drop fit's limit at one p, n to 8000, against the kill; at p = 0, C0's fit on the grid at the same n.""" E = family(p, ns) n1, n2, n3, n4 = ns L, rho = fit(E, n2, n3, n4) L1, rho1 = fit(E, n1, n2, n3) print(f" p {p}: limit L {L:.7f} (rho {rho:.3f}), L' {L1:.7f} " f"(rho {rho1:.3f}), spread {L - L1:+.1e}") if p == 0: off = max(abs(E[n] - (0.25 + 0.25 / n)) for n in ns) check(f"C0 the grid at n = {n1}..{n4}: E within 1e-9 of 1/4 + " "1/(4n), the fit 1/4 within 1e-6", off < 1e-9 and abs(L - 0.25) < 1e-6, f"E off by {off:.1e} at most; L - 1/4 = {L - 0.25:+.1e}") return v, _ = Phi(p) print(f" p {p}: n (E - Phi_p) " + ", ".join(f"{n * (E[n] - v):.4f}" for n in ns) + f" at n = {', '.join(map(str, ns))}") readable = abs(L - L1) < SPREAD d = v - L verdict = ("UNREADABLE" if not readable else "KILL FIRES" if abs(d) > KILL else "kill missed") print(f"A p {p}: Phi_p {v:.7f} L {L:.7f} Phi_p - L {d:+.2e} " f"(E({n4}) - Phi_p {E[n4] - v:+.2e}) -> {verdict}") check(f"A p {p}: the fit readable and within {KILL} of Phi_p", readable and abs(d) <= KILL) def section_local(p=0.5, n=1000): cuts = power_cuts(p, n) C = np.asarray(cuts) A, W = C[:-1], np.diff(C) t = time.time() err = cell_errs(cuts) mid = A + W / 2 sig = mid[:, None] + mid[None, :] keep = sig < 1 d = np.clip(np.searchsorted(C, sig, side="right") - 1, 0, len(W) - 1) wd = W[d] al, be = W[:, None] / wd, W[None, :] / wd hi, lo = np.maximum(al, be), np.minimum(al, be) ph = hi / 4 + lo * lo / (12 * hi) wide = keep & (al + be > 2) for i, j in zip(*np.nonzero(wide)): ph[i, j] = phi_general(al[i, j], be[i, j]) pred = W[:, None] * W[None, :] * ph u = A[:, None] / np.maximum(A[:, None] + A[None, :], 1e-300) print(f"LOCAL p {p} n {n} ({time.time() - t:.1f} s; {int(wide.sum())} " f"cells past alpha + beta = 2): error / model by u-bin") for k in range(10): sel = keep & (u >= k / 10) & (u < (k + 1) / 10 + (k == 9)) print(f" u [{k / 10:.1f}, {(k + 1) / 10:.1f}): " f"{err[sel].sum() / pred[sel].sum():.4f} " f"({int(sel.sum())} cells)") print(f" all kept cells: {err[keep].sum() / pred[keep].sum():.4f}; " f"overflow cells' error {err[~keep].sum():.2e}") def section_offsets(rows=250): """p = 1/2: the corner sum (i^2 + j^2)/n^2 against the cut k^2/n^2 below it, as a fraction of that label's width, binned in tenths, the rows i taken a block at a time.""" for n in (1000, 4000): hist = {lo: np.zeros(10) for lo in (0.3, 0.4)} j = np.arange(1, n, dtype=np.int64) for i0 in range(1, n, rows): i = np.arange(i0, min(i0 + rows, n), dtype=np.int64)[:, None] S = i * i + j[None, :] * j[None, :] keep = S < n * n k = np.floor(np.sqrt(S)).astype(np.int64) k -= k * k > S k += (k + 1) * (k + 1) <= S off = (S - k * k) / (2 * k + 1) u = i * i / S for lo in hist: sel = keep & (u >= lo) & (u < lo + 0.1) hist[lo] += np.histogram(off[sel], bins=10, range=(0, 1))[0] for lo, h in hist.items(): print(f"OFFSETS n {n} u [{lo:.1f}, {lo + 0.1:.1f}): " + " ".join(f"{x:.3f}" for x in h * 10 / h.sum())) def section_half(p, top): """HALF at one p: D(n) = n (E - ref), ref 1/4 on the grid and Phi_p else, the rehearsal at 2000 against its record; at p = 1/2 every n doubling from 1000 to top, its steps and their ratios.""" ref = 0.25 if p == 0 else Phi(p)[0] ns = [2000, top] if p != 0.5 else [1000 * 2 ** k for k in range( int(math.log2(top // 1000)) + 1)] D = {} for n in ns: t = time.time() E = cont_error(power_cuts(p, n)) D[n] = n * (E - ref) print(f" p {p} n {n}: E {E:.12f} D {D[n]:.5f} " f"({time.time() - t:.1f} s)", flush=True) known = {n: v for n, v in D_REC[p].items() if n in D} off = max(abs(D[n] - v) for n, v in known.items()) check(f"HALF p {p}: D at n = {', '.join(map(str, known))} within 5e-5 " "of the record", off < 5e-5, f"largest difference {off:.1e}") if p == 0: check(f"HALF C0 the grid: D({top}) within 1e-3 of 1/4", abs(D[top] - 0.25) < 1e-3, f"{D[top]:.5f}") elif p == 0.25: check(f"HALF HOLD p 0.25: D({top}) in [0.17, 0.19]", 0.17 <= D[top] <= 0.19, f"{D[top]:.5f}") else: steps = [D[b] - D[a] for a, b in zip(ns, ns[1:])] print(" steps " + ", ".join(f"{s:.5f}" for s in steps)) print(" step ratios " + ", ".join( f"{b / a:.3f}" for a, b in zip(steps, steps[1:])) + f" (sqrt2 {math.sqrt(2):.3f})") print(f" D({top}) {'negative: E below' if D[top] < 0 else 'positive: E above'}" " Phi_1/2") def full_args(args): """--full P [n1 n2 n3 n4]: P in [0, 1), the n doubling; else None.""" try: p = float(args[0]) ns = tuple(int(x) for x in args[1:]) or NS except ValueError: return None ok = (0 <= p < 1 and len(ns) == 4 and ns[0] >= 2 and all(b == 2 * a for a, b in zip(ns, ns[1:]))) return (p, ns) if ok else None def main(): args = sys.argv[1:] full = (full_args(args[1:]) if args[:1] == ["--full"] and len(args) in (2, 6) else None) if full: section_full(*full) elif args == ["--offsets"]: section_offsets() return elif (args[:1] == ["--half"] and len(args) in (2, 3) and args[1] in ("0", "0.25", "0.5") and args[2:] in ([], ["32000"])): section_half(float(args[1]), int((args[2:] or ["16000"])[0])) elif args: print("usage: phi.py [--full P [n1 n2 n3 n4] | --offsets | " "--half 0|0.25|0.5 [32000]], 0 <= P < 1, each n twice the " "last") raise SystemExit(2) else: section_controls() if not all(CHECKS): print("\nCONTROL FAILED: nothing below is read.") raise SystemExit(1) section_bare() section_local() print(f"{sum(CHECKS)}/{len(CHECKS)} checks passed") raise SystemExit(0 if all(CHECKS) else 1) if __name__ == "__main__": main()