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

Computation 111 -- Bridge Premise (B) attack, milestone M3:
                   the field-strength kernel is forced into exp(-beta X_bar)
                   form by P1's product structure (NOT the Gaussian that
                   obstructs the Jacobian route)
=========================================================================
STATUS (v26.13): this is the crux of the wave-function-renormalisation
attack on Bridge Premise (B) set up in Comp 110.  It establishes the
genuinely-new structural content and assesses honestly how far it
carries (B).

THE M3 TARGET (from Comp 110)
==============================
Show that the substrate-to-SM field-strength (wave-function)
renormalisation Z_phi -- the multiplicative dressing of the order-
parameter field under the matched-scaling flow -- has the form
exp(-beta_KO X_bar), so that

    Z_phi^2 = E_mu[exp(-beta_KO X_bar)] = Z_H(beta_KO) -> e^(-1).

This is the multiplicative factor (B) needs; the wave-function reading
makes it multiplicative by construction (lambda_SM = b * Z_phi^2),
side-stepping the additive-matching obstruction.

WHY THE JACOBIAN ROUTE FAILED, AND WHY THIS ONE IS DIFFERENT
============================================================
Comp 103 asked whether the path-integral MEASURE Jacobian of the
projection Pi equals exp(-beta X_bar).  It found NO:
  - linear-map determinant: configuration-independent (constant);
  - Cramer-Bernoulli LDP near the vacuum: a GAUSSIAN weight
    exp(-alpha (X_bar - 1/2)^2), not exp(-beta X_bar).

The field-strength renormalisation is a DIFFERENT object: it is the
per-configuration normalisation of the order-parameter field (the
kinetic-operator / two-point-function normalisation), not the measure
Jacobian.  The decisive structural fact:

    THE FIELD-STRENGTH KERNEL MUST RESPECT P1's PRODUCT STRUCTURE.

P1's Bernoulli measure is a product measure mu = (x)_a Bern(1/2).  The
matched-scaling cutoff is forced to factorise over bits (Comp 100:
f(x+y) = f(x)f(y) => f = exp).  So the fluctuation integration that
dresses the field factorises over bits, and the per-configuration
dressing K(C) is a PRODUCT kernel K(C) = prod_a g(C_a).

A product kernel over Boolean bits is necessarily of exp(-beta X_bar)
form:

    K(C) = prod_a g(C_a),   C_a in {0,1}
         = exp( sum_a [ln g(0) + (ln g(1) - ln g(0)) C_a] )
         = exp( D ln g(0) ) * exp( (ln g(1) - ln g(0)) * sum_a C_a )
         = const * exp( -beta X_bar ),   beta := -D (ln g(1) - ln g(0)) / D
                                              = -(ln g(1) - ln g(0)) ... [linear in X_bar]

i.e. a bit-factorised multiplicative kernel is exp(LINEAR in X_bar),
NOT exp(QUADRATIC in X_bar).  The Gaussian exp(-alpha (X_bar - 1/2)^2)
that obstructs the Jacobian route has cross-terms C_a C_b and does NOT
factorise -- so it is EXCLUDED as a field-strength kernel by P1's
product structure.

This is the genuinely-new content of M3: the wave-function route is
NOT obstructed, because the field-strength kernel is forced into the
exp(-beta X_bar) form that the substrate side already evaluates to
e^(-1) (Comp 100), whereas the Jacobian route was forced into a
Gaussian that cannot reproduce e^(-1).

This computation verifies the structural claim numerically and assesses
the residual.
=========================================================================
"""

import math
import itertools


def xbar(C):
    """Order parameter X_bar(C) = |C|/D."""
    return sum(C) / len(C)


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


# -------------------------------------------------------------------------
# 1. exp(-beta X_bar) FACTORISES over bits; the Gaussian does NOT.
#    Demonstrated by the induced bit-bit correlation under the tilted
#    measure: a product kernel keeps the bits independent (zero
#    correlation); a non-product kernel correlates them.
# -------------------------------------------------------------------------

def tilted_bit_correlation(D, weight):
    """
    Under the measure proportional to mu(C) * weight(C), compute the
    connected bit-bit correlation Cov(C_0, C_1) = <C_0 C_1> - <C_0><C_1>.
    Zero correlation  <=>  the weight factorises over bits (preserves P1's
    product structure).  weight is a function of the config C.
    """
    Z = 0.0
    e0 = e1 = e01 = 0.0
    for C in all_configs(D):
        w = weight(C)            # mu(C) = 2^-D is a constant factor, cancels
        Z += w
        e0 += C[0] * w
        e1 += C[1] * w
        e01 += C[0] * C[1] * w
    e0 /= Z; e1 /= Z; e01 /= Z
    return e01 - e0 * e1


def main():
    print("=" * 72)
    print("Computation 111: Bridge Premise (B) attack -- M3")
    print("Field-strength kernel forced into exp(-beta X_bar) by P1")
    print("=" * 72)
    print()

    BETA_KO = 2.0
    e_inv = math.exp(-1.0)

    # ---- 1. the structural distinction: product vs non-product kernel ----
    print("1.  exp(-beta X_bar) PRESERVES P1's product structure;")
    print("    the Gaussian exp(-alpha (X_bar-1/2)^2) BREAKS it.")
    print("-" * 72)
    print("    Test: induced bit-bit correlation Cov(C_0, C_1) under the")
    print("    tilted measure mu * kernel.  Zero <=> bits stay independent")
    print("    <=> kernel factorises over bits.")
    print()
    print(f"    {'D':>4} {'Cov [exp(-2 X_bar)]':>22} {'Cov [Gaussian]':>18}")
    for D in (4, 6, 8, 10):
        cov_exp = tilted_bit_correlation(
            D, lambda C: math.exp(-BETA_KO * xbar(C)))
        # Gaussian tuned to a comparable width: alpha chosen O(D) so the
        # weight is non-trivial; the POINT is only whether Cov = 0 or not.
        alpha = float(D)
        cov_gauss = tilted_bit_correlation(
            D, lambda C: math.exp(-alpha * (xbar(C) - 0.5) ** 2))
        print(f"    {D:>4} {cov_exp:>22.2e} {cov_gauss:>18.6f}")
    print()
    print("    exp(-beta X_bar): Cov = 0 to machine precision -- the bits")
    print("    remain INDEPENDENT, so the kernel respects P1's product")
    print("    measure.  The Gaussian: Cov != 0 -- it CORRELATES the bits,")
    print("    breaking the product structure.  A field-strength kernel")
    print("    built from the factorising matched-scaling cutoff (Comp 100)")
    print("    CANNOT be the Gaussian; it is forced into exp(-beta X_bar).")
    print()

    # ---- 2. the exp(-beta X_bar) kernel evaluates to e^-1 at beta=2 ----
    print("2.  THE FORCED KERNEL EVALUATES TO e^(-1) AT beta_KO = 2")
    print("-" * 72)
    print("    Z_phi^2 = E_mu[exp(-beta_KO X_bar)] = ((1+e^(-beta_KO/D))/2)^D")
    print(f"    {'D':>6} {'Z_phi^2':>12} {'dev e^-1':>12}")
    for D in (6, 10, 100, 1000, 10000):
        z = ((1.0 + math.exp(-BETA_KO / D)) / 2.0) ** D
        print(f"    {D:>6} {z:>12.6f} {100*(z-e_inv)/e_inv:>11.3f}%")
    print(f"    {'limit':>6} {e_inv:>12.6f} {'0.000':>11}%")
    print()
    print("    Identical to Comp 100's matched-scaling spectral-action")
    print("    trace (1/2^D) Tr exp(-Delta/D): same number, because")
    print("    X_bar = |C|/D and the Boolean Laplacian eigenvalue 2|S|")
    print("    with binomial multiplicity mirror the bit-sum.  The")
    print("    field-strength renormalisation IS the matched-scaling")
    print("    heat-kernel normalisation of the order-parameter field.")
    print()

    # ---- 3. why beta = 2 (the one-bit Clifford input, shared with Comp 100) ----
    print("3.  beta_KO = 2 -- the matched-scaling exponent")
    print("-" * 72)
    print("    The per-bit cutoff weight is f(2/Lambda^2) with the Boolean")
    print("    Laplacian eigenvalue 2 = the one-bit Clifford Cl(1,0)")
    print("    eigenvalue range {0,2} of (1-tau_a) (Comp 100, 102).  At")
    print("    matched scaling Lambda^2 = D the per-bit exponent is 2/D, so")
    print("    beta_KO = 2.  This is the SAME structural input the substrate")
    print("    side already uses (Comp 100) -- not a new assumption.")
    print()

    # ---- 4. honest assessment ----
    print("=" * 72)
    print("ASSESSMENT: how far M3 carries Bridge Premise (B)")
    print("=" * 72)
    print()
    print("  ESTABLISHED (genuinely new, solid):")
    print("   - The field-strength kernel must respect P1's product")
    print("     structure (the matched-scaling cutoff factorises over bits,")
    print("     Comp 100).  A bit-factorised multiplicative kernel is")
    print("     necessarily exp(LINEAR in X_bar) = exp(-beta X_bar).")
    print("   - The Gaussian exp(-alpha (X_bar-1/2)^2) that obstructs the")
    print("     Jacobian route (Comp 103) is EXCLUDED: it correlates the")
    print("     bits and breaks the product structure (verified, part 1).")
    print("   => The wave-function-renormalisation route is NOT obstructed,")
    print("      and is structurally DISTINCT from the failed Jacobian route.")
    print("      This is the key advance over Comp 103.")
    print("   - The forced kernel evaluates to Z_phi^2 = e^(-1) at beta=2")
    print("     (part 2), identical to the substrate-side Comp 100 value.")
    print()
    print("  REDUCED TO SHARED INPUTS (not independently new):")
    print("   - beta_KO = 2 is the one-bit Clifford matched-scaling input")
    print("     already used by the substrate side (Comp 100).  M3 does not")
    print("     re-derive it; it inherits it.  (The residual 'two 2's'")
    print("     calibration is open-research item 1.4.3.)")
    print("   - The identification 'field-strength renormalisation =")
    print("     matched-scaling heat-kernel trace' is the standard QFT")
    print("     relation (Z_phi from the kinetic-operator normalisation),")
    print("     applied on the discrete substrate via the same Lambda^2 = D")
    print("     matched scaling as Comp 100.  It is asserted via the")
    print("     standard relation, not proven ab initio on the lattice.")
    print()
    print("  NET RESULT:")
    print("   Bridge Premise (B) is ADVANCED from 'open structural")
    print("   hypothesis with a known obstruction (Comp 103)' to 'derivable")
    print("   via wave-function renormalisation, modulo the SAME matched-")
    print("   scaling + one-bit-Clifford inputs already accepted for the")
    print("   substrate side (Comp 100)'.  The wave-function route is shown")
    print("   unobstructed -- the field-strength kernel is forced into the")
    print("   exp(-beta X_bar) form, not the Gaussian -- which is the")
    print("   structural reason (B) can hold at all.")
    print()
    print("   This is NOT yet a clean 'B closed from P1-P3 alone': the")
    print("   beta=2 calibration and the Z_phi<->trace identification are")
    print("   inherited from the substrate side, not independently derived.")
    print("   But (B) and the substrate-side e^(-1) now rest on EXACTLY the")
    print("   same inputs -- so PST's foundational claim sharpens to:")
    print("   'P1-P3 + (matched scaling Lambda^2=D) + (one-bit Clifford")
    print("   beta=2)', with NO separate CC-framework postulate needed for")
    print("   the SM side.  That removes the v26.09 concern that the bridge")
    print("   leaned on an inherited-but-obstructed heat-kernel CC.")


if __name__ == "__main__":
    main()
