#!/usr/bin/env python3
"""
Computation 74 -- Chamseddine-Connes inner-fluctuation Yukawa for the PST substrate triple
============================================================================================
First-cut attempt at the Chamseddine-Connes inner-fluctuation calculation
identified as the remaining structural content of the Z^2 = e^{-1}
conjecture (Computation 72, eq.~\eqref{eq:y-fixed}).

CONTEXT
-------
Comp 72 reduced the Z^2 conjecture to a single scalar condition: the
substrate-Higgs Yukawa coupling at matched scaling Lambda = sqrt(D)
must satisfy

    y_substrate / Lambda = mu_site^{1/4} = (1/2)^{1/4} = 2^{-1/4}
                        ~ 0.8409.

Comp 72 left open whether the Chamseddine-Connes inner-fluctuation
calculation D -> D + A + epsilon' J A J^{-1} delivers this specific
value when A is built from elements of the quaternion factor
H subset A_F = C (+) H (+) M_3(C).

THIS COMPUTATION
----------------
Performs the inner-fluctuation calculation for an explicit and natural
Higgs-perturbation parameterisation, computes the resulting effective
Yukawa coupling y_eff, and compares against the Comp 72 target.

SETUP
-----
Substrate Hilbert space H_sub = C^{2^D} carrying the Clifford algebra
Cl(0, D) via Jordan-Wigner generators

    e_a = sigma_z^{(x)(a-1)} (x) sigma_x (x) I^{(x)(D-a)},   a = 1, ..., D

so that {e_a, e_b} = 2 delta_{ab} I.  The substrate Dirac is

    D_sub = sum_{a=1}^D e_a,        D_sub^2 = D * I,

with eigenvalues +/- sqrt(D) each of multiplicity 2^{D-1}.

The quaternion factor H subset A_F embeds naturally into Cl(0, 2)
subset Cl(0, D):

    H = span{I, e_1, e_2, e_1 e_2},

with the volume element omega = e_1 e_2 satisfying omega^2 = -I (the
quaternion imaginary unit).

NATURAL HIGGS PERTURBATION
--------------------------
For a real scalar Higgs field phi, the natural inner-fluctuation
parameterisation is

    A = i phi * [D_sub, omega] / 2

(the factor /2 is the standard Connes-Chamseddine normalisation).
Compute [D_sub, omega]:

    [D_sub, omega] = sum_a [e_a, e_1 e_2]
                   = [e_1, e_1 e_2] + [e_2, e_1 e_2] + sum_{a>=3} [e_a, e_1 e_2]
                   = (anticomm computations below)

For a >= 3: e_a anticommutes with both e_1 and e_2, so e_a commutes with
the PRODUCT e_1 e_2 (two sign flips); [e_a, e_1 e_2] = 0.
For a = 1: [e_1, e_1 e_2] = e_1 e_1 e_2 - e_1 e_2 e_1 = e_2 - (-e_1^2 e_2)
                          = e_2 + e_2 = 2 e_2.
For a = 2: [e_2, e_1 e_2] = e_2 e_1 e_2 - e_1 e_2 e_2 = -e_1 - e_1 = -2 e_1.

So [D_sub, omega] = 2 e_2 - 2 e_1 = -2 (e_1 - e_2).
And A = i phi * (-2)(e_1 - e_2) / 2 = -i phi (e_1 - e_2).

PERTURBED DIRAC AND ITS SQUARE
------------------------------
D_phi = D_sub + A = sum_a e_a - i phi (e_1 - e_2)
     = (1 - i phi) e_1 + (1 + i phi) e_2 + sum_{a>=3} e_a.

(The J A J^{-1} term contributes additively under KO-6 reality with
epsilon' = +1; this script computes the A contribution alone and notes
the doubling factor where relevant.)

D_phi^2 = sum_a (coeff_a)^2 + sum_{a != b} coeff_a coeff_b {e_a, e_b}.
With {e_a, e_b} = 2 delta_{ab} I for a != b (vanishing), we get

    D_phi^2 = |1 - i phi|^2 + |1 + i phi|^2 + (D - 2)
           = (1 + phi^2) + (1 + phi^2) + (D - 2)
           = D + 2 phi^2.

[Note: this is real and proportional to identity, so eigenvalues of
D_phi are +/- sqrt(D + 2 phi^2), each with multiplicity 2^{D-1}.]

SPECTRAL ACTION
---------------
At matched scaling Lambda = sqrt(D), the perturbed eigenvalues are

    lambda_+/-(phi) / Lambda = +/- sqrt(1 + 2 phi^2 / D).

With Gaussian cutoff f(x) = exp(-x^2),

    f(lambda / Lambda) = exp(-(1 + 2 phi^2 / D)) = exp(-1) * exp(-2 phi^2 / D).

Total spectral action / 2^D:

    S(D_phi, Lambda, f) / 2^D = exp(-1) * exp(-2 phi^2 / D)
                              = exp(-1) * [1 - 2 phi^2 / D + 2 phi^4 / D^2 - ...]

The phi^4 coefficient is 2 exp(-1) / D^2.

COMPARE TO COMP 72
------------------
Comp 72 predicted phi^4 coefficient = exp(-1) * y^4 / (2 Lambda^4)
                                    = exp(-1) * y^4 / (2 D^2).

Equating: y^4 / (2 D^2) = 2 / D^2  =>  y^4 = 4  =>  y = sqrt(2).

So this Higgs perturbation gives y = sqrt(2) at ALL matched scalings,
D-INDEPENDENT (in absolute terms, not as y/Lambda).

y / Lambda = sqrt(2) / sqrt(D).

For D = 2:  y/Lambda = 1.
For D = 4:  y/Lambda = 0.7071.
For D = 6:  y/Lambda = 0.5774.

The Comp 72 target was y/Lambda = 2^{-1/4} = 0.8409 (D-independent).

CONCLUSION
----------
The natural Higgs inner-fluctuation A = i phi [D_sub, omega]/2 does NOT
deliver the Comp 72 target.  It gives y = sqrt(2) at ALL D (in absolute
units), or y/Lambda = sqrt(2/D) (decreasing in D).  The Comp 72 target
was D-independent y/Lambda = 2^{-1/4}.

This is an HONEST partial answer: the specific Higgs perturbation tested
here does not close Z^2 = e^{-1}.  At D = 4 (the only D at which
sqrt(2)/sqrt(D) and 2^{-1/4} agree to 16%), there is approximate
agreement; at other D the calibration breaks.

Three plausible explanations for the discrepancy:

  (1) The candidate identification Z^2 = e^{-1} is genuinely a
      0.8% numerical near-coincidence, not a structural identity.
      The substrate-side S_sub/2^D = e^{-1} is exact (Comp 62)
      independently of any Higgs sector; the Z^2 SM-side value
      depends on RGE truncations and is naturally near e^{-1}
      without requiring structural identification.

  (2) The Higgs perturbation should be parameterised differently,
      e.g. via a SUM over multiple quaternion generators, or via the
      full A_F = C (+) H (+) M_3(C) inner-fluctuation (not just H),
      or with a specific Hermiticity / Reality / order-one constraint
      that fixes y/Lambda = 2^{-1/4} structurally.  This would require
      working through the full Chamseddine-Connes-Marcolli machinery.

  (3) The matched scaling Lambda = sqrt(D) is not the right cutoff
      identification; a different Lambda(D) might deliver the target.

REMAINING WORK
--------------
The cleanest next step is to compute the y value under the FULL
CC inner-fluctuation including the J A J^{-1} term and the
order-one constraint on a chosen H_F representation.  This is
a multi-day calculation that would either:
  - deliver y = Lambda * 2^{-1/4} exactly (closing Z^2 = e^{-1}), or
  - confirm the discrepancy structurally (retiring the candidate
    identification as a genuine 0.8% near-coincidence).
"""

from __future__ import annotations
import math
import numpy as np


def jordan_wigner(D: int):
    """Returns the Hermitian Jordan-Wigner generators e_1, ..., e_D
    on the substrate Hilbert space C^{2^D}.
    {e_a, e_b} = 2 delta_{ab} I; e_a^dagger = e_a; e_a^2 = I.
    """
    sigma_x = np.array([[0, 1], [1, 0]], dtype=complex)
    sigma_z = np.array([[1, 0], [0, -1]], dtype=complex)
    I = np.eye(2, dtype=complex)
    generators = []
    for a in range(1, D + 1):
        # e_a = sigma_z (x) ... (x) sigma_z (x) sigma_x (x) I (x) ... (x) I
        op = np.array([[1.0]], dtype=complex)
        for k in range(1, D + 1):
            if k < a:
                op = np.kron(op, sigma_z)
            elif k == a:
                op = np.kron(op, sigma_x)
            else:
                op = np.kron(op, I)
        generators.append(op)
    return generators


def main():
    print("=" * 100)
    print("  Computation 74 -- CC inner-fluctuation Yukawa for the PST substrate triple")
    print("=" * 100)
    print()

    print("SETUP: substrate Dirac D_sub = sum_a e_a, Cl(0, D) Jordan-Wigner generators.")
    print()

    for D in [2, 4, 6, 8]:
        gens = jordan_wigner(D)
        # Verify anticommutation
        ok = True
        for a in range(D):
            for b in range(D):
                anticomm = gens[a] @ gens[b] + gens[b] @ gens[a]
                expected = 2 * (1.0 if a == b else 0.0) * np.eye(2 ** D, dtype=complex)
                if not np.allclose(anticomm, expected):
                    ok = False
        # Build D_sub and verify D_sub^2 = D * I
        D_sub = sum(gens)
        Dsub_sq = D_sub @ D_sub
        ok2 = np.allclose(Dsub_sq, D * np.eye(2 ** D, dtype=complex))
        eigenvalues = np.linalg.eigvalsh(D_sub)
        eigenvalues_unique = sorted(set(round(float(np.real(v)), 6) for v in eigenvalues))
        Lambda = math.sqrt(D)
        print(f"  D = {D}: anticomm OK = {ok}; D_sub^2 = D I OK = {ok2}; "
              f"eigenvalues = {eigenvalues_unique}; matched Lambda = sqrt({D}) = {Lambda:.4f}")
    print()

    print("HIGGS PERTURBATION A = i phi [D_sub, omega] / 2, omega = e_1 e_2.")
    print("-" * 100)
    print()
    print(f"  {'D':>4}  {'phi^4 coeff':>14}  {'y from Comp 72':>14}  "
          f"{'y/Lambda':>10}  {'target 2^(-1/4)':>16}  {'ratio':>10}")
    target = 2 ** (-0.25)
    for D in [2, 4, 6, 8]:
        # phi^4 coefficient (from analytic derivation in docstring):
        # exp(-1) * 2 / D^2
        phi4_coeff = math.exp(-1) * 2 / D ** 2
        # Comp 72: phi^4 coefficient = exp(-1) * y^4 / (2 * Lambda^4) at Lambda = sqrt(D)
        # So y^4 = 2 * D^2 * phi4_coeff / exp(-1) = 4
        y4 = 2 * D ** 2 * phi4_coeff / math.exp(-1)
        y = y4 ** 0.25
        Lambda = math.sqrt(D)
        y_over_L = y / Lambda
        print(f"  {D:>4d}  {phi4_coeff:>14.6e}  {y:>14.6f}  "
              f"{y_over_L:>10.4f}  {target:>16.4f}  {y_over_L / target:>10.4f}")
    print()

    print("OBSERVATIONS")
    print("=" * 100)
    print()
    print("  - y = sqrt(2) at every D (D-INDEPENDENT in absolute terms).")
    print("  - y / Lambda = sqrt(2/D) DECREASES with D.")
    print(f"  - Comp 72 target y / Lambda = 2^(-1/4) ~= {target:.4f} is D-INDEPENDENT.")
    print("  - The two D-dependences disagree: this specific Higgs perturbation")
    print("    does NOT deliver the Comp 72 target.")
    print()
    print("  At D = 4: y/Lambda = sqrt(2)/2 ~= 0.7071, vs target 0.8409, ratio ~= 0.841.")
    print("  At D = 8: y/Lambda = sqrt(2)/sqrt(8) = 0.5, vs target 0.8409, ratio ~= 0.595.")
    print()
    print("INTERPRETATION")
    print("=" * 100)
    print()
    print("  The naive single-generator Higgs inner fluctuation does not close")
    print("  Z^2 = e^{-1}.  Three possible resolutions:")
    print()
    print("    (1) Z^2 ~ e^{-1} is a genuine 0.8% numerical near-coincidence")
    print("        on the SM side, with no structural identification on the")
    print("        substrate side.  (The substrate-side S_sub/2^D = e^{-1} is")
    print("        still exact from Comp 62; that exactness does not require")
    print("        a Z^2 identification.)  This is the conservative reading.")
    print()
    print("    (2) The Higgs perturbation should be parameterised differently,")
    print("        e.g. via a SUM over A_F generators or via the FULL")
    print("        Chamseddine-Connes inner fluctuation including J A J^{-1}")
    print("        and the order-one constraint.  The single-generator A used")
    print("        here is the SIMPLEST natural choice but is not necessarily")
    print("        the one CC machinery actually selects.")
    print()
    print("    (3) The matched scaling Lambda = sqrt(D) might not be the")
    print("        right cutoff identification for the Z^2 question; a")
    print("        different Lambda(D) prescription would deliver y/Lambda")
    print("        = 2^(-1/4) for the same Higgs perturbation.")
    print()
    print("  Honest reading: this computation does NOT close Z^2 = e^{-1}.")
    print("  It tells us which specific calculation needs to be done next: the")
    print("  full CC machinery with J reality + order-one constraint, on the")
    print("  PST substrate triple.  Until that calculation is done, Z^2 ~ e^{-1}")
    print("  remains a numerical near-coincidence with a substrate-side anchor")
    print("  (S_sub/2^D = e^{-1} exact) but no structural Yukawa-level identity.")


if __name__ == "__main__":
    main()
