#!/usr/bin/env node
// verify.mjs — the check behind the stratum "Why does ice float?"
// Reproduces the density of liquid water vs temperature from Kell's (1975)
// equation of state, locates the density MAXIMUM (the anomaly), and confirms
// the numbers the instrument surfaces to the reader.
//
// Source of the formula:
//   G. S. Kell, "Density, thermal expansivity, and compressibility of liquid
//   water from 0° to 150°C," J. Chem. Eng. Data 20 (1975) 97-105.
//   Density of air-free water at 1 atm (101.325 kPa), SMOW isotopic standard,
//   valid 0-150 °C. rho in kg/m^3, t in °C.
//
// Run: node research/ice-float/verify.mjs

'use strict';

// ---- Kell 1975, 1 atm, air-free water (kg/m^3) --------------------------------
function rhoKell(t) {
  const num = 999.83952
    + 16.945176   * t
    - 7.9870401e-3 * t * t
    - 46.170461e-6 * t ** 3
    + 105.56302e-9 * t ** 4
    - 280.54253e-12 * t ** 5;
  const den = 1 + 16.879850e-3 * t;
  return num / den;
}

// ---- 1. reproduce standard tabulated reference densities ---------------------
// Independently tabulated values (air-free water, 1 atm), widely published from
// Kell 1975 / CRC Handbook. We require agreement to < 0.01 kg/m^3.
const REF = [
  [0,  999.8395],
  [4,  999.9720],
  [5,  999.9666],
  [10, 999.7026],
  [15, 999.1026],
  [20, 998.2071],
  [25, 997.0479],
  [30, 995.6502],
];
let ok = true;
console.log('T(°C)   Kell(kg/m³)   ref        Δ');
for (const [t, ref] of REF) {
  const r = rhoKell(t);
  const d = r - ref;
  const pass = Math.abs(d) < 0.01;
  ok = ok && pass;
  console.log(
    `${String(t).padStart(4)}   ${r.toFixed(4).padStart(10)}   ${ref.toFixed(4)}   ${d>=0?'+':''}${d.toFixed(4)}  ${pass?'ok':'FAIL'}`
  );
}

// ---- 2. locate the density maximum (the anomaly) -----------------------------
// Fine scan then parabolic refine around the peak.
let best = { t: 0, r: -Infinity };
for (let t = 0; t <= 12; t += 0.0005) {
  const r = rhoKell(t);
  if (r > best.r) best = { t, r };
}
// derivative sign check: rho increases 0->peak, decreases peak->8
const dRho = (t) => (rhoKell(t + 1e-4) - rhoKell(t - 1e-4)) / 2e-4;
const risesBelow = dRho(2) > 0;         // warming from 2°C still increases density
const fallsAbove = dRho(6) < 0;         // warming from 6°C decreases density
const anomaly    = rhoKell(4) > rhoKell(0) && rhoKell(4) > rhoKell(8); // 4°C denser than both 0 and 8

console.log(`\nDensity maximum: T = ${best.t.toFixed(3)} °C,  ρ = ${best.r.toFixed(4)} kg/m³`);
console.log(`  d(ρ)/dT > 0 at 2°C (density still rising as it warms)?  ${risesBelow}`);
console.log(`  d(ρ)/dT < 0 at 6°C (density falling as it warms)?       ${fallsAbove}`);
console.log(`  ρ(4°C) > ρ(0°C) and ρ(4°C) > ρ(8°C) (the anomaly)?      ${anomaly}`);

// ---- 3. ice floats: density ratio and submerged fraction ---------------------
// Ice Ih at 0°C, 1 atm. IAPWS / standard value.
const RHO_ICE   = 916.7;                 // kg/m^3, ice Ih at 0°C
const RHO_WATER0 = rhoKell(0);           // liquid water at 0°C
const RHO_SEA   = 1025;                  // typical surface seawater
const lessDense = 100 * (1 - RHO_ICE / RHO_WATER0);         // % less dense than 0°C water
const subFresh  = 100 * (RHO_ICE / RHO_WATER0);             // % submerged in fresh water
const subSea    = 100 * (RHO_ICE / RHO_SEA);               // % submerged in seawater
console.log(`\nIce Ih ρ = ${RHO_ICE} kg/m³  vs  liquid @0°C ρ = ${RHO_WATER0.toFixed(2)} kg/m³`);
console.log(`  ice is ${lessDense.toFixed(1)}% less dense than water at 0°C  → it floats`);
console.log(`  fraction submerged in FRESH water: ${subFresh.toFixed(1)}%  (≈ ${(100-subFresh).toFixed(1)}% shows)`);
console.log(`  fraction submerged in SEAWATER:    ${subSea.toFixed(1)}%  (the "≈90% underwater" figure)`);

// ---- verdict -----------------------------------------------------------------
const maxOk = Math.abs(best.t - 3.983) < 0.02 && Math.abs(best.r - 999.972) < 0.01;
const all = ok && maxOk && risesBelow && fallsAbove && anomaly && lessDense > 8 && lessDense < 9;
console.log(`\n${all ? 'PASS' : 'FAIL'} — all checks ${all ? 'reproduce' : 'do NOT reproduce'} the published physics.`);
process.exit(all ? 0 : 1);
