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

Computation 121 -- Bridge Premise (B): the all-orders decoupling closed
                   EXACTLY by sufficiency (subsumes the Morse-Bott lemma)
=========================================================================
STATUS (v26.29+): closes the one residual rigour task carried by F11 /
Comp 118 (the all-orders S_D-equivariant decoupling), and answers the
v26.28 referee's M2(i): "extending zero-matrix-element from the quadratic
Hessian to the quartic 1PI vertex is a genuinely higher-order statement
than F11 as proved."

The single open content of (B) left after this -- the SM-side matching --
is quantified by Comp 123: a rigid, D-independent 1.0-sigma test
(lambda_SM(M_*) = 0.0927 +- 0.0007 m_t/m_h-dominated vs e^-1/4 = 0.09197).

THE POINT
=========
F8 (Comp 89) makes the substrate Higgs Hamiltonian EXACTLY the linear
collective coordinate,

    H_Higgs(C) = X_bar(C) = (1/D) sum_a B_a(C),     B_a i.i.d. (P1),

with NO free parameters. So the interaction F_int = Phi(X_bar) is a
function of the EMPIRICAL MEAN of i.i.d. per-site variables -- i.e. a
function of a SUFFICIENT STATISTIC for the product measure.

By the Fisher-Neyman factorisation, the configurations sharing a given
mean X_bar = k/D are counted by the multiplicity (the binomial
coefficient C(D,k)), and that multiplicity is INDEPENDENT of Phi. Hence
the substrate partition function factorises EXACTLY, at every finite D:

    Z[Phi] = E_mu[ exp(-Phi(X_bar)) ]
           = sum_{k=0}^{D}  ( C(D,k) / 2^D )  exp(-Phi(k/D)).      (*)

The transverse (non-collective) modes are EXACTLY the C(D,k) configs at
fixed mean; integrating them out returns the Phi-independent factor
C(D,k)/2^D. Therefore:

  - NO transverse mode contributes a Phi-dependent vertex at ANY order
    (Z_Gamma4 = 1 to all orders, and the same for every n-point) --
    EXACTLY, at finite D, not as a Gaussian-order + all-ones-tensor
    statement. This is the answer to M2(i): the "higher-order" worry
    dissolves because (*) is an exact all-orders factorisation.

  - The field-strength piece is the Phi-independent marginal of X_bar,
    whose D->inf de Moivre-Laplace normalisation gives e^-1 (= the
    Cramer-Bernoulli value F9 already uses). The only D->inf limit is the
    VALUE of the 1-D collective integral (*), with the standard O(1/D)
    correction to the saddle -- the substrate-limit caveat every PST
    quantity carries. The DECOUPLING (the structure) is exact at all D.

  - The all-orders S_D-equivariant Morse-Bott lemma (Comp 118) is the
    Gaussian (de Moivre-Laplace) shadow of (*): the all-ones derivative
    tensor that annihilates the standard rep W is the leading term of the
    exact sufficiency factorisation. Comp 118 (perturbative) is subsumed.

This computation verifies (*), the exact vertex triviality, the
isolation of O(1/D) to the value, and the Morse-Bott reduction, and it
runs a CONTROL (an interaction that depends on a transverse mode) to show
the vertex test has teeth.
=========================================================================
"""

import math
from itertools import product

import numpy as np


# ---------------------------------------------------------------------------
def exact_partition_by_enumeration(D, weight):
    """Z = (1/2^D) sum over all 2^D configs of weight(config). Brute force."""
    Z = 0.0
    for C in product((0, 1), repeat=D):
        Z += weight(np.array(C))
    return Z / 2**D


def multiplicity_factorised(D, phi):
    """RHS of (*): sum_k (C(D,k)/2^D) exp(-phi(k/D))."""
    Z = 0.0
    for k in range(D + 1):
        Z += math.comb(D, k) / 2**D * math.exp(-phi(k / D))
    return Z


def transverse_multiplicity_is_phi_independent(D):
    """Show that the count of configs at fixed mean k/D is C(D,k),
    independent of any interaction. Returns max deviation over k."""
    counts = [0] * (D + 1)
    for C in product((0, 1), repeat=D):
        counts[int(sum(C))] += 1
    binom = [math.comb(D, k) for k in range(D + 1)]
    return max(abs(counts[k] - binom[k]) for k in range(D + 1))


# ---------------------------------------------------------------------------
def collective_effective_potential(D, phi):
    """U(k) = phi(k/D) - log( C(D,k)/2^D ): the effective potential for the
    collective coordinate after EXACTLY integrating out the transverse modes.
    The second term is the transverse (multiplicity) contribution."""
    U = np.zeros(D + 1)
    for k in range(D + 1):
        U[k] = phi(k / D) - math.log(math.comb(D, k) / 2**D)
    return U


def main():
    print("=" * 72)
    print("Computation 121: all-orders decoupling closed EXACTLY by")
    print("sufficiency (Fisher-Neyman); Morse-Bott (Comp 118) subsumed")
    print("=" * 72)
    print()

    # ---- 1. the exact factorisation (*) and Phi-independent multiplicity ----
    print("1.  EXACT FACTORISATION  Z[Phi] = sum_k (C(D,k)/2^D) e^{-Phi(k/D)}")
    print("-" * 72)
    # try several non-linear interactions Phi(x) to stress the identity
    phis = {
        "linear  -2x": lambda x: -2.0 * x,
        "quartic 5x^4": lambda x: 5.0 * x**4,
        "mixed":        lambda x: -2.0 * x + 3.0 * x**2 - 4.0 * x**3 + 5.0 * x**4,
    }
    for D in (6, 10, 14):
        print(f"    D={D}:")
        # multiplicity equals binomial, independent of any interaction
        dev = transverse_multiplicity_is_phi_independent(D)
        print(f"      transverse count at fixed mean == C(D,k)?  "
              f"max|count-binom| = {dev}  (Phi-independent multiplicity)")
        for name, phi in phis.items():
            Z_enum = exact_partition_by_enumeration(
                D, lambda C: math.exp(-phi(C.mean())))
            Z_fact = multiplicity_factorised(D, phi)
            rel = abs(Z_enum - Z_fact) / abs(Z_enum)
            print(f"      Phi={name:>16}:  Z_enum={Z_enum:.10f}  "
                  f"Z_fact={Z_fact:.10f}  rel.diff={rel:.1e}")
    print()
    print("    (*) holds to machine precision for every interaction: the")
    print("    transverse modes enter ONLY through the Phi-independent")
    print("    multiplicity C(D,k). X_bar is a sufficient statistic.")
    print()

    # ---- 2. Z_Gamma4 = 1 EXACTLY: no Phi-dependent transverse vertex --------
    print("2.  VERTEX TRIVIALITY  Z_Gamma4 = 1  EXACT AT FINITE D")
    print("-" * 72)
    print("    Effective potential  U_Phi(k) = Phi(k/D) - log(C(D,k)/2^D).")
    print("    Add a quartic probe  Phi -> Phi + delta*(x-1/2)^4  and ask")
    print("    whether the transverse term renormalises the added vertex.")
    D = 16
    base = lambda x: -2.0 * x
    delta = 0.37
    probe = lambda x: delta * (x - 0.5) ** 4
    U0 = collective_effective_potential(D, base)
    U1 = collective_effective_potential(D, lambda x: base(x) + probe(x))
    diff = U1 - U0
    # the difference must equal the bare probe EXACTLY (transverse term cancels)
    xs = np.array([k / D for k in range(D + 1)])
    bare = delta * (xs - 0.5) ** 4
    max_resid = np.max(np.abs(diff - bare))
    print(f"    max | (U_[Phi+probe] - U_Phi) - bare probe | = {max_resid:.2e}")
    print("    -> the transverse (multiplicity) term is bit-for-bit identical")
    print("       under Phi -> Phi+probe, so it cannot renormalise the added")
    print("       quartic. Z_Gamma4 = 1 exactly, at finite D, ALL orders.")
    print()
    # CONTROL: an interaction that depends on a transverse mode DOES get a
    # vertex correction (the test has teeth).
    print("    CONTROL (teeth): interaction depending on a TRANSVERSE mode")
    print("    w = C_0 - C_1 (sum_a w_a = 0, a W-direction).  Then the")
    print("    transverse integration is NOT Phi-independent:")
    Dc = 12
    g = 0.9
    # Z with transverse-coupled weight exp(-g*(C0 - C1)^2), enumerated, and the
    # naive 'multiplicity-only' factorisation that wrongly ignores it:
    Z_true = exact_partition_by_enumeration(
        Dc, lambda C: math.exp(-g * (C[0] - C[1]) ** 2))
    Z_naive_collective = multiplicity_factorised(Dc, lambda x: 0.0)  # = 1
    print(f"      Z_true (transverse-coupled)      = {Z_true:.6f}")
    print(f"      collective-only factorisation    = {Z_naive_collective:.6f}")
    print(f"      gap = {abs(Z_true - Z_naive_collective):.6f}  "
          f"-> transverse coupling leaves a residue; sufficiency BROKEN,")
    print("         exactly when the interaction is NOT a function of X_bar.")
    print("      (Confirms: Z_Gamma4 = 1 is a consequence of F8 -- interaction")
    print("       = function of the sufficient statistic X_bar -- not generic.)")
    print()

    # ---- 3. O(1/D) is in the VALUE, not the decoupling ----------------------
    print("3.  O(1/D) LIVES IN THE VALUE  Z -> e^-1,  NOT IN THE STRUCTURE")
    print("-" * 72)
    print("    Decoupling (*) is exact at every D (parts 1-2: zero residual).")
    print("    The VALUE of the collective integral approaches e^-1 with the")
    print("    standard Cramer-Bernoulli / de Moivre-Laplace O(1/D) tail:")
    e_inv = math.exp(-1.0)
    print(f"      {'D':>6} {'Z=E[e^{-2 Xbar}]':>18} {'Z - e^-1':>14} "
          f"{'(Z-e^-1)*D':>12}")
    for D in (10, 50, 200, 1000, 5000):
        Z = ((1.0 + math.exp(-2.0 / D)) / 2.0) ** D     # = E[exp(-2 Xbar)]
        print(f"      {D:>6} {Z:>18.10f} {Z - e_inv:>14.2e} "
              f"{(Z - e_inv) * D:>12.4f}")
    print("    (Z - e^-1)*D -> const: the correction is O(1/D), in the VALUE")
    print("    only. The structural decoupling carries no D-dependence.")
    print()

    # ---- 4. Morse-Bott (Comp 118) is the Gaussian shadow of (*) -------------
    print("4.  COMP 118 (MORSE-BOTT) IS THE de MOIVRE-LAPLACE SHADOW OF (*)")
    print("-" * 72)
    print("    Gaussian-approximate the multiplicity:  C(D,k)/2^D  ~=")
    print("    N(mean=1/2, var=1/(4D)) in m=k/D.  The transverse Gaussian")
    print("    fluctuation IS the W-sector Gaussian integral of Comp 118;")
    print("    the all-ones derivative tensor Phi^(n)/D^n annihilating W is")
    print("    the leading term of the exact sufficiency factorisation (*).")
    D = 40
    var = 1.0 / (4 * D)
    ks = np.arange(D + 1)
    exact = np.array([math.comb(D, k) / 2**D for k in ks])
    m = ks / D
    gauss = (1.0 / D) * np.exp(-(m - 0.5) ** 2 / (2 * var)) / math.sqrt(
        2 * math.pi * var)
    # compare on the bulk (within 3 sigma)
    sig = math.sqrt(var)
    bulk = np.abs(m - 0.5) < 3 * sig
    rel = np.max(np.abs(exact[bulk] - gauss[bulk]) / exact[bulk])
    print(f"    D={D}: max rel.dev (multiplicity vs Gaussian, |m-1/2|<3sigma)")
    print(f"          = {rel:.3f}  -> Comp 118's Gaussian/Hessian picture is")
    print("          the leading approximation; (*) is the exact parent.")
    print()

    # ---- 5. assessment ------------------------------------------------------
    print("=" * 72)
    print("ASSESSMENT: the residual all-orders rigour task is CLOSED")
    print("=" * 72)
    print()
    print("  Given F8 (H_Higgs = X_bar exactly, the empirical mean of i.i.d.")
    print("  bits), the interaction is a function of a SUFFICIENT STATISTIC.")
    print("  Fisher-Neyman => the transverse modes factor out as the")
    print("  Phi-independent multiplicity C(D,k), exactly, at every finite D")
    print("  and every order (eq. *). Therefore:")
    print("    - Z_Gamma4 = 1 to all orders, EXACTLY (part 2) -- this answers")
    print("      the v26.28 M2(i) 'higher-order' worry: there is no")
    print("      higher-order gap, the factorisation is exact at all orders")
    print("      simultaneously, not Gaussian-order + numerics;")
    print("    - the field-strength is the Phi-independent marginal of X_bar,")
    print("      its de Moivre-Laplace normalisation -> e^-1 (the same")
    print("      Cramer-Bernoulli value F9 uses), O(1/D) in the VALUE only;")
    print("    - Comp 118's all-orders S_D-equivariant Morse-Bott lemma is the")
    print("      Gaussian shadow of (*) and is subsumed.")
    print()
    print("  NET: F11's 'residual all-orders rigour task' is closed by an")
    print("  EXACT, non-perturbative, combinatorial identity (sufficiency of")
    print("  the empirical mean). The substrate side of (B) no longer carries")
    print("  a perturbative all-orders caveat -- only the O(1/D) substrate-")
    print("  limit on the VALUE e^-1, shared by every PST result. The single")
    print("  open content of (B) remains the SM-side matching (F4 + RGE).")


if __name__ == "__main__":
    main()
