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

Computation 110 -- Bridge Premise (B) attack, milestones M1 + M2:
                   discrete Wilson-Polchinski flow + wave-function
                   renormalisation identification of the bridge factor
=========================================================================
STATUS (v26.13): IN PROGRESS.  This computation sets up the framework
for closing Bridge Premise (B) from P1-P3 alone, via the wave-function
renormalisation route, and reduces the open problem to a single sharp
statement (milestone M3).  It does NOT close (B).  It is the scaffolding
+ precise target, analogous to how Comp 101 reduced (B) to two sub-
questions before Comp 103 attacked one of them.

THE TARGET (Bridge Premise B)
==============================
The substrate-side factor is closed from P1-P3 (Comp 100):

    Z_H(beta_KO) = E_mu[exp(-beta_KO * X_bar)]
                 = ((1 + e^(-beta_KO/D))/2)^D
                 -> e^(-beta_KO/2) = e^(-1)   at beta_KO = 2, D -> infty.

Bridge Premise (B) is the identification

    lambda_SM(M_*) = b * Z_H(beta_KO) = (1/4) * e^(-1) = 0.0920    (B)

between the SM Higgs quartic at M_* and the substrate bare quartic
b = lambda_PST = 1/4 times the substrate partition function.

WHY THE NAIVE ROUTE FAILED (Comp 103)
======================================
Standard Wilsonian threshold matching of a quartic is ADDITIVE in the
loop corrections (lambda_IR = lambda_UV + finite), not a multiplicative
dressing.  Comp 103 showed the multiplicative form is NOT derivable as a
path-integral (measure change-of-variable) Jacobian:
  - linear-map determinant: configuration-independent (constant);
  - Cramer-Bernoulli LDP: Gaussian in (X_bar - 1/2), not exp(X_bar).

THE OPENING (this computation)
===============================
A coupling flows MULTIPLICATIVELY under the RG -- not additively --
precisely when the flow is dominated by WAVE-FUNCTION (field-strength)
renormalisation Z_phi:

    psi -> Z_phi^(1/2) psi   =>   lambda -> lambda / Z_phi^2 (with Z_Gamma4 = 1).

This is exactly the multiplicative structure (B) needs, and it is the
reinterpretation Comp 101 proposed (Z^2 as wave-function renormalisation
rather than coupling renormalisation).  The sharpened conjecture:

    THE BRIDGE FACTOR IS THE FIELD-STRENGTH RENORMALISATION OF THE
    SUBSTRATE-TO-SM PROJECTION Pi, with Z_phi^2 = Z_H(beta_KO) = e^(-1).

i.e. (B) is NOT a coupling-matching Jacobian (Comp 103 killed that), it
is the wave-function renormalisation of the modal field as it projects
to the SM Higgs.

This computation does:
  M1 -- set up the discrete Wilson-Polchinski flow on the Boolean
        lattice with cutoff f(x) = e^(-x) (Comp 100) and matched scaling
        Lambda^2 = D; show the flow reduces to the low Walsh shells
        V_0 + V_1 where X_bar lives (Comp 98).
  M2 -- define the field-strength renormalisation Z_phi from the
        substrate two-point function of the order-parameter field, and
        show that IF the matched-scaling flow weights the field by the
        substrate Boltzmann factor exp(-beta_KO X_bar), then
        Z_phi^2 = Z_H(beta_KO) = e^(-1) numerically.
  M3 (NOT done here) -- prove the Polchinski flow actually GENERATES the
        weight exp(-beta_KO X_bar) as its field-strength kernel.  This is
        the genuinely new mathematics and the remaining crux.

=========================================================================
"""

import math


# -------------------------------------------------------------------------
# Substrate primitives (P1): Bernoulli measure, Walsh basis, Boolean
# Laplacian.  Conventions match Comp 100: Delta = sum_a (1 - tau_a), each
# (1 - tau_a) has eigenvalues {0, 2}, so Delta chi_S = 2|S| chi_S.
# -------------------------------------------------------------------------

def boolean_laplacian_eigenvalue(s):
    """Delta chi_S = 2|S| chi_S  (|S| = s)."""
    return 2 * s


def cutoff(x):
    """Matched-scaling cutoff f(x) = e^(-x), forced by P1's tensor-product
    independence (Comp 100: f(x+y) = f(x)f(y) => f = exp)."""
    return math.exp(-x)


def propagator_mode(s, D):
    """Substrate propagator in Walsh mode of weight s at matched scaling
    Lambda^2 = D:   G_S = f(2|S|/Lambda^2) / (2|S|)  for |S| >= 1.
    The zero mode (s = 0) is the order parameter / massless direction and
    is handled separately (it is NOT a propagating mode integrated out)."""
    if s == 0:
        return None  # order-parameter zero mode
    lam2 = D
    return cutoff(boolean_laplacian_eigenvalue(s) / lam2) / boolean_laplacian_eigenvalue(s)


# -------------------------------------------------------------------------
# The Higgs Hamiltonian / order-parameter field (Comp 89, Comp 98):
#   X_bar(C) = (1/D) sum_a C_a,  with Walsh decomposition
#   X_bar = (1/2) chi_emptyset - (1/(2D)) sum_{|S|=1} chi_S
# supported entirely on the lowest two Walsh shells V_0 (+) V_1.
# -------------------------------------------------------------------------

def xbar_walsh_support():
    """Return the Walsh-shell support of X_bar (Comp 98)."""
    return {0: 0.5,        # coefficient of chi_emptyset
            1: -0.5}       # coefficient of (1/D) sum_{|S|=1} chi_S


def xbar_mean():
    """E_mu[X_bar] = 1/2 (Bernoulli site mean)."""
    return 0.5


def xbar_variance(D):
    """Var_mu(X_bar) = (1/D^2) * D * Var(C_a) = (1/D^2)*D*(1/4) = 1/(4D)."""
    return 1.0 / (4 * D)


# -------------------------------------------------------------------------
# KO-tempered Bernoulli partition function (Comp 87/88/100):
#   Z_H(beta) = E_mu[exp(-beta X_bar)] = ((1 + e^(-beta/D))/2)^D
#            -> e^(-beta/2)   as D -> infty.
# At beta_KO = 2 (one-bit Clifford eigenvalue range, Comp 100/102): e^(-1).
# -------------------------------------------------------------------------

def Z_H(beta, D):
    """Closed-form KO-tempered partition function."""
    return ((1.0 + math.exp(-beta / D)) / 2.0) ** D


def Z_H_limit(beta):
    """D -> infty limit."""
    return math.exp(-beta / 2.0)


# -------------------------------------------------------------------------
# M2: wave-function renormalisation from the substrate two-point function.
#
# The substrate generating functional with a source J coupled to the
# order-parameter field, and the matched-scaling Boltzmann weight
# exp(-beta X_bar) supplied by the substrate fluctuations:
#
#   Z[J] = E_mu[ exp(-beta X_bar + J * field) ].
#
# The NORMALISATION Z[0] = Z_H(beta) is the multiplicative factor that
# dresses the bare quartic.  Identifying it as a FIELD-STRENGTH
# renormalisation: the projected SM field phi = Z_phi^(1/2) psi is
# canonically normalised only after the substrate fluctuations are
# integrated with their matched-scaling weight, which rescales the field
# normalisation by exactly Z[0]:
#
#   Z_phi^2 = Z[0] / Z[0]_{beta=0} = Z_H(beta_KO) / 1 = Z_H(beta_KO).
#
# Then with trivial vertex renormalisation (Z_Gamma4 = 1 at tree level,
# CC inner fluctuations; Comp 101 sub-question 2 satisfied):
#
#   lambda_SM(M_*) = b * Z_phi^2 = (1/4) * Z_H(beta_KO) -> (1/4) e^(-1).
# -------------------------------------------------------------------------

def wavefunction_renormalisation(beta, D):
    """Z_phi^2 candidate = Z_H(beta) (the field-strength rescaling under
    the matched-scaling projection).  CONDITIONAL on M3 (that the flow
    generates the weight exp(-beta X_bar))."""
    return Z_H(beta, D)


def main():
    print("=" * 72)
    print("Computation 110: Bridge Premise (B) attack -- M1 + M2")
    print("Wave-function renormalisation route (sets up the M3 target)")
    print("=" * 72)
    print()

    BETA_KO = 2  # one-bit Clifford Cl(1,0) eigenvalue range (Comp 100/102)
    b = 0.25     # lambda_PST, doublet convention

    # ----- M1: discrete Wilson-Polchinski flow setup -----
    print("M1.  DISCRETE WILSON-POLCHINSKI FLOW")
    print("-" * 72)
    print("  Cutoff f(x) = e^(-x) (Comp 100, forced by P1 independence).")
    print("  Boolean Laplacian Delta chi_S = 2|S| chi_S.")
    print("  Matched scaling Lambda^2 = D.")
    print("  Propagator in mode S (|S| >= 1): G_S = e^(-2|S|/D) / (2|S|).")
    print()
    D = 12
    print(f"  Sample propagators at D = {D}:")
    print(f"    {'|S|':>4} {'eig 2|S|':>9} {'cutoff':>10} {'G_S':>12}")
    for s in range(0, 6):
        if s == 0:
            print(f"    {s:>4} {'0':>9} {'1 (zero mode = order parameter)':>30}")
        else:
            eig = boolean_laplacian_eigenvalue(s)
            c = cutoff(eig / D)
            g = propagator_mode(s, D)
            print(f"    {s:>4} {eig:>9} {c:>10.5f} {g:>12.6f}")
    print()
    print("  X_bar (the Higgs Hamiltonian, Comp 89) is supported ONLY on")
    print("  the lowest two Walsh shells V_0 (+) V_1 (Comp 98):")
    print("    X_bar = (1/2) chi_emptyset - (1/(2D)) sum_{|S|=1} chi_S.")
    print("  => integrating out the |S| >= 2 modes is a TRIVIAL fixed-point")
    print("     step for X_bar (Comp 98): the flow leaves X_bar unchanged")
    print("     until it reaches the low shells.  The relevant field")
    print("     content at M_* is exactly X_bar.")
    print()

    # ----- M2: wave-function renormalisation -----
    print("M2.  WAVE-FUNCTION RENORMALISATION FROM THE TWO-POINT FUNCTION")
    print("-" * 72)
    print(f"  Order-parameter field statistics under mu:")
    print(f"    E_mu[X_bar]   = {xbar_mean()}")
    for Dv in (10, 100, 1000):
        print(f"    Var_mu(X_bar) = 1/(4D) = {xbar_variance(Dv):.6e}   (D = {Dv})")
    print()
    print("  Field-strength renormalisation candidate (CONDITIONAL on M3):")
    print("    Z_phi^2 = Z[0] = E_mu[exp(-beta_KO X_bar)] = Z_H(beta_KO)")
    print()
    print(f"  Numerical Z_phi^2 = Z_H(beta_KO = {BETA_KO}):")
    print(f"    {'D':>6} {'Z_phi^2':>12} {'dev from e^-1':>16}")
    e_inv = math.exp(-1.0)
    for Dv in (6, 10, 100, 1000, 10000):
        z = wavefunction_renormalisation(BETA_KO, Dv)
        dev = 100.0 * (z - e_inv) / e_inv
        print(f"    {Dv:>6} {z:>12.6f} {dev:>15.3f}%")
    print(f"    {'limit':>6} {e_inv:>12.6f} {'0.000':>15}%")
    print()
    print("  => Z_phi^2 -> e^(-1) (D -> infty), reproducing the substrate")
    print("     factor of Comp 100 in the wave-function-renormalisation")
    print("     reading.")
    print()

    # ----- the resulting bridge value -----
    print("RESULTING BRIDGE VALUE (conditional on M3)")
    print("-" * 72)
    print("  With Z_Gamma4 = 1 (trivial vertex, tree-level CC inner")
    print("  fluctuations, Comp 101 sub-question 2):")
    print(f"    lambda_SM(M_*) = b * Z_phi^2 = {b} * Z_H({BETA_KO})")
    for Dv in (100, 10000):
        lam = b * Z_H(BETA_KO, Dv)
        print(f"      D = {Dv:>5}: {lam:.6f}")
    lam_lim = b * e_inv
    print(f"      limit:     {lam_lim:.6f}   (= e^(-1)/4)")
    print(f"    observed lambda_SM(M_*) ~ 0.0927 (Buttazzo)")
    print(f"    ratio: {lam_lim/0.0927:.4f}")
    print()

    # ----- honest status: what M1+M2 achieve, what M3 must prove -----
    print("=" * 72)
    print("STATUS: what M1 + M2 achieve, and the remaining crux (M3)")
    print("=" * 72)
    print()
    print("  ACHIEVED (M1, M2):")
    print("   - The discrete Wilson-Polchinski flow is set up with the")
    print("     P1-forced cutoff f = exp and matched scaling Lambda^2 = D.")
    print("   - The flow reduces to the low Walsh shells where X_bar lives")
    print("     (Comp 98), so the field content at M_* is exactly X_bar.")
    print("   - The bridge factor is RE-CAST as a field-strength")
    print("     renormalisation Z_phi^2 (multiplicative by construction),")
    print("     side-stepping the additive-matching obstruction that")
    print("     Comp 103 established for the coupling-Jacobian reading.")
    print("   - Numerically, Z_phi^2 = Z_H(beta_KO) -> e^(-1), reproducing")
    print("     the Comp 100 value in the new reading.")
    print()
    print("  NOT ACHIEVED -- the remaining crux (M3):")
    print("   The identification Z_phi^2 = E_mu[exp(-beta_KO X_bar)] is so")
    print("   far IMPOSED (the field is weighted by the substrate Boltzmann")
    print("   factor).  What must be PROVEN is that the Wilson-Polchinski")
    print("   flow GENERATES this weight as its field-strength kernel --")
    print("   i.e. that integrating the substrate fluctuations from")
    print("   Lambda = sqrt(D) down to M_* produces exactly the multiplier")
    print("   exp(-beta_KO X_bar) on the order-parameter field, with")
    print("   beta_KO = 2 inherited from the one-bit Clifford range.")
    print()
    print("   Until M3 is proven, this is the SAME gap as (B) in a sharper")
    print("   form: 'derive the multiplicative bridge factor' has become")
    print("   'show the Polchinski field-strength kernel is the KO-tempered")
    print("   Boltzmann weight'.  That is a concrete, well-posed RG-flow")
    print("   computation -- the natural next milestone -- and it either")
    print("   closes (B) or yields a Comp-103-style sharp obstruction.")
    print()
    print("  This computation does NOT close Bridge Premise (B).")


if __name__ == "__main__":
    main()
