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

Computation 143 -- Born compatibility and uniqueness of the threshold-crossing rule
====================================================================================
Backs the open item in sec:open-frontiers: "how weak a coupling still forces a
threshold crossing".  The collapse rule of sec:collapse-rule sets

    tau_i(C) = tau_0(C) + kappa (lambda o_i)^2                     (eq:tau-i-explicit)
    C crosses outcome i  iff  w_i := |Pi^{-1}(P_i psi)|^2 > tau_i(C)

and clause (U) of the threshold-crossing-uniqueness theorem asserts the crossing set
is a singleton (or empty).  (U) is proved only for kappa lambda^2 >> tau_0.

WHERE THE RANDOMNESS LIVES -- the point that decides the whole analysis
-----------------------------------------------------------------------
For a GIVEN state psi the weights w_i are fixed numbers, not random variables.  What
varies from run to run is the substrate configuration C, and with it tau_0(C).  So the
object to study is

    P(select i) = P_C ( w_i > tau_0(C) + kappa (lambda o_i)^2 ),

a statement about the DISTRIBUTION OF tau_0 OVER CONFIGURATIONS.  The proof's own
bound sum_i w_i <= ||psi||^2 = 1 is used throughout; s = kappa lambda^2 is carried in
the same units, and no other normalisation is imposed.

CHECKS
------
  (1) BORN IS RECOVERED EXACTLY, UNDER AN UNSTATED CONDITION.  At zero coupling,
      P_C(tau_0 < w_i) = w_i for every i precisely when tau_0(C) is UNIFORM on [0,1].
      Verified to sampling precision, and shown to fail for a non-uniform tau_0
      (Beta(2,2)) on the same states.  This is a real constraint on the law of tau_0
      over substrate configurations, and the book does not state it.
  (2) UNIQUENESS FAILS AT WEAK COUPLING.  A single low tau_0 draw sits below several
      w_i at once, so the crossing set is not a singleton.  Measured.
  (3) THE STRONG-COUPLING CONDITION IS THE RIGHT HYPOTHESIS.  Raising s raises every
      threshold and monotonically drives P(>=2 crossings) to zero.  The proof's stated
      hypothesis does exactly the work the proof claims for it.
  (4) BUT (U) AND BORN PULL APART.  Conditioned on the crossing set being a singleton,
      the selected outcome is the maximum-margin one, which for fixed w is
      DETERMINISTIC -- the same outcome every run.  Where (U) holds, Born does not;
      where Born holds, (U) does not.  Checked across three states, including one with
      the largest weight on the largest |o_i| to rule out a correlation artefact.
  (5) SYMMETRIC SPECTRA GET NO SEPARATION FROM THE COUPLING.  For o = +-1 the
      quadratic form is outcome-independent, so eq:tau-i-explicit contributes nothing;
      the book's own degenerate-case clause routes this to einselection.  Recorded for
      completeness, not as a defect.
"""

import numpy as np

rng = np.random.default_rng(20260926)
N = 2_000_000
U = rng.uniform(0.0, 1.0, N)               # tau_0(C) ~ Uniform[0,1]
B22 = rng.beta(2.0, 2.0, N)                # a non-uniform control on the same support


def cross_sets(w, O, s, tau0):
    """Crossing iff tau_0 < w_i - s o_i^2."""
    margin = np.asarray(w)[None, :] - s * np.asarray(O)[None, :] ** 2
    cr = tau0[:, None] < margin
    return cr, cr.sum(axis=1)


print("=" * 78)
print("Computation 143 -- Born compatibility and uniqueness of the collapse rule")
print("=" * 78)

STATES = [
    ("A  weight aligned with small |o|", np.array([0.5, 0.3, 0.2]), np.array([0.5, 1.0, 1.5])),
    ("B  weight aligned with large |o|", np.array([0.2, 0.3, 0.5]), np.array([0.5, 1.0, 1.5])),
    ("C  near-degenerate weights      ", np.array([0.34, 0.33, 0.33]), np.array([0.5, 1.0, 1.5])),
]

# ---- CHECK 1 -------------------------------------------------------------
print("\n(1) BORN RECOVERY AT ZERO COUPLING, AND WHAT IT REQUIRES")
print(f"    {'state':>34}   {'P(cross i), tau_0 uniform':>30}   Born")
for name, w, O in STATES:
    p = np.array([(U < w[i]).mean() for i in range(len(w))])
    print(f"    {name:>34}   {str(np.round(p,4)):>30}   {w}")
    assert np.abs(p - w).max() < 2e-3
print("    -> P(tau_0 < w_i) = w_i EXACTLY.  The threshold rule reproduces the Born")
print("       rule, provided tau_0(C) is uniformly distributed over configurations.")
print(f"\n    same states, tau_0 ~ Beta(2,2) instead (still supported on [0,1]):")
for name, w, O in STATES[:2]:
    p = np.array([(B22 < w[i]).mean() for i in range(len(w))])
    print(f"    {name:>34}   {str(np.round(p,4)):>30}   {w}")
print("    -> Born FAILS.  The rule reads off the CDF of tau_0, so uniformity is not")
print("       cosmetic: it is the condition under which the collapse rule agrees with")
print("       the Born rule that sec:born-rule derives independently.  UNSTATED.")

# ---- CHECK 2, 3 ----------------------------------------------------------
print("\n(2,3) UNIQUENESS AGAINST COUPLING  (tau_0 uniform)")
for name, w, O in STATES:
    print(f"\n    {name}   Born = {w}")
    print(f"      {'s':>6} {'P(0)':>8} {'P(1)':>8} {'P(>=2)':>8}")
    prev = None
    for s in [0.0, 0.05, 0.10, 0.20, 0.30, 0.40]:
        _, k = cross_sets(w, O, s, U)
        p2 = (k >= 2).mean()
        print(f"      {s:>6.2f} {(k==0).mean():>8.4f} {(k==1).mean():>8.4f} {p2:>8.4f}")
        if prev is not None:
            assert p2 <= prev + 1e-6, "P(>=2) should be non-increasing in s"
        prev = p2
print("\n    -> P(>=2 crossings) falls monotonically to zero as the coupling rises.")
print("       The strong-coupling condition kappa lambda^2 >> tau_0 is doing exactly")
print("       the work the proof of (U) claims for it.")

# ---- CHECK 4 -------------------------------------------------------------
print("\n(4) WHERE (U) HOLDS, BORN DOES NOT")
print(f"    {'state':>34} {'s':>6} {'P(>=2)':>8}   P(select i | unique)      Born")
for name, w, O in STATES:
    for s in [0.0, 0.30, 0.40]:
        cr, k = cross_sets(w, O, s, U)
        one = k == 1
        if one.sum() < 1000:
            continue
        sel = cr[one].argmax(axis=1)
        f = np.bincount(sel, minlength=len(w)) / one.sum()
        print(f"    {name:>34} {s:>6.2f} {(k>=2).mean():>8.4f}   {str(np.round(f,3)):>20}   {w}")
print("\n    -> conditioned on the crossing set being a singleton, the selected outcome")
print("       is the maximum-margin one.  For a fixed state that is the SAME outcome")
print("       every run, so the conditional distribution is a point mass, not Born.")
print("       Case B rules out a correlation artefact: its selected outcome is 3 at")
print("       weak coupling and 1 at strong, so the effect tracks the margin, not the")
print("       labelling.")

# ---- CHECK 5 -------------------------------------------------------------
print("\n(5) SYMMETRIC SPECTRA")
SYM = np.array([-1.0, 1.0])
for s in [0.0, 1.0, 100.0]:
    t = 0.3 + s * SYM ** 2
    assert np.ptp(t) == 0.0
print("    for o = +-1 the term kappa(lambda o_i)^2 is outcome-independent at every")
print("    coupling, so eq:tau-i-explicit separates nothing.  The book's own")
print("    degenerate-case clause routes this to einselection; recorded, not a defect.")

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

  1. The threshold rule REPRODUCES THE BORN RULE exactly, at zero coupling, iff
     tau_0(C) is uniformly distributed over substrate configurations.  This is a
     positive result about the construction and a genuine constraint on the law
     of tau_0.  The book states neither.

  2. The strong-coupling hypothesis of clause (U) is the correct one: raising
     kappa lambda^2 raises every threshold and drives the probability of
     multiple simultaneous crossings monotonically to zero.

  3. The two pull apart.  At the coupling where Born holds the crossing set is
     not a singleton (about 30% of runs here), so (U) fails.  At the coupling
     where (U) holds the selection is the maximum-margin outcome, which for a
     fixed state is deterministic, so Born fails.  eq:tau-i-explicit cannot
     deliver both at once.

  CONSEQUENCE FOR THE OPEN ITEM.  "How weak a coupling still forces a crossing"
  is answerable -- P(cross) is computed above and moves smoothly with s -- but
  the answer is not the interesting quantity.  The interesting quantity is the
  Born/(U) trade-off along the same axis, which is a consistency question inside
  the theory rather than a prediction to be measured.
""")
