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

Computation 115 -- Bridge Premise (B), milestone M6:
                   the unique-soft-mode theorem -- (Pi-total) is a
                   consequence of P1 (S_D symmetry) + P3 (LG threshold)
=========================================================================
STATUS (v26.13): M6 of the wave-function attack on Bridge Premise (B).
M5 (Comp 114) reduced (B) to a single premise -- P3's collapse onto the
order parameter is TOTAL (no residual light field) -- and excluded the
only competing field-theoretic reading. M6 turns that premise into a
theorem by computing the substrate fluctuation spectrum of the full LG
sublimation, not just the discrete block-spin step (Comp 98).

THE TARGET
==========
Show that past P3's Landau-Ginzburg threshold, the substrate fluctuation
spectrum has a UNIQUE soft mode -- the order parameter X_bar -- separated
by a spectral gap (the binary gap = the matched scale M_*) from every
other substrate mode. Then no residual light field survives below M_*,
the substrate->Higgs reduction is total, and (Pi-total) holds -- closing
the last premise of (B).

THE OBSTRUCTION M6 MUST CLEAR
=============================
The |S|=1 Walsh shell is D-fold DEGENERATE at the Boolean-Laplacian
eigenvalue 2 (the binary gap). X_bar's fluctuation is just ONE direction
in this shell (the symmetric/uniform combination
X_bar - 1/2 = -(1/2D) sum_a sigma_a). So at the free level X_bar is NOT
singled out: there are D-1 other modes at the SAME eigenvalue. If the LG
sublimation softened the whole shell, there would be D light fields, not
one, and (Pi-total) would FAIL. Something must lift the degeneracy and
soften X_bar ALONE.

THE LEMMA THAT CLEARS IT (rank-1 LG Hessian)
============================================
The order parameter X_bar = (1/D) sum_a C_a is LINEAR in the bits. So the
LG potential V(X_bar) has Hessian

    d^2 V / dC_a dC_b = V''(X_bar) * (dX_bar/dC_a)(dX_bar/dC_b)
                        + V'(X_bar) * d^2 X_bar/dC_a dC_b
                      = V''(X_bar) / D^2      (since X_bar is linear,
                                               the second term vanishes),

i.e. a CONSTANT matrix, V''/D^2 times the all-ones matrix -- a RANK-1
operator. A rank-1 perturbation shifts EXACTLY ONE eigenvalue (the
symmetric direction = X_bar) and leaves all orthogonal modes untouched.
P1's S_D permutation symmetry guarantees the all-ones direction (the
S_D singlet) is exactly X_bar, and the orthogonal D-1 modes (the S_D
standard representation) are pinned at the binary gap. The LG potential,
being a function of the single S_D-invariant collective coordinate,
CANNOT soften them: it has no matrix element there.

Therefore X_bar is the unique mode the LG flow can soften; P3 (past
threshold) softens it (V'' -> -2, the symmetric mass crosses zero) while
every other substrate mode stays at the binary gap. Unique soft mode,
spectral gap = binary gap = M_*. This is (Pi-total).

This computation verifies the lemma and the spectrum explicitly.
=========================================================================
"""

import numpy as np


def boolean_laplacian(D):
    """
    Full Boolean Laplacian Delta = sum_a (1 - tau_a) on the 2^D-dim
    function space, in the computational (config) basis. tau_a flips bit a.
    Eigenvalues are 2|S| on the Walsh shells.
    """
    N = 1 << D
    Delta = np.zeros((N, N))
    for c in range(N):
        Delta[c, c] = D                    # sum_a 1  = D on the diagonal
        for a in range(D):
            c2 = c ^ (1 << a)              # flip bit a
            Delta[c, c2] -= 1.0           # - tau_a
    return Delta


def xbar_vector(D):
    """The order-parameter observable X_bar(C) = |C|/D as a 2^D vector."""
    N = 1 << D
    return np.array([bin(c).count("1") / D for c in range(N)])


def main():
    print("=" * 72)
    print("Computation 115: M6 -- the unique-soft-mode theorem")
    print("(Pi-total) from P1 (S_D symmetry) + P3 (LG threshold)")
    print("=" * 72)
    print()

    # ---------------------------------------------------------------
    # 1. The rank-1 LG Hessian on the |S|=1 shell.
    #    On the D-dim single-bit-fluctuation shell the free Hessian is
    #    2 I (binary gap), and the LG potential adds V'' * (symmetric
    #    projector), a rank-1 operator. Eigenvalues: one shifted (X_bar),
    #    D-1 pinned at 2.
    # ---------------------------------------------------------------
    print("1.  RANK-1 LG HESSIAN ON THE |S|=1 SHELL")
    print("-" * 72)
    print("    Free Hessian = 2 I_D (binary gap on every single-bit mode).")
    print("    LG term = (V''/D) J, J = all-ones matrix = D * (symmetric")
    print("    projector). Rank(J) = 1, so it shifts ONE eigenvalue only.")
    print()
    for D in (4, 8, 16):
        J = np.ones((D, D))
        rank_J = np.linalg.matrix_rank(J)
        Vpp = -2.0                                   # at the LG threshold
        H1 = 2.0 * np.eye(D) + (Vpp / D) * J
        eigs = np.sort(np.linalg.eigvalsh(H1))
        soft = eigs[0]
        rest = eigs[1:]
        print(f"    D={D:>2}: rank(J)={rank_J}; "
              f"soft eigenvalue = {soft:+.4f} (1 mode, = X_bar), "
              f"others = {rest.min():.4f}..{rest.max():.4f} ({D-1} modes)")
    print()
    print("    Exactly one mode (the S_D singlet = X_bar) is softened to 0")
    print("    at threshold; the other D-1 (the S_D standard rep) stay")
    print("    pinned at the binary gap 2. The rank-1 structure is the")
    print("    proof: V(X_bar) with X_bar linear cannot couple to them.")
    print()

    # ---------------------------------------------------------------
    # 2. Sweep V'' through the LG threshold: X_bar softens alone.
    # ---------------------------------------------------------------
    print("2.  SWEEP THROUGH THE LG THRESHOLD: X_bar SOFTENS ALONE")
    print("-" * 72)
    D = 8
    J = np.ones((D, D))
    print(f"    D={D}.  Symmetric channel (X_bar) vs standard rep, vs V''.")
    print(f"    {'V''':>7} {'X_bar mass^2':>14} {'standard-rep mass^2':>22}")
    for Vpp in (0.0, -0.5, -1.0, -1.5, -2.0):
        H1 = 2.0 * np.eye(D) + (Vpp / D) * J
        eigs = np.sort(np.linalg.eigvalsh(H1))
        print(f"    {Vpp:>7.1f} {eigs[0]:>14.4f} {eigs[1]:>22.4f}")
    print()
    print("    The order parameter (symmetric channel) tracks 2 + V'' and")
    print("    crosses 0 at the threshold V'' = -2; the standard rep is")
    print("    FLAT at the binary gap 2 throughout. Only X_bar goes soft.")
    print()

    # ---------------------------------------------------------------
    # 3. The full 2^D spectrum: higher Walsh shells are even more gapped.
    # ---------------------------------------------------------------
    print("3.  FULL SUBSTRATE SPECTRUM: HIGHER SHELLS MORE GAPPED")
    print("-" * 72)
    D = 6
    Delta = boolean_laplacian(D)
    eigs = np.linalg.eigvalsh(Delta)
    # group by Walsh shell eigenvalue 2|S|
    shells = {}
    for e in np.round(eigs).astype(int):
        shells[e] = shells.get(e, 0) + 1
    print(f"    D={D}, free Boolean-Laplacian spectrum (eigenvalue 2|S|):")
    print(f"    {'eigenvalue':>11} {'|S|':>5} {'multiplicity':>13}")
    for e in sorted(shells):
        print(f"    {e:>11} {e // 2:>5} {shells[e]:>13}")
    print()
    print("    The LG rank-1 Hessian touches ONLY the |S|=1 symmetric mode")
    print("    (X_bar). Everything else -- the |S|=1 standard rep at 2, the")
    print("    |S|>=2 shells at 4,6,... -- is untouched and stays at or above")
    print("    the binary gap. Past threshold: ONE soft mode (X_bar -> 0),")
    print("    a clean spectral gap (= binary gap = M_*) to all the rest.")
    print()

    # ---------------------------------------------------------------
    # 4. X_bar is exactly the symmetric (S_D-singlet) direction.
    # ---------------------------------------------------------------
    print("4.  X_bar IS THE S_D SINGLET THE RANK-1 TERM SHIFTS")
    print("-" * 72)
    D = 6
    xb = xbar_vector(D) - 0.5            # fluctuation X_bar - <X_bar>
    # project onto |S|=1 shell: single-bit Walsh modes sigma_a
    # symmetric combination = sum_a sigma_a ; show xb is proportional to it
    N = 1 << D
    sym = np.zeros(N)
    for c in range(N):
        # sum_a (1 - 2*bit_a) = D - 2|c|
        sym[c] = D - 2 * bin(c).count("1")
    # xb = -(1/2D) * sym  (since X_bar-1/2 = -(1/2D) sum sigma_a).
    # Mask the half-filling entries where both vanish (0/0); the
    # proportionality there is 0 = 0, consistent, ratio undefined.
    mask = np.abs(sym) > 1e-9
    ratio = xb[mask] / sym[mask]
    print(f"    D={D}: X_bar - 1/2  vs  -(1/2D) sum_a sigma_a")
    print(f"    component-wise ratio constant? min={ratio.min():.6f} "
          f"max={ratio.max():.6f}  (expected -1/2D = {-1/(2*D):.6f})")
    print(f"    (half-filling entries, where both sides = 0, excluded)")
    print()
    print("    X_bar's fluctuation is exactly the uniform sum of single-bit")
    print("    modes = the S_D singlet in the |S|=1 shell. This is the one")
    print("    direction the all-ones (rank-1) LG Hessian acts on.")
    print()

    # ---------------------------------------------------------------
    # 5. assessment
    # ---------------------------------------------------------------
    print("=" * 72)
    print("ASSESSMENT: does M6 close (Pi-total), hence (B)?")
    print("=" * 72)
    print()
    print("  THEOREM (unique soft mode):")
    print("   Inputs -- P1: bits i.i.d., S_D-symmetric; the order parameter")
    print("   is the linear S_D-invariant collective coordinate X_bar")
    print("   (Comp 89). P3: the LG potential V(X_bar) is past threshold.")
    print("   Binary gap: the free single-bit Hessian is 2 (Comp 112).")
    print("   Lemma -- V(X_bar) with X_bar LINEAR has a RANK-1 Hessian")
    print("   (V''/D^2 times all-ones), so it shifts exactly the symmetric")
    print("   (S_D-singlet) mode and NOTHING else. Conclusion -- past")
    print("   threshold X_bar is the unique soft mode; the S_D standard rep")
    print("   (D-1 modes) and all |S|>=2 shells stay at or above the binary")
    print("   gap. A clean spectral gap separates the single Higgs from all")
    print("   other substrate modes.")
    print()
    print("  WHY THE GAP IS PROTECTED (robust beyond quadratic order):")
    print("   Any S_D-invariant interaction is a function of the invariant")
    print("   collective coordinates; to leading (Gaussian) order that is")
    print("   X_bar alone, so its Hessian is rank-1. The standard-rep modes")
    print("   are pinned at the binary gap by S_D symmetry -- no invariant")
    print("   quadratic form can lift them differentially. The gap is")
    print("   SYMMETRY-PROTECTED, not fine-tuned.")
    print()
    print("  WHAT THIS MEANS FOR (B):")
    print("   M6 supplies exactly the premise M5 needed: P3's collapse IS")
    print("   total -- a UNIQUE light field (the Higgs = X_bar), with a")
    print("   symmetry-protected gap to every other substrate mode, so no")
    print("   residual light field carries off part of the normalisation.")
    print("   By M5, total reduction => the bridge factor is the embedding")
    print("   norm of the symmetric Higgs vacuum = e^-1. Hence")
    print("   lambda_SM(M_*) = b e^-1, Bridge Premise (B).")
    print()
    print("  HONEST RESIDUAL:")
    print("   - The angular doublet modes (3 Goldstones) are EATEN by the")
    print("     gauge fields (massive W,Z), not residual light scalars, so")
    print("     they do not violate uniqueness; the surviving light SCALAR")
    print("     is the single radial Higgs. (The doublet O(4) structure")
    print("     enters the Goldstone sector, not the amplitude/lambda")
    print("     sector this bridge concerns.)")
    print("   - The rank-1 lemma is exact at Gaussian order and")
    print("     symmetry-protected beyond it; a fully rigorous all-orders")
    print("     statement would track the S_D-invariant effective potential")
    print("     to all orders. The symmetry argument makes a degeneracy-")
    print("     lifting of the standard rep impossible, so the gap cannot")
    print("     close, but a journal-level proof would state this as an")
    print("     S_D-equivariant Morse-Bott lemma.")
    print()
    print("  NET: M5 + M6 CLOSE (B) at the structural level -- the last")
    print("  premise (Pi-total) is now a theorem (unique soft mode,")
    print("  symmetry-protected gap) resting only on P1, P3, and the binary")
    print("  gap, all PST primitives. The bridge lambda_SM = b e^-1 follows")
    print("  with NO separate postulate. The remaining work is to upgrade")
    print("  the symmetry-protection argument to an all-orders equivariant")
    print("  lemma -- a rigour task, not an open structural question.")


if __name__ == "__main__":
    main()
