#!/usr/bin/env node

import { readFileSync } from "node:fs";

/*
  Reid's paradox, from-scratch numerical verifier.

  There are no imports and no dependencies. The constants below are mirrored in
  public/strata/reids-paradox/index.html. The verifier derives the displayed
  Fisher-Skellam arithmetic, the matched kernel moments, the MGF distinction,
  and the integrodifference front series.
*/

const BASE_R = 0.1;                 // yr^-1
const BASE_D = 250;                 // m^2 yr^-1
const POLLEN_LOW = 100;             // m yr^-1
const POLLEN_HIGH = 1000;           // m yr^-1

const GRID_N = 8192;
const DX = 10;                      // m
const KERNEL_SD = 40;               // m per generation
const NET_REPRODUCTION = 1.5;       // low-density multiplier per generation
const GENERATIONS = 36;
const ESTABLISHED_THRESHOLD = 0.01;
const INITIAL_WIDTH = 500;          // m

let passed = 0;
let failed = 0;

function report(label, ok, detail) {
  const state = ok ? "PASS" : "FAIL";
  console.log(`${state.padEnd(4)}  ${label}: ${detail}`);
  if (ok) passed += 1;
  else failed += 1;
}

function close(a, b, tolerance = 1e-10) {
  return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));
}

function fisherSpeed(r, D) {
  return 2 * Math.sqrt(r * D);
}

function requiredParameterFactor(currentSpeed, targetSpeed) {
  return (targetSpeed / currentSpeed) ** 2;
}

function fft(real, imag, inverse) {
  const n = real.length;

  for (let i = 1, j = 0; i < n; i += 1) {
    let bit = n >> 1;
    while (j & bit) {
      j ^= bit;
      bit >>= 1;
    }
    j ^= bit;
    if (i < j) {
      const tr = real[i];
      const ti = imag[i];
      real[i] = real[j];
      imag[i] = imag[j];
      real[j] = tr;
      imag[j] = ti;
    }
  }

  for (let length = 2; length <= n; length <<= 1) {
    const angle = (inverse ? 2 : -2) * Math.PI / length;
    const stepReal = Math.cos(angle);
    const stepImag = Math.sin(angle);
    for (let offset = 0; offset < n; offset += length) {
      let twiddleReal = 1;
      let twiddleImag = 0;
      const half = length >> 1;
      for (let j = 0; j < half; j += 1) {
        const even = offset + j;
        const odd = even + half;
        const oddReal = real[odd] * twiddleReal - imag[odd] * twiddleImag;
        const oddImag = real[odd] * twiddleImag + imag[odd] * twiddleReal;
        real[odd] = real[even] - oddReal;
        imag[odd] = imag[even] - oddImag;
        real[even] += oddReal;
        imag[even] += oddImag;

        const nextReal = twiddleReal * stepReal - twiddleImag * stepImag;
        twiddleImag = twiddleReal * stepImag + twiddleImag * stepReal;
        twiddleReal = nextReal;
      }
    }
  }

  if (inverse) {
    for (let i = 0; i < n; i += 1) {
      real[i] /= n;
      imag[i] /= n;
    }
  }
}

function gaussianDensity(x, sd) {
  return Math.exp(-(x * x) / (2 * sd * sd)) / (sd * Math.sqrt(2 * Math.PI));
}

/*
  Student t with 3 degrees of freedom, rescaled so its variance is sd^2:
  k(x) = 2 / (pi*sd) * (1 + x^2/sd^2)^-2.
*/
function student3Density(x, sd) {
  return (2 / (Math.PI * sd)) * (1 + (x * x) / (sd * sd)) ** -2;
}

/*
  Integrate over the full real line with x = sd*tan(pi*u/2), -1 < u < 1.
  Midpoints avoid the infinite endpoints. Mass, first moment, and second raw
  moment are accumulated from the density itself, then converted to a central
  variance.
*/
function numericalMoments(density, sd, steps = 4096) {
  const du = 2 / steps;
  let mass = 0;
  let firstMoment = 0;
  let secondRawMoment = 0;

  for (let i = 0; i < steps; i += 1) {
    const u = -1 + (i + 0.5) * du;
    const angle = Math.PI * u / 2;
    const cosine = Math.cos(angle);
    const x = sd * Math.tan(angle);
    const jacobian = (sd * Math.PI / 2) / (cosine * cosine);
    const weightedDensity = density(x, sd) * jacobian * du;
    mass += weightedDensity;
    firstMoment += x * weightedDensity;
    secondRawMoment += x * x * weightedDensity;
  }

  const mean = firstMoment / mass;
  return {
    mass,
    mean,
    variance: secondRawMoment / mass - mean * mean
  };
}

function momentDetail(moments) {
  const displayedMean = Math.abs(moments.mean) < 0.0000005 ? 0 : moments.mean;
  return `mass ${moments.mass.toFixed(6)}, mean ${displayedMean.toFixed(6)} m, ` +
    `variance ${moments.variance.toFixed(3)} m^2`;
}

function makeKernelSpectrum(kind) {
  const real = new Float64Array(GRID_N);
  const imag = new Float64Array(GRID_N);
  const density = kind === "gaussian" ? gaussianDensity : student3Density;
  let mass = 0;

  for (let i = 0; i < GRID_N; i += 1) {
    const displacement = (i <= GRID_N / 2 ? i : i - GRID_N) * DX;
    real[i] = density(displacement, KERNEL_SD) * DX;
    mass += real[i];
  }
  for (let i = 0; i < GRID_N; i += 1) real[i] /= mass;
  fft(real, imag, false);
  return { real, imag, gridMassBeforeNormalizing: mass };
}

function frontPosition(population, originIndex) {
  for (let i = GRID_N - 1; i >= originIndex; i -= 1) {
    if (population[i] >= ESTABLISHED_THRESHOLD) return (i - originIndex) * DX;
  }
  return 0;
}

function simulate(kind) {
  const spectrum = makeKernelSpectrum(kind);
  let population = new Float64Array(GRID_N);
  const originIndex = GRID_N >> 2;

  for (let i = 0; i < GRID_N; i += 1) {
    const x = (i - originIndex) * DX;
    population[i] = x <= 0 && x >= -INITIAL_WIDTH ? 1 : 0;
  }

  const fronts = [frontPosition(population, originIndex)];
  for (let generation = 0; generation < GENERATIONS; generation += 1) {
    const real = new Float64Array(GRID_N);
    const imag = new Float64Array(GRID_N);

    for (let i = 0; i < GRID_N; i += 1) {
      const n = population[i];
      real[i] = (NET_REPRODUCTION * n) / (1 + (NET_REPRODUCTION - 1) * n);
    }

    fft(real, imag, false);
    for (let i = 0; i < GRID_N; i += 1) {
      const ar = real[i];
      const ai = imag[i];
      real[i] = ar * spectrum.real[i] - ai * spectrum.imag[i];
      imag[i] = ar * spectrum.imag[i] + ai * spectrum.real[i];
    }
    fft(real, imag, true);

    population = real;
    for (let i = 0; i < GRID_N; i += 1) {
      population[i] = Math.max(0, Math.min(1, population[i]));
    }
    fronts.push(frontPosition(population, originIndex));
  }

  return {
    fronts,
    kernelMass: spectrum.gridMassBeforeNormalizing,
    rightBoundary: (GRID_N - 1 - originIndex) * DX
  };
}

function meanSpeed(series, start, end) {
  return (series[end] - series[start]) / (end - start);
}

console.log("REID'S PARADOX: INDEPENDENT RECOMPUTATION\n");

const pageSource = readFileSync(
  new URL("../../public/strata/reids-paradox/index.html", import.meta.url),
  "utf8"
);
const pageConstants = {
  BASE_R: Number(pageSource.match(/var BASE_R = ([0-9.]+);/)?.[1]),
  BASE_D: Number(pageSource.match(/var BASE_D = ([0-9.]+);/)?.[1]),
  POLLEN_LOW: Number(pageSource.match(/var POLLEN_LOW = ([0-9.]+);/)?.[1]),
  POLLEN_HIGH: Number(pageSource.match(/var POLLEN_HIGH = ([0-9.]+);/)?.[1]),
  GRID_N: Number(pageSource.match(/var GRID_N = ([0-9.]+);/)?.[1]),
  DX: Number(pageSource.match(/var DX = ([0-9.]+);/)?.[1]),
  KERNEL_SD: Number(pageSource.match(/var KERNEL_SD = ([0-9.]+);/)?.[1]),
  NET_REPRODUCTION: Number(
    pageSource.match(/var NET_REPRODUCTION = ([0-9.]+);/)?.[1]
  ),
  GENERATIONS: Number(pageSource.match(/var GENERATIONS = ([0-9.]+);/)?.[1]),
  ESTABLISHED_THRESHOLD: Number(
    pageSource.match(/var ESTABLISHED_THRESHOLD = ([0-9.]+);/)?.[1]
  ),
  INITIAL_WIDTH: Number(pageSource.match(/var INITIAL_WIDTH = ([0-9.]+);/)?.[1])
};
const verifierConstants = {
  BASE_R,
  BASE_D,
  POLLEN_LOW,
  POLLEN_HIGH,
  GRID_N,
  DX,
  KERNEL_SD,
  NET_REPRODUCTION,
  GENERATIONS,
  ESTABLISHED_THRESHOLD,
  INITIAL_WIDTH
};
const constantsMatch = Object.keys(verifierConstants).every(
  (key) => pageConstants[key] === verifierConstants[key]
);
report("page and verifier constants match", constantsMatch,
  Object.entries(pageConstants).map(([key, value]) => `${key}=${value}`).join(", "));

const baseSpeed = fisherSpeed(BASE_R, BASE_D);
const rmsStep = Math.sqrt(2 * BASE_D);
const lowGap = POLLEN_LOW / baseSpeed;
const highGap = POLLEN_HIGH / baseSpeed;
const lowInflation = requiredParameterFactor(baseSpeed, POLLEN_LOW);
const highInflation = requiredParameterFactor(baseSpeed, POLLEN_HIGH);
const lowRequiredR = POLLEN_LOW ** 2 / (4 * BASE_D);
const highRequiredR = POLLEN_HIGH ** 2 / (4 * BASE_D);
const lowRequiredD = POLLEN_LOW ** 2 / (4 * BASE_R);
const highRequiredD = POLLEN_HIGH ** 2 / (4 * BASE_R);

report("Fisher-Skellam base speed", close(baseSpeed, 10),
  `2*sqrt(${BASE_R}*${BASE_D}) = ${baseSpeed.toFixed(6)} m/yr`);
report("effective RMS dispersal step", close(rmsStep, Math.sqrt(500)),
  `sqrt(2D) = ${rmsStep.toFixed(6)} m in one year`);
report("pollen-band speed gaps", close(lowGap, 10) && close(highGap, 100),
  `${lowGap.toFixed(1)}x to ${highGap.toFixed(1)}x`);
report("sqrt-scaling inflation", close(lowInflation, 100) && close(highInflation, 10000),
  `${lowInflation.toFixed(0)}x to ${highInflation.toFixed(0)}x in r or D`);
report("growth rates required at fixed D", close(lowRequiredR, 10) && close(highRequiredR, 1000),
  `${lowRequiredR.toFixed(1)} to ${highRequiredR.toFixed(1)} yr^-1`);
report("diffusion constants required at fixed r",
  close(lowRequiredD, 25000) && close(highRequiredD, 2500000),
  `${lowRequiredD.toFixed(0)} to ${highRequiredD.toFixed(0)} m^2/yr`);

const gaussianMoments = numericalMoments(gaussianDensity, KERNEL_SD);
const studentMoments = numericalMoments(student3Density, KERNEL_SD);
report("Gaussian density moments",
  close(gaussianMoments.mass, 1, 1e-9) &&
    close(gaussianMoments.mean, 0, 1e-9) &&
    close(gaussianMoments.variance, KERNEL_SD * KERNEL_SD, 1e-9),
  momentDetail(gaussianMoments));
report("Student t3 density moments",
  close(studentMoments.mass, 1, 1e-9) &&
    close(studentMoments.mean, 0, 1e-9) &&
    close(studentMoments.variance, KERNEL_SD * KERNEL_SD, 1e-9),
  momentDetail(studentMoments));

const MGF_TEST_S = 0.01;
const gaussianMgf = Math.exp(0.5 * KERNEL_SD * KERNEL_SD * MGF_TEST_S ** 2);
report("Gaussian MGF is finite", Number.isFinite(gaussianMgf),
  `M(${MGF_TEST_S}) = exp(sd^2*s^2/2) = ${gaussianMgf.toFixed(6)}`);

/*
  For Student t3, k(x) is asymptotic to C*x^-4. For every s > 0,
  exp(s*x)*k(x) therefore fails to tend to zero as x tends to infinity,
  so its positive-tail integral and M(s) diverge.
*/
const studentLogIntegrandAt = (x) =>
  MGF_TEST_S * x + Math.log(student3Density(x, KERNEL_SD));
const tailLogRise = studentLogIntegrandAt(4000) - studentLogIntegrandAt(2000);
report("Student t3 MGF diverges", tailLogRise > 0,
  `log(e^(s*x)k(x)) rises by ${tailLogRise.toFixed(3)} from 2 km to 4 km`);

const gaussian = simulate("gaussian");
const student = simulate("student3");
const gaussianEarly = meanSpeed(gaussian.fronts, 9, 18);
const gaussianLate = meanSpeed(gaussian.fronts, 27, 36);
const studentEarly = meanSpeed(student.fronts, 9, 18);
const studentLate = meanSpeed(student.fronts, 27, 36);
const gaussianDrift = Math.abs(gaussianLate - gaussianEarly) / gaussianEarly;
const studentAcceleration = studentLate / studentEarly;

report("sampled kernels retain their mass",
  Math.abs(gaussian.kernelMass - 1) < 0.01 && Math.abs(student.kernelMass - 1) < 0.01,
  `Gaussian ${gaussian.kernelMass.toFixed(12)}, Student t3 ${student.kernelMass.toFixed(12)}`);
report("Gaussian front approaches constant speed", gaussianDrift < 0.12,
  `g9-18 ${gaussianEarly.toFixed(3)} m/gen, g27-36 ${gaussianLate.toFixed(3)} m/gen`);
report("Student t3 front accelerates", studentAcceleration > 1.5,
  `g9-18 ${studentEarly.toFixed(3)} m/gen, g27-36 ${studentLate.toFixed(3)} m/gen, ${studentAcceleration.toFixed(3)}x`);
report("heavy-tail front is super-linear",
  student.fronts[36] / 36 > 1.35 * (student.fronts[18] / 18),
  `x18/18 ${(student.fronts[18] / 18).toFixed(3)}, x36/36 ${(student.fronts[36] / 36).toFixed(3)} m/gen`);
report("fronts remain clear of the finite boundary",
  student.fronts.at(-1) < student.rightBoundary * 0.5,
  `furthest ${student.fronts.at(-1).toFixed(0)} m, boundary ${student.rightBoundary.toFixed(0)} m`);

console.log("\nFront positions at generations 0, 6, 12, 18, 24, 30, 36:");
console.log(`  Gaussian:  ${[0, 6, 12, 18, 24, 30, 36].map((i) => gaussian.fronts[i]).join(", ")} m`);
console.log(`  Student t3: ${[0, 6, 12, 18, 24, 30, 36].map((i) => student.fronts[i]).join(", ")} m`);

console.log(`\n${passed}/${passed + failed} checks passed.`);
process.exit(failed === 0 ? 0 : 1);
