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

Computation 146 -- What the substrate layer contributes that decoherence cannot
================================================================================
Computation 144 concluded that a threshold crossing at the slits is redundant with
the decoherence PST inherits, in the sense that no fringe-visibility measurement
separates them.  Read carelessly that sounds deflationary: if the crossing changes
no statistic, what is it for?

This computation answers that, and the answer is standard physics rather than a PST
claim.  Decoherence does two things and conspicuously fails to do a third:

  it DOES suppress interference in the pointer basis;
  it DOES select that basis (einselection);
  it does NOT produce a definite outcome.

What unitary system-apparatus-environment evolution leaves behind is an IMPROPER
mixture: a reduced density matrix numerically identical to a proper statistical
mixture, while the global state stays pure and entangled, so there is no fact in
the formalism about which outcome obtained.  That is not a minority reading; it is
why the measurement problem survives decoherence at all.

So the division of labour is exact:

  Gleason (sec:born-rule)          -> the probabilities
  decoherence (Closure 2)          -> the basis, and the loss of interference
  threshold crossing (Closures 1,3)-> the definiteness, and one world

and the reason Computation 144 found no observable signature is the same reason
the contribution is real: the improper and proper mixtures are locally
indistinguishable BY CONSTRUCTION, so a statistic cannot see the difference that
definiteness makes.

CHECKS
------
  (1) DECOHERENCE WORKS.  Off-diagonal elements of the system's reduced density
      matrix decay to zero as the environment records the pointer value.
  (2) NOTHING COLLAPSED.  The global state stays pure (Tr rho^2 = 1) throughout:
      unitary evolution cannot produce a definite outcome, by construction.
  (3) THE MIXTURE IS IMPROPER.  The decohered reduced state is compared, entry by
      entry, with a PROPER mixture built by hand from definite outcomes.  They
      agree to machine precision, so no measurement on the system distinguishes
      "one outcome occurred, unknown to us" from "no outcome occurred".
  (4) AND NO LOCAL OBSERVABLE CAN TELL THEM APART.  Over many random Hermitian
      observables on the system, expectation values agree to machine precision.
  (5) THE DIFFERENCE IS REAL BUT GLOBAL.  Global purity separates the two cases
      perfectly (1 vs < 1), so the distinction exists in the formalism; it is
      simply not locally accessible.  That is exactly the gap a crossing fills.
"""

import numpy as np

rng = np.random.default_rng(20260926)


def dm(v):
    v = v / np.linalg.norm(v)
    return np.outer(v, v.conj())


def purity(r):
    return float(np.real(np.trace(r @ r)))


def partial_trace(rho, dims, keep):
    """Trace out every factor except `keep`."""
    n = len(dims)
    rho = rho.reshape(dims + dims)
    for ax in sorted([i for i in range(n) if i != keep], reverse=True):
        rho = np.trace(rho, axis1=ax, axis2=ax + (rho.ndim // 2))
    return rho


print("=" * 78)
print("Computation 146 -- what the substrate layer contributes that decoherence cannot")
print("=" * 78)

c = np.array([np.sqrt(0.7), np.sqrt(0.3)])        # Born weights 0.7 / 0.3
dS, dA = 2, 2

# ---- CHECK 1 & 2 ---------------------------------------------------------
print("\n(1,2) DECOHERENCE ACTS; THE GLOBAL STATE STAYS PURE")
print(f"    {'env dim':>8} {'|rho_01|':>12} {'global purity':>15} {'system purity':>14}")
for dE in [1, 2, 4, 8, 16, 32]:
    # |psi> = sum_i c_i |o_i>|a_i>|e_i>, with environment states growing more distinct
    env = np.zeros((2, dE), dtype=complex)
    if dE == 1:
        env[0, 0] = env[1, 0] = 1.0                     # environment records nothing
    else:
        env[0, 0] = 1.0
        env[1, min(1, dE - 1)] = 1.0                    # orthogonal records
    psi = np.zeros((dS, dA, dE), dtype=complex)
    for i in range(2):
        psi[i, i, :] = c[i] * env[i]
    psi = psi.reshape(-1)
    rho = dm(psi)
    rS = partial_trace(rho, [dS, dA, dE], keep=0)
    print(f"    {dE:>8} {abs(rS[0,1]):>12.3e} {purity(rho):>15.10f} {purity(rS):>14.6f}")
    assert abs(purity(rho) - 1.0) < 1e-12, "global state must stay pure"

print("    -> once the environment holds an orthogonal record the off-diagonal is 0:")
print("       interference is gone.  Global purity is 1.000000 at every step:")
print("       NOTHING collapsed.  Unitary evolution cannot make an outcome definite.")

# the fully decohered reduced state
dE = 32
env = np.zeros((2, dE), dtype=complex); env[0, 0] = 1.0; env[1, 1] = 1.0
psi = np.zeros((dS, dA, dE), dtype=complex)
for i in range(2):
    psi[i, i, :] = c[i] * env[i]
rho_glob = dm(psi.reshape(-1))
rS_improper = partial_trace(rho_glob, [dS, dA, dE], keep=0)

# ---- CHECK 3 -------------------------------------------------------------
print("\n(3) THE RESULT IS AN IMPROPER MIXTURE")
rS_proper = (c[0] ** 2) * dm(np.array([1, 0])) + (c[1] ** 2) * dm(np.array([0, 1]))
print(f"    decohered reduced state : {np.round(np.real(rS_improper), 6).tolist()}")
print(f"    proper mixture by hand  : {np.round(np.real(rS_proper), 6).tolist()}")
diff = np.abs(rS_improper - rS_proper).max()
print(f"    max entrywise difference: {diff:.3e}")
assert diff < 1e-12
print("    -> identical.  'one outcome occurred, we do not know which' and 'no")
print("       outcome occurred' have the SAME reduced state.  The formalism carries")
print("       no fact about which, and decoherence does not supply one.")

# ---- CHECK 4 -------------------------------------------------------------
print("\n(4) NO LOCAL OBSERVABLE SEPARATES THEM")
worst = 0.0
for _ in range(4000):
    M = rng.normal(size=(2, 2)) + 1j * rng.normal(size=(2, 2))
    M = M + M.conj().T
    d = abs(np.trace(M @ rS_improper) - np.trace(M @ rS_proper))
    worst = max(worst, float(np.real(d)))
print(f"    worst |<M>_improper - <M>_proper| over 4000 random observables: {worst:.3e}")
assert worst < 1e-10
print("    -> no measurement on the system can tell the two apart.  This is WHY")
print("       Computation 144 found no fringe-visibility signature: there is none")
print("       to find, and its absence is a theorem, not a weakness.")

# ---- CHECK 5 -------------------------------------------------------------
print("\n(5) THE DIFFERENCE IS REAL, BUT GLOBAL")
rho_proper_glob = (c[0] ** 2) * dm(np.kron(np.kron([1, 0], [1, 0]), np.eye(dE)[0])) \
                + (c[1] ** 2) * dm(np.kron(np.kron([0, 1], [0, 1]), np.eye(dE)[1]))
print(f"    global purity, unitary/entangled (no outcome) : {purity(rho_glob):.10f}")
print(f"    global purity, genuine single outcome         : {purity(rho_proper_glob):.10f}")
assert purity(rho_glob) > 0.99 and purity(rho_proper_glob) < 0.99
print("    -> the two ARE different states of the world; the difference is simply")
print("       not locally accessible.  Something must move the first to the second,")
print("       and decoherence provably cannot, because it is unitary (check 2).")

print("\n" + "=" * 78)
print("""SUMMARY

  Decoherence supplies the pointer basis and destroys interference.  It does
  not supply a definite outcome: the global state stays pure, and the reduced
  state is an improper mixture that no local observable separates from a proper
  one.  That is standard quantum mechanics, not a PST claim.

  So the three layers of the measurement postulate do disjoint work:

      Gleason, sec:born-rule          the probabilities
      decoherence, Closure (2)        the basis, and the loss of interference
      threshold crossing, (1) and (3) the definiteness, and one world

  The threshold crossing is therefore NOT redundant.  It supplies precisely the
  step decoherence cannot take, and it does so without a collapse postulate and
  without branching.

  Computation 144's "no observable signature" now reads correctly: the improper
  and proper mixtures are locally indistinguishable by construction, so no
  statistic could have separated them.  The absence of a signature is what the
  formalism REQUIRES, not evidence that the crossing does nothing.
""")
