// engine.mjs: the arithmetic behind /strata/why-is-magnetism-quantum/.
// Runs in the reader's browser and, unchanged, in the verifier under Node.
//
// A square box of side L holds N electrons that do not touch each other. A uniform
// magnetic field B points out of the screen. Units: electron mass 1, charge -1, and
// temperature chosen so kT = 1, which makes each velocity component a standard normal
// number and the typical circle radius 1/B.
//
// Between walls an electron moves on an exact circle (no time-stepping error). When the
// circle would carry it out of the box, the exit time is found by bisection, the velocity
// component normal to that wall is reversed (a mirror bounce), and the circle continues.
// Mirroring the whole step instead, the easy shortcut, is wrong here: the mirror image of
// a path in a magnetic field curls the wrong way, and the error drifts the answer.

export const Q = -1;          // electron charge, in units of e
export const DEFAULT = { N: 20000, L: 60, B: 1, seed: 1 };

// mulberry32: a small, fast, seeded generator, so the page and the verifier draw the same box.
export function rng(seed) {
  let s = seed >>> 0;
  return () => {
    s = (s + 0x6D2B79F5) >>> 0;
    let t = s;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
function gauss(r) { let u = 0; while (u === 0) u = r(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * r()); }

// Thermal equilibrium: positions uniform in the box, velocities Maxwell-Boltzmann.
// The field does not enter this distribution at all, because a magnetic force does no work.
export function makeBox({ N = DEFAULT.N, L = DEFAULT.L, B = DEFAULT.B, seed = DEFAULT.seed } = {}) {
  const r = rng(seed);
  const w = Q * B;                       // signed cyclotron frequency (mass 1)
  const S = {
    N, L, B, w, t: 0, samples: 0,
    x: new Float64Array(N), y: new Float64Array(N), vx: new Float64Array(N), vy: new Float64Array(N),
    edge: new Uint8Array(N),             // 1 if this electron's circle meets a wall
    sum: new Float64Array(N),            // running sum of each electron's moment, for time averages
  };
  for (let i = 0; i < N; i++) {
    S.x[i] = r() * L; S.y[i] = r() * L; S.vx[i] = gauss(r); S.vy[i] = gauss(r);
    S.edge[i] = meetsWall(S, i) ? 1 : 0;
  }
  return S;
}

// Centre and radius of the circle an electron is on right now.
export function circle(S, i) {
  const cx = S.x[i] + S.vy[i] / S.w, cy = S.y[i] - S.vx[i] / S.w;
  return { cx, cy, rc: Math.hypot(S.vx[i], S.vy[i]) / Math.abs(S.w) };
}
// A circle that meets a wall keeps meeting one: after a bounce the new circle passes through
// the bounce point. A circle clear of every wall is never disturbed. So the split is permanent.
export function meetsWall(S, i) {
  const { cx, cy, rc } = circle(S, i);
  return !(cx - rc > 0 && cx + rc < S.L && cy - rc > 0 && cy + rc < S.L);
}

function arc(w, x, y, vx, vy, t, o) {
  const cx = x + vy / w, cy = y - vx / w, c = Math.cos(w * t), s = Math.sin(w * t);
  const nvx = vx * c + vy * s, nvy = -vx * s + vy * c;
  o[0] = cx - nvy / w; o[1] = cy + nvx / w; o[2] = nvx; o[3] = nvy;
}
const P = new Float64Array(4);

// Advance every electron by time dt, exactly along its circles and bounces.
export function step(S, dt) {
  const { N, L, w } = S;
  const out = () => P[0] < 0 || P[0] > L || P[1] < 0 || P[1] > L;
  for (let i = 0; i < N; i++) {
    let x = S.x[i], y = S.y[i], vx = S.vx[i], vy = S.vy[i], rem = dt;
    for (let guard = 0; rem > 0 && guard < 16; guard++) {
      arc(w, x, y, vx, vy, rem, P);
      if (!out()) { x = P[0]; y = P[1]; vx = P[2]; vy = P[3]; rem = 0; break; }
      let lo = 0, hi = rem;
      for (let k = 0; k < 44; k++) { const m = (lo + hi) / 2; arc(w, x, y, vx, vy, m, P); if (out()) hi = m; else lo = m; }
      arc(w, x, y, vx, vy, hi, P); x = P[0]; y = P[1]; vx = P[2]; vy = P[3]; rem -= hi;
      if (x < 0) { x = 0; vx = Math.abs(vx); } else if (x > L) { x = L; vx = -Math.abs(vx); }
      if (y < 0) { y = 0; vy = Math.abs(vy); } else if (y > L) { y = L; vy = -Math.abs(vy); }
    }
    S.x[i] = x; S.y[i] = y; S.vx[i] = vx; S.vy[i] = vy;
  }
  S.t += dt;
}

// Magnetic moment of one electron (the z component, out of the screen), about the box centre:
// m = (q/2) (r x v). A current loop's moment is this, summed.
export function moment(S, i) {
  const h = S.L / 2;
  return 0.5 * Q * ((S.x[i] - h) * S.vy[i] - (S.y[i] - h) * S.vx[i]);
}

// Record one sample: add every electron's moment to its running sum. Returns the instant's totals.
export function sample(S) {
  let bulk = 0, edge = 0;
  for (let i = 0; i < S.N; i++) {
    const m = moment(S, i); S.sum[i] += m;
    if (S.edge[i]) edge += m; else bulk += m;
  }
  S.samples++;
  return { bulk, edge, total: bulk + edge };
}

// A circle clear of the walls is a closed current loop. Its moment averaged over one turn is
// -v^2 / (2B) for either sign of charge: always against the field. This is exact, no simulation.
export function bulkPrediction(S) {
  let m = 0, n = 0;
  for (let i = 0; i < S.N; i++) if (!S.edge[i]) { m -= (S.vx[i] ** 2 + S.vy[i] ** 2) / (2 * S.B); n++; }
  return { moment: m, count: n };
}

// Time averages so far, split by kind, and a standard error for the total. The total of
// independent electrons has mean zero if the theorem holds; its scatter from one box of N
// electrons to the next is estimated by sqrt(sum of each electron's own time-averaged moment squared).
export function averages(S) {
  let bulk = 0, edge = 0, ss = 0, nb = 0;
  const k = Math.max(1, S.samples);
  for (let i = 0; i < S.N; i++) {
    const a = S.sum[i] / k; ss += a * a;
    if (S.edge[i]) edge += a; else { bulk += a; nb++; }
  }
  return { bulk, edge, total: bulk + edge, se: Math.sqrt(ss), nBulk: nb, nEdge: S.N - nb, samples: S.samples, t: S.t };
}

// Run a box for a while and report. Used by the verifier; the page does the same thing frame by frame.
export function run({ N, L, B, seed, dt = 0.05, steps = 2000, every = 1 } = {}) {
  const S = makeBox({ N, L, B, seed });
  sample(S);
  for (let k = 1; k <= steps; k++) { step(S, dt); if (k % every === 0) sample(S); }
  return { S, avg: averages(S), pred: bulkPrediction(S) };
}

// What the circling electrons alone are expected to give, per electron, without simulating:
// an electron of speed v circles with radius v/B, and in a square box of side L its circle is
// clear of every wall with probability (1 - 2v/(BL))^2 (the centre must sit at least one radius
// from each wall). In 2D thermal equilibrium the speed has density v exp(-v^2/2). So
//   bulk moment per electron = -(1/B) * integral_0^{BL/2} (1 - 2v/(BL))^2 (v^2/2) v exp(-v^2/2) dv
//   share of electrons circling = integral_0^{BL/2} (1 - 2v/(BL))^2 v exp(-v^2/2) dv
// Simpson's rule, 2000 intervals (the integrands are smooth).
function simpson(f, a, b, n = 2000) {
  const h = (b - a) / n; let s = f(a) + f(b);
  for (let k = 1; k < n; k++) s += (k % 2 ? 4 : 2) * f(a + k * h);
  return s * h / 3;
}
export function expectedBulk(B, L = DEFAULT.L) {
  const vmax = B * L / 2, g = (v) => (1 - v / vmax) ** 2 * v * Math.exp(-v * v / 2);
  return {
    perElectron: -simpson((v) => g(v) * v * v / 2, 0, vmax) / B,
    share: simpson(g, 0, vmax),
  };
}
