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

SCOPE NOTE, 2026-10-10 (comp 199).  Everything below stands for the pair sum itself:
it is semidefinite and no pair sum equals a static magnetic or electric field.  comp
199 shows the obstruction does not reach the identification, which is a statement
about CONFORMAL PARTS: the conformal part of the pair sum, Pi - (1/4) g tr Pi, is a
conic sum of traceless dyads Delta Delta - (s/4) g, which are indefinite, and that
cone is exactly the metric-traceless tensors obeying the null energy condition.  The
magnetic and electric tensors are reached by bonds in the transverse plane.  No number
in this file changes; "the reachable set is exactly the semidefinite cone" is the
reachable set of the raw sum, and the identification was never of the raw sum.

Computation 164, the conformal identification: what the pair sum can represent, and
what it cannot
=================================================================================
NAMING.  This was called "the bridge" when first written.  The book already uses that
word for the substrate-to-SM bridge (Bridge Premise (B), the bridge map b_D, the bridge
symbol and degree of the Dirac-convergence chapter), so the collision was renamed on
2026-09-27.  Say "the conformal identification" and do not reintroduce the other name.

\S sec:einstein identifies Pi_mn as the conformal part of T^(fields)_mn and says
plainly that the identification is not established.  comp 163 then showed that both
the conservation result and the settlement of the gauge ambiguity lean on it, so the
identification is now the single residue of the whole Pi_mn programme.  This computation
attacks it, and finds the answer is sharper than "not established": there is an exact
criterion, and a class of conformal matter that fails it.

THE CRITERION, AND IT IS ONE LINE
----------------------------------
Every term of eq:Pimunu is W(s_ab) Delta_m Delta_n B, and

    W(s) = -|s|   is single-signed          (forced, comp 158)
    B >= 0        is a bond kernel          (supported between the two points)
    Delta_m Delta_n is rank one and semidefinite

so Pi_mn is a conic combination of semidefinite rank-one dyads with coefficients that
never change sign.  **Pi_mn is therefore SEMIDEFINITE, always**, with the sign
convention of comp 158 making it positive semidefinite.  This is not a property of the
ensembles tried; it is forced by the weight being single-signed.

Measured against six adversarial ensemble shapes, including ones flattened to a plane,
stretched along time, split into clumps, laid on a light cone and collapsed onto a
line: not one negative eigenvalue anywhere.

CONFORMAL MATTER NEED NOT BE SEMIDEFINITE, AND THE COUNTEREXAMPLE IS ORDINARY
------------------------------------------------------------------------------
A static magnetic field has

    T_mn = diag(u, u, u, -u),   u = B^2/2,   metric trace zero

the negative entry being the TENSION along the field lines, with pressure transverse.
Eigenvalue pattern (+,+,+,-): indefinite.  Metric-traceless, so it is conformal matter
by the book's own classification, and homogeneous, so comp 159's scope covers it.  A
pure electric field has the same structure.  **No pair sum can equal it.**

The physical statement is shorter than the algebra.  A bond can push or a bond can
pull, but with a single-signed weight every bond in the sum does the same one.  A
magnetic field does both at once: tension along the lines, pressure across them.

THE RESCUE IS AVAILABLE, AND IT HAS A PRICE
---------------------------------------------
comp 163 left exactly one gauge freedom, a constant metric-traceless shift H (the
Hessian of a global quadratic harmonic function).  With H = diag(3u, u, u, u) the
magnetic tensor becomes positive semidefinite, so the obstruction to the GAUGED
statement dissolves.

    A first draft of this computation argued that the vacuum forbids H, since Pi
    vanishes where there are no pairs.  THAT ARGUMENT IS WRONG FOR PST and is recorded
    here so it is not made again: rho: D ->> M is a QUOTIENT map (\S sec:emergence,
    line "rho is a quotient map and a spacetime point IS a fibre"), so it is
    surjective and there is no region of M without realisation points.  There is no
    empty asymptotic region to pin H against.

So what fails is the identification AS STATED, "Pi_mn is that tensor's conformal part".
What
survives is "Pi_mn is the conformal part plus a universal constant metric-traceless
tensor", and the price is stated rather than hidden:

  * the constant is UNIVERSAL, one tensor for the whole manifold;
  * it must dominate the largest tension anywhere in the universe, since it has to
    make T + H semidefinite everywhere at once;
  * and nothing in the construction fixes it, precisely because surjectivity removes
    the asymptotic condition that would have.

WHAT IS AND IS NOT REACHED
---------------------------
    reachable   isotropic radiation, diag(rho, rho/3, rho/3, rho/3), positive definite
    reachable   a null plane wave, T = Phi k_m k_n, rank one and semidefinite
    NOT         a static magnetic or electric field, anywhere it is non-zero
    NOT         Lambda g_mn, which is indefinite, and which the book already assigns
                to the separate scalar sector, so that exclusion is now FORCED rather
                than chosen

WHAT THIS COSTS AND WHAT IT DOES NOT
--------------------------------------
It costs the identification as stated.  Pi_mn is not the conformal part of
T^(fields)_mn in
general; it is the conformal part on the semidefinite sector and nothing outside it.

It costs nothing already claimed.  Every result the book rests on for this sector
lives inside the reachable class: comp 158's w = 1/3, comp 159's worldline kinetic
law, comp 160's polarisations and Stefan-Boltzmann, comp 161's Planck spectrum.  All
of them are equilibrium radiation, and equilibrium radiation is positive definite.

And the failure is not small.  It is O(1) in the eigenvalues, not the O((d_0/L)^2)
of comp 162.  A scope statement, not a correction.

A "pass": Pi semidefinite over all six ensembles; the magnetic and electric tensors
metric-traceless and indefinite; radiation and a null wave semidefinite; the constant
shift rescuing the magnetic case but forbidden by the vacuum; and any semidefinite
metric-traceless target reconstructible from dyads, so the reachable set is exactly
that cone and no smaller.
"""

import numpy as np
import sympy as sp

ETA = np.diag([1.0, -1.0, -1.0, -1.0])


def rule(ch="="):
    print(ch * 100)


def pi_of(pts, cut=4.0):
    """eq:Pimunu on a point cloud, with comp 158's overall sign so rho > 0."""
    P = np.zeros((4, 4))
    for i in range(len(pts)):
        D = pts[i] - pts[i + 1:]
        if len(D) == 0:
            continue
        s = np.einsum("pi,ij,pj->p", D, ETA, D)
        keep = np.abs(s) <= cut
        D, s = D[keep], s[keep]
        if len(s) == 0:
            continue
        Dl = D @ ETA
        P += np.einsum("p,pm,pn->mn", np.abs(s), Dl, Dl)
    return P


# ---------------------------------------------------------------------------
# 1.  Pi is semidefinite, necessarily
# ---------------------------------------------------------------------------
def part1_semidefinite():
    rule()
    print("  1.  Pi IS SEMIDEFINITE, AND IT IS FORCED RATHER THAN OBSERVED")
    rule()
    print("      W(s) = -|s| is single-signed (comp 158), B >= 0 is a bond kernel, and")
    print("      Delta_m Delta_n is rank one and semidefinite.  A conic combination of")
    print("      semidefinite matrices with same-signed coefficients is semidefinite.")
    print()
    rng = np.random.default_rng(20260927)
    shapes = [
        ("isotropic gaussian", lambda: rng.normal(size=(250, 4)) * 1.5),
        ("flattened to a plane", lambda: rng.normal(size=(250, 4))
            * np.array([1.5, 1.5, 1.5, 0.05])),
        ("stretched along time", lambda: rng.normal(size=(250, 4))
            * np.array([6.0, 0.4, 0.4, 0.4])),
        ("two clumps", lambda: np.vstack([rng.normal(size=(125, 4)) * 0.4,
                                          rng.normal(size=(125, 4)) * 0.4
                                          + np.array([0, 3, 0, 0])])),
        ("laid on a light cone", lambda: (lambda v: np.column_stack(
            [np.linalg.norm(v, axis=1), v]))(rng.normal(size=(250, 3)))),
        ("collapsed onto a line", lambda: np.column_stack([
            rng.normal(size=250) * 0.02, np.linspace(-3, 3, 250),
            rng.normal(size=250) * 0.02, rng.normal(size=250) * 0.02])),
    ]
    worst = 0.0
    for name, gen in shapes:
        mins = []
        for _ in range(8):
            ev = np.linalg.eigvalsh(pi_of(gen()))
            mins.append(ev.min() / max(1e-30, abs(ev).max()))
        m = min(mins)
        worst = min(worst, m)
        print(f"      {name:22s} min eigenvalue / scale, 8 draws : {m:+.3e}")
    ok = worst > -1e-9
    print(f"      not one negative eigenvalue anywhere                      : {ok}")
    print()
    return bool(ok)


# ---------------------------------------------------------------------------
# 2.  Conformal matter need not be
# ---------------------------------------------------------------------------
def part2_counterexample():
    rule()
    print("  2.  CONFORMAL MATTER NEED NOT BE, AND THE COUNTEREXAMPLE IS ORDINARY")
    rule()
    g = sp.diag(1, -1, -1, -1)
    ginv = g.inv()

    def Tem(F):
        F2 = sp.simplify(sum(F[i, j] * ginv[i, al] * ginv[j, be] * F[al, be]
                             for i in range(4) for j in range(4)
                             for al in range(4) for be in range(4)))
        T = sp.zeros(4, 4)
        for m in range(4):
            for n in range(4):
                T[m, n] = sp.simplify(
                    -sum(F[m, al] * ginv[al, be] * F[n, be]
                         for al in range(4) for be in range(4)) + g[m, n] * F2 / 4)
        return sp.simplify(T)

    results = {}
    B = sp.Symbol("B", positive=True)
    Fb = sp.zeros(4, 4)
    Fb[1, 2], Fb[2, 1] = B, -B                     # magnetic field along z
    results["static magnetic"] = Tem(Fb)

    E = sp.Symbol("E", positive=True)
    Fe = sp.zeros(4, 4)
    Fe[0, 3], Fe[3, 0] = E, -E                     # electric field along z
    results["static electric"] = Tem(Fe)

    ok_indef = True
    for name, T in results.items():
        tr = sp.simplify(sum(ginv[i, j] * T[i, j] for i in range(4) for j in range(4)))
        sub = {B: 1, E: 1}
        M = np.array(sp.Matrix(T).subs(sub).evalf(), dtype=float)
        ev = np.linalg.eigvalsh(M)
        indef = ev.min() < -1e-12 < 1e-12 < ev.max()
        ok_indef = ok_indef and indef and sp.simplify(tr) == 0
        print(f"      {name:18s} metric trace = {tr},  eigenvalues {np.round(ev, 3)}")
        print(f"      {'':18s} metric-traceless and INDEFINITE                : {indef}")
    print("      the negative eigenvalue is the TENSION along the field lines, with")
    print("      pressure transverse.  A single-signed bond sum has one or the other.")
    print()

    # and the two that ARE reachable
    rho = 1.0
    rad = np.diag([rho, rho / 3, rho / 3, rho / 3])
    k = np.array([1.0, 1.0, 0.0, 0.0])
    kl = ETA @ k
    wave = np.outer(kl, kl)
    ok_rad = np.linalg.eigvalsh(rad).min() > -1e-12
    ok_wave = np.linalg.eigvalsh(wave).min() > -1e-12
    tr_rad = rad[0, 0] - rad[1, 1] - rad[2, 2] - rad[3, 3]
    tr_wave = float(kl @ np.linalg.inv(ETA) @ kl)
    print(f"      isotropic radiation  metric trace {tr_rad:+.3f}  semidefinite : {ok_rad}")
    print(f"      null plane wave      metric trace {tr_wave:+.3f}  semidefinite : {ok_wave}")
    print()
    return bool(ok_indef and ok_rad and ok_wave)


# ---------------------------------------------------------------------------
# 3.  The rescue, and why the vacuum forbids it
# ---------------------------------------------------------------------------
def part3_rescue_and_its_price():
    rule()
    print("  3.  THE ONE GAUGE LEFT DOES RESCUE IT, AND WHAT THAT COSTS")
    rule()
    u = 0.5
    T = np.diag([u, u, u, -u])
    H = np.diag([3 * u, u, u, u])
    mtr = H[0, 0] - H[1, 1] - H[2, 2] - H[3, 3]
    ev_before = np.linalg.eigvalsh(T)
    ev_after = np.linalg.eigvalsh(T + H)
    print("      comp 163 leaves exactly one freedom: a CONSTANT metric-traceless H,")
    print("      the Hessian of a global quadratic harmonic gauge function.")
    print(f"      H = diag(3u, u, u, u), metric trace {mtr:+.1f}")
    print(f"      magnetic T eigenvalues {np.round(ev_before, 3)}  ->  "
          f"{np.round(ev_after, 3)}")
    rescued = ev_after.min() > -1e-12
    print(f"      a constant shift makes it semidefinite                    : {rescued}")
    print()
    print("      A FIRST DRAFT OF THIS COMPUTATION ARGUED THE VACUUM FORBIDS H, and")
    print("      that argument is wrong for PST.  rho is a QUOTIENT map onto M, so it")
    print("      is surjective: every spacetime point is a fibre and there is no region")
    print("      without realisation points.  There is no empty asymptotic region to")
    print("      pin H against.  Recorded so the mistake is not made twice.")
    print()
    print("      So what fails is the identification AS STATED.  What survives is the")
    print("      gauged version, and its price is three things:")
    print("      version, and its price is three things:")
    print("        (i)   H is universal, one constant tensor for the whole manifold;")
    need = []
    for tension in (0.5, 5.0, 50.0):
        Tt = np.diag([tension, tension, tension, -tension])
        # smallest c with diag(3c, c, c, c) making it semidefinite
        c = tension
        ok = np.linalg.eigvalsh(Tt + np.diag([3 * c, c, c, c])).min() > -1e-12
        need.append((tension, c, ok))
        print(f"        (ii)  it must dominate the largest tension anywhere: u = "
              f"{tension:5.1f} needs c >= {c:5.1f}  ({ok})")
    print("        (iii) and nothing fixes its value, precisely because surjectivity")
    print("              removed the asymptotic condition that would have.")
    print()
    scales = all(ok for _, _, ok in need)
    indef = ev_before.min() < -1e-12
    print(f"      the shift scales with the worst tension                   : {scales}")
    print(f"      and the ungauged tensor is genuinely indefinite           : {indef}")
    print(f"      the failure is O(1), not the {1e-23:.0e}-scale residue of comp 162.")
    print()
    return bool(rescued and scales and indef)


# ---------------------------------------------------------------------------
# 4.  The reachable set is exactly the semidefinite cone, no smaller
# ---------------------------------------------------------------------------
def part4_reachable_set():
    rule()
    print("  4.  AND THE REACHABLE SET IS EXACTLY THAT CONE, NOT A PROPER SUBSET")
    rule()
    print("      Any semidefinite target is a non-negative combination of rank-one")
    print("      dyads, by its own eigendecomposition, and each dyad is a Delta Delta")
    print("      with the weight absorbed into the scale of Delta.  So nothing inside")
    print("      the cone is out of reach, and the criterion is sharp in both directions.")
    print()
    rng = np.random.default_rng(4242)
    worst = 0.0
    for trial in range(6):
        A = rng.normal(size=(4, 4))
        M = A @ A.T                                  # a random PSD target
        ev, V = np.linalg.eigh(M)
        rebuilt = sum(ev[i] * np.outer(V[:, i], V[:, i]) for i in range(4))
        rel = np.abs(rebuilt - M).max() / np.abs(M).max()
        worst = max(worst, rel)
        neg = (ev < -1e-12).sum()
        print(f"      target {trial + 1}: {neg} negative eigenvalues, rebuilt from "
              f"{(ev > 1e-12).sum()} dyads, rel error {rel:.2e}")
    ok = worst < 1e-10
    print(f"      every semidefinite target is a dyad sum                   : {ok}")
    print()
    return bool(ok)


def main():
    print()
    rule()
    print("  COMPUTATION 164: THE CONFORMAL IDENTIFICATION, AND THE OBSTRUCTION")
    rule()
    print("  The identification of Pi_mn with the conformal part of T^(fields)_mn is the")
    print("  single residue of the Pi_mn programme.  It has an exact criterion, and a")
    print("  class of ordinary conformal matter fails it.")
    print()

    c1 = part1_semidefinite()
    c2 = part2_counterexample()
    c3 = part3_rescue_and_its_price()
    c4 = part4_reachable_set()

    rule()
    print("  ASSESSMENT")
    rule()
    print(f"  1. Pi is semidefinite, over six adversarial ensemble shapes      : {c1}")
    print(f"  2. magnetic and electric fields are conformal and indefinite     : {c2}")
    print(f"  3. the constant-shift rescue works, and its price is stated      : {c3}")
    print(f"  4. the reachable set is exactly the semidefinite cone            : {c4}")
    print()
    ok = all([c1, c2, c3, c4])
    print("  RESULT: " + (
        "THE CONFORMAL IDENTIFICATION HOLDS ON THE SEMIDEFINITE SECTOR AND FAILS OUTSIDE IT.  "
        "Pi_mn is a "
        "conic sum of same-signed rank-one dyads, so it is semidefinite; a static "
        "magnetic or electric field is metric-traceless and indefinite, the negative "
        "eigenvalue being the tension along the field lines; the one gauge freedom left "
        "by comp 163 DOES rescue it, at the price of a universal constant that must dominate "
        "the largest tension anywhere and that nothing in the construction fixes.  "
        "Every result the book rests on in this sector is equilibrium radiation, which "
        "is inside the reachable class, so nothing already claimed is damaged.  What is "
        "damaged is the claim that Pi_mn IS the conformal part of T^(fields)_mn in "
        "general"
        if ok else "MISMATCH -- revise"))
    print()


if __name__ == "__main__":
    main()
