/*
 * Independent numerical spine for "The Compass Noise Should Drown".
 *
 * No dependencies. Run with:
 *   node research/the-compass-noise-should-drown/verify-the-compass-noise-should-drown.mjs
 *
 * The quantum toy uses an 8-dimensional Hilbert space:
 * electron 1 (spin 1/2) x electron 2 (spin 1/2) x one nucleus (spin 1/2).
 * It evolves two pure states, one for each initially populated nuclear basis
 * state. Their equal mixture is the density matrix
 * rho(t) = 1/2 sum_n |psi_n(t)><psi_n(t)|.
 */

const MU_B = 9.2740100657e-24; // J/T, 2022 CODATA
const K_B = 1.380649e-23;      // J/K, exact in SI
const G = 2;                   // deliberately rounded free-electron g-factor
const GAMMA_HZ_T = 28e9;       // rounded electron Larmor frequency, Hz/T

function energyNumbers(fieldMicrotesla, temperatureKelvin) {
  const fieldTesla = fieldMicrotesla * 1e-6;
  const zeemanJ = G * MU_B * fieldTesla;
  const thermalJ = K_B * temperatureKelvin;
  return {
    zeemanJ,
    thermalJ,
    ratio: thermalJ / zeemanJ,
    larmorHz: GAMMA_HZ_T * fieldTesla
  };
}

function assert(condition, message) {
  if (!condition) throw new Error(message);
}

function close(actual, expected, tolerance, label) {
  const error = Math.abs(actual - expected);
  assert(error <= tolerance, `${label}: got ${actual}, expected ${expected} +/- ${tolerance}`);
}

const DIM = 8;

function zeroMatrix() {
  return Array.from({ length: DIM }, () =>
    Array.from({ length: DIM }, () => ({ re: 0, im: 0 }))
  );
}

function kron3(a, b, c) {
  const out = zeroMatrix();
  for (let ai = 0; ai < 2; ai += 1) {
    for (let aj = 0; aj < 2; aj += 1) {
      for (let bi = 0; bi < 2; bi += 1) {
        for (let bj = 0; bj < 2; bj += 1) {
          for (let ci = 0; ci < 2; ci += 1) {
            for (let cj = 0; cj < 2; cj += 1) {
              const row = ai * 4 + bi * 2 + ci;
              const col = aj * 4 + bj * 2 + cj;
              const abRe = a[ai][aj].re * b[bi][bj].re - a[ai][aj].im * b[bi][bj].im;
              const abIm = a[ai][aj].re * b[bi][bj].im + a[ai][aj].im * b[bi][bj].re;
              out[row][col] = {
                re: abRe * c[ci][cj].re - abIm * c[ci][cj].im,
                im: abRe * c[ci][cj].im + abIm * c[ci][cj].re
              };
            }
          }
        }
      }
    }
  }
  return out;
}

const I2 = [
  [{ re: 1, im: 0 }, { re: 0, im: 0 }],
  [{ re: 0, im: 0 }, { re: 1, im: 0 }]
];
const SX = [
  [{ re: 0, im: 0 }, { re: 0.5, im: 0 }],
  [{ re: 0.5, im: 0 }, { re: 0, im: 0 }]
];
const SY = [
  [{ re: 0, im: 0 }, { re: 0, im: -0.5 }],
  [{ re: 0, im: 0.5 }, { re: 0, im: 0 }]
];
const SZ = [
  [{ re: 0.5, im: 0 }, { re: 0, im: 0 }],
  [{ re: 0, im: 0 }, { re: -0.5, im: 0 }]
];

const OPS = {
  e1x: kron3(SX, I2, I2),
  e1y: kron3(SY, I2, I2),
  e1z: kron3(SZ, I2, I2),
  e2x: kron3(I2, SX, I2),
  e2z: kron3(I2, SZ, I2),
  nx: kron3(I2, I2, SX),
  ny: kron3(I2, I2, SY),
  nz: kron3(I2, I2, SZ)
};

function matrixProduct(a, b) {
  const out = zeroMatrix();
  for (let i = 0; i < DIM; i += 1) {
    for (let j = 0; j < DIM; j += 1) {
      let re = 0;
      let im = 0;
      for (let q = 0; q < DIM; q += 1) {
        re += a[i][q].re * b[q][j].re - a[i][q].im * b[q][j].im;
        im += a[i][q].re * b[q][j].im + a[i][q].im * b[q][j].re;
      }
      out[i][j] = { re, im };
    }
  }
  return out;
}

function addScaled(target, source, scale) {
  for (let i = 0; i < DIM; i += 1) {
    for (let j = 0; j < DIM; j += 1) {
      target[i][j].re += source[i][j].re * scale;
      target[i][j].im += source[i][j].im * scale;
    }
  }
}

function hamiltonian(angleDegrees, fieldMicrotesla, hyperfineMHz) {
  const angle = angleDegrees * Math.PI / 180;
  const bx = Math.sin(angle);
  const bz = Math.cos(angle);
  const omega = 2 * Math.PI * 28e3 * fieldMicrotesla * 1e-6; // rad/us
  const h = zeroMatrix();
  addScaled(h, OPS.e1x, omega * bx);
  addScaled(h, OPS.e2x, omega * bx);
  addScaled(h, OPS.e1z, omega * bz);
  addScaled(h, OPS.e2z, omega * bz);

  const axes = [
    [OPS.e1x, OPS.nx, hyperfineMHz[0]],
    [OPS.e1y, OPS.ny, hyperfineMHz[1]],
    [OPS.e1z, OPS.nz, hyperfineMHz[2]]
  ];
  for (const [electronOp, nuclearOp, couplingMHz] of axes) {
    addScaled(h, matrixProduct(electronOp, nuclearOp), 2 * Math.PI * couplingMHz);
  }
  return h;
}

function derivative(h, psi) {
  const out = Array.from({ length: DIM }, () => ({ re: 0, im: 0 }));
  for (let i = 0; i < DIM; i += 1) {
    let hre = 0;
    let him = 0;
    for (let j = 0; j < DIM; j += 1) {
      hre += h[i][j].re * psi[j].re - h[i][j].im * psi[j].im;
      him += h[i][j].re * psi[j].im + h[i][j].im * psi[j].re;
    }
    // d|psi>/dt = -i H|psi>
    out[i] = { re: him, im: -hre };
  }
  return out;
}

function shifted(psi, slope, scale) {
  return psi.map((v, i) => ({
    re: v.re + slope[i].re * scale,
    im: v.im + slope[i].im * scale
  }));
}

function rk4(h, psi, dt) {
  const k1 = derivative(h, psi);
  const k2 = derivative(h, shifted(psi, k1, dt / 2));
  const k3 = derivative(h, shifted(psi, k2, dt / 2));
  const k4 = derivative(h, shifted(psi, k3, dt));
  return psi.map((v, i) => ({
    re: v.re + dt * (k1[i].re + 2 * k2[i].re + 2 * k3[i].re + k4[i].re) / 6,
    im: v.im + dt * (k1[i].im + 2 * k2[i].im + 2 * k3[i].im + k4[i].im) / 6
  }));
}

function initialState(nuclearBit) {
  const psi = Array.from({ length: DIM }, () => ({ re: 0, im: 0 }));
  psi[2 + nuclearBit].re = 1 / Math.sqrt(2); // |up,down,n>
  psi[4 + nuclearBit].re = -1 / Math.sqrt(2); // |down,up,n>
  return psi;
}

function singletProbability(states) {
  let probability = 0;
  for (const psi of states) {
    for (let nuclearBit = 0; nuclearBit < 2; nuclearBit += 1) {
      const a = psi[2 + nuclearBit];
      const b = psi[4 + nuclearBit];
      const singletRe = (a.re - b.re) / Math.sqrt(2);
      const singletIm = (a.im - b.im) / Math.sqrt(2);
      probability += 0.5 * (singletRe * singletRe + singletIm * singletIm);
    }
  }
  return probability;
}

function radicalPairYield(angleDegrees, options = {}) {
  const fieldMicrotesla = options.fieldMicrotesla ?? 50;
  const hyperfineMHz = options.hyperfineMHz ?? [0.4, 0.4, 1.6];
  const lifetimeMicroseconds = options.lifetimeMicroseconds ?? 1;
  const dt = options.dt ?? 0.0025;
  const duration = options.duration ?? 12 * lifetimeMicroseconds;
  const h = hamiltonian(angleDegrees, fieldMicrotesla, hyperfineMHz);
  let states = [initialState(0), initialState(1)];
  const rate = 1 / lifetimeMicroseconds;
  let t = 0;
  let previous = rate * Math.exp(-rate * t) * singletProbability(states);
  let yieldValue = 0;

  const steps = Math.ceil(duration / dt);
  for (let step = 0; step < steps; step += 1) {
    const nextDt = Math.min(dt, duration - t);
    states = states.map((psi) => rk4(h, psi, nextDt));
    t += nextDt;
    const current = rate * Math.exp(-rate * t) * singletProbability(states);
    yieldValue += (previous + current) * nextDt / 2;
    previous = current;
  }
  return yieldValue;
}

const energy = energyNumbers(50, 300);
close(energy.zeemanJ, 9.2740100657e-28, 1e-39, 'Zeeman energy');
close(energy.thermalJ, 4.141947e-21, 1e-32, 'thermal energy');
assert(energy.ratio > 4.46e6 && energy.ratio < 4.47e6, 'thermal/Zeeman ratio is outside the expected range');
close(energy.larmorHz, 1.4e6, 1e-6, 'Larmor frequency');

const yield0 = radicalPairYield(0);
const yield45 = radicalPairYield(45);
const yield90 = radicalPairYield(90);
const yieldDifference = Math.abs(yield90 - yield0);
const orientationCurve = [];
for (let degrees = 0; degrees <= 180; degrees += 15) {
  orientationCurve.push(radicalPairYield(degrees));
}
const orientationSpan = Math.max(...orientationCurve) - Math.min(...orientationCurve);
close(yield0, 0.50972222, 1e-8, '0 degree displayed yield');
close(yield45, 0.49487731, 1e-8, '45 degree displayed yield');
close(yield90, 0.68041245, 1e-8, '90 degree displayed yield');
close(yieldDifference, 0.17069023, 1e-8, 'displayed endpoint direction contrast');
close(orientationSpan * 100, 18.899, 5e-4, 'displayed sampled orientation span in percentage points');

// Re-run the endpoints with half the timestep. This checks that the displayed
// direction effect is not a coarse-integration artefact.
const fine0 = radicalPairYield(0, { dt: 0.00125 });
const fine90 = radicalPairYield(90, { dt: 0.00125 });
close(yield0, fine0, 2e-5, '0 degree yield timestep convergence');
close(yield90, fine90, 2e-5, '90 degree yield timestep convergence');
assert(yieldDifference > 0.005, 'toy singlet yield did not vary enough with field direction');

console.log('50 µT, 300 K');
console.log(`Zeeman energy: ${energy.zeemanJ.toExponential(6)} J`);
console.log(`Thermal energy kBT: ${energy.thermalJ.toExponential(6)} J`);
console.log(`Thermal / Zeeman ratio: ${energy.ratio.toFixed(3)}`);
console.log(`Larmor frequency: ${(energy.larmorHz / 1e6).toFixed(6)} MHz`);
console.log('Toy model: A = [0.4, 0.4, 1.6] MHz, lifetime = 1 µs, B = 50 µT');
console.log(`Singlet yield at 0 degrees: ${yield0.toFixed(8)}`);
console.log(`Singlet yield at 45 degrees: ${yield45.toFixed(8)}`);
console.log(`Singlet yield at 90 degrees: ${yield90.toFixed(8)}`);
console.log(`Endpoint direction contrast: ${yieldDifference.toFixed(8)}`);
console.log(`Endpoint direction contrast: ${(yieldDifference * 100).toFixed(6)} percentage points`);
console.log(`Sampled half-turn span: ${(orientationSpan * 100).toFixed(3)} percentage points`);
console.log(`Half-step convergence errors: ${Math.abs(yield0 - fine0).toExponential(3)}, ${Math.abs(yield90 - fine90).toExponential(3)}`);
console.log('All assertions passed.');
