// verify-water-under-tension.mjs — every number the stratum
// "The Water That Is Pulled, Not Pushed" (/strata/water-under-tension/) displays,
// recomputed from scratch, offline, with no dependencies.
//
//   run:  node research/water-under-tension/verify-water-under-tension.mjs
//
// THE SPINE OF THE PAGE
//
//   1. A perfect vacuum pump at the top of a pipe can at best drop the pressure
//      there to absolute zero. The column it then supports is h = P_atm/(rho*g).
//      With rho = 1000 kg/m^3 that is 10.33 m. That is the barometric ceiling on
//      SUCTION, and it is the mercury barometer's 760 mm re-expressed in water.
//   2. Living Sequoia sempervirens exceed 115 m. So the water is not being pushed
//      (root pressure is far too small) and it is not being sucked (the ceiling
//      above). It is being PULLED: the column is in tension, at negative
//      ABSOLUTE pressure, which is a metastable state of liquid water.
//   3. Capillarity does not do it either, and the page shows the number rather
//      than waving: 2*gamma/(rho*g*r) for xylem-conduit radii is order 0.1 to 3 m.
//      The menisci that CAN hold the tension are the ~5 nm pores of the leaf cell
//      wall, and those hold, they do not lift.
//   4. Layer 2. The sophisticated objection: liquid at -3 MPa is metastable and
//      "should" cavitate. Answer: cavitation in xylem is not homogeneous
//      nucleation, it is AIR SEEDING through a pit-membrane pore, so the
//      threshold is Young-Laplace, dP = 4*gamma*cos(theta)/D. Recomputing that
//      from four published P50 values reproduces the published equivalent pore
//      diameters (Choat et al. 2003).
//   5. Layer 2, second beat. A vulnerability curve is a sigmoid in P50 and slope
//      (Pammenter & Vander Willigen 1998). Safety margin = Psi_min - P50, and
//      Choat et al. 2012 report 70% of 226 species from 81 sites below 1 MPa.
//   6. Layer 2, flagship. The open-vessel artefact. Impose an artefactual
//      open-vessel component on a true sigmoid and the curve turns 'r'-shaped and
//      the fitted P50 moves by MPa, i.e. a measurement method manufactures a
//      physiological conclusion. Also implemented: the Torres-Ruiz & Cochard
//      (2017) diagnostic, which is zero for a clean sample and nonzero otherwise.
//
// Free choices are flagged FREE CHOICE in the comments; the page names them too.

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

// ── constants ───────────────────────────────────────────────────────────────
const P_ATM = 101325;        // Pa, standard atmosphere (exact by definition)
const G = 9.80665;           // m/s^2, standard gravity (exact by definition)
const RHO_HG = 13595.1;      // kg/m^3, mercury at 0 C (the barometric convention)
// FREE CHOICE: the density of "water". The page lets the reader switch.
const RHO = { 'textbook 1000': 1000, '10 C (999.7)': 999.7, '20 C (998.2)': 998.2 };
// FREE CHOICE: surface tension. Pure water at 20 C. Xylem sap is not pure water.
const GAMMA = 0.07275;       // N/m, air/water at 20 C
const COS_THETA = 1.0;       // ASSUMPTION, not a measurement: contact angle 0

// ── 1. the barometric ceiling ───────────────────────────────────────────────
console.log('\n— 1. the ceiling on suction: h = P_atm/(rho*g) —');
{
  // the standard atmosphere IS 760 mm of mercury, by construction
  const fromHg = RHO_HG * G * 0.76;
  ok('101325 Pa = 760 mm of mercury (rho_Hg*g*0.76)', approx(fromHg, P_ATM, 0.15),
     `${fromHg.toFixed(2)} Pa`);

  const ceiling = (rho) => P_ATM / (rho * G);
  for (const [label, rho] of Object.entries(RHO)) {
    console.log(`  ..  rho = ${String(rho).padStart(6)} kg/m^3  ->  ceiling ${ceiling(rho).toFixed(4)} m`);
  }
  ok('ceiling at rho=1000 is 10.33 m', approx(ceiling(1000), 10.3323, 0.0005), `${ceiling(1000).toFixed(4)} m`);
  ok('ceiling at rho=999.7 is 10.34 m', approx(ceiling(999.7), 10.3354, 0.0005), `${ceiling(999.7).toFixed(4)} m`);
  ok('ceiling at rho=998.2 is 10.35 m', approx(ceiling(998.2), 10.3509, 0.0005), `${ceiling(998.2).toFixed(4)} m`);
  // the whole density choice moves the answer by under 2 cm
  const spread = ceiling(998.2) - ceiling(1000);
  ok('the density choice moves the ceiling by < 2 cm', spread < 0.02, `${(spread * 100).toFixed(1)} cm`);
  // the same digits as the mercury column, in water: 10332.3 kgf/m^2
  ok('P_atm expressed as a water column = 10332 mm', approx(ceiling(1000) * 1000, 10332.3, 0.5));
}

// ── 2. the gravitational gradient, and where absolute pressure goes negative ──
console.log('\n— 2. gravity alone: 0.0098 MPa of extra tension per metre —');
const gradMPa = (rho) => rho * G / 1e6;           // MPa per metre
const psiGrav = (h, rho) => -gradMPa(rho) * h;     // water potential, MPa (gauge)
const pAbs = (psi) => P_ATM / 1e6 + psi;           // absolute pressure, MPa
{
  ok('gradient at rho=1000 is 0.00981 MPa/m', approx(gradMPa(1000), 0.0098066, 1e-6),
     `${gradMPa(1000).toFixed(6)} MPa/m`);
  ok('gradient at rho=998.2 is 0.00979 MPa/m', approx(gradMPa(998.2), 0.0097890, 1e-6),
     `${gradMPa(998.2).toFixed(6)} MPa/m`);

  // the crossing height IS the barometric ceiling. This is an identity, not a
  // coincidence: P_abs(h) = P_atm - rho*g*h = 0  <=>  h = P_atm/(rho*g).
  const rho = 1000;
  const crossing = (P_ATM / 1e6) / gradMPa(rho);
  ok('absolute pressure hits zero exactly at the barometric ceiling',
     approx(crossing, P_ATM / (rho * G), 1e-9), `${crossing.toFixed(4)} m`);

  // heights the page marks, each cited with its measurement date
  const marks = [
    ['Koch 2004 tallest studied', 112.7],
    ['Hyperion, Sillett 2006', 115.55],
    ['Hyperion, 2019 listing', 116.07],
    ['Hyperion, 2026 listing', 116.22],
    ['Koch regression ceiling, low', 122],
    ['Koch regression ceiling, high', 130],
  ];
  for (const [label, h] of marks) {
    const psi = psiGrav(h, rho), pa = pAbs(psi);
    console.log(`  ..  ${label.padEnd(30)} ${String(h).padStart(6)} m  ->  Psi = ${psi.toFixed(4)} MPa,  P_abs = ${pa.toFixed(4)} MPa`);
    ok(`${label}: absolute pressure is negative`, pa < 0);
  }
  ok('Hyperion 2006 (115.55 m): Psi_grav = -1.1332 MPa', approx(psiGrav(115.55, rho), -1.13315, 5e-5),
     `${psiGrav(115.55, rho).toFixed(5)}`);
  ok('Hyperion 2006 (115.55 m): P_abs = -1.0318 MPa', approx(pAbs(psiGrav(115.55, rho)), -1.03183, 5e-5),
     `${pAbs(psiGrav(115.55, rho)).toFixed(5)}`);
  ok('Hyperion 2026 (116.22 m): P_abs = -1.0384 MPa', approx(pAbs(psiGrav(116.22, rho)), -1.03840, 5e-5),
     `${pAbs(psiGrav(116.22, rho)).toFixed(5)}`);
  ok('Koch 2004 (112.7 m): P_abs = -1.0038 MPa', approx(pAbs(psiGrav(112.7, rho)), -1.00385, 5e-5),
     `${pAbs(psiGrav(112.7, rho)).toFixed(5)}`);
  ok('a 130 m tree needs P_abs = -1.1735 MPa from gravity alone',
     approx(pAbs(psiGrav(130, rho)), -1.17351, 5e-5), `${pAbs(psiGrav(130, rho)).toFixed(5)}`);
  // Hyperion's remeasurement spread is small next to the effect
  ok('the 0.67 m of Hyperion remeasurement is worth only 0.0066 MPa',
     approx(gradMPa(1000) * (116.22 - 115.55), 0.00657, 1e-4));
}

// ── 3. capillarity cannot do it, and here is the number ─────────────────────
console.log('\n— 3. capillary rise h = 2*gamma*cos(theta)/(rho*g*r) —');
const capRise = (r_m, rho = 1000) => 2 * GAMMA * COS_THETA / (rho * G * r_m);
{
  const rows = [
    ['5 um   (narrow tracheid)', 5e-6],
    ['10 um  (tracheid)', 10e-6],
    ['20 um  (wide tracheid)', 20e-6],
    ['25 um  (narrow vessel)', 25e-6],
    ['50 um  (vessel)', 50e-6],
    ['100 um (wide vessel)', 100e-6],
  ];
  for (const [label, r] of rows) {
    console.log(`  ..  r = ${label.padEnd(26)} ->  ${capRise(r).toFixed(3)} m`);
  }
  ok('r = 20 um gives capillary rise under 1 m', capRise(20e-6) < 1, `${capRise(20e-6).toFixed(3)} m`);
  ok('r = 5 um  gives capillary rise under 3 m', capRise(5e-6) < 3.0, `${capRise(5e-6).toFixed(3)} m`);
  ok('no xylem-sized conduit reaches even 5 m by capillarity alone',
     rows.every(([, r]) => capRise(r) < 5));
  // the menisci that CAN hold 100 m of tension are three orders of magnitude smaller,
  // and they are in the leaf cell wall, where they hold rather than lift
  ok('a 5 nm cell-wall pore could support a column over 2000 m tall',
     capRise(5e-9) > 2000, `${Math.round(capRise(5e-9))} m`);
  ok('5 nm pore column height = 2967 m', approx(capRise(5e-9), 2967, 2), `${capRise(5e-9).toFixed(0)} m`);
}

// ── 4. air seeding: Young-Laplace, cross-checked against published values ────
console.log('\n— 4. air seeding threshold  dP = 4*gamma*cos(theta)/D  —');
// diameter form (what the pit-membrane literature uses); radius form is 2*gamma/r.
const airSeedFromDiameter = (D_m, gamma = GAMMA, shape = 1) => shape * 4 * gamma * COS_THETA / D_m;
const diameterFromP50 = (P50_MPa, gamma = GAMMA) => 4 * gamma * COS_THETA / (Math.abs(P50_MPa) * 1e6);
{
  // Choat, Ball, Luly & Holtum 2003, Plant Physiology 131:41-48, Table: four
  // co-existing dry-rainforest species, P50 from bench-dehydration curves, and
  // the equivalent pore diameter the paper reports from the same equation.
  const CHOAT2003 = [
    ['Cochlospermum gillivraei', -1.44, 200],
    ['Brachychiton australis',   -3.17,  90],
    ['Austromyrtus bidwillii',   -5.12,  60],
    ['Alphitonia excelsa',       -5.56,  50],
  ];
  for (const [sp, p50, pubD] of CHOAT2003) {
    const d_nm = diameterFromP50(p50) * 1e9;
    const rel = Math.abs(d_nm - pubD) / pubD;
    ok(`${sp.padEnd(26)} P50 ${String(p50).padStart(6)} MPa -> D = ${d_nm.toFixed(0)} nm (published ${pubD})`,
       rel < 0.13, `delta = ${(100 * rel).toFixed(1)}%`);
  }
  // the round trip: published diameter back to a pressure lands on the P50
  for (const [sp, p50, pubD] of CHOAT2003) {
    const back = airSeedFromDiameter(pubD * 1e-9) / 1e6;
    ok(`${sp.split(' ')[0].padEnd(16)} round trip D -> P = ${back.toFixed(2)} MPa vs P50 ${Math.abs(p50)}`,
       Math.abs(back - Math.abs(p50)) / Math.abs(p50) < 0.13);
  }
  // the page's own dial, radius form
  const airSeedFromRadius = (r_m, gamma = GAMMA, shape = 1) => shape * 2 * gamma * COS_THETA / r_m;
  ok('r = 50 nm  -> 2.910 MPa', approx(airSeedFromRadius(50e-9) / 1e6, 2.910, 0.002));
  ok('r = 10 nm  -> 14.55 MPa', approx(airSeedFromRadius(10e-9) / 1e6, 14.550, 0.01));
  ok('r = 100 nm -> 1.455 MPa', approx(airSeedFromRadius(100e-9) / 1e6, 1.455, 0.002));
  // Zhang et al. 2020 quote 7.2 MPa for a 20 nm pore with a 0.5 shape correction
  ok('20 nm pore with a 0.5 shape factor -> 7.2 MPa (Zhang et al. 2020)',
     approx(airSeedFromDiameter(20e-9, GAMMA, 0.5) / 1e6, 7.2, 0.15),
     `${(airSeedFromDiameter(20e-9, GAMMA, 0.5) / 1e6).toFixed(2)} MPa`);
  // gamma is the loose bolt: 20 C water vs a plausibly surfactant-lowered sap
  const d20 = diameterFromP50(-3.17, 0.07275) * 1e9;
  const d50 = diameterFromP50(-3.17, 0.0500) * 1e9;
  ok('lowering gamma from 72.75 to 50 mN/m moves the inferred pore by ~31%',
     approx((d20 - d50) / d20, 0.3127, 0.01), `${d20.toFixed(0)} nm -> ${d50.toFixed(0)} nm`);
  // homogeneous nucleation, for contrast: pure water needs far more tension
  ok('a 3 MPa air-seed threshold is far weaker than water\'s cohesive strength',
     airSeedFromRadius(50e-9) / 1e6 < 25);
}

// ── 5. the vulnerability curve and the safety margin ────────────────────────
console.log('\n— 5. vulnerability curve: PLC = 100/(1+exp((s/25)*(Psi - P50))) —');
// Pammenter & Vander Willigen 1998 sigmoid. s is the slope at P50 in %/MPa.
const plc = (psi, p50, s) => 100 / (1 + Math.exp((s / 25) * (psi - p50)));
{
  const P50 = -3.17, S = 50;
  ok('PLC at P50 is exactly 50%', approx(plc(P50, P50, S), 50, 1e-12));
  // slope at P50: d/dPsi of the logistic = 100*(s/25)/4 = s
  const eps = 1e-6, slope = (plc(P50 + eps, P50, S) - plc(P50 - eps, P50, S)) / (2 * eps);
  // PLC falls as Psi rises toward zero, so the derivative is -s; s is its magnitude
  ok('|slope| at P50 equals s (50 %/MPa)', approx(Math.abs(slope), S, 1e-3), `${slope.toFixed(4)}`);
  ok('PLC is monotone decreasing in Psi', (() => {
    let prev = -1;
    for (let p = 0; p >= -10.0001; p -= 0.05) { const v = plc(p, P50, S); if (v < prev) return false; prev = v; }
    return true;
  })());
  ok('a healthy stem at -0.5 MPa has under 1% loss', plc(-0.5, P50, S) < 1,
     `${plc(-0.5, P50, S).toFixed(3)}%`);
  ok('PLC(-4.0) = 84.02%', approx(plc(-4.0, P50, S), 84.02, 0.02), `${plc(-4.0, P50, S).toFixed(2)}%`);

  // safety margin, Choat et al. 2012 definition: Psi_min - P50
  const margin = (psiMin, p50) => psiMin - p50;
  ok('default case: Psi_min -2.40, P50 -3.17 -> margin 0.77 MPa',
     approx(margin(-2.40, P50), 0.77, 1e-9), `${margin(-2.40, P50).toFixed(2)} MPa`);
  ok('that 0.77 MPa margin is inside the <1 MPa band 70% of Choat 2012 species occupy',
     margin(-2.40, P50) < 1.0);
  ok('a margin of 0 means the plant sits exactly at 50% loss of conductivity',
     approx(plc(P50, P50, S), 50, 1e-12));
}

// ── 6. the open-vessel artefact: a method manufacturing a conclusion ────────
console.log('\n— 6. the open-vessel artefact —');
// MODEL, stated openly (FREE CHOICE, not a measurement):
//   vessel lengths ~ Exponential(mean lambda); the fraction of vessels at a cut
//   end reaching the rotor centre (a distance D/2 away) is f = exp(-(D/2)/lambda).
//   Those vessels are open air-to-water paths and embolize at trivial tensions.
//   The measured curve is f*(artefact sigmoid) + (1-f)*(true sigmoid).
// Real vessel-length distributions are not exactly exponential and conductivity is
// weighted toward wide, long vessels, so f is an order-of-magnitude estimate.
const fOpen = (lambda_m, D_m) => Math.exp(-(D_m / 2) / lambda_m);
const P50_ART = -0.30, S_ART = 120;   // FREE CHOICE: "embolizes almost at once"
const measured = (psi, p50, s, f) => f * plc(psi, P50_ART, S_ART) + (1 - f) * plc(psi, p50, s);
{
  const P50 = -3.17, S = 50, LAM = 0.50, D = 0.27;
  const f = fOpen(LAM, D);
  ok('lambda = 50 cm, rotor 27 cm -> open fraction 0.7634',
     approx(f, 0.763379, 1e-5), `f = ${f.toFixed(6)}`);
  ok('open fraction goes to 0 for short vessels in a big rotor',
     fOpen(0.02, 0.42) < 1e-4, `f = ${fOpen(0.02, 0.42).toExponential(2)}`);
  ok('open fraction goes to 1 as vessels get long', fOpen(50, 0.27) > 0.99);

  const at05 = measured(-0.5, P50, S, f);
  ok('contaminated curve shows 55.3% loss at only -0.5 MPa (an "r" shape)',
     approx(at05, 55.31, 0.1), `${at05.toFixed(2)}%`);
  ok('the TRUE curve at -0.5 MPa shows under 1% loss', plc(-0.5, P50, S) < 1,
     `${plc(-0.5, P50, S).toFixed(3)}%`);

  // fit an apparent P50 by bisection on the contaminated curve
  const fit = (f_) => {
    let lo = 0, hi = -25;
    for (let i = 0; i < 200; i++) {
      const mid = (lo + hi) / 2;
      if (measured(mid, P50, S, f_) < 50) lo = mid; else hi = mid;
    }
    return (lo + hi) / 2;
  };
  const app = fit(f);
  ok('apparent P50 from the contaminated curve is -0.4324 MPa',
     approx(app, -0.4324, 0.002), `${app.toFixed(4)} MPa`);
  ok('the artefact moves the fitted P50 by more than 2.5 MPa',
     Math.abs(app - P50) > 2.5, `shift = ${(app - P50).toFixed(3)} MPa`);
  ok('with f = 0 the fit recovers the true P50 exactly',
     approx(fit(0), P50, 1e-6), `${fit(0).toFixed(6)}`);

  // and the physiological conclusion flips sign
  const trueMargin = -2.40 - P50, appMargin = -2.40 - app;
  ok('true safety margin +0.77 MPa becomes an apparent deficit of -1.97 MPa',
     trueMargin > 0 && appMargin < 0 && approx(appMargin, -1.9676, 0.003),
     `${trueMargin.toFixed(2)} -> ${appMargin.toFixed(2)} MPa`);

  // Torres-Ruiz & Cochard (2017) diagnostic: dry a sample to Psi_prior, then spin
  // it at a LESS negative pressure. A clean sample can lose nothing new. Anything
  // above zero is the artefact announcing itself.
  const diagnostic = (psiPrior, psiSpin, f_) => {
    if (psiSpin < psiPrior) return NaN;      // the test requires a less negative spin
    return f_ * plc(psiSpin, P50_ART, S_ART);
  };
  ok('diagnostic on a clean sample (f=0) returns exactly 0% new loss',
     approx(diagnostic(-3.0, -1.0, 0), 0, 1e-12));
  const d = diagnostic(-3.0, -1.0, f);
  ok('diagnostic on the long-vesselled sample returns 73.8% new loss',
     approx(d, 73.77, 0.1), `${d.toFixed(2)}%`);
  ok('the diagnostic is monotone in the open fraction',
     diagnostic(-3.0, -1.0, 0.2) < diagnostic(-3.0, -1.0, 0.8));
  // the page's stated walk-down of the diagnostic as vessels shorten
  ok('diagnostic at lambda = 5 cm is 6.5% new loss, still above the 0.5% threshold',
     approx(diagnostic(-3.0, -1.0, fOpen(0.05, 0.27)), 6.4949, 0.02),
     `${diagnostic(-3.0, -1.0, fOpen(0.05, 0.27)).toFixed(2)}%`);
  ok('diagnostic at lambda = 2 cm is 0.11% and passes the 0.5% threshold',
     approx(diagnostic(-3.0, -1.0, fOpen(0.02, 0.27)), 0.1132, 0.002)
     && diagnostic(-3.0, -1.0, fOpen(0.02, 0.27)) < 0.5,
     `${diagnostic(-3.0, -1.0, fOpen(0.02, 0.27)).toFixed(2)}%`);
  // the rotor-diameter lever (Lopez et al. 2019: the artefact scales with maximum
  // vessel length relative to rotor diameter)
  const fBig = fOpen(LAM, 1.00);
  ok('a 1 m rotor would cut the open fraction from 0.763 to 0.368',
     approx(fBig, 0.36788, 1e-4), `f = ${fBig.toFixed(4)}`);
  ok('shortening the vessels (5 cm) is the stronger lever: f falls to 0.067',
     approx(fOpen(0.05, 0.27), 0.0672, 1e-3), `f = ${fOpen(0.05, 0.27).toFixed(4)}`);
}

// ── 7. the whole argument, end to end ───────────────────────────────────────
console.log('\n— 7. the argument, assembled —');
{
  const ceiling = P_ATM / (1000 * G);
  const hyperion2006 = 115.55;
  ok('a living tree exceeds the suction ceiling by more than a factor of 11',
     hyperion2006 / ceiling > 11, `${(hyperion2006 / ceiling).toFixed(2)}x`);
  ok('capillarity in the narrowest plausible conduit covers 29% of even that ceiling',
     approx(capRise(5e-6) / ceiling, 0.2872, 0.002),
     `${(100 * capRise(5e-6) / ceiling).toFixed(1)}%`);
  ok('so the sap at the top of Hyperion is at negative absolute pressure',
     pAbs(psiGrav(hyperion2006, 1000)) < 0);
  ok('and the tension there (1.03 MPa from gravity alone) is far short of the '
     + 'air-seed threshold of a 50 nm pore (2.91 MPa)',
     Math.abs(pAbs(psiGrav(hyperion2006, 1000))) < 2 * GAMMA / 50e-9 / 1e6);
}

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