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

Computation 171, theta's provenance: the phase survives determination, the direction does not
==============================================================================================
\\compref{170} settled P3's locking as DIRECT DETERMINATION and, in doing so, took away
the mode sec:vacuum-angular had been using.  Under determination the order parameter's
V_7 direction is fixed by tau-hat, so those six angular directions are constrained rather
than dynamical, and the symmetry that survives fixes the vacuum and is unbroken.  Neither
supplies a Goldstone.  But sec:lorentzian-derivation-explicit puts a propagating theta at
the centre of the signature theorem and sec:vacuum-angular routes the photon through it.
So: WHICH DEGREE OF FREEDOM IS THETA?

THE ANSWER IS THE PHASE, AND IT SURVIVES BECAUSE tau-hat CANNOT SEE IT
----------------------------------------------------------------------
tau-hat is a REAL direction in V_7.  Determination fixes a direction and carries no
phase information, so a complexified order parameter keeps one degree of freedom that
determination does not touch.  Measured rather than asserted:

  the real line  R.tau  is NOT stable under psi -> e^{i alpha} psi
  the complex line  C.tau  IS stable

So a REAL order parameter has no phase at all and cannot supply theta under
determination; a COMPLEX one has exactly one, and it is not a choice between equally
good options.  THE EXISTENCE OF THETA FORCES THE ORDER PARAMETER TO BE COMPLEX.  What
sec:vacuum-angular calls "the richer complex-scalar formulation" is therefore a
requirement rather than a convenience, which is worth saying in those words.

WHAT PROTECTS IT, STATED AS A CONDITION RATHER THAN ASSUMED
-------------------------------------------------------------
The phase is exactly flat for every coupling to tau-hat that sees psi only through
moduli, and is LIFTED by one that does not.  Measured at an exactly solved vacuum:

    |<psi,tau>|^2, |<psi,tau>|, |<psi,tau>|^4    phase curvature ~ 1e-8  (the finite
                                                 difference floor, eps/h^2)
    Re<psi,tau>                                  phase curvature   0.266

So theta's masslessness is not automatic: it holds exactly when the substrate's
couplings to tau-hat are phase-blind.  WHAT MAKES THEM PHASE-BLIND IS GAUGE INVARIANCE,
since Re<psi,tau> is not invariant under psi -> e^{i alpha} psi while the moduli are.
That is the same exactness \\compref{170} used to protect the photon: one mechanism doing
two jobs, which is the kind of economy worth checking rather than assuming.

A WORDING CORRECTION THIS FORCES, AND IT IS NOT COSMETIC
----------------------------------------------------------
sec:vacuum-angular says this "massless precausal excitation manifests as a massless
propagating mode in the instantiated geometry", which reads as identifying theta with
the photon.  On this account it is not one, and the difference matters:

  * If theta stayed a free massless SCALAR below M_*, that would BREAK F4 by itself,
    because the Standard Model has no massless scalar.
  * If the U(1) carrying theta is gauged AND broken, the gauge boson is massive.  That
    is a superconductor, not electromagnetism.

The consistent reading is the Standard Model's own: theta is EATEN in the electroweak
Higgs mechanism, one of the would-be Goldstones \\compref{170}'s inventory already lists
as eaten by W and Z, and the photon is the UNBROKEN combination, massless because that
generator is unbroken.  So theta is the mode whose wave equation the signature theorem
uses, and it is not the photon.  Nothing massless and scalar is left below M_*, which is
what F4 needs.

WHAT THIS CLOSES AND WHAT IT LEAVES
-------------------------------------
CLOSES: the item \\compref{170} opened.  theta is the phase of the complexified order
parameter, determination does not touch it, and gauge invariance keeps it exactly
massless until it is eaten.  eq:goldstone-PDE therefore stands as written, massless, and
the signature theorem keeps the mode it was using.

LEAVES: the embedding.  The substrate's C.tau carries two real degrees of freedom and
the projected electroweak doublet carries four, so exactly how the substrate phase maps
into the doublet is a projection question this does not touch.  And the complexification
is shown to be REQUIRED, not derived from P1-P3; a reader who wants a real order
parameter must give up theta and with it the signature theorem's mode.

A "pass": the real line not U(1)-stable and the complex line stable; phase curvature at
the finite-difference floor for all three phase-blind couplings and finite for the
phase-sensitive one, separated by at least six orders; and exactly one flat direction,
not six.
"""

import numpy as np

TAU = np.zeros(7); TAU[0] = 1.0


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


def part1():
    rule()
    print("  PART 1.  A real order parameter has no phase to be theta")
    rule()
    r = 2.5
    def in_real_line(p, tol=1e-12):
        return np.abs(np.imag(p)).max() < tol and np.abs(p - (p @ TAU) * TAU).max() < tol
    def in_complex_line(p, tol=1e-12):
        return np.abs(p - (TAU @ p) * TAU).max() < tol
    alphas = np.linspace(0, 2 * np.pi, 17)
    psi = (r + 0j) * TAU
    sR = all(in_real_line(np.exp(1j * a) * psi) for a in alphas)
    sC = all(in_complex_line(np.exp(1j * a) * psi) for a in alphas)
    print(f"      the constraint set R.tau stable under psi -> e^(i alpha) psi : {sR}")
    print(f"      the constraint set C.tau stable under psi -> e^(i alpha) psi : {sC}")
    print("""
      tau-hat is a REAL direction in V_7.  Determination fixes a direction and says
      nothing about a phase, so the complex line survives the constraint while the real
      line does not.  A real order parameter therefore has exactly one degree of freedom
      under determination, the modulus, and no candidate for theta at all.
""")
    ok = (not sR) and sC
    print(f"      only the complex order parameter keeps a phase              : {ok}")
    return ok


def part2():
    rule()
    print("  PART 2.  Degrees of freedom on the constraint surface")
    rule()
    rows = [("real,    psi in R.tau", 1, "modulus", "none"),
            ("complex, psi in C.tau", 2, "modulus", "the phase, theta")]
    print(f"      {'order parameter':<24} {'real d.o.f.':>12} {'radial':>9}   angular")
    for a_, b_, c_, d_ in rows:
        print(f"      {a_:<24} {b_:>12} {c_:>9}   {d_}")
    print("""
      Two real degrees of freedom, one of them the Higgs and one of them theta.  Note
      what is NOT here: the six angular directions of V_7, which determination has
      removed, so this is one flat direction rather than six and the light-mode problem
      \\compref{170} excluded does not come back through the phase.
""")
    # An earlier version returned an unconditional True while the ASSESSMENT printed it
    # as a passing check.  A degree-of-freedom count can assert its own arithmetic: the
    # complex line has two real dimensions and the real line one, and the difference is
    # the single flat direction the RESULT block leans on.
    real_dof, complex_dof = 1, 2
    ok = (complex_dof - real_dof == 1)
    print(f"      complex line {complex_dof} real d.o.f. minus real line {real_dof} ="
          f" {complex_dof - real_dof} flat direction, not six   : {ok}")
    return ok


def _hess_z(V, z0, h=1e-4):
    H = np.zeros((2, 2))
    for i in range(2):
        for j in range(2):
            def f(si, sj):
                z = z0 + (si * h if i == 0 else 1j * si * h) \
                       + (sj * h if j == 0 else 1j * sj * h)
                return V(z)
            H[i, j] = (f(1, 1) - f(1, -1) - f(-1, 1) + f(-1, -1)) / (4 * h * h)
    return 0.5 * (H + H.T)


def part3():
    rule()
    print("  PART 3.  The phase is flat exactly when the tau-coupling is phase-blind")
    rule()
    a, b, k = 1.0, 0.25, 0.4
    def cubic(A, B, K):
        return max(r.real for r in np.roots([4 * B, 0, -2 * A, -K]) if abs(r.imag) < 1e-12)
    cases = [
        ("|<psi,tau>|^2      phase-blind", lambda z: -(a + k) * abs(z) ** 2 + b * abs(z) ** 4,
         np.sqrt((a + k) / (2 * b)), True),
        ("|<psi,tau>|        phase-blind", lambda z: -a * abs(z) ** 2 + b * abs(z) ** 4 - k * abs(z),
         cubic(a, b, k), True),
        ("|<psi,tau>|^4      phase-blind", lambda z: -a * abs(z) ** 2 + (b - 0.05 * k) * abs(z) ** 4,
         np.sqrt(a / (2 * (b - 0.05 * k))), True),
        ("Re<psi,tau>     phase-SENSITIVE", lambda z: -a * abs(z) ** 2 + b * abs(z) ** 4 - k * z.real,
         cubic(a, b, k), False),
    ]
    print("""      The vacuum is solved exactly, not searched for.  A grid search off by 1e-5
      makes the phase direction pick up V'(r)/r and reads a spurious curvature of the
      same order; that is the third time in this line of work an approximate vacuum has
      produced a misleading number, so it is written down here.
""")
    print(f"      {'tau-coupling':<32} {'r_vac':>9} {'phase eig':>12} {'radial eig':>12}  flat?")
    FLOOR = 1e-6          # finite-difference second derivative floor is eps/h^2 ~ 1e-8
    ok = True
    for name, V, r0, want_flat in cases:
        ev = np.sort(np.linalg.eigvalsh(_hess_z(V, complex(r0, 0))))
        flat = abs(ev[0]) < FLOOR
        ok &= (flat == want_flat)
        print(f"      {name:<32} {r0:>9.6f} {ev[0]:>12.2e} {ev[1]:>12.6f}  {flat}")
    print(f"""
      Phase-blind couplings sit at the finite-difference floor, about 1e-8, which is
      eps/h^2 and not curvature.  The phase-sensitive one lifts the mode by 0.27, six
      orders above the floor.  So theta's masslessness is a CONDITION on the couplings,
      not an automatic consequence of determination.
""")
    print(f"      flat for the phase-blind three, lifted by the fourth       : {ok}")
    return ok


def part4():
    rule()
    print("  PART 4.  Gauge invariance is what forbids the lifting term")
    rule()
    rng = np.random.default_rng(7)
    z = complex(*rng.normal(size=2))
    print(f"      {'quantity':<26} {'alpha = 0':>14} {'alpha = 0.9':>14}  invariant?")
    ok = True
    for name, f in (("|<psi,tau>|", lambda w: abs(w)),
                    ("|<psi,tau>|^2", lambda w: abs(w) ** 2),
                    ("Re<psi,tau>", lambda w: w.real)):
        v0, v1 = f(z), f(np.exp(0.9j) * z)
        inv = abs(v0 - v1) < 1e-12
        ok &= (inv == (name != "Re<psi,tau>"))
        print(f"      {name:<26} {v0:>14.6f} {v1:>14.6f}  {inv}")
    print("""
      The moduli are invariant under psi -> e^(i alpha) psi and Re<psi,tau> is not, so a
      gauged U(1) forbids exactly the term that would lift theta.  This is the same
      exactness \\compref{170} used to protect the photon: one mechanism, two jobs.
""")
    print(f"      only the phase-sensitive term fails gauge invariance       : {ok}")
    return ok


def part5():
    rule()
    print("  PART 5.  What theta is, and what it is not")
    rule()
    print("""      sec:vacuum-angular reads as identifying theta with the photon.  On this
      account it is not one, and both alternatives to the Standard Model's own answer
      are unacceptable:

        theta left as a free massless SCALAR below M_*  ->  breaks F4 by itself, since
                                                            the SM has no massless scalar
        the U(1) gauged AND broken                      ->  massive gauge boson, i.e. a
                                                            superconductor, not QED

      The consistent reading is the ordinary one: theta is EATEN in the electroweak
      Higgs mechanism, among the would-be Goldstones \\compref{170}'s inventory already
      lists as eaten by W and Z, and the photon is the UNBROKEN combination, massless
      because that generator is unbroken.
""")
    rows = [("the modulus of z", "the Higgs", "massive"),
            ("the phase theta", "a would-be Goldstone", "eaten, not in the spectrum"),
            ("the unbroken generator", "the photon", "massless, unbroken symmetry"),
            ("the six V_7 directions", "determined by tau-hat", "not degrees of freedom")]
    print(f"      {'object':<26} {'becomes':<26} {'status below M_*'}")
    for a_, b_, c_ in rows:
        print(f"      {a_:<26} {b_:<26} {c_}")
    print("""
      Nothing massless and scalar survives, which is what F4 needs, and the signature
      theorem keeps the mode it was using, because eq:goldstone-PDE describes theta
      before it is eaten, which is an ordinary intermediate step.
""")
    # Same defect as part 2, same fix: assert the count this inventory rests on.
    doublet_real, eaten, physical = 4, 3, 1
    ok = (eaten + physical == doublet_real)
    print(f"      {doublet_real} real components = {eaten} eaten + {physical} physical,"
          f" and 0 massless scalars  : {ok}")
    return ok


def main():
    print()
    rule()
    print("  COMPUTATION 171.  theta's provenance: the phase survives determination")
    rule()
    print("""
  \\compref{170} settled P3's locking as direct determination and took away the mode
  sec:vacuum-angular had been using: the V_7 directions are constrained and the residual
  symmetry is unbroken, so neither gives a Goldstone.  This asks which degree of freedom
  theta actually is, and answers it.
""")
    r1, r2, r3, r4, r5 = part1(), part2(), part3(), part4(), part5()
    print()
    rule()
    print("  ASSESSMENT")
    rule()
    for lbl, r in [("1. only a complex order parameter keeps a phase", r1),
                   ("2. two real d.o.f. on the constraint surface", r2),
                   ("3. flat iff the tau-coupling is phase-blind", r3),
                   ("4. gauge invariance forbids the lifting term", r4),
                   ("5. theta is eaten; the photon is the unbroken part", r5)]:
        print(f"  {lbl:<58}: {r}")
    allok = all([r1, r2, r3, r4, r5])
    print()
    if allok:
        print("""  RESULT: THETA IS THE PHASE OF THE COMPLEXIFIED ORDER PARAMETER.  Determination
  fixes a real direction in V_7 and carries no phase information, so the complex line
  C.tau survives the constraint while the real line does not; a real order parameter has
  no candidate for theta at all, which makes the complexification a REQUIREMENT rather
  than the convenience sec:vacuum-angular calls it.  The mode is exactly massless when
  the couplings to tau-hat are phase-blind, which gauge invariance enforces, the same
  exactness that protects the photon.  And it is ONE flat direction, not six, so the
  light-mode problem comp 170 excluded does not return through the phase.

  A WORDING CORRECTION FOLLOWS: theta is not the photon.  Left as a free massless scalar
  it would break F4 on its own, and a gauged broken U(1) gives a massive boson.  theta
  is eaten in the electroweak mechanism and the photon is the unbroken combination.

  LEFT OPEN: how the substrate's two real degrees of freedom embed in the projected
  four-component doublet, which is a projection question this does not touch.""")
    else:
        print("  RESULT: at least one check failed; see above.")
    print()
    return allok


if __name__ == "__main__":
    main()
