// verify.mjs — the Kuramoto model of spontaneous synchronization, the genuine
// mean-field dynamics, with its exact critical coupling and order-parameter law
// CONFIRMED BY SIMULATION (detect, never assert from memory).
//
// THE MODEL (Yoshiki Kuramoto, 1975). N phase oscillators, each a point θ_i on the
// circle turning at its own natural frequency ω_i, pulled toward one another by a
// global coupling K:
//      dθ_i/dt = ω_i + (K/N) · Σ_j sin(θ_j − θ_i).
// The whole population's coherence is one complex number, the ORDER PARAMETER
//      r · e^{iψ} = (1/N) · Σ_j e^{iθ_j},
// where r ∈ [0,1] measures how clustered the phases are (r=0 scattered evenly
// around the circle; r=1 all at one phase) and ψ is their mean phase. Substituting
// it back collapses the all-to-all sum into a MEAN FIELD — every oscillator feels
// only (r, ψ):
//      dθ_i/dt = ω_i + K · r · sin(ψ − θ_i).
// Each oscillator is drawn toward the mean phase with a strength K·r set by how
// synchronized the crowd already is — the positive feedback that makes sync a
// genuine phase transition. (This collapse is the exact identity the WLTV world
// public/tv/systems/kuramoto.js integrates, byte for byte.)
//
// THE FREQUENCIES. We draw ω_i from a Lorentzian (Cauchy) centred at ω0 with
// half-width-at-half-maximum γ:   g(ω) = (1/π) · γ / ((ω−ω0)² + γ²),  by inverse
// transform sampling  ω = ω0 + γ·tan(π·(u − 1/2)),  u ~ U(0,1) from the same
// mulberry32 PRNG the world uses. (We trim the heavy Cauchy tails so finite N and
// a finite Euler step stay well-behaved; see TAIL below — the trim leaves g(ω0),
// hence Kc, unchanged to the precision we test.)
//
// THE EXACT FACTS we CONFIRM BY SIMULATION:
//   1. CRITICAL COUPLING. For a symmetric unimodal g, partial synchrony first
//      appears at Kc = 2 / (π·g(ω0)).  For the Lorentzian g(ω0)=1/(πγ), so
//          Kc = 2γ.
//   2. THE ORDER-PARAMETER LAW. For the Lorentzian the stationary coherence is
//      known in closed form (Kuramoto 1975; Strogatz, Physica D 143 (2000) 1–20):
//          r* = 0                  for K ≤ Kc,
//          r* = sqrt(1 − Kc/K)     for K ≥ Kc.
//      We integrate the genuine dynamics at several K, time-average r past the
//      transient, and check it tracks this curve within a finite-N band.
//   3. THE TRANSITION. Below Kc the coherence sits at the finite-N incoherent
//      floor (≈ 1/sqrt(N), pure sampling noise of N random phases); above Kc it
//      lifts clear of that floor. Sweeping K from low to high, the detected onset
//      sits at Kc within tolerance (finite N rounds the sharp infinite-N corner).
//
// Refs: Y. Kuramoto, "Self-entrainment of a population of coupled non-linear
// oscillators," Lecture Notes in Physics 39 (1975) 420. — S. H. Strogatz, "From
// Kuramoto to Crawford," Physica D 143 (2000) 1. — J. A. Acebrón et al., Rev. Mod.
// Phys. 77 (2005) 137.
//
// Run:  node research/kuramoto/verify.mjs   → prints PASS/FAIL + every measured value.

// ── deterministic PRNG — the exact mulberry32 the world (and palette.js) uses ──
function mulberry32(a) {
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const TAU = Math.PI * 2;

// Lorentzian natural frequencies by inverse-CDF, with the extreme tails trimmed so
// a finite Euler step never sees a runaway ω. We resample any |ω−ω0| beyond TAIL·γ.
// TAIL=200 keeps essentially the whole distribution (>99.6%); g near ω0 — and thus
// Kc — is untouched at our test precision. This is exactly what the world does.
const TAIL = 200;
function drawFreqs(N, omega0, gamma, rnd) {
  const w = new Float64Array(N);
  for (let i = 0; i < N; i++) {
    let x;
    do { x = gamma * Math.tan(Math.PI * (rnd() - 0.5)); } while (Math.abs(x) > TAIL * gamma);
    w[i] = omega0 + x;
  }
  return w;
}

// ── ONE mean-field Kuramoto step (forward Euler), THE rule the world runs ──
// Returns the order parameter r measured at the START of the step (the value that
// drove this step's coupling) — that's the quantity the world also displays.
function stepMeanField(theta, omega, K, dt) {
  const N = theta.length;
  // order parameter r·e^{iψ} = mean of e^{iθ}
  let C = 0, S = 0;
  for (let i = 0; i < N; i++) { C += Math.cos(theta[i]); S += Math.sin(theta[i]); }
  C /= N; S /= N;
  const r = Math.hypot(C, S);
  // cos ψ, sin ψ without atan2 (= C/r, S/r); guard r→0
  const cpsi = r > 1e-12 ? C / r : 1, spsi = r > 1e-12 ? S / r : 0;
  const Kr = K * r;
  // dθ_i = ω_i + K·r·sin(ψ − θ_i),  sin(ψ−θ) = sinψ·cosθ − cosψ·sinθ
  for (let i = 0; i < N; i++) {
    const ct = Math.cos(theta[i]), st = Math.sin(theta[i]);
    const dtheta = omega[i] + Kr * (spsi * ct - cpsi * st);
    let v = theta[i] + dt * dtheta;
    // keep θ bounded (numerically cosmetic; identical mod 2π)
    if (v > TAU) v -= TAU; else if (v < 0) v += TAU;
    theta[i] = v;
  }
  return r;
}

// run the dynamics at coupling K; return time-averaged r over the last `avg`
// fraction of the run (past the transient). Deterministic in `seed`.
function runR(K, { N = 3000, gamma = 1.0, omega0 = 0.0, dt = 0.01, steps = 6000, avg = 0.4, seed = 0x5ED } = {}) {
  const rnd = mulberry32(seed >>> 0);
  const omega = drawFreqs(N, omega0, gamma, rnd);
  const theta = new Float64Array(N);
  for (let i = 0; i < N; i++) theta[i] = rnd() * TAU;   // incoherent start
  const startAvg = Math.floor(steps * (1 - avg));
  let acc = 0, n = 0;
  for (let s = 0; s < steps; s++) {
    const r = stepMeanField(theta, omega, K, dt);
    if (s >= startAvg) { acc += r; n++; }
  }
  return acc / n;
}

// ── the checks ────────────────────────────────────────────────────────────────
const results = [];
const ok = (name, pass, detail) => { results.push({ name, pass, detail }); };

const GAMMA = 1.0, OMEGA0 = 0.0;
const Kc = 2 * GAMMA;                       // exact: 2/(π·g(ω0)) = 2γ
const law = (K) => (K <= Kc ? 0 : Math.sqrt(1 - Kc / K));
const N = 3000;
const floor = 1 / Math.sqrt(N);             // incoherent finite-N order-parameter floor

console.log('Kuramoto mean-field — synchronization, verified by simulation');
console.log(`  N=${N}  γ=${GAMMA}  ω0=${OMEGA0}  ⇒  Kc = 2γ = ${Kc}`);
console.log(`  incoherent finite-N floor ≈ 1/√N = ${floor.toFixed(4)}\n`);

// 1. Kc closed form: 2/(π g(ω0)) must equal 2γ for the Lorentzian.
{
  const g0 = 1 / (Math.PI * GAMMA);         // g(ω0) for the Lorentzian
  const KcFromG = 2 / (Math.PI * g0);
  const pass = Math.abs(KcFromG - 2 * GAMMA) < 1e-12;
  ok('Kc = 2/(π·g(ω0)) = 2γ', pass, `2/(π·g0)=${KcFromG}  2γ=${2 * GAMMA}`);
}

// 2. Below Kc the population stays at the incoherent floor (no macroscopic sync).
{
  const K = 0.5 * Kc;                        // K=1, sub-critical
  const r = runR(K, { N, gamma: GAMMA, omega0: OMEGA0 });
  const pass = r < 4 * floor;               // floor ≈ 0.018; sub-critical r should be O(floor)
  ok('below Kc: incoherent (r ≈ floor)', pass, `K=${K}=${(K / Kc).toFixed(2)}Kc → r=${r.toFixed(4)} (floor≈${floor.toFixed(4)})`);
}

// 3. Above Kc: r matches the exact Lorentzian law r*=√(1−Kc/K) within a finite-N band.
for (const mult of [1.5, 2.0, 3.0, 4.0]) {
  const K = mult * Kc;
  const r = runR(K, { N, gamma: GAMMA, omega0: OMEGA0 });
  const pred = law(K);
  const err = Math.abs(r - pred);
  const pass = err < 0.05;                   // finite N + Euler band
  ok(`above Kc: r ≈ √(1−Kc/K) at K=${mult}Kc`, pass, `r=${r.toFixed(4)}  predicted=${pred.toFixed(4)}  |Δ|=${err.toFixed(4)}`);
}

// 4. K=0 (uncoupled): coherence decays to the incoherent floor (drift scrambles it).
{
  const r = runR(0, { N, gamma: GAMMA, omega0: OMEGA0 });
  const pass = r < 4 * floor;
  ok('uncoupled K=0: r → floor', pass, `r=${r.toFixed(4)} (floor≈${floor.toFixed(4)})`);
}

// 5. Transition detected at Kc: sweep K, find the onset where r first lifts clear
//    of the floor; it must land near Kc (finite N rounds the corner, so a band).
{
  const ths = 3 * floor;                     // "clearly above the floor"
  let onset = null;
  for (let K = 0.2 * Kc; K <= 3 * Kc + 1e-9; K += 0.1 * Kc) {
    const r = runR(K, { N, gamma: GAMMA, omega0: OMEGA0 });
    if (r > ths) { onset = K; break; }
  }
  const pass = onset !== null && Math.abs(onset - Kc) < 0.6 * Kc;
  ok('transition onset near Kc', pass, onset === null ? 'no onset found' : `detected onset K≈${onset.toFixed(2)}  (Kc=${Kc})`);
}

// 6. r is always a valid coherence in [0,1], every step, across the regime.
{
  let bad = false, worst = 0;
  for (const mult of [0, 0.5, 1, 2, 4]) {
    const rnd = mulberry32(0xC0FFEE);
    const omega = drawFreqs(800, OMEGA0, GAMMA, rnd);
    const theta = new Float64Array(800);
    for (let i = 0; i < 800; i++) theta[i] = rnd() * TAU;
    for (let s = 0; s < 800; s++) {
      const r = stepMeanField(theta, omega, mult * Kc, 0.01);
      if (!(r >= -1e-9 && r <= 1 + 1e-9)) bad = true;
      worst = Math.max(worst, r);
    }
  }
  ok('r ∈ [0,1] throughout', !bad, `max r observed = ${worst.toFixed(4)}`);
}

// ── report ──────────────────────────────────────────────────────────────────
console.log('Checks:');
let passed = 0;
for (const r of results) {
  console.log(`  ${r.pass ? 'PASS' : 'FAIL'}  ${r.name}\n        ${r.detail}`);
  if (r.pass) passed++;
}
console.log(`\n${passed}/${results.length} checks passed.`);
process.exit(passed === results.length ? 0 : 1);
