// verify-the-touch-your-brain-saw-coming.mjs — the math behind the stratum
// "The Touch Your Brain Saw Coming" (/strata/the-touch-your-brain-saw-coming/).
//
// THE CLAIM THE PAGE MAKES (and this script proves, offline, recomputing every
// number the page displays):
//
//   You can't tickle yourself because the cerebellum runs a FORWARD MODEL: from the
//   motor command to your moving hand it PREDICTS the touch that will land, and
//   subtracts the prediction from the real sensation. When prediction and reality
//   match, the residual error is ~0 and the touch is attenuated (not ticklish).
//   Break the match — Blakemore, Frith & Wolpert (1999) did it with two robots,
//   inserting a DELAY or a TRAJECTORY ROTATION between the moving hand and the
//   resulting touch — and the residual grows, attenuation fails, and the self-touch
//   feels as ticklish as an external one.
//
//   The verified experimental facts (Blakemore, Frith & Wolpert 1999,
//   J. Cognitive Neuroscience 11(5):551-559; and Blakemore, Wolpert & Frith 1998,
//   Nature Neuroscience 1(7):635-640):
//     - 16 right-handed subjects; touch was a foam tip moving sinusoidally at 2 Hz,
//       amplitude 1.5 cm, 0.5 N down; rated 0 (not at all) to 10 (extremely) tickly.
//     - DELAYS tested: 0, 100, 200, 300 ms. Tickly rating rose significantly from
//       0->100 ms and 100->200 ms; NO significant difference between 200 ms, 300 ms
//       and an EXTERNAL touch. (1998 paper: rose "between 0 and 200 ms".)
//     - ROTATIONS tested: 0, 30, 60, 90 deg. Tickly rating rose significantly to
//       90 deg, which was indistinguishable from an external touch.
//   So the empirical plateau is "~200 ms OR ~90 deg" -> feels external.
//
// WHAT THIS SCRIPT CHECKS:
//   1. The exact closed-form mean-square prediction error for a 2-D sinusoidal
//      touch:  E(theta, tau) = 1 - cos(theta)*cos(omega*tau),  omega = 2*pi*f.
//      Verified term-by-term against a brute-force numerical average over a cycle.
//   2. The corner values the page prints: E(0,0)=0; E(90deg,0)=1; the residual at
//      the experiment's anchor points.
//   3. The page's perceived-tickliness model T(theta,tau) on the 0..10 scale:
//      monotone, ~0 at perfect match, and AT the empirical plateau (200 ms or
//      90 deg) it reaches the external level T_ext within tolerance.
//   4. omega*tau hits exactly pi (full anti-phase) at tau = 250 ms for f = 2 Hz,
//      and the touch geometrically re-aligns at one full period tau = 500 ms ->
//      the honest caveat the page surfaces: the raw geometry is periodic in delay,
//      while perception is not (we cap the model at the 300 ms tested range).
//
//   run:  node research/the-touch-your-brain-saw-coming/verify-the-touch-your-brain-saw-coming.mjs
//
// No dependencies. Every displayed number is recomputed here the same way the page
// computes it in JS.

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;
const deg = (d) => (d * Math.PI) / 180;

// ── experimental constants (from the papers) ────────────────────────────────
const F_HZ = 2;                  // tactile stimulus moved sinusoidally at 2 Hz
const OMEGA = 2 * Math.PI * F_HZ; // angular frequency (rad/s)
const SCALE_MAX = 10;            // rating scale 0 (not at all) .. 10 (extremely)
const T_EXT = 7.0;               // modeled "external touch" plateau on the 0..10 scale
const PLATEAU_DELAY = 0.200;     // s — empirical plateau onset (Exp. delay)
const PLATEAU_ROT = deg(90);     // rad — empirical plateau onset (Exp. rotation)

console.log('\n— experimental constants (Blakemore, Frith & Wolpert 1998/1999) —');
console.log(`  f = ${F_HZ} Hz   omega = 2*pi*f = ${OMEGA.toFixed(6)} rad/s`);
console.log(`  rating scale: 0..${SCALE_MAX};  delays tested 0/100/200/300 ms;  rotations 0/30/60/90 deg`);

// ── 1. closed-form prediction error vs brute-force average over a cycle ──────
// Actual touch:    a(t) = A*sin(omega*t - phi) * [cos theta, sin theta],  phi = omega*tau
// Predicted touch: p(t) = A*sin(omega*t)       * [1, 0]
// Mean-square error per period, normalised by A^2:
//   E = <|a-p|^2>/A^2 = 1 - cos(theta)*cos(omega*tau)
function predErrorClosed(theta, tau) {
  return 1 - Math.cos(theta) * Math.cos(OMEGA * tau);
}
function predErrorBrute(theta, tau) {
  const A = 1, phi = OMEGA * tau, N = 200000, T = 1 / F_HZ;
  let acc = 0;
  for (let i = 0; i < N; i++) {
    const t = (i / N) * T;
    const ax = A * Math.sin(OMEGA * t - phi) * Math.cos(theta);
    const ay = A * Math.sin(OMEGA * t - phi) * Math.sin(theta);
    const px = A * Math.sin(OMEGA * t);
    const py = 0;
    acc += (ax - px) * (ax - px) + (ay - py) * (ay - py);
  }
  return acc / N; // = <|a-p|^2> with A=1, i.e. already normalised
}

console.log('\n— closed-form residual  E = 1 - cos(theta)*cos(omega*tau)  vs brute force —');
const cases = [
  ['theta=0,  tau=0',     0,            0],
  ['theta=90, tau=0',     deg(90),      0],
  ['theta=0,  tau=100ms',  0,           0.100],
  ['theta=0,  tau=200ms',  0,           0.200],
  ['theta=0,  tau=250ms',  0,           0.250],
  ['theta=45, tau=120ms',  deg(45),     0.120],
  ['theta=60, tau=200ms',  deg(60),     0.200],
  ['theta=90, tau=300ms',  deg(90),     0.300],
];
for (const [label, th, ta] of cases) {
  const c = predErrorClosed(th, ta);
  const b = predErrorBrute(th, ta);
  console.log(`  ${label.padEnd(20)}  closed=${c.toFixed(6)}  brute=${b.toFixed(6)}`);
  ok(`closed form == brute force  (${label})`, approx(c, b, 2e-4), `Δ=${Math.abs(c - b).toExponential(1)}`);
}

// ── 2. the corner values the page prints ────────────────────────────────────
console.log('\n— corner residuals the page shows —');
const E00 = predErrorClosed(0, 0);
const E900 = predErrorClosed(deg(90), 0);
console.log(`  perfect prediction  E(0deg, 0ms)   = ${E00.toFixed(4)}  (no error -> fully attenuated)`);
console.log(`  pure 90deg rotation E(90deg, 0ms)  = ${E900.toFixed(4)}`);
ok('E(0deg, 0ms) = 0 exactly (prediction matches reality)', approx(E00, 0, 1e-12), `${E00}`);
ok('E(90deg, 0ms) = 1 exactly (orthogonal touch, cos90=0)', approx(E900, 1, 1e-12), `${E900}`);

// at tau=250 ms the touch is exactly anti-phase (omega*tau = pi)
const phi250 = OMEGA * 0.250;
console.log(`  omega*tau at 250 ms = ${phi250.toFixed(6)} rad  (pi = ${Math.PI.toFixed(6)})`);
ok('omega*tau = pi exactly at tau = 250 ms (f = 2 Hz)', approx(phi250, Math.PI, 1e-9), `${phi250.toFixed(6)}`);
const E0_250 = predErrorClosed(0, 0.250);
ok('E(0deg, 250ms) = 2 (max geometric mismatch: anti-phase)', approx(E0_250, 2, 1e-9), `${E0_250.toFixed(4)}`);
// honest caveat made checkable: the raw geometry RE-ALIGNS at one full period.
const phi500 = OMEGA * 0.500;
const E0_500 = predErrorClosed(0, 0.500);
console.log(`  omega*tau at 500 ms = ${phi500.toFixed(6)} rad (= 2*pi);  E(0deg, 500ms) = ${E0_500.toFixed(4)}`);
ok('raw geometry is PERIODIC: E(0deg, 500ms) returns to 0 (one full cycle)', approx(E0_500, 0, 1e-9),
   'this is why the perceived-tickliness model is capped at the 300 ms tested range, not the bare geometry');

// ── 3. the perceived-tickliness model on the 0..10 scale ────────────────────
// We map the broken prediction into a TICKLINESS rating that (a) is ~0 when the
// prediction is perfect, (b) rises monotonically, and (c) reaches the external
// level by the experiment's plateau (200 ms OR 90 deg). The page and this script
// use the SAME function. It is an honest *model* of the paper's qualitative curve,
// NOT a digitised fit (the paper reports significance, not mean rating values).
//
//   temporal drive:  dT = clamp(tau / PLATEAU_DELAY, 0, 1)         (0 at 0 ms, 1 at >=200 ms)
//   spatial  drive:  dS = (1 - cos(theta)) / (1 - cos(PLATEAU_ROT)) (0 at 0deg, 1 at 90deg)
//   combined  drive: d  = 1 - (1 - dT)*(1 - dS)   (either one alone can reach plateau)
//   tickliness:      T  = T_EXT * d               (0 .. T_EXT)
function clamp01(x) { return Math.max(0, Math.min(1, x)); }
function tickliness(theta, tau) {
  const dT = clamp01(tau / PLATEAU_DELAY);
  const dS = clamp01((1 - Math.cos(theta)) / (1 - Math.cos(PLATEAU_ROT)));
  const d = 1 - (1 - dT) * (1 - dS);
  return T_EXT * d;
}

console.log('\n— perceived-tickliness model T(theta, tau) on the 0..10 scale —');
const Tcorner = tickliness(0, 0);
console.log(`  self-touch, perfect prediction  T(0deg, 0ms)    = ${Tcorner.toFixed(2)}  (you can't tickle yourself)`);
ok('T(0deg, 0ms) = 0 (a perfectly predicted self-touch is not ticklish)', approx(Tcorner, 0, 1e-12), `${Tcorner.toFixed(3)}`);

const Tdelay = tickliness(0, PLATEAU_DELAY);
console.log(`  delay to 200 ms (no rotation)    T(0deg, 200ms)  = ${Tdelay.toFixed(2)}  (= external level)`);
ok('at 200 ms delay, tickliness reaches the external level', approx(Tdelay, T_EXT, 1e-9), `${Tdelay.toFixed(2)} vs ${T_EXT}`);

const Trot = tickliness(PLATEAU_ROT, 0);
console.log(`  rotate to 90 deg (no delay)      T(90deg, 0ms)   = ${Trot.toFixed(2)}  (= external level)`);
ok('at 90 deg rotation, tickliness reaches the external level', approx(Trot, T_EXT, 1e-9), `${Trot.toFixed(2)} vs ${T_EXT}`);

// monotonic in delay (rotation fixed at 0): rises 0 -> 100 -> 200 ms, then flat
console.log('\n— monotonic rise with delay (rotation = 0), matching the paper —');
const delays = [0, 0.050, 0.100, 0.150, 0.200, 0.250, 0.300];
let monoUp = true, prev = -1;
for (const ta of delays) {
  const T = tickliness(0, ta);
  const star = ta <= 0.200 ? '' : '  (plateau: not sig. different from external)';
  console.log(`   delay ${(ta * 1000).toFixed(0).padStart(3)} ms  ->  T = ${T.toFixed(2)}${star}`);
  if (T < prev - 1e-9) monoUp = false;
  prev = T;
}
ok('tickliness is non-decreasing as delay grows 0..300 ms (paper: monotone to plateau)', monoUp);
// the two anchored midpoints the page can show:
const T100 = tickliness(0, 0.100);
ok('T(0deg, 100ms) = 3.5 (half-way up, by construction tau/200ms = 0.5)', approx(T100, 3.5, 1e-9), `${T100.toFixed(2)}`);

// monotonic in rotation (delay fixed at 0): 0 -> 30 -> 60 -> 90 deg
console.log('\n— monotonic rise with rotation (delay = 0), matching the paper —');
let monoRot = true; prev = -1;
for (const dd of [0, 30, 60, 90]) {
  const T = tickliness(deg(dd), 0);
  console.log(`   rotation ${String(dd).padStart(2)} deg  ->  T = ${T.toFixed(2)}`);
  if (T < prev - 1e-9) monoRot = false;
  prev = T;
}
ok('tickliness is non-decreasing as rotation grows 0..90 deg (paper: monotone to plateau)', monoRot);

// combined: either knob alone saturates, and both together stay at the cap
const Tboth = tickliness(PLATEAU_ROT, PLATEAU_DELAY);
ok('both knobs maxed stays at the external cap (no double-counting past plateau)',
   approx(Tboth, T_EXT, 1e-9), `${Tboth.toFixed(2)}`);

// attenuation reported as a percentage the page prints: (1 - T/T_ext)*100
console.log('\n— attenuation % the page prints  = (1 - T/T_ext) * 100 —');
for (const [label, th, ta] of [['self, predicted (0deg,0ms)', 0, 0], ['90deg twist', deg(90), 0], ['200ms delay', 0, 0.200], ['45deg,100ms', deg(45), 0.100]]) {
  const T = tickliness(th, ta);
  const att = (1 - T / T_EXT) * 100;
  console.log(`   ${label.padEnd(26)} T=${T.toFixed(2)}  attenuation=${att.toFixed(1)}%`);
}
const attFull = (1 - tickliness(0, 0) / T_EXT) * 100;
ok('a perfectly predicted self-touch is 100% attenuated', approx(attFull, 100, 1e-9), `${attFull.toFixed(1)}%`);

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