// verify.mjs — the physics behind the stratum
// "How Far You Actually Sink" (/strata/quicksand/).
//
// The claim the page corrects: in the movies, a person steps into quicksand and
// is slowly swallowed whole. That cannot happen. Quicksand is a suspension of
// sand grains in water with a bulk density of about 2 g/cm^3 — roughly TWICE the
// density of a human body (~1 g/cm^3). By Archimedes' principle a body floats
// when the weight of fluid it displaces equals its own weight, so a person sinks
// only until they have displaced their own weight of quicksand: about HALF their
// volume — to roughly the waist — and then stops. The danger is not drowning by
// sinking (impossible); it is being TRAPPED — the force to extract a stuck foot
// at ~1 cm/s is about the force needed to lift a car — long enough for exposure
// or, on a tidal flat, a rising tide.
//
// What this script proves, offline and from scratch:
//   1. Archimedes: equilibrium submerged-VOLUME fraction f = rho_body / rho_fluid.
//      For rho_body ~ 1.0 and rho_quicksand ~ 2.0 g/cm^3, f ~ 0.5 — a human-density
//      object floats with half its volume above the surface. (This is exactly the
//      "beads never more than half submerged" result of Khaldoun et al., Nature
//      437:635, 2005.)
//   2. Mapping that volume fraction onto an UPRIGHT body using a segmented body-
//      volume model (Dempster 1955 segment masses ~ volumes at uniform density,
//      placed by standard stature landmarks) puts the waterline at ~0.61 of
//      stature for f = 0.5 — i.e. just above the navel, "about the waist". The
//      headline ("you sink to about the waist") is robust to the model details.
//   3. The contrast with water (rho_fluid = 1.0): lungs full (rho_body ~ 0.98)
//      gives f ~ 0.98 — nearly submerged, only the face out (floating on your
//      back); lungs empty (rho_body ~ 1.06 > 1.0) gives f > 1 — you SINK. This is
//      why you can drown in water but not by sinking in quicksand.
//   4. The extraction force: F ~ 1.0e4 N reported by Khaldoun et al. to pull a
//      foot out at ~1 cm/s equals the weight of ~1.0e3 kg — a small/family car.
//
//   run:  node research/quicksand/verify.mjs
//
// No dependencies. Every number the page displays is recomputed here.

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;

console.log('\n── 1. Archimedes: equilibrium submerged-volume fraction ──────────────');
// A floating body sinks until displaced-fluid weight = body weight:
//   rho_body * V_total * g  =  rho_fluid * V_submerged * g
//   => f = V_submerged / V_total = rho_body / rho_fluid   (capped at 1; if > 1 it sinks).
const frac = (rhoBody, rhoFluid) => rhoBody / rhoFluid;

const RHO_BODY = 1.00;        // g/cm^3, average human body (near water)
const RHO_QUICKSAND = 2.00;   // g/cm^3, Khaldoun et al. 2005 / Wikipedia
const fQ = frac(RHO_BODY, RHO_QUICKSAND);
ok('f = rho_body/rho_quicksand = 1.0/2.0 = 0.50', approx(fQ, 0.5, 1e-9),
   `f = ${fQ.toFixed(3)}`);
ok('a human-density object floats with HALF its volume above the surface',
   fQ < 1, `${(fQ * 100).toFixed(0)}% submerged`);
// robustness band: body density 0.95..1.08, quicksand 1.8..2.1 -> f stays well below 1
{
  let maxF = 0;
  for (let rb = 0.95; rb <= 1.081; rb += 0.01)
    for (let rq = 1.8; rq <= 2.101; rq += 0.05)
      maxF = Math.max(maxF, frac(rb, rq));
  ok('over plausible densities (body 0.95-1.08, qs 1.8-2.1) you never exceed ~60% submerged',
     maxF < 0.61, `max f = ${maxF.toFixed(3)}`);
}

console.log('\n── 2. Where ~50% of VOLUME puts the waterline on an upright body ─────');
// Segmented body-volume model. Dempster (1955) segment masses as % of body mass;
// at ~uniform density these are volume fractions. Each segment's volume is spread
// uniformly over its vertical extent (fraction of stature H), from the ground up.
// Arms hang alongside the trunk, so their height ranges overlap it. Landmarks are
// standard anthropometric stature fractions. This is an IDEALISATION (the page
// says so); the exact claim is the volume fraction in step 1.
const SEGMENTS = [
  // name           vol (frac)  hLow    hHigh
  ['feet',          0.029,      0.000,  0.039],
  ['shanks',        0.093,      0.039,  0.285],
  ['thighs',        0.200,      0.285,  0.530],
  ['trunk',         0.497,      0.530,  0.818],
  ['head+neck',     0.081,      0.818,  1.000],
  ['upper arms',    0.056,      0.620,  0.818],
  ['forearms',      0.032,      0.460,  0.620],
  ['hands',         0.012,      0.380,  0.460],
];
const totalVol = SEGMENTS.reduce((s, [, v]) => s + v, 0);
ok('segment volumes sum to 1.000 (Dempster fractions are complete)',
   approx(totalVol, 1.0, 1e-9), `sum = ${totalVol.toFixed(3)}`);

// cumulative volume below height h (h as fraction of stature)
const volBelow = (h) => {
  let v = 0;
  for (const [, vol, lo, hi] of SEGMENTS) {
    if (h >= hi) v += vol;
    else if (h > lo) v += vol * (h - lo) / (hi - lo);
  }
  return v;
};
// invert: find waterline height h such that volBelow(h) = f  (bisection)
const waterlineFor = (f) => {
  if (f <= 0) return 0;
  if (f >= 1) return 1;
  let lo = 0, hi = 1;
  for (let i = 0; i < 60; i++) {
    const mid = (lo + hi) / 2;
    if (volBelow(mid) < f) lo = mid; else hi = mid;
  }
  return (lo + hi) / 2;
};

const NAVEL = 0.60;  // omphalion height ~0.60 H
ok('cumulative volume at the navel (0.60 H) is ~48% — already nearly half',
   approx(volBelow(NAVEL), 0.483, 0.02), `V(0.60) = ${volBelow(NAVEL).toFixed(3)}`);
const hWaist = waterlineFor(0.5);
ok('waterline for f = 0.50 lands at ~0.61 H — just above the navel ("about the waist")',
   hWaist > 0.55 && hWaist < 0.66, `h = ${hWaist.toFixed(3)} of stature`);

console.log('\n── 3. Contrast with WATER (rho_fluid = 1.0) ─────────────────────────');
const fWaterFull = frac(0.98, 1.00);   // lungs full of air
const fWaterEmpty = frac(1.06, 1.00);  // lungs exhaled
ok('water, lungs full (rho_body 0.98): f ~ 0.98 — nearly submerged, face out',
   fWaterFull < 1 && fWaterFull > 0.95, `f = ${fWaterFull.toFixed(3)}`);
ok('water, lungs empty (rho_body 1.06): f > 1 — you SINK (this is why you can drown in water)',
   fWaterEmpty > 1, `f = ${fWaterEmpty.toFixed(3)}`);
ok('the SAME body that sinks in water (f>1) floats high in quicksand (f~0.5)',
   fWaterEmpty > 1 && fQ < 0.6, `water ${fWaterEmpty.toFixed(2)} vs qs ${fQ.toFixed(2)}`);

console.log('\n── 4. Why you get stuck: the extraction force ───────────────────────');
// Khaldoun, Eiser, Wegdam & Bonn, Nature 437:635 (2005): the force to pull a
// trapped foot out at ~1 cm/s is ~1e4 N, "equal to lifting a car". Check the
// equivalent mass.
const F_EXTRACT = 1.0e4;   // N, reported
const g = 9.81;            // m/s^2
const equivMass = F_EXTRACT / g;
ok('F ~ 1e4 N to extract a foot equals the weight of ~1.0e3 kg — a small/family car',
   approx(equivMass, 1019, 30), `${equivMass.toFixed(0)} kg`);
ok('that force is ~13x a trapped person\'s own weight (75 kg * g ~ 736 N)',
   approx(F_EXTRACT / (75 * g), 13.6, 1), `ratio = ${(F_EXTRACT / (75 * g)).toFixed(1)}x`);

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

// Emit the canonical numbers the page asserts, so a reader can diff page vs verifier.
console.log('canonical figures the page uses:');
console.log(`  quicksand density           ~2.0 g/cm^3`);
console.log(`  human body density          ~1.0 g/cm^3 (0.98 lungs full .. 1.06 empty)`);
console.log(`  submerged volume fraction   f = rho_body/rho_quicksand = ${fQ.toFixed(2)}`);
console.log(`  waterline (upright, f=0.5)  ~${(hWaist * 100).toFixed(0)}% of stature (about the waist)`);
console.log(`  extraction force            ~1e4 N at ~1 cm/s = lift a ~${equivMass.toFixed(0)} kg car`);

process.exit(fails === 0 ? 0 : 1);
