// verify-the-year-that-keeps-getting-shorter.mjs — the arithmetic behind the stratum
// "The Year That Keeps Getting Shorter" (/strata/the-year-that-keeps-getting-shorter/).
//
// The claim the page makes interactive: the felt acceleration of time with age is not a
// vague mood but a recomputable fraction, under two classic descriptive models.
//
//   1. JANET'S PROPORTIONAL MODEL (Paul Janet, 1877/1897; popularised via William James,
//      Principles of Psychology, 1890, ch. XV). The felt length of a fixed real interval
//      is proportional to its fraction of the life lived so far: the instantaneous felt
//      RATE goes as 1/age, so cumulative subjective time is
//
//            S_J(a) = ln(a)                              (dS = dt / t)
//
//      Consequence: a fixed calendar YEAR at age a feels (a0 / a) as long as it did at a0.
//      A year at 50 feels (5/50) = 1/10 as long as a year at 5. And every DOUBLING of age
//      (5->10->20->40->80) carries the SAME subjective span, ln 2, because ln(2a)-ln(a)=ln 2
//      for all a. Geometric age intervals feel equal — that is the proportional model's
//      signature, and it is EXACT, not approximate.
//
//   2. LEMLICH'S SQUARE-ROOT MODEL (Robert Lemlich, "Subjective Acceleration of Time with
//      Aging," Perceptual and Motor Skills 41(1):235-238, 1975, DOI 10.2466/pms.1975.41.1.235).
//      Lemlich's hypothesis: the felt duration of a real interval is inversely proportional
//      to TOTAL ACCUMULATED SUBJECTIVE time S, not to total real time. That is dS/dt = k/S,
//      so S dS = k dt, S^2/2 = k t, and with S(0)=0:
//
//            S_L(a) = 2 * sqrt(a)        (taking k = 2 so the constant is clean; ANY k>0
//                                         gives S ∝ sqrt(a) and the same ratios)
//            felt RATE  dS/dt = k/S ∝ 1 / sqrt(a)        ("inversely with the sqrt of age")
//
//      Consequence: a fixed calendar YEAR at age a feels sqrt(a0 / a) as long as at a0.
//      A year at 50 feels sqrt(5/50) ≈ 0.316 (about 1/3) as long as a year at 5 — markedly
//      gentler than Janet's 1/10. Under Lemlich, HALF of your subjectively-felt life is
//      already behind you by age T/4 (e.g. age 20 of an 80-year life), because the felt
//      midpoint solves sqrt(a) = sqrt(T)/2.
//
// What this script proves, offline, recomputing every number the page can display:
//   A. Janet: every age-doubling carries exactly ln 2 of subjective time.
//   B. Janet: a year at 50 vs a year at 5 = 1/10, exactly (the spec's headline ratio).
//   C. Lemlich is the solution of dS/dt = k/S: S(a)=2*sqrt(a) satisfies it, and the
//      felt rate is exactly 1/sqrt(a) up to the constant.
//   D. Lemlich: a year at 50 vs at 5 = sqrt(1/10) ≈ 0.3162 (NOT 1/10 — the two models
//      give genuinely different numbers; the page must not conflate them).
//   E. Lemlich felt half-life of a life to age T is exactly T/4.
//   F. The two cumulative curves match their own definitions when integrated numerically
//      (trapezoid of the felt rate == closed form), to < 1e-6 — i.e. the page's plotted
//      integral agrees with the formula it claims to plot.
//
//   run:  node research/the-year-that-keeps-getting-shorter/verify-the-year-that-keeps-getting-shorter.mjs
//
// No dependencies. Every number the page displays is recomputed here, the same way.

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 models, exactly as the page implements them ─────────────────────
// Janet (proportional / logarithmic): cumulative subjective time
const S_janet   = (a) => Math.log(a);
// Janet instantaneous felt rate (subjective time per real year) ∝ 1/a
const rate_janet = (a) => 1 / a;
// Lemlich (square-root): cumulative subjective time, constant k=2 (S = 2*sqrt(a))
const S_lemlich = (a) => 2 * Math.sqrt(a);
// Lemlich instantaneous felt rate dS/dt = d/da[2*sqrt(a)] = 1/sqrt(a)
const rate_lemlich = (a) => 1 / Math.sqrt(a);

// felt length of a fixed calendar year at age a relative to a reference age a0:
//   Janet:   (a0 / a)        (ratio of 1/a rates)
//   Lemlich: sqrt(a0 / a)    (ratio of 1/sqrt(a) rates)
const yearFeel_janet   = (a, a0) => a0 / a;
const yearFeel_lemlich = (a, a0) => Math.sqrt(a0 / a);

// ── A. Janet: every doubling of age carries exactly ln 2 of subjective time ──
console.log('\n— A. Janet (proportional): each age-DOUBLING feels equal (= ln 2) —');
const LN2 = Math.log(2);
console.log(`  ln 2 = ${LN2.toFixed(6)}`);
let janetDoublingsEqual = true;
for (const [a, b] of [[5, 10], [10, 20], [20, 40], [40, 80]]) {
  const span = S_janet(b) - S_janet(a);
  console.log(`  age ${String(a).padStart(2)} -> ${String(b).padStart(2)}:  S span = ${span.toFixed(6)}`);
  if (!approx(span, LN2, 1e-12)) janetDoublingsEqual = false;
}
ok('Janet: 5->10, 10->20, 20->40, 40->80 each carry exactly ln 2', janetDoublingsEqual,
   `all = ${LN2.toFixed(6)}`);
// the geometric-feels-equal property is EXACT for any doubling, at any starting age:
let anyDoubling = true;
for (const a of [3, 7, 13, 29, 61, 100]) {
  if (!approx(S_janet(2 * a) - S_janet(a), LN2, 1e-12)) anyDoubling = false;
}
ok('Janet: ln(2a) - ln(a) = ln 2 for EVERY a (geometric intervals feel equal)', anyDoubling);

// ── B. Janet headline ratio: a year at 50 feels 1/10 of a year at 5 ─────────
console.log('\n— B. Janet: a calendar year at 50 vs at 5 —');
const janet_50_vs_5 = yearFeel_janet(50, 5);
console.log(`  (1/50) / (1/5) = 5/50 = ${janet_50_vs_5}`);
ok('Janet: a year at 50 feels exactly 1/10 of a year at 5', approx(janet_50_vs_5, 0.1, 1e-12),
   `${janet_50_vs_5}`);

// ── C. Lemlich is the solution of dS/dt = k/S ───────────────────────────────
// Check 1: S=2*sqrt(a) satisfies dS/dt = k/S with k=2.  dS/da = 1/sqrt(a).
//          k/S = 2 / (2*sqrt(a)) = 1/sqrt(a).  They match.
console.log('\n— C. Lemlich: S = 2*sqrt(a) solves dS/dt = k/S (k=2) and rate ∝ 1/sqrt(a) —');
let solvesODE = true;
for (const a of [1, 4, 9, 25, 50, 80]) {
  const h = 1e-6;
  const dSda = (S_lemlich(a + h) - S_lemlich(a - h)) / (2 * h);   // numeric derivative
  const kOverS = 2 / S_lemlich(a);                                // k/S with k=2
  if (!approx(dSda, kOverS, 1e-6)) solvesODE = false;
  if (!approx(dSda, rate_lemlich(a), 1e-6)) solvesODE = false;    // and equals 1/sqrt(a)
}
ok('Lemlich: dS/da == k/S == 1/sqrt(a) at every tested age (the ODE Lemlich derived)',
   solvesODE);

// ── D. Lemlich headline ratio: a year at 50 vs at 5 = sqrt(1/10), NOT 1/10 ───
console.log('\n— D. Lemlich: a calendar year at 50 vs at 5 (different from Janet!) —');
const lem_50_vs_5 = yearFeel_lemlich(50, 5);
console.log(`  sqrt(5/50) = sqrt(0.1) = ${lem_50_vs_5.toFixed(6)}`);
ok('Lemlich: a year at 50 feels sqrt(1/10) ≈ 0.3162 of a year at 5', approx(lem_50_vs_5, 0.316228, 1e-5),
   `${lem_50_vs_5.toFixed(6)}`);
ok('the two models genuinely disagree (Lemlich 0.316 != Janet 0.100)',
   !approx(lem_50_vs_5, janet_50_vs_5, 0.01), `Δ = ${(lem_50_vs_5 - janet_50_vs_5).toFixed(4)}`);
// Lemlich rate ratios the page quotes: a quarter of your age ran half as fast; half ran 0.71x
ok('Lemlich: at 1/4 your age, time ran at 1/sqrt(1/4)=2x your felt rate (i.e. you ran 1/2 as "slow")',
   approx(1 / rate_lemlich(0.25) , 0.5, 1e-12), `rate(1/4)=${rate_lemlich(0.25)} = 2x`);
// at half your current age a0, a year felt yearFeel_lemlich(a0/2, a0) = sqrt(a0/(a0/2)) = sqrt(2)
// relative to NOW? No — relative to now a year THEN felt LONGER. The page quotes it the other way:
// the felt rate at half your age was 1/sqrt(1/2) = sqrt(2) ≈ 1.414x of now, i.e. a fixed real year
// at half your age felt sqrt(2) ≈ 1.41x as long as one now — equivalently a year now feels
// 1/sqrt(2) ≈ 0.707 of a year at half your age.
ok('Lemlich: a year now feels sqrt(1/2) ≈ 0.707 of a year at half your age',
   approx(Math.sqrt(0.5), 0.70710678, 1e-7),
   `sqrt(1/2)=${Math.sqrt(0.5).toFixed(6)}`);

// ── E. Lemlich felt half-life of a life to age T is exactly T/4 ─────────────
console.log('\n— E. Lemlich: half of felt life is over by age T/4 —');
let halfLifeOk = true;
for (const T of [80, 76, 100, 64]) {
  // felt half-life a* solves S_L(a*) = S_L(T)/2  =>  2*sqrt(a*) = sqrt(T)  =>  a* = T/4
  const aStar = T / 4;
  const lhs = S_lemlich(aStar);
  const rhs = S_lemlich(T) / 2;
  console.log(`  life to ${T}: felt half-life at age ${aStar}  (S=${lhs.toFixed(4)} vs S(T)/2=${rhs.toFixed(4)})`);
  if (!approx(lhs, rhs, 1e-12)) halfLifeOk = false;
}
ok('Lemlich: the felt midpoint of a life to age T is exactly T/4', halfLifeOk);
// the page's flagship line: for an 80-year life, half your felt time is gone by 20
ok('Lemlich: for an 80-year life, half of felt life is behind you by age 20',
   approx(S_lemlich(20), S_lemlich(80) / 2, 1e-12));
// fraction of felt life lived by age a of a life to T is sqrt(a)/sqrt(T)
const fracFeltLemlich = (a, T) => Math.sqrt(a) / Math.sqrt(T);
console.log('  fraction of felt life lived (life to 80):');
for (const a of [5, 10, 18, 20, 40]) {
  console.log(`    by age ${String(a).padStart(2)}: ${(fracFeltLemlich(a, 80) * 100).toFixed(1)}%`);
}
ok('Lemlich: by age 18, ~47.4% of an 80-year felt life is already lived',
   approx(fracFeltLemlich(18, 80) * 100, 47.4, 0.1), `${(fracFeltLemlich(18, 80) * 100).toFixed(1)}%`);

// ── F. the plotted integral agrees with the closed form (what the canvas draws) ──
// The page plots cumulative subjective time S(a). Verify the trapezoid integral of the
// felt RATE equals the closed form, for both models, to <1e-6 — i.e. the curve the canvas
// integrates is the curve the formula claims.
console.log('\n— F. plotted integral (trapezoid of felt rate) == closed form —');
function integrateRate(rateFn, a0, a1, n) {
  const h = (a1 - a0) / n;
  let sum = 0;
  for (let i = 0; i < n; i++) {
    const x0 = a0 + i * h, x1 = x0 + h;
    sum += 0.5 * (rateFn(x0) + rateFn(x1)) * h;
  }
  return sum;
}
// Janet: integral of 1/a from a0 to a1 = ln(a1)-ln(a0); start at a0=1 (ln 1 = 0 anchor)
{
  const num = integrateRate(rate_janet, 1, 80, 400000);
  const closed = S_janet(80) - S_janet(1);
  console.log(`  Janet:   ∫1/a [1..80] num=${num.toFixed(6)}  closed=${closed.toFixed(6)}`);
  ok('Janet: numeric ∫(1/a) matches ln(80)-ln(1)', approx(num, closed, 1e-4), `Δ=${Math.abs(num - closed).toExponential(1)}`);
}
// Lemlich: integral of 1/sqrt(a) from 1 to 80 = 2*sqrt(80) - 2*sqrt(1) = S_L(80) - S_L(1).
// (We integrate from age 1, not 0: 1/sqrt(a) has an integrable singularity at 0 that the
// trapezoid rule resolves poorly, and the page plots from age 1 anyway — felt time before
// the first birthday is not meaningfully modelled.)
{
  const num = integrateRate(rate_lemlich, 1, 80, 400000);
  const closed = S_lemlich(80) - S_lemlich(1);
  console.log(`  Lemlich: ∫1/√a [1..80] num=${num.toFixed(6)}  closed=${closed.toFixed(6)}`);
  ok('Lemlich: numeric ∫(1/√a) matches 2√80 - 2√1', approx(num, closed, 1e-4), `Δ=${Math.abs(num - closed).toExponential(1)}`);
}

// ── G. the naive "fraction of life" intuition the page opens with ───────────
// A year is 1/age of your life: 1/5 at five, 1/50 at fifty. This is the raw Janet fraction.
console.log('\n— G. the opening intuition: a year is 1/age of the life lived —');
ok('a year is 1/5 of a 5-year-old\'s life', approx(1 / 5, 0.2, 1e-12), '0.2');
ok('a year is 1/50 of a 50-year-old\'s life', approx(1 / 50, 0.02, 1e-12), '0.02');
ok('ratio (1/50)/(1/5) = 1/10 (a year at 50 is a tenth the slice it was at 5)',
   approx((1 / 50) / (1 / 5), 0.1, 1e-12), '0.1');

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