rho_closed.py

Checks: FLATTEN: Every rank's band of failing depths ends theorem; rule; pattern.

Cited on: FLATTEN.

To run it: save rho_closed.py, with bandend.py, dualtail.py, flatten.py, prunerr.py beside it; needs mpmath, sympy.

"""rho_closed.py -- the least squared norm at a point, in closed form.

QUESTION. Q_s = (1 + x)^J (1 - x)^s, m_s the least ||Q_s c||^2 over
real c of degree <= d = r - 1 - s with c(1) = 1, rho_s = m_s / C(2J, J)
(vartail.py's objects). Is rho_s a closed form at every rank, order and
depth, and which?

BY HAND (before any engine code).
  (a) c* is reversal-fixed (vartail.py (a)): at d = 2e, c(e^(i th)) =
  e^(i e th) h(cos th), h real of degree <= e, h(1) = 1, a bijection
  onto the reversal-fixed c; at d = 2e + 1, c = (1 + x) ct, ct
  reversal-fixed of degree 2e, ct(1) = 1/2.
  (b) ||P||^2 = (1/2 pi) int |P(e^(i th))|^2 dth, |1 + x|^2 = 2(1 + t),
  |1 - x|^2 = 2(1 - t), t = cos th, dth = dt / sqrt(1 - t^2). So at
  d = 2e
    m_s = (2^(J+s) / pi) min_{h(1) = 1} int h^2 (1 - t)^a (1 + t)^b dt
        = (2^(J+s) / pi) / K_e(1, 1),  a = s - 1/2, b = J - 1/2,
  K_e the Christoffel-Darboux kernel of the Jacobi weight (the least
  form at a point is the reciprocal of the kernel there); at d = 2e + 1
  the same with J + 1 for J and a factor 1/4, so b = J + 1/2.
  (c) KNOWN (Szego, Orthogonal Polynomials, (4.5.8); read by hand at
  e = 0 and at Legendre, e = 1): K_e(1, 1) = 2^(-a-b-1) G(e + a + b + 2)
  G(e + a + 2) / (G(a + 1) G(a + 2) e! G(e + b + 1)).
  (d) Divided by C(2J, J) = 4^J G(J + 1/2) / (sqrt(pi) J!), with
  u = ceil(d/2), e = floor(d/2):
    rho_s = gamma(s, e) (J + 1/2)_u / (J + 1)_(s+u),
    gamma(s, e) = 2^s (2s - 1)!! e! / (s + 3/2)_e,
  (x)_n the rising factorial. At d = 1 (e = 0, u = 1) this is
  vartail.py's 2^(s-1) (2s - 1)!! (2J + 1) / ((J + 1)...(J + s + 1)).
  By hand: rank 3, s = 0, J = 1: c = (1 + x^2)/2 gives (1 + x + x^2 +
  x^3)/2, norm^2 1, and the form reads (2/3)(3/2)/2 = 1/2 = m / C(2, 1);
  J = 0: 1/3.
  (e) So m_s = rho_s C(2J, J) ~ gamma 4^J J^(-s-1/2) / sqrt(pi).

PREDICTIONS. (1) The closed form equals m_s / C(2J, J) computed by an
exact Gram solve at every cell of the family (strongly: (a)-(d)).
(2) At ranks 3..8, every order, det N / (D S) by dualtail.polys equals
the closed form as a rational function of J (strongly). (3) Past the
cancellation with D = (J + 1)...(J + r - 1), det N / S carries the
factors (2J + 2i + 1), i < u, over (J + s + u + 1)...(J + r - 1) when
u < d (weakly: read off (2)).

KILL (frozen; what the script PRINTS):
  "KILL closed: mismatches X of Y cells; symbolic: Z of 27 orders
  differ", fires iff X + Z > 0. The family: ranks 3..14, every order
  s = 0..r - 2, depths J = 0..40, exact rationals; the symbolic arm
  ranks 3..8, every order.

CONTROLS (read before any verdict).
  POSITIVE: the Gram engine at rank 3, s = 0, J = 0 and 1 reads 1/3
  and 1/2; at d = 1 it equals vartail.py's closed form at every rank
  and depth of the family. PLANT: the form with b = J + 1/2 at even d
  (u + 1 and s + u + 1 for u and s + u) differs at some even-d cell,
  and gamma with (e + 1)! for e! at some e >= 1 cell.

FINDINGS. The kill misses: "KILL closed: mismatches 0 of 3690 cells;
symbolic: 0 of 27 orders differ". (1) and (2) held; (3) as frozen did
not (below).
  CONTROLS: "the Gram engine at rank 3, s = 0 reads 1/3, 1/2"; at
  d = 1 "492 of 492 cells"; the plants "1722 and 3198 cells differ".
  (1): "exact: 3690 of 3690 cells agree", 3690 Gram solves in 1.2 s.
  (2): "symbolic: 27 of 27 orders agree"; at rank 5 the four orders
  read 2(2J + 1)(2J + 3)/(15 (J + 1)(J + 2)), (2J + 1)(2J + 3)/(5 (J +
  1)(J + 2)(J + 3)), 12(2J + 1)/(7 (J + 1)(J + 2)(J + 3)) and 60(2J +
  1)/((J + 1)...(J + 4)), gamma = 8/15, 4/5, 24/7 and 120, over 4, 4, 2
  and 2. (3) as frozen put (J + s + u + 1)...(J + r - 1) in a
  denominator; by (2), det N / S = rho_s D carries those factors in
  its numerator, a polynomial: at rank 5, "2*(J + 3)*(J + 4)*(2*J +
  1)*(2*J + 3)/15", "(J + 4)*(2*J + 1)*(2*J + 3)/5", "12*(J + 4)*(2*J +
  1)/7", "60*(2*J + 1)".
  (c) needs no source opened: with the Jacobi values P_e(1) = (a +
  1)_e / e! and h_e = 2^(a+b+1) G(e + a + 1) G(e + b + 1) / ((2e + a +
  b + 1) G(e + a + b + 1) e!) (DLMF 18.3, 18.6.1), the right side F(e)
  of (c) has F(0) = 1/h_0 and F(e) - F(e - 1) = F(e - 1)(a + 1)(2e + a
  + b + 1)/(e(e + b)) = P_e(1)^2 / h_e, so F(e) = K_e(1, 1) by
  induction; a = s - 1/2 and b = J -+ 1/2 lie above -1 at every s, J
  >= 0, and at s = J = 0, d even (a + b + 1 = 0) h_0 is the limit
  value pi, the formula's (a + b + 1) G(a + b + 1) read as G(a + b + 2).
  So the form is a theorem at every rank, order and depth. The
  frozen hand example named c = (1 + x + x^2)/2 for (1 + x^2)/2.
  4/4 checks, the kill the fourth, 2.4 s, 55.2 MB under gate --run.

RUN: python rho_closed.py.
"""
import sys
import time
from fractions import Fraction
from math import comb, factorial

RANKS = range(3, 15)
DEPTHS = range(0, 41)
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 q_coeffs(J, s):
    """Coefficients of (1 + x)^J (1 - x)^s."""
    a = [comb(J, k) for k in range(J + 1)]
    for _ in range(s):
        a = [x - y for x, y in zip(a + [0], [0] + a)]
    return a


def gram_rho(r, s, J):
    """m_s / C(2J, J) by an exact solve of G y = 1, m = 1 / sum y."""
    d = r - 1 - s
    q = q_coeffs(J, s)
    ac = [sum(q[k] * q[k + m] for k in range(len(q) - m)) if m < len(q)
          else 0 for m in range(d + 1)]
    A = [[Fraction(ac[abs(i - k)]) for k in range(d + 1)] + [Fraction(1)]
         for i in range(d + 1)]
    n = d + 1
    for c in range(n):
        p = next(i for i in range(c, n) if A[i][c] != 0)
        A[c], A[p] = A[p], A[c]
        for i in range(n):
            if i != c and A[i][c] != 0:
                f = A[i][c] / A[c][c]
                A[i] = [x - f * y for x, y in zip(A[i], A[c])]
    total = sum(A[i][n] / A[i][i] for i in range(n))
    return 1 / total / comb(2 * J, J)


def rising(x, n):
    out = Fraction(1)
    for i in range(n):
        out *= x + i
    return out


def dfact(n):
    """(2n - 1)!!."""
    out = 1
    for k in range(1, 2 * n, 2):
        out *= k
    return out


def closed(r, s, J, plant=None):
    d = r - 1 - s
    e, u = d // 2, d - d // 2
    if plant == "b" and d % 2 == 0:
        u += 1
    ef = factorial(e + 1) if plant == "kappa" else factorial(e)
    kappa = Fraction(2 ** s * dfact(s) * ef) / rising(
        Fraction(2 * s + 3, 2), e)
    return kappa * rising(Fraction(2 * J + 1, 2), u) / rising(
        Fraction(J + 1), s + u)


def vartail_d1(r, J):
    """vartail.py's rho_(r-2) = 2^(r-3) (2r - 5)!! (2J + 1) / ((J + 1)...
    (J + r - 1))."""
    return Fraction(2 ** (r - 3) * dfact(r - 2) * (2 * J + 1)) / rising(
        Fraction(J + 1), r - 1)


if __name__ == "__main__":
    t0 = time.time()
    print("CONTROLS")
    a0, a1 = gram_rho(3, 0, 0), gram_rho(3, 0, 1)
    check("POSITIVE: the Gram engine at rank 3, s = 0 reads 1/3, 1/2",
          a0 == Fraction(1, 3) and a1 == Fraction(1, 2), f"{a0}, {a1}")
    cells = [(r, s, J) for r in RANKS for s in range(r - 1) for J in DEPTHS]
    gram = {}
    for c in cells:
        gram[c] = gram_rho(*c)
    print(f"  {len(cells)} Gram solves, {time.time() - t0:.1f} s", flush=True)
    d1 = [(r, J) for r in RANKS for J in DEPTHS]
    d1_ok = sum(gram[(r, r - 2, J)] == vartail_d1(r, J) for r, J in d1)
    check("POSITIVE: at d = 1 the engine is vartail.py's closed form",
          d1_ok == len(d1), f"{d1_ok} of {len(d1)} cells")
    pb = sum(closed(*c, plant="b") != gram[c] for c in cells
             if (c[0] - 1 - c[1]) % 2 == 0)
    pk = sum(closed(*c, plant="kappa") != gram[c] for c in cells
             if (c[0] - 1 - c[1]) // 2 >= 1)
    check("PLANT: b = J + 1/2 at even d, and (e + 1)! for e!, each differ "
          "somewhere", pb > 0 and pk > 0, f"{pb} and {pk} cells differ")
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)
    print("THE FORM")
    X = sum(closed(*c) != gram[c] for c in cells)
    print(f"  exact: {len(cells) - X} of {len(cells)} cells agree")
    import sympy as sp
    from dualtail import Jv, polys
    Z, n_ord, shown = 0, 0, 0
    for r in range(3, 9):
        for s in range(r - 1):
            d = r - 1 - s
            e, u = d // 2, d - d // 2
            detN, A, S, D = polys(r, s)
            sym = sp.cancel(detN.as_expr() / (D.as_expr() * S.as_expr()))
            kappa = sp.Rational(2 ** s * dfact(s) * factorial(e)) / sp.rf(
                sp.Rational(2 * s + 3, 2), e)
            form = kappa * sp.rf(Jv + sp.Rational(1, 2), u) / sp.rf(Jv + 1,
                                                                    s + u)
            diff = sp.cancel(sym - sp.expand_func(form))
            n_ord += 1
            Z += diff != 0
            if r in (5, 8) and shown < 8:
                shown += 1
                print(f"  r = {r}, s = {s}: det N / (D S) = "
                      f"{sp.factor(sym)}; det N / S = "
                      f"{sp.factor(sp.cancel(detN.as_expr() / S.as_expr()))}",
                      flush=True)
    print(f"  symbolic: {n_ord - Z} of {n_ord} orders agree, "
          f"{time.time() - t0:.1f} s")
    print(f"KILL closed: mismatches {X} of {len(cells)} cells; symbolic: "
          f"{Z} of {n_ord} orders differ")
    check("the kill misses: the form is m_s / C(2J, J) at every cell and "
          "order", X + Z == 0, f"{X} cells, {Z} orders differ")
    if not all(CHECKS):
        print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks FAILED")
        sys.exit(1)
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")