#!/usr/bin/env python3
"""
PROVENANCE: NUMERICAL

Computation 210 -- the spectral dimension on the book's own bridged model: three between
the truncation and the compact scale, zero below the truncation, no rise
=========================================================================================
WHAT THIS DOES.  comp 207 computed the spectral dimension of the projected geometry on the
i.i.d. surrogate (Gaussian displacements in a flat bulk) and found three regimes: four
above d_0, at most 4.5 at the resolution d_0, a rise to about 23 at the grain.  This file
computes the same quantity on the finite model the book itself uses for the Mosco limit,
comp 9's bridge: Walsh weight n of the Boolean Laplacian is mapped to spherical-harmonic
degree n on S^3, the eigenvalue to n(n+2)/ell^2, the binomial multiplicity C(D, n) absorbed
into the measure so that degree n carries the S^3 multiplicity (n+1)^2, and the ladder
truncated at the degree k_n where the S^3 mode count equals the substrate's, k_n^3/3 = 2^D,
so k_n = (3 2^D)^(1/3) (comp 62's matched scaling).  The spectral dimension is Carlip's
d_s = -2 d log P / d log s with P the heat trace sum_n m_n exp(-s lambda_n), ell = 1.

THREE MODELS, ALL EXACT SUMS.
  (B) the bridged model as comp 9 states it: degrees 0..k_n, multiplicity (n+1)^2;
  (C) the same truncation with the binomial multiplicity C(D, n) kept, the bridge without
      its measure reweighting (degrees capped at D where k_n exceeds D);
  (S) the exact S^3 Laplacian to degree 400.

RESULTS (D = 12, 16, 20, 24; k_n = 23, 58, 147, 369).
  1. THE PLATEAU IS THERE AND IS EXACTLY THREE.  On (B), |d_s - 3| < 0.15 on s between
     about 5/k_n^2 and 0.075 (the compact scale of S^3, where (S) leaves three as well):
     [9e-3, 7.5e-2] at D = 12, [1.5e-3, ...] at 16, [2.4e-4, ...] at 20, [3.9e-5, ...] at
     24, the lower end falling as 2^(-2D/3) with the truncation.  The maximum of d_s on
     (B) is 2.96 to 3.00: the bridged model never exceeds three.
  2. BELOW THE TRUNCATION IT FALLS TO ZERO, AS ON A LATTICE.  For s below 1/k_n^2 the
     trace is a finite sum and d_s -> 0: dimensional reduction to zero at the cutoff, with
     no rise.  There is no two anywhere.
  3. THE RISE OF comp 207 LIVES IN THE MODES THE BRIDGE REWEIGHTS AWAY.  On (C), with the
     binomial multiplicity kept, d_s rises above three to 4.5, 5.7, 6.9, 8.1 for D = 12 to
     24, growing with D without bound, the peak sitting near the compact scale because the
     binomial puts almost every mode at degree D/2.  Reweighting to (n+1)^2 removes the
     rise entirely.  So the sub-d_0 rise of comp 207 is a property of the hypercube's
     configuration walk, present when a probe couples to the full Walsh ladder, absent
     from the emergent geometry the bridge delivers.

WHAT THIS CHANGES.  The Conclusion's computed statement acquires its condition: the spectral
dimension of the projected geometry is three (spatial, four with time) between the
truncation and the compact scale on the book's own model, with no rise and no two; the
rise between the grain and d_0 is carried by the Walsh modes the bridge absorbs into the
measure, and whether a sub-d_0 probe sees it is whether it sees the substrate's walk
rather than the emergent geometry, which is comp 207's resolution statement in the
bridge's terms.  On the book's model the direction of flow below d_0 is reduction, as in
CDT, to zero rather than to two; above d_0 it is flat at the Mosco value.

Tamper: dropping the truncation (degrees to 400 with (n+1)^2) reproduces the exact S^3
curve, so the lower end of the plateau is the truncation and nothing else.
"""
import numpy as np
from scipy.special import gammaln

S = np.logspace(-6, 2, 500)


def log_trace(lam, logw):
    out = np.empty(len(S))
    for i, s in enumerate(S):
        a = -s * lam + logw
        m = a.max(); out[i] = m + np.log(np.sum(np.exp(a - m)))
    return out


def ds(logP):
    return -2 * np.gradient(logP, np.log(S))


def plateau(d, target=3.0, tol=0.15):
    w = S[np.abs(d - target) < tol]
    return (w.min(), w.max()) if len(w) else (np.nan, np.nan)


def main():
    print("Computation 210 -- the spectral dimension on the bridged model of comp 9")
    print("=" * 76)
    m = np.arange(0, 401); lamS = m * (m + 2.0)
    dS = ds(log_trace(lamS, 2 * np.log(m + 1.0)))
    loS, hiS = plateau(dS)
    print(f"(S) exact S^3 to degree 400: plateau |d_s - 3| < 0.15 on s in [{loS:.1e}, {hiS:.1e}], max {dS.max():.2f}")
    print()
    rows = {}
    for D in (12, 16, 20, 24):
        kn = int(round((3 * 2.0 ** D) ** (1 / 3)))
        n = np.arange(0, kn + 1); lam = n * (n + 2.0)
        dB = ds(log_trace(lam, 2 * np.log(n + 1.0)))
        nn = n[n <= D]; lamC = nn * (nn + 2.0)
        logw = gammaln(D + 1) - gammaln(nn + 1) - gammaln(D - nn + 1)
        dC = ds(log_trace(lamC, logw))
        loB, hiB = plateau(dB)
        rows[D] = (kn, dB.max(), loB, hiB, dC.max(), S[np.argmax(dC)], dB[np.argmin(np.abs(S - 0.3 / kn ** 2))])
        print(f"D = {D:2d}, k_n = {kn:4d}: (B) max d_s {dB.max():.2f}, plateau [{loB:.1e}, {hiB:.1e}], d_s at s = 0.3/k_n^2: {rows[D][6]:.2f};  (C) max d_s {dC.max():.1f} at s = {S[np.argmax(dC)]:.1e}")
        print("      s     : " + "  ".join(f"{s:7.0e}" for s in (1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1)))
        print("      (B)   : " + "  ".join(f"{dB[np.argmin(np.abs(S - s))]:7.2f}" for s in (1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1)))
        print("      (C)   : " + "  ".join(f"{dC[np.argmin(np.abs(S - s))]:7.2f}" for s in (1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1)))
    print()
    ok1 = all(abs(r[1] - 3.0) < 0.05 and r[3] > 0.07 for r in rows.values())
    los = [rows[D][2] for D in (12, 16, 20, 24)]
    ok2 = all(los[i + 1] < los[i] for i in range(3)) and all(r[6] < 1.0 for r in rows.values())
    cs = [rows[D][4] for D in (12, 16, 20, 24)]
    ok3 = all(cs[i + 1] > cs[i] for i in range(3)) and cs[0] > 4
    ratio = [los[i] / los[i + 1] for i in range(3)]
    print(f"1. the bridged model's maximum is three (within 0.05) at every D and its plateau reaches the compact scale: {ok1}")
    print(f"2. the plateau's lower end falls with the truncation (ratios per 4 in D: {', '.join(f'{r:.1f}' for r in ratio)}, 2^(8/3) = 6.3) and d_s is below one at s = 0.3/k_n^2: {ok2}")
    print(f"3. with the binomial multiplicity kept the maximum rises above four and grows with D: {ok3}")
    # tamper
    n = np.arange(0, 401); dT = ds(log_trace(n * (n + 2.0), 2 * np.log(n + 1.0)))
    ok4 = np.max(np.abs(dT - dS)) < 1e-9
    print(f"4. tamper: without the truncation the bridged curve is the exact S^3 curve: {ok4}")
    ok = ok1 and ok2 and ok3 and ok4
    print()
    print("SUMMARY")
    print(f"  [{'PASS' if ok1 else 'FAIL'}] on the bridged model the spectral dimension is exactly three between the truncation and the compact scale")
    print(f"  [{'PASS' if ok2 else 'FAIL'}] below the truncation it falls to zero: reduction, no rise, no two")
    print(f"  [{'PASS' if ok3 else 'FAIL'}] the rise of comp 207 is carried by the binomial multiplicity the bridge reweights away")
    print(f"  [{'PASS' if ok4 else 'FAIL'}] tamper: the lower end of the plateau is the truncation and nothing else")
    print()
    print("  CONCLUSION: on the book's own finite model the spectral dimension of the projected geometry is")
    print("  the Mosco value between the truncation and the compact scale and falls to zero below the")
    print("  truncation; the rise between the grain and d_0 reported by comp 207 lives in the Walsh modes")
    print("  the bridge absorbs into the measure, so it is seen by a probe of the substrate's walk and not")
    print("  by one of the emergent geometry.")
    print("  ALL CHECKS PASSED" if ok else "  SOME CHECKS FAILED")


if __name__ == "__main__":
    main()
