#!/usr/bin/env python3
"""
PST Computation 7 — Stage 6 of the 10-foundational programme
============================================================================
Chirality and the order-one condition, on an explicit one-generation finite
geometry. This is the crux and the only stage that engages D_F directly.

Track J established: the naive substrate LADDER SU(2) (a number-changing
ladder on a single Fock space) is, under either natural chirality grading,
vector-like or chirality-mixing -- NOT the Standard Model's chiral SU(2)_L.
The resolution in the Connes framework is to use the CHIRAL representation:
the quaternions H are represented to act on the LEFT-handed doublets only.
Then SU(2)_L is chiral by construction, and the order-one condition
[[D_F,a], J b* J^{-1}] = 0 selects the Yukawa form of D_F.

This script builds a clean, explicit lepton-sector one-generation finite
geometry (8-dim: nu_L,e_L,nu_R,e_R + 4 antiparticles) and verifies:
  O1  the representation is EVEN ([gamma,a]=0) and the SU(2)_L action of H is
      CHIRAL (supported on left-handed particles only; annihilates the
      right-handed ones). Contrast Track J.
  O2  order-zero  [a, J b* J^{-1}] = 0  for all a,b in A_F.
  O3  order-one   [[D_F,a], J b* J^{-1}] = 0  for the Yukawa D_F, and its
      FAILURE for a generic admissible D_F -- so order-one SELECTS the
      Yukawa structure (it is a genuine constraint, not an identity).
  O4  the KO-6 sign of the finite real structure (eps = +1), consistent.

Honest residual (the PST-specific open piece): this uses the CHIRAL
representation (H on L only), which is the CCM input. Track J showed the
naive substrate ladder gives instead a vector-like SU(2). So the remaining
question is whether the SUBSTRATE furnishes the chiral representation (equiv.
a substrate D_F satisfying order-one with it), not whether chirality is
compatible with the framework -- it is, as verified here.

Run:
    python3 computation_07.py
"""
import numpy as np

SEP = "=" * 78
def hdr(s): print(f"\n{SEP}\n  {s}\n{SEP}")
def comm(A, B): return A @ B - B @ A

print(SEP)
print("  PST Computation 7 — chirality and the order-one condition (Stage 6)")
print(SEP)

# ─────────────────────────────────────────────────────────────────────
# Finite geometry: 8-dim lepton sector, one generation
#   basis 0..3 particles:     nu_L, e_L, nu_R, e_R
#   basis 4..7 antiparticles: nu_L^c, e_L^c, nu_R^c, e_R^c
# ─────────────────────────────────────────────────────────────────────
# grading gamma_F: +1 on L particles, -1 on R particles; opposite on
# antiparticles (so that J gamma = -gamma J, KO-6).
gamma = np.diag([+1,+1,-1,-1, -1,-1,+1,+1]).astype(complex)

# real structure J = S.K  (S swaps particle<->antiparticle blocks, K conj)
S = np.zeros((8,8))
S[:4,4:] = np.eye(4); S[4:,:4] = np.eye(4)
def conj_by_J(X): return S @ np.conj(X) @ S      # J X J^{-1}
# J^2 = +1 since S real and S^2 = I:
J2_plus = np.allclose(S @ S, np.eye(8))

# quaternion basis as 2x2 matrices (H -> SU(2) form)
H1 = np.eye(2, dtype=complex)
Hi = np.array([[1j,0],[0,-1j]], dtype=complex)
Hj = np.array([[0,1],[-1,0]], dtype=complex)
Hk = np.array([[0,1j],[1j,0]], dtype=complex)
Z2 = np.zeros((2,2), dtype=complex)

def rho(lam, q):
    """Representation of A_F element (lam in C, q in H as 2x2) on H_F.
       Particles: H acts on the L doublet (nu_L,e_L); C acts on R singlets
       (nu_R<-lam, e_R<-conj(lam)). Antiparticles (no colour): scalar lam."""
    P = np.zeros((4,4), dtype=complex)
    P[:2,:2] = q
    P[2,2] = lam
    P[3,3] = np.conj(lam)
    AP = lam * np.eye(4, dtype=complex)
    out = np.zeros((8,8), dtype=complex)
    out[:4,:4] = P; out[4:,4:] = AP
    return out

# spanning set of A_F = C (+) H
AF = [(1+0j, Z2), (1j, Z2), (0j, H1), (0j, Hi), (0j, Hj), (0j, Hk)]

# ─────────────────────────────────────────────────────────────────────
# §1. Even representation; chiral SU(2)_L (H acts on L only)
# ─────────────────────────────────────────────────────────────────────
hdr("§1 — even representation; chiral SU(2)_L from H on left-handed only")
even = all(np.allclose(comm(gamma, rho(l,q)), 0) for (l,q) in AF)
print(f"  [gamma_F, A_F] = 0 (even triple): {even}")

# the su(2) generators are rho(0, imaginary quaternion); check they are
# supported on left-handed particles (idx 0,1) and annihilate the rest.
P_L = np.diag([1,1,0,0, 0,0,0,0]).astype(complex)   # left-handed particles
su2_gens = [rho(0j, Hi), rho(0j, Hj), rho(0j, Hk)]
chiral = all(np.allclose(G, P_L @ G @ P_L) for G in su2_gens)
annihilates_R = all(np.allclose(G[2:4,2:4], 0) for G in su2_gens)
print(f"  SU(2)_L generators supported on LEFT-handed subspace only: {chiral}")
print(f"  SU(2)_L annihilates right-handed states (weak singlets): {annihilates_R}")
print("  => chiral SU(2)_L by representation (contrast Track J's vector-like")
print("     / chirality-mixing ladder SU(2)).")

# ─────────────────────────────────────────────────────────────────────
# §2. Order-zero
# ─────────────────────────────────────────────────────────────────────
hdr("§2 — order-zero: [a, J b* J^{-1}] = 0 for all a,b in A_F")
def right(b_lam, b_q):
    bo_in = rho(b_lam, b_q).conj().T          # b*
    return conj_by_J(bo_in)                    # J b* J^{-1}
order0 = True
for (la,qa) in AF:
    for (lb,qb) in AF:
        if not np.allclose(comm(rho(la,qa), right(lb,qb)), 0, atol=1e-9):
            order0 = False
print(f"  order-zero holds for all pairs: {order0}")

# ─────────────────────────────────────────────────────────────────────
# §3. Order-one: Yukawa D_F passes; generic D_F fails (selection)
# ─────────────────────────────────────────────────────────────────────
hdr("§3 — order-one: Yukawa D_F satisfies it; a generic D_F does not")

# Yukawa D_F: connects L<->R within particles (Dirac masses), J-mirrored on
# antiparticles. y_nu, y_e arbitrary nonzero complex.
y_nu, y_e = 0.7+0.2j, 1.3-0.4j
M_p = np.zeros((4,4), dtype=complex)
M_p[0,2] = y_nu; M_p[2,0] = np.conj(y_nu)      # nu_L <-> nu_R
M_p[1,3] = y_e;  M_p[3,1] = np.conj(y_e)       # e_L  <-> e_R
D_yuk = np.zeros((8,8), dtype=complex)
D_yuk[:4,:4] = M_p
D_yuk[4:,4:] = np.conj(M_p)                     # forces J D = D J (eps'=+1)

# sanity: self-adjoint, gamma-odd, J-compatible
print(f"  Yukawa D_F self-adjoint: {np.allclose(D_yuk, D_yuk.conj().T)};  "
      f"gamma-odd: {np.allclose(gamma@D_yuk + D_yuk@gamma, 0)};  "
      f"J D = D J: {np.allclose(conj_by_J(D_yuk), D_yuk)}")

def order_one_residual(D):
    worst = 0.0
    for (la,qa) in AF:
        one_form = comm(D, rho(la,qa))           # [D, a]
        for (lb,qb) in AF:
            r = comm(one_form, right(lb,qb))      # [[D,a], J b* J^{-1}]
            worst = max(worst, np.max(np.abs(r)))
    return worst

res_yuk = order_one_residual(D_yuk)
print(f"  order-one residual for Yukawa D_F:   {res_yuk:.2e}  "
      f"(=0 -> satisfies order-one)")

# generic admissible D_F: random Hermitian, gamma-odd, J-symmetrised.
rng = np.random.default_rng(6)
R = rng.standard_normal((8,8)) + 1j*rng.standard_normal((8,8))
R = (R + R.conj().T)/2
R = (R - gamma@R@gamma)/2                         # gamma-odd part
R = (R + conj_by_J(R))/2                          # J-compatible part
res_gen = order_one_residual(R)
print(f"  order-one residual for generic D_F:  {res_gen:.2e}  "
      f"(!=0 -> fails order-one)")
print(f"  => order-one is a genuine constraint: it SELECTS the Yukawa form")
print(f"     ({res_yuk:.1e} vs {res_gen:.1e}).")

# ─────────────────────────────────────────────────────────────────────
# §4. KO-6 sign of the finite real structure
# ─────────────────────────────────────────────────────────────────────
hdr("§4 — finite real structure sign (KO-6 consistency)")
# eps = J^2: J = S K, J^2 = S conj(S) ... = S^2 = I -> +1
print(f"  J^2 = +1: {J2_plus}  (KO-6 has eps = +1)")
print(f"  J gamma = -gamma J: "
      f"{np.allclose(conj_by_J(gamma), -gamma)}  (KO-6 has eps'' = -1)")

# ─────────────────────────────────────────────────────────────────────
# §5. Verdict
# ─────────────────────────────────────────────────────────────────────
hdr("§5 — Stage 6 verdict")
print(f"""
  Verified on the explicit one-generation lepton finite geometry:
    - even representation [gamma,A_F]=0; and SU(2)_L (the H-action) is
      CHIRAL: supported on left-handed particles, annihilating the
      right-handed singlets ({chiral and annihilates_R}). This is the
      genuine chiral SU(2)_L, in contrast to Track J's vector-like /
      chirality-mixing ladder SU(2).
    - order-zero holds ({order0}).
    - order-one is SATISFIED by the Yukawa D_F (residual {res_yuk:.1e}) and
      FAILS for a generic admissible D_F (residual {res_gen:.1e}), so the
      order-one condition selects the Yukawa form. This is exactly the CCM
      mechanism by which the matter Dirac operator is fixed.
    - KO-6 signs (eps,eps'') = (+1,-1) consistent.

  So chirality is FULLY COMPATIBLE with the framework, and within it the
  chiral SU(2)_L plus the Yukawa structure follow from the chiral
  representation + order-one. Track J's reduction is realised concretely
  here: PST supplies A_F and KO-6, and order-one selects the Yukawa D_F.

  The honest residual (the one genuine open piece of the matter sector):
    This construction uses the CHIRAL representation (H on left-handed
    doublets only), which is the CCM input. Track J showed the naive
    substrate LADDER instead furnishes a vector-like SU(2). So the remaining
    question is whether the SUBSTRATE produces the chiral representation
    (equivalently, a substrate-derived D_F satisfying order-one with it),
    rather than the vector-like ladder. That is now the single sharp open
    problem of the matter sector: not 'is chirality possible' (yes, shown
    here) but 'does the substrate select the chiral bimodule'.

  Stage 6 outcome: chirality compatible and mechanised within the framework;
  the open piece reduced to one sharp question (substrate -> chiral bimodule),
  consistent with and sharper than the Track J CCM reduction.
""")
