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

Computation 113 -- Bridge Premise (B), milestone M4(b):
                   the Z_phi <-> matched-scaling trace identification,
                   attempted ab initio on the discrete substrate
=========================================================================
STATUS (v26.13): M4(b) of the wave-function attack on Bridge Premise (B).
M3 (Comp 111) reduced (B) to two shared inputs; M4(a) (Comp 112) closed
the first (beta_KO = 2 is the binary-alphabet gap). This computation
attacks the second: prove that the order-parameter field-strength
renormalisation Z_phi^2 EQUALS the matched-scaling heat-kernel object
e^(-1), ab initio on the lattice -- rather than asserting it via the
standard QFT relation.

THE TARGET
==========
Bridge factor:  lambda_SM = b * Z_phi^2,  with  Z_phi^2 =? e^(-1).
On the substrate side, e^(-1) appears as the matched-scaling object

    (1/2^D) Tr exp(-Delta/D) = ((1+e^(-2/D))/2)^D -> e^(-1)        (Comp 100)
    = E_mu[exp(-2 X_bar)]                                          (Comp 111)

i.e. a VACUUM AMPLITUDE (a partition function / trace over ALL substrate
modes). The question M4(b) must settle: is the FIELD-STRENGTH of the
order-parameter Higgs equal to this vacuum amplitude?

THE TENSION THIS COMPUTATION SURFACES (the honest core)
=======================================================
A field-strength renormalisation and a vacuum amplitude are a priori
DIFFERENT objects:
  - Z_phi (field-strength) is a normalisation of ONE field's two-point
    function -- the residue of the order-parameter propagator.
  - (1/2^D) Tr exp(-Delta/D) is a vacuum amplitude -- a trace/product
    over ALL D modes.
Computing the order-parameter two-point residue directly gives a
SINGLE-MODE factor (the |S|=1 shell where X_bar lives, Comp 98), which
is NOT the full product e^(-1) unless every substrate mode is folded in.

So the identification holds IFF the substrate->Higgs projection Pi is the
TOTAL reduction: all 2^D substrate configurations collapse onto the one
surviving order parameter X_bar, so the Higgs field-strength absorbs the
FULL substrate vacuum amplitude. This computation makes that precise and
tests it numerically; it does NOT prove Pi is the total reduction (that
is the residual M4(b) isolates).
=========================================================================
"""

import math
import itertools


def xbar(C):
    return sum(C) / len(C)


def all_configs(D):
    return itertools.product((0, 1), repeat=D)


def laplacian_eigenvalue(S_size):
    """Boolean Laplacian eigenvalue on the |S|-Walsh shell: 2|S|."""
    return 2.0 * S_size


def vacuum_amplitude(D):
    """(1/2^D) Tr exp(-Delta/D) = product over ALL modes -> e^-1."""
    # Tr exp(-Delta/D) = sum_S exp(-2|S|/D) = (1 + e^{-2/D})^D
    return ((1.0 + math.exp(-2.0 / D)) / 2.0) ** D


def single_mode_residue(D, s):
    """
    Field-strength of the order parameter from its OWN two-point function.
    X_bar - 1/2 = -(1/2D) sum_a sigma_a lives on the |S|=1 shell
    (eigenvalue 2). Heat-kernel smoothing exp(-s Delta) scales each
    sigma_a by e^{-2s}, so the order-parameter field-strength from the
    single shell is e^{-2s}. (One factor, not a product over D modes.)
    """
    return math.exp(-2.0 * s)


def main():
    print("=" * 72)
    print("Computation 113: M4(b) -- Z_phi^2 vs matched-scaling trace")
    print("=" * 72)
    print()

    e_inv = math.exp(-1.0)

    # ---- 1. the two candidate objects are numerically different ----
    print("1.  TWO CANDIDATE OBJECTS FOR Z_phi^2 -- AND THEY DIFFER")
    print("-" * 72)
    print("    (a) vacuum amplitude (trace over ALL modes) = e^-1.")
    print("    (b) single-mode residue of the order parameter = e^{-2s}.")
    print()
    print(f"    vacuum amplitude (1/2^D)Tr exp(-Delta/D):")
    for D in (100, 1000, 10000):
        print(f"      D={D:>6}: {vacuum_amplitude(D):.6f}  (-> {e_inv:.6f})")
    print()
    print(f"    single-mode residue e^{{-2s}} at various heat-times s:")
    for s in (0.10, 0.25, 0.50, 1.00):
        r = single_mode_residue(0, s)
        hit = "= e^-1" if abs(r - e_inv) < 1e-9 else ""
        print(f"      s={s:>4.2f}: {r:.6f}  {hit}")
    print()
    print("    The single-mode residue equals e^-1 ONLY at the tuned value")
    print("    s = 1/2; at generic s it does not. So the order-parameter")
    print("    two-point residue, by itself, does NOT reproduce e^-1 -- the")
    print("    vacuum amplitude (all modes) is a genuinely different object.")
    print()

    # ---- 2. they reconcile iff Pi is the TOTAL reduction ----
    print("2.  RECONCILIATION: Pi as the TOTAL substrate->Higgs reduction")
    print("-" * 72)
    print("    The Higgs is the UNIQUE surviving order parameter: every")
    print("    substrate degree of freedom is integrated out onto X_bar.")
    print("    Then the Higgs field-strength is the full fluctuation")
    print("    normalisation = the vacuum amplitude over ALL D modes:")
    print()
    print("       Z_phi^2 = (1/2^D) Tr exp(-Delta/D) = E_mu[exp(-2 X_bar)]")
    print("               -> e^-1.")
    print()
    print("    Verify the two vacuum-amplitude forms coincide exactly")
    print("    (trace-over-modes  ==  tempered expectation), small D:")
    print(f"    {'D':>4} {'(1/2^D)Tr e^{-D.L/D}':>22} {'E_mu[e^{-2 Xbar}]':>20}")
    for D in (2, 4, 6, 8):
        trace = 0.0
        for k in range(D + 1):
            trace += math.comb(D, k) * math.exp(-laplacian_eigenvalue(k) / D)
        trace /= 2 ** D
        emu = sum(math.exp(-2.0 * xbar(C)) for C in all_configs(D)) / 2 ** D
        print(f"    {D:>4} {trace:>22.8f} {emu:>20.8f}")
    print()
    print("    Exact agreement: the trace over all Walsh shells IS the")
    print("    tempered expectation of the order parameter (X_bar = |C|/D,")
    print("    Laplacian eigenvalue 2|S| with binomial multiplicity mirror")
    print("    the bit-sum). So IF Pi folds in all modes, Z_phi^2 = e^-1")
    print("    is exact, not approximate.")
    print()

    # ---- 3. honest assessment ----
    print("=" * 72)
    print("ASSESSMENT: how far M4(b) carries Bridge Premise (B)")
    print("=" * 72)
    print()
    print("  ESTABLISHED:")
    print("   - The matched-scaling trace and the tempered order-parameter")
    print("     expectation are EXACTLY the same number (verified, part 2).")
    print("     So the only question is WHICH object is the Higgs")
    print("     field-strength -- and a total-reduction Pi makes it the")
    print("     vacuum amplitude = e^-1, exactly.")
    print("   - The naive single-field two-point residue does NOT give e^-1")
    print("     at generic heat-time (part 1): the identification genuinely")
    print("     requires the FULL mode content, i.e. a total reduction.")
    print()
    print("  NOT ESTABLISHED (the residual M4(b) isolates):")
    print("   - That Pi IS the total substrate->Higgs reduction -- i.e.")
    print("     that the single surviving order parameter's field-strength")
    print("     absorbs the entire substrate vacuum amplitude. This is")
    print("     plausible (the Higgs is the unique order parameter past the")
    print("     LG threshold, P3) and consistent with Comp 98 (all |S|>=2")
    print("     modes are trivial fixed points integrated out), but it is")
    print("     a STRUCTURAL PROPERTY OF Pi, asserted, not proven on the")
    print("     lattice.")
    print()
    print("  NET RESULT:")
    print("   M4(b) does NOT close (B) ab initio. It reduces the residual to")
    print("   ONE precise, defensible structural statement:")
    print()
    print("     (Pi-total)  the substrate->Higgs projection Pi is the total")
    print("                 reduction: the field-strength of the unique")
    print("                 surviving order parameter X_bar equals the full")
    print("                 substrate vacuum amplitude (1/2^D)Tr exp(-Delta/D).")
    print()
    print("   This is strictly cleaner than the original residual ('the")
    print("   multiplicative partition-function CC correspondence is a")
    print("   structural hypothesis'): (Pi-total) is a single, concrete,")
    print("   falsifiable property of one map, and Comp 98 already supplies")
    print("   the mechanism (all |S|>=2 modes are trivial fixed points, so")
    print("   only the order parameter survives -- consistent with total")
    print("   reduction). Proving (Pi-total) is the genuinely-remaining")
    print("   mathematics; it is no longer a vague correspondence.")


if __name__ == "__main__":
    main()
