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

SCOPE NOTE, 2026-10-10 (comp 201).  "(d_0/l_*)^6, about 1e63" in the text below was
written at the old 5.3 nm bound; the script's own constant is the 2.3 nm bound and it
prints 1e61.  Under the canonical normalisation d_0 = 2.2 am and the same ratio is
(14.5)^6 = 9e6.  The conclusion, that neither length is a realisation-point spacing,
does not depend on the number.

Computation 167, what fixes the absolute scale of Pi_mn, and what does not
===========================================================================
The question this answers was not in any register.  It arose from comp 164: rho is a
QUOTIENT map onto M, so realisation points exist everywhere, and Pi_mn is a positive
semidefinite sum over pairs.  Then Pi_mn is nonzero in what we call empty space, and
under the conformal identification it has to BE the conformal part of T^(fields) there.
So: what energy density does the pair sum predict for the vacuum, and does it match the
microwave background or overshoot it by the usual embarrassing margin?

THE ANSWER IS THAT IT PREDICTS NO DENSITY AT ALL, and the reason is worth having.

WHAT Pi's MAGNITUDE DEPENDS ON
-------------------------------
Every term of eq:Pimunu is W(s) Delta_m Delta_n B.  With W(s) = -|s| forced (comp 158)
and B a normalised bond kernel (comp 159), the only remaining freedom in the magnitude
is HOW MANY PAIRS THERE ARE.  Measured below: at fixed box and fixed cutoff, rho grows
as the square of the point count, which is linear in the pair count, while w does not
move at all.

    rho  is proportional to the pair density.      w  is not.

AND THE THEORY DOES NOT SUPPLY THAT DENSITY.  PST owns two lengths and neither is a
realisation-point spacing:

    d_0  <= 2.3e-9 m    the COHERENCE length, and \\S sec:grain-vs-coherence says in as
                        many words that it "is not the microscopic grain of the
                        substrate"
    l_*  = 1.5e-19 m    the grain, which enters as a momentum CUTOFF on field modes
                        (\\S sec:renorm), not as a spacing of realisation points

Searched: "realisation point" occurs three times in the body, all three inside the
Pi_mn construction itself, and none of them fixes a density.

SO THERE IS NO ABSOLUTE PREDICTION, AND THAT EXPLAINS A PATTERN
----------------------------------------------------------------
Every result the pair sum has produced is a ratio or a shape, and not one of them is a
magnitude.  In retrospect that is conspicuous, and it is exactly what a construction
with a free overall scale would produce:

    comp 158   w = 1/3, and rho = 3p                     a ratio
    comp 159   w = beta^2/3, and the worldline share f   ratios
    comp 160   g = 2 polarisations                       a COUNT, not a scale
    comp 161   the Planck spectral shape                 a shape
    comp 164   the semidefinite metric-traceless cone    a cone, scale-free by definition

comp 160's radiation constant is an absolute number, and it is worth being exact about
why that is not a counterexample: it comes from the polarisation COUNT together with
hbar, c and k_B, and not from Pi's magnitude.  The pair sum contributed an integer.

CHECKS
------
  1.  rho is proportional to the pair count and w is not, over a factor of 8 in the
      point count at fixed box and cutoff.
  2.  Rescaling the ensemble's density leaves w, the trace ratio and the eigenvalue
      PATTERN unchanged while rho moves by orders: the scale is a prefactor and
      nothing else depends on it.
  3.  The underdetermination is quantified rather than asserted.  Reading the spacing
      off d_0 rather than off l_* changes the implied density by (d_0/l_*)^6, about
      1e63, so the theory does not merely fail to pin the number, it fails to pin it
      by sixty-three orders.

WHAT THIS COSTS AND WHAT IT DOES NOT
--------------------------------------
It costs nothing already claimed: every standing result in this sector is scale-free,
which check 2 verifies directly rather than by inspection.

It adds a second, independent gap to the conformal identification.  comp 164 showed
Pi_mn reaches exactly the semidefinite metric-traceless cone; this shows its magnitude
WITHIN that cone is unfixed.  So the identification cannot be tested pointwise until a
realisation-point density is supplied, and supplying one is a new open item.

And it rules something out, which is the reason the question was worth asking.  THERE
IS NO VACUUM-ENERGY CATASTROPHE IN THIS SECTOR, because there is no absolute prediction
to be catastrophic.  The 10^120 problem needs a computed scale to disagree with
measurement; this construction does not produce one.  That is not a rescue, it is a
statement of what the construction is.

A "pass": rho proportional to the pair count with w flat across the same range; every
scale-free observable unchanged under a density rescaling that moves rho by more than
an order; and the d_0-versus-l_* span coming out above 1e60.
"""

import numpy as np

ETA = np.diag([1.0, -1.0, -1.0, -1.0])
D0 = 2.3e-9          # m, coherence length
L_STAR = 1.5e-19     # m, substrate grain


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


def pi_tensor(pts, cut=4.0):
    P = np.zeros((4, 4))
    npairs = 0
    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)
        k = np.abs(s) <= cut
        D, s = D[k], s[k]
        if len(s) == 0:
            continue
        npairs += int(k.sum())
        Dl = D @ ETA
        P += np.einsum("p,pm,pn->mn", np.abs(s), Dl, Dl)
    return P, npairs


def observables(P):
    rho = P[0, 0]
    p = (P[1, 1] + P[2, 2] + P[3, 3]) / 3.0
    metric_trace = P[0, 0] - P[1, 1] - P[2, 2] - P[3, 3]
    ev = np.linalg.eigvalsh(P)
    return rho, p, p / rho, metric_trace / rho, ev / ev.max()


# ---------------------------------------------------------------------------
# 1.  rho follows the pair count; w does not
# ---------------------------------------------------------------------------
def part1_scaling():
    rule()
    print("  1.  rho FOLLOWS THE PAIR COUNT.  w DOES NOT.")
    rule()
    print("      Fixed box, fixed cutoff, only the number of realisation points varies.")
    print()
    rng = np.random.default_rng(20260928)
    print(f"      {'points':>8}{'pairs kept':>13}{'rho':>16}{'rho/pairs':>13}{'w':>10}")
    ratios, ws = [], []
    for N in (200, 400, 800, 1600):
        P, npairs = pi_tensor(rng.normal(size=(N, 4)) * 1.5)
        rho, p, w, _, _ = observables(P)
        ratios.append(rho / npairs)
        ws.append(w)
        print(f"      {N:8d}{npairs:13d}{rho:16.1f}{rho / npairs:13.4f}{w:10.4f}")
    rho_span = max(ratios) / min(ratios)
    w_span = max(ws) - min(ws)
    ok = rho_span < 1.5 and w_span < 0.05
    print()
    print(f"      rho per pair varies by a factor {rho_span:.3f} over an 8-fold range in")
    print(f"      the point count, so rho is proportional to the pair count.")
    print(f"      w varies by {w_span:.4f} over the same range, so it is not.")
    print(f"      (the converged value of w is 1/3, comp 158; what matters here is that")
    print(f"       it does not move with the density, not its value)")
    print(f"      magnitude tracks the density, the equation of state does not : {ok}")
    print()
    return bool(ok)


# ---------------------------------------------------------------------------
# 2.  every scale-free observable is untouched
# ---------------------------------------------------------------------------
def part2_scale_free():
    rule()
    print("  2.  EVERY SCALE-FREE OBSERVABLE IS UNTOUCHED BY THE DENSITY")
    rule()
    rng = np.random.default_rng(31415)
    base = rng.normal(size=(300, 4)) * 1.5
    dense = np.vstack([base, rng.normal(size=(600, 4)) * 1.5])

    Pa, _ = pi_tensor(base)
    Pb, _ = pi_tensor(dense)
    ra, pa, wa, tra, eva = observables(Pa)
    rb, pb, wb, trb, evb = observables(Pb)

    print(f"      {'':22}{'sparse':>16}{'dense':>16}{'change':>12}")
    print(f"      {'rho (the scale)':22}{ra:16.1f}{rb:16.1f}{rb / ra:11.2f}x")
    print(f"      {'w = p/rho':22}{wa:16.4f}{wb:16.4f}{abs(wb - wa):12.4f}")
    print(f"      {'metric trace / rho':22}{tra:16.4f}{trb:16.4f}{abs(trb - tra):12.4f}")
    for i in range(4):
        lbl = "eigenvalue pattern" if i == 0 else ""
        print(f"      {lbl:22}{eva[i]:16.4f}{evb[i]:16.4f}{abs(evb[i] - eva[i]):12.4f}")
    moved = rb / ra > 3.0
    invariant = (abs(wb - wa) < 0.05 and abs(trb - tra) < 0.05
                 and np.abs(evb - eva).max() < 0.05)
    ok = moved and invariant
    print()
    print(f"      rho moved by more than 3x while every ratio held        : {ok}")
    print("      The density is a prefactor.  Nothing the book claims in this sector")
    print("      reads it, which is why nothing the book claims is affected.")
    print()
    return bool(ok)


# ---------------------------------------------------------------------------
# 3.  how badly the density is underdetermined
# ---------------------------------------------------------------------------
def part3_span():
    rule()
    print("  3.  AND THE UNDERDETERMINATION IS SIXTY-THREE ORDERS WIDE")
    rule()
    print("      Part 1 measured rho proportional to the pair count, so at spacing a the")
    print("      density per unit volume goes as (1/a^3)^2 = a^-6.  PST owns two lengths")
    print("      and neither is a realisation-point spacing, so read the spacing off")
    print("      either one and compare:")
    print()
    print(f"        d_0    = {D0:.1e} m   the coherence length, explicitly NOT the grain")
    print(f"        l_*    = {L_STAR:.1e} m   the grain, a momentum cutoff on field modes")
    span = (D0 / L_STAR) ** 6
    print()
    print(f"      implied densities differ by (d_0/l_*)^6 = {span:.2e}")
    ok = span > 1e60
    print(f"      the theory does not pin the number, by more than 1e60       : {ok}")
    print()
    print("      So the vacuum question that prompted this computation is not merely")
    print("      unanswered, it is not well posed until a density is supplied.  There is")
    print("      no catastrophe here because there is no prediction to be catastrophic.")
    print()
    return bool(ok)


def main():
    print()
    rule()
    print("  COMPUTATION 167: WHAT FIXES THE ABSOLUTE SCALE OF Pi_mn, AND WHAT DOES NOT")
    rule()
    print("  Prompted by comp 164: rho is surjective, so Pi_mn is nonzero in empty space.")
    print("  What density does it predict there?  None, and the reason is the result.")
    print()

    c1 = part1_scaling()
    c2 = part2_scale_free()
    c3 = part3_span()

    rule()
    print("  ASSESSMENT")
    rule()
    print(f"  1. rho follows the pair count, w does not                        : {c1}")
    print(f"  2. every scale-free observable survives a density change         : {c2}")
    print(f"  3. the d_0 versus l_* span exceeds 1e60                          : {c3}")
    print()
    ok = all([c1, c2, c3])
    print("  RESULT: " + (
        "Pi_mn's MAGNITUDE IS NOT DETERMINED BY THE THEORY.  The weight is forced and the "
        "bond kernel normalised, so the only remaining freedom is the pair density, and "
        "PST's two lengths are a coherence length and a momentum cutoff, neither of them a "
        "realisation-point spacing.  Nothing already claimed is affected, because every "
        "result the pair sum has produced is a ratio, a shape or a count, which check 2 "
        "verifies rather than assumes.  Two things follow: the conformal identification "
        "carries a second gap, its magnitude within the cone being free; and there is no "
        "vacuum-energy catastrophe in this sector, because there is no absolute prediction "
        "to be catastrophic"
        if ok else "MISMATCH -- revise"))
    print()


if __name__ == "__main__":
    main()
