#!/usr/bin/env python3
"""EPR with photons, minimal: two local bits per pair, every pair counted.

A source emits pairs of photons with orthogonal linear polarisations, lam and
lam + 90 deg.  Each photon meets a two-channel polariser set at its own angle
and leaves by the channel whose axis is nearer its polarisation:

    A = sign cos 2(lam - theta_a)        B = sign cos 2(lam + 90 deg - theta_b)

Each record uses its own polariser angle and the polarisation that reaches it.
Nothing is filtered.  The two runs below keep these records and differ in one
thing, the measure of lam:

  uniform     lam uniform in angle, the same for every polariser setting.
              E is the triangle, CHSH = 2: Bell's bound.
  projection  the pair's record lands uniformly across the projected aperture
              of the polariser that hosts it: x = sin 2(lam - theta_host) is
              uniform on [-1, 1], density |cos 2(lam - theta_host)| / 2 in lam.
              E = -cos 2(theta_a - theta_b), CHSH = 2 sqrt 2.

Fundamental Density Theory, core I-4.  MIT License, (c) 2026 Manuel Alfaro.
Paper and full simulation: https://densitytheory.com/applications/bell-correlations/
"""
import numpy as np            # the only dependency; Matplotlib draws the graph if present

N = 1_000_000                 # photon pairs per pair of polariser angles
rng = np.random.default_rng(271828)


def polarisation(n, theta_a, theta_b, measure):
    """Polarisation lam of photon A in radians; photon B has lam + pi/2."""
    if measure == "uniform":
        return rng.uniform(0.0, np.pi, n)
    x = rng.uniform(-1.0, 1.0, n)    # uniform across the projected aperture
    front = rng.random(n) < 0.5      # front or back sheet of the circle
    u = np.where(front, np.arcsin(x), np.pi - np.arcsin(x))
    host_is_a = rng.random(n) < 0.5  # either polariser hosts the record
    return u / 2 + np.where(host_is_a, theta_a, theta_b - np.pi / 2)


def records(lam, theta_a, theta_b):
    """The two local bits, +1 or -1: the channel each photon takes."""
    a = np.where(np.cos(2 * (lam - theta_a)) > 0, 1, -1)
    b = np.where(np.cos(2 * (lam + np.pi / 2 - theta_b)) > 0, 1, -1)
    return a, b


def experiment(deg_a, deg_b, measure, n=N):
    """Correlation E and each wing's share of +1, every pair counted."""
    theta_a, theta_b = np.radians(deg_a), np.radians(deg_b)
    a, b = records(polarisation(n, theta_a, theta_b, measure), theta_a, theta_b)
    return (a * b).mean(), (a > 0).mean(), (b > 0).mean()


def chsh(measure):
    """S = E00 + E01 + E10 - E11 at polarisers 0, 45 deg (A) and -67.5, 67.5 deg (B)."""
    e = [[experiment(a, b, measure)[0] for b in (-67.5, 67.5)] for a in (0.0, 45.0)]
    s = e[0][0] + e[0][1] + e[1][0] - e[1][1]
    return s, np.sqrt(sum(1 - x * x for row in e for x in row) / N)


if __name__ == "__main__":
    print(f"{N:,} photon pairs per setting, all counted")
    for measure in ("projection", "uniform"):
        s, se = chsh(measure)
        print(f"CHSH, {measure:10s} measure:  S = {s:.4f} +/- {se:.4f}")
    print(f"local bound 2, Tsirelson 2 sqrt 2 = {2 * np.sqrt(2):.4f}")

    wing = [experiment(0.0, b, "projection")[1] for b in (-67.5, 0.0, 30.0, 67.5)]
    print("P(A = +1), A at 0 deg, B at -67.5, 0, 30, 67.5 deg:", " ".join(f"{p:.4f}" for p in wing))

    angles = np.arange(0.0, 181.0, 7.5)      # theta_a - theta_b, in degrees
    curve = {m: [experiment(d, 0.0, m, 200_000)[0] for d in angles] for m in ("projection", "uniform")}
    cosine = np.round(-np.cos(2 * np.radians(angles)), 9) + 0.0
    triangle = np.round(-2 / np.pi * np.arcsin(np.cos(2 * np.radians(angles))), 9) + 0.0
    print("\n angle   projection   -cos 2D    uniform   triangle")
    for i in range(0, len(angles), 3):
        print(f"{angles[i]:6.1f}   {curve['projection'][i]:+.4f}      {cosine[i]:+.4f}    "
              f"{curve['uniform'][i]:+.4f}   {triangle[i]:+.4f}")

    try:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
    except ImportError:
        raise SystemExit("\nMatplotlib is not installed: no graph written.")
    d, blue, orange = np.linspace(0.0, 180.0, 361), "#2a78d6", "#eb6834"
    c = np.cos(2 * np.radians(d))
    fig, ax = plt.subplots(figsize=(7.2, 4.4))
    ax.plot(d, -c, color=blue, lw=2, label="-cos 2(theta_a - theta_b), quantum mechanics")
    ax.plot(d, -2 / np.pi * np.arcsin(c), color=orange, lw=2, ls="--", label="triangle")
    ax.plot(angles, curve["projection"], "o", color=blue, ms=7, mec="white", label="records, projection measure")
    ax.plot(angles, curve["uniform"], "s", color=orange, ms=6, mec="white", label="records, uniform measure")
    ax.set(xlabel="angle between the two polarisers (degrees)", ylabel="correlation E, every pair counted")
    ax.set_xticks(range(0, 181, 45))
    ax.grid(color="#dddddd", lw=0.6)
    ax.legend(frameon=False, fontsize=8)
    fig.savefig("bell_epr_photons_minimal.png", dpi=150, bbox_inches="tight")
    print("\ngraph written: bell_epr_photons_minimal.png")
