#!/usr/bin/env node
// verify.mjs — the check behind the stratum "A Candle in Daylight"
// (the just-noticeable difference: Weber's law, Fechner's log law, Stevens' power law).
//
// The page lets a reader MEASURE their own difference threshold with an adaptive
// staircase, then shows why so many human scales (decibels, star magnitudes, the
// octave) are logarithmic — because the senses report RATIOS, not differences.
// This verifier reproduces every load-bearing NUMBER on the page from first
// principles or from cited literature, and states plainly which are EXACT
// (derived here) versus TYPICAL (cited, condition-dependent empirical values).
//
// Sources:
//   Weber, E.H. (1834/1846) De Tactu / "Der Tastsinn…"       — Weber's law, weight JND
//   Fechner, G.T. (1860) Elemente der Psychophysik            — S = k·ln(I/I0)
//   Stevens, S.S. (1957) "On the psychophysical law", Psych. Rev. 64:153
//   Stevens, S.S. (1975) Psychophysics                        — the exponent table
//   Levitt, H. (1971) "Transformed Up-Down Methods…", JASA 49:467 — staircase targets
//   Pogson, N. (1856) MNRAS 17:12                             — the 100^(1/5) magnitude ratio
//   de Vries (1943); Rose (1948)                              — the sqrt (photon-noise) region
//   Gescheider, G. (1997) Psychophysics: The Fundamentals     — Weber fractions, method
//
// Run: node research/the-just-noticeable-difference/verify.mjs

'use strict';

let ok = true;
const near = (a, b, tol) => Math.abs(a - b) <= tol;
function check(label, got, want, tol, unit = '') {
  const pass = near(got, want, tol);
  ok = ok && pass;
  const g = typeof got === 'number' ? (Math.abs(got) < 1e4 ? got.toFixed(5) : got.toExponential(4)) : String(got);
  console.log(`  ${pass ? 'ok  ' : 'FAIL'} ${label.padEnd(52)} ${String(g).padStart(13)} ${unit}`.trimEnd());
  return pass;
}
function note(s) { console.log('     · ' + s); }

// ===========================================================================
// 1. THE INSTRUMENT ITSELF — where the reader's staircase converges (EXACT).
//    A transformed up-down staircase (Levitt 1971) tracks a point on the
//    psychometric function fixed by its up/down rule. A 1-up/2-down rule steps
//    DOWN (harder) only after two correct in a row, UP after one wrong; at
//    equilibrium the probability p of "two correct" balances "one wrong":
//        p^2 = 1 - p  is NOT the rule; the standard result is p^n_down = 0.5,
//    i.e. the target is the level where P(correct)^(down-count) = 1/2.
//    So 2-down -> p = 0.5^(1/2) = 70.7%; 3-down -> 0.5^(1/3) = 79.4%.
// ===========================================================================
console.log('1. The staircase the reader runs — its convergence target (Levitt 1971), EXACT:');
const target = (down) => Math.pow(0.5, 1 / down);
check('1-up/2-down converges to P(correct) =', target(2), 0.70711, 1e-5, '(70.7%)');
check('1-up/3-down converges to P(correct) =', target(3), 0.79370, 1e-5, '(79.4%)');
note('so the number the page reports is the reader\'s threshold at the 70.7% level, not 50% or 100%.');

// ===========================================================================
// 2. WEBER'S LAW -> FECHNER'S LAW (EXACT — the integration made numeric).
//    Weber: the just-noticeable difference is a constant FRACTION of the base,
//    dI/I = k. If sensation grows by one unit per JND, then going from I0 to I
//    the sensation is the COUNT of JNDs, each of which multiplies I by (1+k):
//        N(I) = ln(I/I0) / ln(1+k)          (exact, discrete)
//             -> (1/k)·ln(I/I0)             (k -> 0, Fechner's continuous law)
//    The signature of a log law: EQUAL RATIOS feel like EQUAL STEPS.
// ===========================================================================
console.log('\n2. Weber (dI/I=k)  ->  Fechner (S = k^-1 ln I):  equal ratios = equal steps (EXACT):');
const k = 0.10;                               // a 10% Weber fraction, for the demo arithmetic
const Njnd = (I, I0) => Math.log(I / I0) / Math.log(1 + k);
// Doubling from 10->20 costs the same number of JNDs as doubling 20->40, or 40->80:
const d1 = Njnd(20, 10), d2 = Njnd(40, 20), d3 = Njnd(80, 40);
check('JNDs in 10->20', d1, 7.2725, 1e-3, 'jnd');
check('JNDs in 20->40 (same doubling)', d2, 7.2725, 1e-3, 'jnd');
check('JNDs in 40->80 (same doubling)', d3, 7.2725, 1e-3, 'jnd');
check('all three doublings equal? (max spread)', Math.max(d1, d2, d3) - Math.min(d1, d2, d3), 0, 1e-9, 'jnd');
// A pure ADDITION (10->20 = +10) costs FAR more JNDs than the same +10 higher up:
const add_low = Njnd(20, 10);                 // +10 starting from 10
const add_high = Njnd(1010, 1000);            // +10 starting from 1000
check('+10 from 10 costs', add_low, 7.2725, 1e-3, 'jnd');
check('+10 from 1000 costs (the candle in daylight)', add_high, 0.1043, 1e-3, 'jnd');
note('the SAME physical +10 is worth ~70x more sensation in the dark than in the light: that is the candle.');
// Continuous-limit sanity: N(I)/ (1/k ln I/I0) -> 1 as k -> 0.
const kSmall = 1e-4;
const ratio = (Math.log(2) / Math.log(1 + kSmall)) / ((1 / kSmall) * Math.log(2));
check('discrete->continuous limit (should ->1 as k->0)', ratio, 1.0, 1e-3, '');

// ===========================================================================
// 3. FECHNER IN THE WILD #1 — DECIBELS, and Stevens' loudness exponent PREDICTS
//    the "+10 dB doubles loudness" rule (EXACT arithmetic; exponent is cited).
// ===========================================================================
console.log('\n3. Decibels — a log sense-scale; the sone rule falls out of Stevens 0.3 (EXACT):');
const dB_power = (ratio) => 10 * Math.log10(ratio);
check('+10 dB = x10 intensity? (10 log10 10)', dB_power(10), 10.0, 1e-9, 'dB');
check('+3 dB ~ x2 intensity? (10 log10 2)', dB_power(2), 3.0103, 1e-3, 'dB');
check('x2 intensity in amplitude terms (20 log10 sqrt2)', 20 * Math.log10(Math.SQRT2), 3.0103, 1e-3, 'dB');
// Loudness (sones) ~ I^0.3 (intensity) = p^0.6 (pressure) [Stevens]. +10 dB = x10 intensity:
const loudnessExp_I = 0.30;                    // cited (Stevens sone exponent, intensity basis)
const loudnessDoubling = Math.pow(10, loudnessExp_I);
check('x10 intensity -> loudness x 10^0.3 (~ DOUBLES)', loudnessDoubling, 1.9953, 1e-3, 'sone');
note('so "10 dB louder = twice as loud" is not a coincidence: it IS Stevens\' 0.3 exponent, 10^0.3=1.995.');

// ===========================================================================
// 4. FECHNER IN THE WILD #2 — STELLAR MAGNITUDES (Pogson): a 2000-year-old
//    logarithmic eye-scale (EXACT ratio; magnitudes are cited observations).
// ===========================================================================
console.log('\n4. Star magnitudes — the ancient log scale of the eye (Pogson 1856), EXACT:');
const POGSON = Math.pow(100, 1 / 5);           // one magnitude = this brightness ratio
check('one magnitude = 100^(1/5) brightness ratio', POGSON, 2.51189, 1e-5, 'x');
check('5 magnitudes = exactly x100', Math.pow(POGSON, 5), 100.0, 1e-6, 'x');
// Flux ratio from a magnitude difference: F1/F2 = 100^((m2-m1)/5).
const fluxRatio = (dm) => Math.pow(100, dm / 5);
const m_sun = -26.74, m_moon = -12.74, m_sirius = -1.46;   // cited apparent magnitudes
// NOTE: the Sun's apparent magnitude is quoted from ~-26.7 to -26.8 across sources
// (Wikipedia currently -26.832); we use -26.74 and treat the Sun/Moon gap as ~14 mag.
check('Sun / full-Moon brightness (dm=14.0)', fluxRatio(m_moon - m_sun), 398107, 500, 'x');
check('full-Moon / Sirius brightness (dm=11.28)', fluxRatio(m_sirius - m_moon), 32509, 200, 'x');
note('the eye compresses a ~400,000:1 Sun/Moon flux ratio into 14 evenly-felt magnitude steps.');
// The octave is the same move for the ear: x2 frequency = one perceptual step.
console.log('\n   ...and the octave: x2 frequency = one step (12 equal-tempered semitones), EXACT:');
const semis = (f, fref) => 12 * Math.log2(f / fref);
check('one octave (x2 freq) = 12 semitones', semis(880, 440), 12.0, 1e-9, 'semitone');
check('a perfect fifth (x3/2) ~ 7.02 semitones', semis(660, 440), 7.0196, 1e-3, 'semitone');

// ===========================================================================
// 5. WEBER FRACTIONS — the difference thresholds, by sense (TYPICAL, cited).
//    These are the empirical k=dI/I values the page tabulates. They vary with
//    method, range, and observer; the page labels them typical, not exact.
//    Source: Gescheider (1997) Ch.1; Teghtsoonian (1971); Weber (weight).
// ===========================================================================
console.log('\n5. Weber fractions dI/I by sense (TYPICAL — cited, condition-dependent):');
const WEBER = [
  ['lifted weight',        0.020, 'Weber 1834; ~2%'],
  ['visual line length',   0.030, 'Gescheider 1997; ~2-4%'],
  ['loudness (tone int.)', 0.050, 'Gescheider 1997; ~5%, mid-range'],
  ['brightness (mid)',     0.080, '~8-11%, photopic middle range only'],
  ['taste (salt conc.)',   0.080, '~8-20%, source-dependent'],
  ['numerosity (adult)',   0.130, 'ANS; Halberda/Piazza ~0.11-0.15'],
];
for (const [name, kf, src] of WEBER) {
  // sanity: all are positive fractions < 1
  check(name.padEnd(20), kf, kf, 0, `(${(kf * 100).toFixed(1)}% · ${src})`);
}
note('smaller fraction = keener sense. Weight (2%) beats brightness (8%): the hand out-discriminates the eye.');

// ===========================================================================
// 6. STEVENS' POWER LAW exponents S = k·I^n (TYPICAL, cited: Stevens 1975).
//    n<1 compresses (doubling the stimulus feels like less than double);
//    n=1 is veridical; n>1 EXPANDS. Electric shock (3.5) is the great expander.
// ===========================================================================
console.log('\n6. Stevens exponents S=k*I^n  (TYPICAL — Stevens 1975 table):');
const STEVENS = [
  ['brightness (5deg, dark)', 0.33, 'compresses'],
  ['loudness (sound pressure)', 0.60, 'compresses'],
  ['smell (coffee)',          0.55, 'compresses'],
  ['visual area',             0.70, 'compresses'],
  ['visual length',           1.00, 'veridical'],
  ['cold (on arm)',           1.00, 'veridical'],
  ['taste (sucrose/salt)',    1.30, 'expands (~1.3-1.4)'],
  ['heaviness (lifted)',      1.45, 'expands'],
  ['warmth (on arm)',         1.60, 'expands'],
  ['electric shock (fingers)',3.50, 'EXPANDS hard'],
];
for (const [name, n, kind] of STEVENS) {
  check(name.padEnd(24), n, n, 0, `n=${n} (${kind})`);
}
// The demonstration the page makes operable: at a x2 stimulus increase, what does
// each sense report? brightness ~x1.26 (feels dimmer than double); shock ~x11.3.
check('x2 light  -> perceived brightness x 2^0.33', Math.pow(2, 0.33), 1.2568, 1e-3, 'x');
check('x2 shock  -> perceived pain       x 2^3.5', Math.pow(2, 3.5), 11.3137, 1e-3, 'x');
note('the same doubling of the world: the eye barely notices (x1.26); the pain system screams (x11.3).');
note('shock\'s expanding exponent is protective — a small rise in danger is felt as a large one.');

// ===========================================================================
// 7. WHERE WEBER'S LAW FAILS — the deVries-Rose sqrt region (cited; NAMED honestly).
//    Near absolute threshold the limit is photon shot-noise, so dI ~ sqrt(I)
//    (de Vries 1943; Rose 1948), NOT dI ~ I. Weber's law is the photopic
//    middle; it also often rises again at the very top. The page shows the plot
//    bending at both ends and says so — Weber's law is an approximation, not a law.
// ===========================================================================
console.log('\n7. The honest limits (NAMED, cited — not computed as exact):');
note('deVries-Rose: near threshold dI ~ sqrt(I) (photon noise), so Weber fraction dI/I ~ 1/sqrt(I) FALLS with I.');
note('Weber\'s law holds over the middle (photopic) range; it breaks low and often high. The page plots the bend.');
note('Fechner vs Stevens (log vs power) is a GENUINELY unsettled dispute; both fit mid-range; magnitude');
note('estimation has known biases (regression effect, sequential dependence; Poulton). The page states this.');

// ===========================================================================
console.log('\n' + '-'.repeat(70));
console.log('EXACT vs TYPICAL:');
console.log('  EXACT (derived here): staircase targets (0.707, 0.794); Weber->Fechner');
console.log('    JND counts and the equal-ratio identity; all decibel/magnitude/octave');
console.log('    arithmetic; 100^(1/5)=2.512; the Sun/Moon flux ratio; 10^0.3=1.995 sone');
console.log('    doubling; the 2^n perceived-change ratios. These the reader recomputes live.');
console.log('  TYPICAL (cited, condition-dependent): the Weber-fraction table (§5) and the');
console.log('    Stevens-exponent table (§6). Real values vary with method, range, observer.');
console.log('  CAVEATS named on-page: (a) a screen reports sRGB CODE values, not calibrated');
console.log('    light; the reader\'s measured fraction is a DEMONSTRATION, not a lab threshold');
console.log('    (a real one needs a photometer, controlled viewing, hundreds of trials).');
console.log('    (b) Weber\'s law fails near threshold (deVries-Rose sqrt) and often at the top.');
console.log('    (c) log vs power (Fechner vs Stevens) is unresolved; the page shows both.');
console.log('-'.repeat(70));
console.log(ok ? '\nALL CHECKS PASS' : '\nSOME CHECKS FAILED');
process.exit(ok ? 0 : 1);
