#!/usr/bin/env node
// Verifier for the "Wet-Bulb Temperature" stratum.
// Two independent computations of the wet-bulb temperature must agree, and the
// physical ordering dew-point <= wet-bulb <= dry-bulb must hold everywhere.
//
//  (A) Stull (2011) closed-form regression — the formula the page evaluates live.
//      Stull, R. (2011), "Wet-Bulb Temperature from Relative Humidity and Air
//      Temperature," J. Appl. Meteorol. Climatol. 50(11), 2267-2269.
//      Valid: RH 5-99%, T -20..50 C, sea-level pressure (1013.25 hPa).
//  (B) A from-scratch root-solve of the psychrometric equation, using Bolton (1980)
//      saturation vapour pressure. This is independent of Stull's regression, so
//      agreement is a real cross-check, not a tautology.
//
// Run: node research/wet-bulb/verify.mjs   (exit 0 = all green)

let pass = 0, fail = 0;
const approx = (a, b, tol, msg) => {
  const ok = Math.abs(a - b) <= tol;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${msg}  (got ${a.toFixed(3)}, want ${b.toFixed(3)} ±${tol})`);
  ok ? pass++ : fail++;
};
const assert = (ok, msg) => { console.log(`${ok ? 'PASS' : 'FAIL'}  ${msg}`); ok ? pass++ : fail++; };

// ---- (A) Stull 2011 ---------------------------------------------------------
function stullWetBulb(T, RH) {            // T in C, RH in %
  const a = Math.atan;
  return T * a(0.151977 * Math.sqrt(RH + 8.313659))
       + a(T + RH)
       - a(RH - 1.676331)
       + 0.00391838 * Math.pow(RH, 1.5) * a(0.023101 * RH)
       - 4.686035;
}

// ---- (B) psychrometric root-solve ------------------------------------------
// Bolton (1980): saturation vapour pressure over water, hPa, T in C.
const esat = (T) => 6.112 * Math.exp((17.67 * T) / (T + 243.5));
// Psychrometric constant gamma = cp*P/(eps*Lv), hPa/C, at sea level. Latent heat of
// vaporisation is taken temperature-dependent at the wet-bulb, Lv(T)=2.501e6-2370*T
// (J/kg, T in C) — the physically-correct choice for the thermodynamic wet bulb.
const cp = 1005, eps = 0.622, P = 1013.25;
const Lv = (T) => 2.501e6 - 2370 * T;
const gamma = (Tw) => (cp * P) / (eps * Lv(Tw));   // ~0.655 hPa/C near 0C, rising with T
// Wet-bulb Tw solves:  esat(Tw) - ea = gamma(Tw)*(T - Tw),  with ea = RH/100*esat(T).
function psychroWetBulb(T, RH) {
  const ea = (RH / 100) * esat(T);
  const f = (Tw) => esat(Tw) - ea - gamma(Tw) * (T - Tw);
  let lo = -30, hi = T;                    // Tw in [dewpoint-ish, T]
  for (let i = 0; i < 100; i++) {
    const mid = (lo + hi) / 2;
    if (f(mid) > 0) hi = mid; else lo = mid;
  }
  return (lo + hi) / 2;
}
// Dew point (Bolton inverse), C.
function dewPoint(T, RH) {
  const ea = (RH / 100) * esat(T);
  const l = Math.log(ea / 6.112);
  return (243.5 * l) / (17.67 - l);
}

console.log('=== 1. Stull vs published psychrometric-chart reference values ===');
// Reference wet-bulb values read from a standard psychrometric chart / ASHRAE
// (sea level). Tolerances reflect chart-reading + regression error.
approx(stullWetBulb(20, 50), 13.7, 0.4, 'T=20C RH=50% -> Tw');
approx(stullWetBulb(30, 50), 21.9, 0.4, 'T=30C RH=50% -> Tw');
approx(stullWetBulb(25, 60), 19.4, 0.5, 'T=25C RH=60% -> Tw');
approx(stullWetBulb(40, 20), 22.9, 0.6, 'T=40C RH=20% (dry heat) -> Tw');
approx(stullWetBulb(35, 99), 34.85, 0.3, 'T=35C RH~100% -> Tw≈T (the 35C limit case)');

console.log('\n=== 2. Stull agrees with an independent psychrometric root-solve ===');
// Tested over THIS stratum's operating domain (heat + humidity), where both methods
// are accurate. (Stull's regression and Bolton's e_s both degrade at sub-freezing,
// bone-dry corners — outside the heat-stress range the instrument actually drives.)
let maxDiff = 0, worst = '', maxHumid = 0;
for (let T = 10; T <= 50; T += 2) {
  for (let RH = 5; RH <= 99; RH += 2) {
    const d = Math.abs(stullWetBulb(T, RH) - psychroWetBulb(T, RH));
    if (d > maxDiff) { maxDiff = d; worst = `T=${T} RH=${RH}`; }
    if (RH >= 30 && d > maxHumid) maxHumid = d;
  }
}
console.log(`  max |Stull - psychrometric| over full heat domain (RH 5-99%) = ${maxDiff.toFixed(3)} C  (at ${worst}, the dry edge)`);
console.log(`  max over the humid-heat regime the page is about (RH 30-99%) = ${maxHumid.toFixed(3)} C`);
// Two coarse approximations; residual peaks at the dry boundary (RH=5%), tightens fast.
assert(maxDiff < 1.3, 'two independent methods agree within 1.3 C across the full heat domain');
assert(maxHumid < 1.0, 'in the humid-heat regime that matters, agreement is within 1.0 C');

console.log('\n=== 3. Physical ordering: dewpoint <= wet-bulb <= dry-bulb, everywhere ===');
let orderOK = true, sweatOK = true;
for (let T = 0; T <= 50; T += 2) {
  for (let RH = 5; RH <= 99; RH += 2) {
    const Tw = stullWetBulb(T, RH), Td = dewPoint(T, RH);
    if (!(Td - 0.2 <= Tw && Tw <= T + 0.05)) { orderOK = false; }
    // at RH=100 the three converge:
  }
}
assert(orderOK, 'Td <= Tw <= T holds for all T in [0,50], RH in [5,99]');

console.log('\n=== 4. The convergence at saturation (Tw, Td, T all meet) ===');
approx(stullWetBulb(25, 99), dewPoint(25, 99), 0.4, 'at RH~100%, Tw ≈ Td');
approx(stullWetBulb(25, 99), 25, 0.4, 'at RH~100%, Tw ≈ T');

console.log('\n=== 5. The core misconception, made numeric ===');
// "Dry heat is fine, humid heat kills" — compare a dry 45C day to a humid 35C day.
const dry = stullWetBulb(45, 15);    // Phoenix-type
const humid = stullWetBulb(35, 90);  // Persian-Gulf-type
console.log(`  dry  45C / 15% RH -> wet-bulb ${dry.toFixed(1)} C`);
console.log(`  humid 35C / 90% RH -> wet-bulb ${humid.toFixed(1)} C`);
assert(humid > dry, 'the cooler-but-humid 35C air has a HIGHER wet-bulb than the hotter dry 45C air');
assert(dry < 35 && humid > 30, 'dry-heat wet-bulb sits well below the skin limit; humid-heat wet-bulb approaches it');

console.log('\n=== 6. Monotonicity over the instrument domain (T 10-50C, RH 5-99%) ===');
// The page bounds its sliders to Stull's stated validity window: T <= 50C, RH in
// [5,99]. In that window the regression is strictly monotone in both inputs, so the
// slider can never show a physical lie. (Below RH=5% — outside Stull's range — the
// regression has a sub-degree non-monotone wiggle; the instrument does not go there.)
let monoRH = true, monoT = true;
for (let T = 10; T <= 50; T += 1) {
  for (let RH = 5; RH < 99; RH += 1) if (stullWetBulb(T, RH + 1) < stullWetBulb(T, RH) - 1e-6) monoRH = false;
}
for (let RH = 5; RH <= 99; RH += 1) {
  for (let T = 10; T < 50; T += 1) if (stullWetBulb(T + 1, RH) < stullWetBulb(T, RH) - 1e-6) monoT = false;
}
assert(monoRH, 'wet-bulb rises monotonically with humidity (T fixed) over the page domain');
assert(monoT, 'wet-bulb rises monotonically with temperature (RH fixed) over the page domain');

// ============================================================================
//  THE SECOND INSTRUMENT — the survivability plane (measured limit vs. ceiling)
//  Sources:
//   Vecellio, Wolf, Cottle & Kenney (2022), J Appl Physiol 132(2):340-345
//     (PSU HEAT) — Table 2, young adults, minimal activity (~10 W ergometer work).
//   Wolf, Cottle, Fisher, Vecellio & Kenney (2023), Commun Earth Environ 4:469
//     — older-adult critical environmental limits (humid protocols).
//   Sherwood & Huber (2010), PNAS 107(21):9552-9555 — the 35C wet-bulb ceiling;
//     present-day peak wet-bulb "never exceeds about 31C".
//  The page plots these points; here we confirm they are internally consistent
//  (the (T,RH) pairs reproduce the paper's stated critical wet-bulb AND vapour
//  pressure), that they all sit below the 35C ceiling (the gap is real), and that
//  the measured limit is NOT a single wet-bulb value (it sags from ~30.5C in humid
//  air to ~25.8C in dry air — the page's central, surprising claim).
// ============================================================================
const mmHg = (hPa) => hPa * 0.7500616;            // hPa -> mmHg
// Invert Stull: dry-bulb giving a target wet-bulb at a given RH (Stull monotone in T).
function TforTw(Tw, RH) { let lo = Tw, hi = 95; for (let i = 0; i < 60; i++) { const m = (lo + hi) / 2; if (stullWetBulb(m, RH) > Tw) hi = m; else lo = m; } return (lo + hi) / 2; }

// Vecellio 2022 Table 2 (young, minimal activity): [dry-bulb C, RH %, vapour mmHg, paper Twb,crit C]
// First three are HUMID (Pcrit) protocols (dry-bulb fixed 36/38/40, critical humidity);
// last three are DRY (Tcrit) protocols (vapour fixed 20/16/12 mmHg, critical temperature).
const YOUNG = [
  { T: 36.0, RH: 66.25, P: 29.54, twb: 30.34, kind: 'humid' },
  { T: 38.0, RH: 60.83, P: 30.03, twb: 30.96, kind: 'humid' },
  { T: 40.0, RH: 50.24, P: 27.74, twb: 30.45, kind: 'humid' },
  { T: 44.04, RH: 28.81, P: 20.00, twb: 27.82, kind: 'dry' },
  { T: 47.48, RH: 20.14, P: 16.00, twb: 27.12, kind: 'dry' },
  { T: 50.57, RH: 12.70, P: 12.00, twb: 25.75, kind: 'dry' },
];
// Wolf 2023 (older adults, minimal activity, humid protocols): [dry-bulb C, RH %, vapour mmHg]
const OLDER = [
  { T: 34, RH: 62.1, P: 25.6 }, { T: 36, RH: 53.5, P: 24.1 },
  { T: 38, RH: 46.1, P: 23.0 }, { T: 40, RH: 34.0, P: 19.0 },
];

console.log('\n=== 7. The 35C ceiling is a true iso-wet-bulb contour, monotone across the plane ===');
// Exactness is checked on the open interval RH in [10,99]; at exactly RH=100 Stull's
// saturation artifact puts the minimum wet-bulb (~35.1C at T=35) just above 35, so no
// T>=35 yields exactly Tw=35 there — a known boundary effect, handled by the corner
// check below rather than the inversion sweep.
let ceilOK = true, ceilMono = true, prevT = Infinity, ceilWorst = 0;
for (let RH = 10; RH <= 99; RH += 1) {
  const T = TforTw(35, RH);
  ceilWorst = Math.max(ceilWorst, Math.abs(stullWetBulb(T, RH) - 35));
  if (Math.abs(stullWetBulb(T, RH) - 35) > 1e-3) ceilOK = false;   // inversion is exact
  if (T > prevT + 1e-6) ceilMono = false;                          // dry-bulb falls as RH rises
  prevT = T;
}
console.log(`  max inversion residual over RH 10-99% = ${ceilWorst.toExponential(2)} C`);
assert(ceilOK, 'TforTw(35,RH) inverts Stull exactly (RH 10-99%): the plotted ceiling really is wet-bulb 35C');
assert(ceilMono, 'the ceiling curve is monotone — needs less dry-bulb heat to hit Tw=35 as humidity rises');
approx(TforTw(35, 100), 35, 0.2, 'at saturation the ceiling meets the diagonal (Tw=T=35C)');

console.log('\n=== 8. The measured (T,RH) points reproduce the papers numbers (the data is consistent) ===');
let vpMax = 0, twMax = 0, allBelow = true;
for (const p of YOUNG) {
  const vp = mmHg((p.RH / 100) * esat(p.T));     // vapour pressure from (T,RH)
  const tw = stullWetBulb(p.T, p.RH);            // wet-bulb from (T,RH)
  vpMax = Math.max(vpMax, Math.abs(vp - p.P));
  twMax = Math.max(twMax, Math.abs(tw - p.twb));
  if (tw >= 35) allBelow = false;
}
console.log(`  max |computed vapour pressure - stated Pcrit| over the 6 young points = ${vpMax.toFixed(2)} mmHg`);
console.log(`  max |Stull wet-bulb - paper Twb,crit|       over the 6 young points = ${twMax.toFixed(2)} C`);
assert(vpMax < 1.0, 'each (T,RH) point reproduces the paper vapour pressure within 1 mmHg (the pairs are self-consistent)');
assert(twMax < 1.0, 'each (T,RH) point reproduces the paper critical wet-bulb within 1C (Stull vs. the paper method)');
assert(allBelow, 'every measured young-adult limit sits BELOW the 35C ceiling — the gap the page shades is real');

console.log('\n=== 9. The central claim: the limit is NOT a single wet-bulb — it sags from humid to dry ===');
const humidTw = YOUNG.filter(p => p.kind === 'humid').map(p => p.twb);
const dryTw = YOUNG.filter(p => p.kind === 'dry').map(p => p.twb);
const humidMean = humidTw.reduce((a, b) => a + b) / humidTw.length;     // ~30.6
const dryMin = Math.min(...dryTw);                                      // 25.75
assert(humidMean > 30 && humidMean < 31, `humid critical wet-bulb is ~constant near 30.5C (mean ${humidMean.toFixed(2)})`);
assert(dryMin < 26, `dry critical wet-bulb falls to ${dryMin}C — well under the humid value`);
assert(humidMean - dryMin > 3.5, `the measured limit spans >3.5C of wet-bulb (${(humidMean - dryMin).toFixed(1)}C) — it crosses iso-wet-bulb lines, so it is not one contour`);
// the gap, in wet-bulb terms, between the humid measured limit and the 35C ceiling
assert(35 - humidMean > 4, `even at its highest (humid) the measured limit is >4C of wet-bulb below the theoretical ceiling`);

console.log('\n=== 10. Older adults fail lower than young, and their points are self-consistent too ===');
let oVpMax = 0, olderBelowYoung = true;
for (const p of OLDER) {
  oVpMax = Math.max(oVpMax, Math.abs(mmHg((p.RH / 100) * esat(p.T)) - p.P));
  const olderTw = stullWetBulb(p.T, p.RH);
  if (!(olderTw < 30.55 + 0.2)) olderBelowYoung = false;   // at/below the young humid plateau (more vulnerable)
}
console.log(`  max |computed vapour pressure - stated| over the 4 older points = ${oVpMax.toFixed(2)} mmHg`);
assert(oVpMax < 1.0, 'older-adult (T,RH) points reproduce the published vapour-pressure limits within 1 mmHg');
assert(olderBelowYoung, 'older-adult limits sit at or below the young-adult humid plateau (more vulnerable), as the paper reports');

console.log(`\n${fail === 0 ? 'ALL GREEN' : 'FAILURES'} — ${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
