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

Computation 144 -- Does a threshold crossing at the slits leave an observable trace?
====================================================================================
The companion to Computation 143.  143 shows the threshold law of eq:tau-i-explicit
cannot support an intermediate-coupling prediction as written.  This computation asks
the prior question: IF the law were repaired so that stronger coupling makes crossing
more likely, would the resulting intermediate regime predict anything that standard
quantum mechanics does not?

The answer decides whether the open item in sec:open-frontiers is worth pursuing, and
it does not depend on the details of the repair -- only on whether a crossing at the
slits is a PHYSICAL SELECTION or is redundant with decoherence.

THE TWO READINGS
----------------
Write p = P(a threshold crossing occurs at the slit plane) for a given coupling.

  READING 1, "crossing is redundant".  The substrate crossing is bookkeeping on top of
  standard decoherence; the state reaching the screen is the ordinary entangled state
  and the Born rule is applied there.  PST is then numerically identical to QM.

  READING 2, "crossing selects".  A crossing at the slits selects one path, exactly as
  sec:collapse-rule's clause (U) says, so that fraction p of runs carries no
  interference at all, while the remaining 1 - p evolve undisturbed.  The screen
  pattern is the mixture.

Reading 2 is what the book's own no-detector argument asserts ("with no crossing there
is no selection... the projected wavefunction arriving at the screen therefore retains
the contributions of both slit regions"), read in the contrapositive.

THE DISCRIMINANT: WAVE-PARTICLE DUALITY
---------------------------------------
For a two-path interferometer with a which-path pointer, standard QM obeys the
Englert-Greenberger-Yasin relation exactly for pure states:

    V^2 + D^2 = 1,

with V the fringe visibility and D the which-path distinguishability.  For a Gaussian
pointer of width sigma displaced by +-d/2, the overlap is
gamma = exp(-d^2 / (8 sigma^2)), and V_QM = gamma, D = sqrt(1 - gamma^2).

Under Reading 2 the visible fringes come only from the non-crossing fraction, so

    V_PST = (1 - p) * gamma,     D unchanged,

because the which-path information available to the pointer is the same in both
readings.  Hence

    V_PST^2 + D^2 = 1 - (1 - (1-p)^2) gamma^2  <  1   for any p > 0.

So Reading 2 predicts a SUB-DUALITY deficit.  That is a signature, and it is the one
the open item is asking for -- but it is a signature in a quantity that has already
been measured.

CHECKS
------
  (1) The QM duality relation is saturated by the model, V^2 + D^2 = 1 to machine
      precision, across the full range of pointer separation.  (Sanity check on the
      model itself before it is used to test anything.)
  (2) The Reading-2 deficit 1 - (V_PST^2 + D^2) is computed across (p, gamma), and its
      maximum over gamma is located for each p.
  (3) The deficit is monotone in p and vanishes only at p = 0, so ANY nonzero
      crossing probability at the slits is in principle detectable.
  (4) The smallest p that a duality test of a given precision could exclude is
      computed, so the result can be compared against published bounds.
"""

import numpy as np

print("=" * 78)
print("Computation 144 -- observable trace of a threshold crossing at the slits")
print("=" * 78)

gammas = np.linspace(1e-6, 1.0, 200001)       # pointer overlap
V_qm = gammas
D = np.sqrt(np.clip(1.0 - gammas ** 2, 0.0, None))

# ---- CHECK 1 -------------------------------------------------------------
resid = np.abs(V_qm ** 2 + D ** 2 - 1.0).max()
print(f"\n(1) QM DUALITY SATURATION:  max |V^2 + D^2 - 1| = {resid:.3e}")
assert resid < 1e-12
print("    the model saturates the Englert-Greenberger-Yasin relation exactly.")

# ---- CHECK 2, 3 ----------------------------------------------------------
print("\n(2,3) SUB-DUALITY DEFICIT UNDER READING 2  (crossing selects)")
print(f"    {'p':>8} {'max deficit':>13} {'at gamma':>10} {'  (V_PST, D) there':>22}")
rows = []
for p in [0.0, 0.01, 0.05, 0.10, 0.25, 0.50, 0.90, 1.00]:
    V_pst = (1.0 - p) * gammas
    deficit = 1.0 - (V_pst ** 2 + D ** 2)
    j = int(np.argmax(deficit))
    rows.append((p, deficit[j]))
    print(f"    {p:>8.3g} {deficit[j]:>13.6f} {gammas[j]:>10.4f}"
          f"   ({V_pst[j]:.4f}, {D[j]:.4f})")

# the maximum is at gamma = 1 analytically: deficit = 1 - (1-p)^2
for p, dmax in rows:
    assert abs(dmax - (1.0 - (1.0 - p) ** 2)) < 1e-6, (p, dmax)
print("\n    analytic: max deficit = 1 - (1-p)^2, attained at gamma -> 1,")
print("    i.e. in the WEAK-coupling corner where the pointer barely distinguishes")
print("    the paths.  Verified against the numerical maximum to 1e-6.")
print("    monotone in p and zero only at p = 0:")
ds = [1.0 - (1.0 - p) ** 2 for p in [0.0, 0.01, 0.05, 0.1, 0.25, 0.5, 0.9, 1.0]]
assert all(b > a for a, b in zip(ds, ds[1:])) and ds[0] == 0.0
print("    -> any nonzero crossing probability at the slits is observable in principle.")

# ---- CHECK 4 -------------------------------------------------------------
print("\n(4) WHAT A DUALITY TEST OF GIVEN PRECISION EXCLUDES")
print("    A measurement confirming V^2 + D^2 = 1 to within eps excludes any p with")
print("    1 - (1-p)^2 > eps, i.e. p > 1 - sqrt(1 - eps).")
print(f"\n    {'precision eps':>14} {'excludes p >':>14}")
for eps in [1e-1, 5e-2, 1e-2, 5e-3, 1e-3]:
    print(f"    {eps:>14.0e} {1 - np.sqrt(1 - eps):>14.5f}")
print("\n    -> a 1% duality test already excludes crossing probabilities above")
print("       p ~ 0.005 at the slit plane, for every coupling in the weak corner.")

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

  The intermediate-coupling regime does carry a signature, and it is sharp:

    Reading 2 (a crossing at the slits physically selects a path) predicts
    V^2 + D^2 = 1 - [1 - (1-p)^2] gamma^2 < 1,
    a SUB-DUALITY deficit, largest exactly where the coupling is weakest.

  That is the positive prediction the open item was looking for.  It is also,
  on the face of it, the wrong sign for PST: wave-particle duality is measured
  to hold, not to fail, and a percent-level duality test already bounds the
  slit-plane crossing probability near zero.

  So the fork is forced, and neither branch leaves the open item alive:

    * If crossings at the slits select (Reading 2), PST predicts a duality
      deficit and existing interferometry constrains it hard.  This is a
      falsifiable claim the book does not currently make, and it is closer to
      refuted than to confirmed.

    * If crossings are redundant with decoherence (Reading 1), PST reproduces
      QM exactly, there is no intermediate-regime signature to find, and the
      honest move is to say so -- as was done for the pinned-direction item.

  Either way the deciding question is not "how weak a coupling still forces a
  crossing".  It is whether a crossing is a physical selection or bookkeeping.
  That is a question about what sec:collapse-rule MEANS, not a quantity to be
  computed, and it should be settled in the text before any measurement is
  invoked.
""")
