// Interaction-free measurement — correctness-first verification.
//
// For the stratum "Seeing in the Dark" (the Elitzur–Vaidman quantum bomb tester),
// P7 (Technical Honeypot). EVERY number the page claims is reproduced here two ways:
// (a) exact complex-amplitude algebra of the Mach–Zehnder interferometer, and
// (b) a Monte-Carlo that draws each photon's fate from those amplitudes. The two
// must agree. The in-browser instruments use the identical formulae.
//
// Run:  node verify.mjs    (no dependencies — plain Node, complex numbers by hand)

// ---------- tiny complex + 2x2 helpers ----------
const C = (re, im = 0) => ({ re, im });
const add = (a, b) => C(a.re + b.re, a.im + b.im);
const mul = (a, b) => C(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re);
const abs2 = (a) => a.re * a.re + a.im * a.im;
// apply a 2x2 complex matrix [[m00,m01],[m10,m11]] to a 2-vector [v0,v1]
const apply = (M, v) => [add(mul(M[0][0], v[0]), mul(M[0][1], v[1])),
                         add(mul(M[1][0], v[0]), mul(M[1][1], v[1]))];

const approx = (a, b, eps = 1e-9) => Math.abs(a - b) < eps;
let PASS = true;
const check = (name, got, want, eps = 1e-9) => {
  const ok = approx(got, want, eps);
  if (!ok) PASS = false;
  console.log(`  ${ok ? 'PASS' : 'FAIL'}  ${name}: got ${got}  want ${want}`);
};

// ============================================================
// PART 1 — The balanced Mach–Zehnder interferometer (R = 1/2)
// ============================================================
// Path basis: index 0 = LOWER arm, index 1 = UPPER arm (the bomb arm).
// 50:50 beam splitter, symmetric convention (reflection carries phase i):
//   BS = (1/√2) [[1, i],[i, 1]]
const r2 = 1 / Math.sqrt(2);
const BS = [[C(r2, 0), C(0, r2)], [C(0, r2), C(r2, 0)]];

console.log('PART 1 — Balanced Mach–Zehnder (R = 1/2)\n');

// --- No obstruction: two beam splitters compose to swap ports; the photon
//     exits deterministically at the BRIGHT port and the DARK port stays dark. ---
{
  const inState = [C(1, 0), C(0, 0)];      // photon enters the lower input port
  const afterBS1 = apply(BS, inState);
  const afterBS2 = apply(BS, afterBS1);    // equal arms => identity between splitters
  const pBright = abs2(afterBS2[1]);       // UPPER output = bright/light port
  const pDark   = abs2(afterBS2[0]);       // LOWER output = dark port
  console.log(' No bomb (interference):');
  check('   P(bright port)', pBright, 1.0);
  check('   P(dark port)  — must be exactly 0', pDark, 0.0);
}

// --- Bomb in the UPPER arm: it measures which-path. ---
//   After BS1 the upper-arm amplitude is i/√2  => P(explode) = 1/2.
//   Surviving (prob 1/2) collapses the photon into the LOWER arm; BS2 then
//   splits it 50/50 between bright and dark ports.
let evExplode, evDark, evBright;
{
  const afterBS1 = apply(BS, [C(1, 0), C(0, 0)]);
  evExplode = abs2(afterBS1[1]);           // prob photon is in the bomb (upper) arm
  // conditional on survival the photon is in the lower arm (state [1,0] renormalised)
  const survived = apply(BS, [C(1, 0), C(0, 0)]);   // BS2 on |lower>
  const condBright = abs2(survived[1]);    // 1/2
  const condDark   = abs2(survived[0]);    // 1/2
  evBright = (1 - evExplode) * condBright;
  evDark   = (1 - evExplode) * condDark;
  console.log('\n Live bomb (which-path measurement):');
  check('   P(explode)            ', evExplode, 0.5);
  check('   P(dark port, CERTIFIES)', evDark, 0.25);
  check('   P(bright, inconclusive)', evBright, 0.25);
  check('   probabilities sum to 1 ', evExplode + evDark + evBright, 1.0);
}

// --- Resend on every inconclusive (bright) click; stop on explode or dark. ---
//   Eventual outcome is a geometric race: P(safe) = pDark/(pDark+pExplode).
{
  const pSafe = evDark / (evDark + evExplode);     // 1/3
  const pBoom = evExplode / (evDark + evExplode);  // 2/3
  console.log('\n Repeat-until-resolved (discard inconclusive):');
  check('   P(detected safely, eventually)', pSafe, 1 / 3);
  check('   P(detonated)                  ', pBoom, 2 / 3);
}

// ============================================================
// PART 2 — Unbalanced MZ: the Elitzur–Vaidman efficiency ceiling
// ============================================================
// A beam splitter of reflectivity R (prob R into the bomb arm). With a live bomb:
//   P(explode)=R,  P(dark, certifies)=T·R,  P(bright, inconclusive)=T²,  T=1−R.
// Efficiency (fraction of CONCLUSIVE runs that are interaction-free):
//   η(R) = T·R / (T·R + R) = T/(T+1) = (1−R)/(2−R)  →  1/2 as R→0.
console.log('\nPART 2 — Unbalanced MZ efficiency η(R) = (1−R)/(2−R)\n');
const eta = (R) => (1 - R) / (2 - R);
{
  // verify the closed form against the raw probabilities, several R
  for (const R of [0.5, 0.2, 0.05, 0.01]) {
    const T = 1 - R;
    const pExp = R, pDark = T * R, pBright = T * T;
    check(`   R=${R}: probs sum to 1`, pExp + pDark + pBright, 1.0);
    check(`   R=${R}: η raw vs closed`, pDark / (pDark + pExp), eta(R), 1e-12);
  }
  check('   η(1/2) = 1/3', eta(0.5), 1 / 3);
  check('   η→1/2 as R→0 (R=1e-6)', eta(1e-6), 0.5, 1e-5);
  console.log(`   [ceiling] sup η = 1/2 (single-MZ scheme); detection rate T·R→0 there.`);
}

// ============================================================
// PART 3 — The quantum Zeno bomb tester (breaks the 1/2 ceiling → 1)
// ============================================================
// A horizontally polarised photon makes N cycles. Each cycle a rotator turns the
// polarisation by θ = π/(2N): |H> → cosθ|H> + sinθ|V>. A polariser passes V into the
// bomb arm.  NO bomb: rotations add coherently, after N cycles |H>→|V> (measured V).
//   LIVE bomb: each cycle the bomb measures the path; survives that cycle w.p. cos²θ
//   and is projected back to |H>. P(survive all N) = cos^{2N}(π/2N); a final H reading
//   then certifies the bomb. As N→∞ this → 1 and P(explode) → 0.
console.log('\nPART 3 — Quantum Zeno bomb tester\n');
const pZenoDetect = (N) => Math.pow(Math.cos(Math.PI / (2 * N)), 2 * N);
{
  const table = [1, 2, 3, 6, 10, 20, 50, 100, 500];
  console.log('     N    P(detect safely)   P(boom)');
  for (const N of table) {
    const d = pZenoDetect(N);
    console.log(`   ${String(N).padStart(4)}    ${d.toFixed(6)}          ${(1 - d).toFixed(6)}`);
  }
  check('   N=1  detect = 0      (cos²(π/2)=0)', pZenoDetect(1), 0, 1e-12);
  check('   N=2  detect = 1/4    (cos⁴(π/4))  ', pZenoDetect(2), 0.25, 1e-12);
  check('   N=3  detect          (cos⁶(π/6))  ', pZenoDetect(3), Math.pow(3 / 4, 3), 1e-12);
  // convergence is slow: 1 − P(detect) ≈ π²/(4N), so test the asymptotic itself
  check('   N→∞: 1−detect ≈ π²/4N (N=2000)', 1 - pZenoDetect(2000), Math.PI ** 2 / (4 * 2000), 2e-4);
  check('   N huge: detect → 1 (N=2,000,000)', pZenoDetect(2_000_000), 1.0, 1e-5);
  // small-N→0 boom scaling P(boom) ≈ π²/(4N)
  const N = 1000;
  check('   boom ≈ π²/(4N) at N=1000', 1 - pZenoDetect(N), Math.PI * Math.PI / (4 * N), 5e-4);
}

// ============================================================
// PART 4 — Monte-Carlo cross-check (the page samples exactly this way)
// ============================================================
console.log('\nPART 4 — Monte-Carlo cross-check (2,000,000 photons each)\n');
function mt(seed) { let s = seed >>> 0; return () => { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; s >>>= 0; return s / 4294967296; }; }
{
  const rng = mt(12345);
  const N = 2_000_000;
  // Balanced MZ, single shot
  let exp = 0, dark = 0, bright = 0;
  for (let i = 0; i < N; i++) {
    const u = rng();
    if (u < 0.5) exp++;                 // explode w.p. 1/2 (upper-arm amplitude²)
    else if (rng() < 0.5) dark++;       // survived → BS2 → dark w.p. 1/2
    else bright++;
  }
  check('   MC P(explode)', exp / N, 0.5, 3e-3);
  check('   MC P(dark)   ', dark / N, 0.25, 3e-3);
  check('   MC P(bright) ', bright / N, 0.25, 3e-3);

  // Zeno cavity, N=20 cycles, simulated cycle-by-cycle from cos²θ survival
  const Ncyc = 20, theta = Math.PI / (2 * Ncyc), pSurv = Math.cos(theta) ** 2;
  let detected = 0;
  for (let i = 0; i < N; i++) {
    let alive = true;
    for (let c = 0; c < Ncyc; c++) { if (rng() > pSurv) { alive = false; break; } }
    if (alive) detected++;
  }
  check('   MC Zeno(N=20) detect', detected / N, pZenoDetect(20), 3e-3);
}

console.log('\n' + (PASS ? 'ALL CHECKS PASSED' : '*** SOME CHECKS FAILED ***'));
process.exit(PASS ? 0 : 1);
