kfactor.py

Checks: FLATTEN: The takeover depth grows as r^(3/2) theorem; property; rule; pattern; observation.

Cited on: FLATTEN.

To run it: save kfactor.py, with bandend.py, bandscale.py, certclosed.py, csbound.py, cstar_closed.py, dualtail.py, flatten.py, prunerr.py, rho_closed.py beside it; needs mpmath, numpy, sympy.

"""kfactor.py -- the leading-order root of the closed certificate,
J^B_s ~ K_s^(2/d).

QUESTION. Lambda_s(J) = log m_s - log 2 - log(pi tau + 1) - 2 log I_r(J)
(certclosed.py). By Stirling at fixed (r, s), Lambda_s ~ d log J - log
K_s^2, log K_s^2 = (3r - 2) log 2 + 2 log Gamma(r/2) + log rho - log
gamma - (1/2) log pi. Does max_s K_s^(2/d) grow as r^(3/2)?

BY HAND, PREDICTIONS, KILL and CONTROLS: frozen before this file's
code, copied here. As r -> oo at fixed d, K_s^(2/d) = 4
(2^(3/2) sqrt(pi) rho / e!)^(1/d) r^(1 + e/d) (1 + O(1/r)): 11.787
r^(3/2) at d = 2, 6.155 at d = 4. PREDICTIONS. (1) The max over s is
d = 2's at every r read. (2) d = 2's K^(2/d)/r^(3/2) within 1% of
11.787 at r = 10^4. (3) J^B / max_s K_s^(2/d) at certclosed's twelve
ranks tends to 1, above 0.98 at 401. (4) d = 4's over d = 2's within
3% of 0.522 at r = 10^4. KILL: "KILL route: log-slope of max_s
K_s^(2/d)/r^(3/2) over r = 1001, 2001, 5001, 10001: a": KILLED iff a >
0.05; every s <= r - 2, odd r and r + 1 both read. CONTROLS: POSITIVE,
Lambda_s(J) - (d log J - log K_s^2) in mpmath at J = 10^4, 10^6, 10^8
falls toward 0, below 10^-3 at 10^8, at (r, s) = (21, 18), (41, 37);
PLANT, rho = 1 moves d = 2's limit to 2^(11/4) pi^(1/4) = 9.0.

FINDINGS. "KILL route: log-slope of max_s K_s^(2/d)/r^(3/2) over r =
1001, 2001, 5001, 10001: +0.0011: HOLDS".
  CONTROLS: the gap Lambda - (d log J - log K^2) reads -1.541e-03,
  -3.454e-04, -3.645e-05 at (21, 18) and +6.014e-04, -3.244e-04,
  -3.628e-05 at (41, 37), J = 1e4, 1e6, 1e8; the plant reads 8.9536.
  (1) held: d = 2's is the max at every r read, odd and even, d = 4
  next, then 3 (r <= 42) or 6. (2) held: d = 2's K^(2/d)/r^1.5 rises
  10.2543 (r = 21), 11.7050 (401), 11.7836 (10001), 0.9997 of 11.787,
  from below at every r read; r + 1 reads within 0.07 of r. (3) held:
  J^B_s / K_s^(2/d) at d = 2 is 0.9951, 0.9965, 0.9969, 0.9972, 0.9974,
  0.9975, 0.9978, 0.9980, 0.9982, 0.9983, 0.9984, 0.9985 at the twelve
  ranks, rising; at d = 4 0.9818 to 0.9962. (4) held: d = 4 over d = 2
  0.5221 at 10001.
  So J^B ~ 11.787 r^(3/2) is the reading: the leading-order root sits
  0.15% above the closed certificate's at r = 401, both below 11.787
  r^(3/2) at every rank read. The corrections are bounded uniformly in
  s, and no step inequality is needed, by ebound.py's LEMMA E: with
  LEMMA K below, J^B <= ceil(12 r^(3/2)) at every r >= 9.
  LEMMA K, by hand after the run (its check added then, not frozen):
  K_s^2 <= 2^(2d + 3/2) sqrt(pi) rho r^(d + e) / e! at every r and s
  <= r - 2. By duplication K_s^2 = 2^(2d + 1) sqrt(pi) rho
  Gamma(r)/Gamma(s + 1/2) (s + 3/2)_e / e! Gamma(r/2)/Gamma((r + 1)/2);
  Gamma(r)/Gamma(r - 1/2) <= (r - 1/2)^(1/2) (Wendel), the d further
  factors r - 3/2, .., r - d - 1/2 each below r, (s + 3/2)_e <= (r -
  1)^e, Gamma(r/2)/Gamma((r + 1)/2) < (2/(r - 1/2))^(1/2) (Watson). So
  max_s K_s^(2/d) is at most 4 (2^(3/2) sqrt(pi) rho / e!)^(1/d) r^(1 +
  e/d) maximised over d. That d = 2's, 11.787 (rho/sqrt 3)^(1/2)
  r^(3/2) at s = r - 3, is the largest at every r >= 4, by hand: at s
  >= 1 rho^2 <= 2.4e + 1.5 (its fraction is 1/(2(2s - 1)) +
  2e/((2s - 1)(2s + 3))), at s = 0 rho^2 = (8e + 3)/6, so at d >= 3
  (2^(3/2) sqrt(pi) rho / e!)^(1/d) <= (5.014 (1.2d + 1.5)^(1/2))^(1/d)
  <= 2.25, below d = 2's 2.946 (rho_2^2 >= 3 at s >= 1), and r^(1 +
  e/d) <= r^(3/2); d = 1's is 20.06 rho_1 r, rho_1^2 <= 7/6 at s >= 2,
  below 11.787 r^(3/2) once r >= 4. At r = 3 d = 1's is larger. The
  check reads it at r = 4..1000 and the ranks read.
  "LEMMA K: log(bound / K_s^2) >= 0 at every order of every r read"
  prints its least, 1.625e-04 at (r, s) = (10002, 10000), d = 1; "d = 2's bound the
  largest" reads none off and d = 1 at r = 3; a plant, d = 1's bound
  x 10, moves it to d = 1 at r = 50; 5/5 checks.
  Wall 0.8 s.

RUN: python kfactor.py (one process).
"""
import os
import sys
import time
from math import exp, lgamma, log, pi

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import mpmath as mp  # noqa: E402
from certclosed import jb, lam_mp  # noqa: E402

TWELVE = (21, 41, 61, 81, 101, 121, 161, 201, 251, 301, 351, 401)
FAR = (1001, 2001, 5001, 10001)
CHECKS = []


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 logK2(r, s, with_rho=True):
    d = r - 1 - s
    e = d // 2
    rho2 = 2 * e + 1 + (2 * s + 4 * e + 3) / ((4 * s - 2) * (2 * s + 3))
    lgam = (s * log(2) + lgamma(2 * s) - lgamma(s) - (s - 1) * log(2)
            if s else 0.0)                             # log 2^s (2s-1)!!
    lgam += lgamma(e + 1) - (lgamma(s + 1.5 + e) - lgamma(s + 1.5))
    return ((3 * r - 2) * log(2) + 2 * lgamma(r / 2)
            + (0.5 * log(rho2) if with_rho else 0.0) - lgam - 0.5 * log(pi))


def lemma_k(r, s):
    """log of LEMMA K's bound over K_s^2."""
    d = r - 1 - s
    e = d // 2
    rho2 = 2 * e + 1 + (2 * s + 4 * e + 3) / ((4 * s - 2) * (2 * s + 3))
    lb = ((2 * d + 1.5) * log(2) + 0.5 * log(pi) + 0.5 * log(rho2)
          + (d + e) * log(r) - lgamma(e + 1))
    return lb - logK2(r, s)


def top_bound(r, plant=1.0):
    """The d maximising LEMMA K's bound 4 (2^(3/2) sqrt(pi) rho /
    e!)^(1/d) r^(1 + e/d)."""
    best = None
    for s in range(r - 1):
        d = r - 1 - s
        e = d // 2
        rho2 = 2 * e + 1 + (2 * s + 4 * e + 3) / ((4 * s - 2) * (2 * s + 3))
        lb = ((1.5 * log(2) + 0.5 * log(pi) + 0.5 * log(rho2)
               - lgamma(e + 1) + (log(plant) if d == 1 else 0)) / d
              + (1 + e / d) * log(r))
        if best is None or lb > best[0]:
            best = (lb, d)
    return best[1]


def kpow(r, s, with_rho=True):
    """K_s^(2/d)."""
    d = r - 1 - s
    return exp(logK2(r, s, with_rho) / d)


def top(r, with_rho=True):
    """[(K^(2/d)/r^1.5, d)] over every order, largest first."""
    return sorted(((kpow(r, s, with_rho) / r ** 1.5, r - 1 - s)
                   for s in range(r - 1)), reverse=True)


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():
    t0 = time.time()
    lim2 = 2 ** 2.75 * (3 * pi) ** 0.25
    print("CONTROLS", flush=True)
    rows = []
    for r, s in ((21, 18), (41, 37)):
        d = r - 1 - s
        gaps = [float(lam_mp(r, s, J) - (d * mp.log(J) - logK2(r, s)))
                for J in (10 ** 4, 10 ** 6, 10 ** 8)]
        rows.append((r, s, gaps))
        print(f"  (r, s) = ({r}, {s}), d = {d}: Lambda - (d log J - log K^2)"
              f" at J = 1e4, 1e6, 1e8: {gaps[0]:+.3e}, {gaps[1]:+.3e}, "
              f"{gaps[2]:+.3e}", flush=True)
    check("POSITIVE: the gap falls toward 0, below 1e-3 at J = 1e8",
          all(abs(g[2]) < 1e-3 and abs(g[2]) < abs(g[1]) < abs(g[0])
              for _, _, g in rows))
    pl = top(10001, with_rho=False)
    check("PLANT: rho = 1 moves d = 2's K/r^1.5 at r = 10001 near "
          "2^(11/4) pi^(1/4) = 9.0",
          abs([v for v, d in pl if d == 2][0] - 2 ** 2.75 * pi ** 0.25) < 0.1,
          f"reads {[v for v, d in pl if d == 2][0]:.4f}")
    check("PLANT: d = 1's LEMMA K bound x 10 moves the largest to d = 1 "
          "at r = 50", top_bound(50, plant=10.0) == 1)

    print("THE READ", flush=True)
    peaks = {}
    for r in TWELVE + FAR + tuple(x + 1 for x in TWELVE + FAR):
        t = top(r)
        peaks[r] = t[0]
        d2 = [v for v, d in t if d == 2][0]
        d4 = [v for v, d in t if d == 4][0]
        print(f"  r = {r:5d}: max K^(2/d)/r^1.5 {t[0][0]:.4f} at d = "
              f"{t[0][1]}; d = 2 {d2:.4f} ({d2 / lim2:.4f} of 11.787), "
              f"d = 4 {d4:.4f} ({d4 / d2:.4f} of d = 2's); next "
              f"{t[1][1]}, {t[2][1]}", flush=True)
    worst = min((lemma_k(r, s), r, s) for r in TWELVE + FAR
                + tuple(x + 1 for x in TWELVE + FAR) for s in range(r - 1))
    check("LEMMA K: log(bound / K_s^2) >= 0 at every order of every r read",
          worst[0] >= 0, f"least {worst[0]:.3e} at (r, s) = {worst[1:]}")
    off = [r for r in sorted(set(range(4, 1001)) | set(peaks))
           if top_bound(r) != 2]
    check("LEMMA K: d = 2's bound the largest over d, r = 4..1000 and "
          "every r read", not off, f"off at {off[:5]}; r = 3: d = "
          f"{top_bound(3)}")
    for r in TWELVE:
        J2 = jb((r, r - 3, 1))[2]
        J4 = jb((r, r - 5, 1))[2]
        k2 = kpow(r, r - 3)
        k4 = kpow(r, r - 5)
        print(f"  r = {r:3d}: J^B_s / K_s^(2/d) at d = 2: {J2 / k2:.4f} "
              f"({J2}), d = 4: {J4 / k4:.4f} ({J4})", flush=True)
    a = slope(FAR, [peaks[r][0] for r in FAR])
    print(f"KILL route: log-slope of max_s K_s^(2/d)/r^(3/2) over r = "
          f"1001, 2001, 5001, 10001: {a:+.4f}: "
          f"{'KILLED' if a > 0.05 else 'HOLDS'}")
    print(f"{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")
    sys.exit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()