// verify-the-colours-the-dog-keeps.mjs — the optics behind the stratum
// "The Colours the Dog Keeps" (/strata/the-colours-the-dog-keeps/).
//
// The claim the page makes: the dog retina has TWO cone classes with spectral
// peaks at ~429 nm (blue) and ~555 nm (yellow-green) — Neitz, Geist & Jacobs,
// "Color vision in the dog," Visual Neuroscience 1989;3(2):119-125. With short-wave
// and long/medium-wave cone classes, a dog is a DICHROMAT: every wavelength maps
// onto a single chromatic axis, so wavelengths a human reads as red, orange,
// yellow and green all drive the dog's two cones in nearly the same RATIO and
// collapse to one hue, while blue stays distinct. There is one wavelength — the
// NEUTRAL POINT, near 480 nm — that excites the two cones in the same ratio as
// white light and, at matched brightness, is a model match to grey.
//
// Everything below is recomputed from scratch, with zero dependencies, the same
// way the page computes it on screen. The two cone fundamentals are built from
// the published Govardovskii et al. 2000 A1 visual-pigment template, keyed to the
// two measured peak wavelengths — NOT hand-drawn curves.
//
//   run:  node research/the-colours-the-dog-keeps/verify-the-colours-the-dog-keeps.mjs
//
// What this script checks: the table quantities and six display-primary weights.
//   1. The Govardovskii A1 template returns sensitivity = 1 at its own peak
//      (the template is normalised) — for BOTH 429 nm and 555 nm cones.
//   2. The two cones peak where Neitz et al. measured: argmax(S) = 429 nm,
//      argmax(L) = 555 nm, recovered from the template by scanning the spectrum.
//   3. The NEUTRAL POINT — the monochromatic wavelength whose S:L cone ratio
//      equals the S:L ratio of an equal-energy white — lands near 480 nm, the
//      value Neitz et al. report behaviourally. (Independent cross-check.)
//   4. RED-GREEN COLLAPSE: pure display red and pure display green produce a dog
//      "hue" (S-cone fraction) that differs by < 0.02 in this model, while
//      BLUE sits far away on the axis. This is not a measured discrimination threshold.
//   5. Monotone confusion: every wavelength longer than ~560 nm drives the dog's
//      S cone to ~0, so they all share one hue end (the "yellow" pile).
//
// No dependencies. The page's <script> mirrors these exact functions.

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── The two measured cone peaks (Neitz, Geist & Jacobs 1989) ────────────────
const S_PEAK = 429;   // nm  — short-wave ("blue") cone
const L_PEAK = 555;   // nm  — long-wave ("yellow-green") cone

// ── Govardovskii et al. 2000 A1 visual-pigment template ─────────────────────
// alpha-band:  S(x) = 1 / ( exp(A(a−x)) + exp(B(b−x)) + exp(C(c−x)) + D ),
//   with x = lambda_max / lambda  and
//   a = 0.8795 + 0.0459·exp(−(lambda_max−300)^2 / 11940), b = 0.922, c = 1.104,
//   A = 69.7, B = 28, C = −14.9, D = 0.674.
function alphaBand(lambda, lmax) {
  const x = lmax / lambda;
  const A = 69.7, B = 28, C = -14.9, D = 0.674;
  const a = 0.8795 + 0.0459 * Math.exp(-((lmax - 300) ** 2) / 11940);
  const b = 0.922, c = 1.104;
  return 1 / (Math.exp(A * (a - x)) + Math.exp(B * (b - x)) + Math.exp(C * (c - x)) + D);
}
// beta-band (the small secondary hump): A_beta·exp(−((lambda − lmax_beta)/b_beta)^2)
function betaBand(lambda, lmax) {
  const Abeta = 0.26;
  const lmaxBeta = 189 + 0.315 * lmax;
  const bBeta = -40.5 + 0.195 * lmax;
  return Abeta * Math.exp(-(((lambda - lmaxBeta) / bBeta) ** 2));
}
// full pigment sensitivity (clamped non-negative)
function pigment(lambda, lmax) {
  return Math.max(0, alphaBand(lambda, lmax) + betaBand(lambda, lmax));
}

// ── 1. Template is normalised to 1 at its own peak ──────────────────────────
console.log('\n— Govardovskii A1 template: sensitivity at each cone\'s own peak —');
const sAtPeak = alphaBand(S_PEAK, S_PEAK);
const lAtPeak = alphaBand(L_PEAK, L_PEAK);
console.log(`  alpha(429,429) = ${sAtPeak.toFixed(4)}   alpha(555,555) = ${lAtPeak.toFixed(4)}`);
ok('S-cone template = 1 at 429 nm (±0.5%)', approx(sAtPeak, 1, 0.005), `${sAtPeak.toFixed(4)}`);
ok('L-cone template = 1 at 555 nm (±0.5%)', approx(lAtPeak, 1, 0.005), `${lAtPeak.toFixed(4)}`);

// ── 2. The cones peak where Neitz et al. measured ───────────────────────────
function argmax(lmax) {
  let best = 0, bestL = 0;
  for (let l = 380; l <= 720; l += 0.1) {
    const v = pigment(l, lmax);
    if (v > best) { best = v; bestL = l; }
  }
  return bestL;
}
const sArg = argmax(S_PEAK), lArg = argmax(L_PEAK);
console.log('\n— recovered peak wavelengths (argmax of each fundamental) —');
console.log(`  S cone peaks at ${sArg.toFixed(1)} nm   L cone peaks at ${lArg.toFixed(1)} nm`);
ok('S cone peaks at 429 nm (Neitz 1989)', approx(sArg, 429, 1.0), `${sArg.toFixed(1)} nm`);
ok('L cone peaks at 555 nm (Neitz 1989)', approx(lArg, 555, 1.0), `${lArg.toFixed(1)} nm`);

// ── 3. The neutral point: where mono light matches white's S:L ratio ────────
// Equal-energy white drives each cone by the integral of its sensitivity.
let sumS = 0, sumL = 0;
for (let l = 400; l <= 700; l++) { sumS += pigment(l, S_PEAK); sumL += pigment(l, L_PEAK); }
const whiteRatio = sumS / sumL;              // S:L under flat (equal-energy) white
console.log('\n— neutral point: monochromatic wavelength whose S:L = white\'s S:L —');
console.log(`  equal-energy white S:L ratio = ${whiteRatio.toFixed(4)}`);
let neutral = 0, bestErr = Infinity;
for (let l = 400; l <= 600; l += 0.1) {
  const s = pigment(l, S_PEAK), L = pigment(l, L_PEAK);
  if (L < 1e-9) continue;
  const err = Math.abs(s / L - whiteRatio);
  if (err < bestErr) { bestErr = err; neutral = l; }
}
console.log(`  computed neutral point = ${neutral.toFixed(1)} nm   (Neitz et al. report ~480 nm)`);
ok('neutral point lands near the measured ~480 nm (±8 nm)', approx(neutral, 480, 8), `${neutral.toFixed(1)} nm`);

// ── The dog's two channels from an sRGB pixel ───────────────────────────────
// We integrate the cone fundamentals against representative display primaries
// (narrow-ish Gaussians) to get fixed channel weights. This is the SAME mapping
// the page uses to recolour any swatch into dog-view. (The Gaussian primaries are
// a stated idealisation; the red-green collapse does not depend on their exact
// width — see the page's "what's idealised".)
const RC = 611, GC = 549, BC = 465, PW = 35;   // primary centres / width (nm)
function primary(l, center, width) { return Math.exp(-(((l - center) / width) ** 2)); }
let wSR = 0, wSG = 0, wSB = 0, wLR = 0, wLG = 0, wLB = 0, nR = 0, nG = 0, nB = 0;
for (let l = 380; l <= 720; l++) {
  const r = primary(l, RC, PW), g = primary(l, GC, PW), b = primary(l, BC, PW);
  wSR += pigment(l, S_PEAK) * r; wSG += pigment(l, S_PEAK) * g; wSB += pigment(l, S_PEAK) * b;
  wLR += pigment(l, L_PEAK) * r; wLG += pigment(l, L_PEAK) * g; wLB += pigment(l, L_PEAK) * b;
  nR += r; nG += g; nB += b;
}
wSR /= nR; wSG /= nG; wSB /= nB; wLR /= nR; wLG /= nG; wLB /= nB;
console.log('\n— dog cone weights from R,G,B display primaries —');
console.log(`  S = ${wSR.toFixed(3)}·R + ${wSG.toFixed(3)}·G + ${wSB.toFixed(3)}·B`);
console.log(`  L = ${wLR.toFixed(3)}·R + ${wLG.toFixed(3)}·G + ${wLB.toFixed(3)}·B`);
function dogCones(r, g, b) {            // r,g,b linear 0..1
  return [wSR * r + wSG * g + wSB * b, wLR * r + wLG * g + wLB * b];
}
const dogHue = (c) => c[0] + c[1] > 0 ? c[0] / (c[0] + c[1]) : null; // no hue at zero signal

// ── 4. Red-green collapse, blue distinct ────────────────────────────────────
const red = dogCones(1, 0, 0), green = dogCones(0, 1, 0), blue = dogCones(0, 0, 1);
const hRed = dogHue(red), hGreen = dogHue(green), hBlue = dogHue(blue);
console.log('\n— red-green collapse (dog "hue" = S/(S+L)) —');
console.log(`  red   hue = ${hRed.toFixed(4)}`);
console.log(`  green hue = ${hGreen.toFixed(4)}`);
console.log(`  blue  hue = ${hBlue.toFixed(4)}`);
const rgGap = Math.abs(hRed - hGreen);
const rbGap = Math.abs(hRed - hBlue);
console.log(`  |red − green| = ${rgGap.toFixed(4)}   |red − blue| = ${rbGap.toFixed(4)}`);
ok('red and green have nearby model chromatic coordinates (gap < 0.02)', rgGap < 0.02, `gap=${rgGap.toFixed(4)}`);
ok('blue is far from red on the model axis (gap > 0.4)', rbGap > 0.4, `gap=${rbGap.toFixed(4)}`);
ok('blue is far from green on the dog axis too', Math.abs(hGreen - hBlue) > 0.4,
   `gap=${Math.abs(hGreen - hBlue).toFixed(4)}`);

// ── 5. Everything past ~560 nm piles into one end (S cone ≈ 0) ───────────────
console.log('\n— the long-wavelength pile: S-cone sensitivity collapses to ~0 —');
let maxLongS = 0;
for (let l = 560; l <= 700; l += 1) maxLongS = Math.max(maxLongS, pigment(l, S_PEAK));
console.log(`  max S-cone sensitivity over 560–700 nm = ${maxLongS.toFixed(5)}`);
ok('S cone is essentially blind past 560 nm (max < 0.01)', maxLongS < 0.01, `${maxLongS.toFixed(5)}`);
// and the dog-hue is monotone-tiny across that whole band → one "yellow" pile
const wavelengths = [560, 580, 600, 620, 650, 680];
let allTiny = true;
for (const l of wavelengths) {
  const c = [pigment(l, S_PEAK), pigment(l, L_PEAK)];
  const h = c[0] / (c[0] + c[1] + 1e-12);
  if (h > 0.02) allTiny = false;
}
ok('sampled wavelengths 560-680 nm have model dog-hue < 0.02', allTiny);

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
