// research/maxwell-demon — de-risking "The Price of Forgetting"
// (Maxwell's demon, the Szilard engine, and Landauer's principle).
//
// The thesis: a demon that sorts molecules looks like it breaks the Second Law,
// and the Szilard engine (one molecule, one measured bit) makes the "free lunch"
// concrete — it extracts W = kT·ln2 of work per cycle from a SINGLE heat bath.
// The resolution (Landauer 1961 + Bennett 1982): measuring is, in principle,
// free, but the demon must ERASE its one-bit memory to run the next cycle, and
// complete erasure of an initially unbiased bit in this symmetric thermal memory
// costs at least kT·ln2 of heat on average. The ideal reversible bill cancels
// the lunch in this illustrated cycle. Information is physical.
//
// The live instrument readouts use the deterministic engines checked here.
// Quadrature, stochastic simulation and the molar conversion run offline:
//
//   ENGINE 1 — the Szilard engine, EXACT. Work extracted when the partition is
//              inserted at fraction f of the box: W(f) = kT·H(f), the Shannon
//              entropy of the measurement outcome (in nats). Peaks at kT·ln2 for
//              a fair (f = 1/2) bit. Cross-checked against the isothermal work
//              integral ∫ P dV by Simpson quadrature.
//   ENGINE 2 — Landauer erasure as a two-state master equation, integrated in
//              time, starting with an unbiased bit. The finite ramp has
//              ΔF = kT[ln2 - ln(1 + exp(-Emax))]. Full-cycle work also includes
//              restoration; the residual population lowers its quasistatic limit.
//              The tested durations give mean work above kT·ln2.
//   ENGINE 3 — an independent stochastic (Gillespie) simulation of the SAME
//              two-state erasure; the trajectory-averaged work must match Engine 2.
//
//   THE LEDGER — per demon cycle: extract +kT·H(f) (Engine 1), pay −kT·H(f) to
//                erase (ideal entropy floor; Engine 2 starts fair) → net ≤ 0.
//                Let the demon forget for free
//                and the net is +kT·H(f) > 0: a perpetuum mobile. The erasure
//                cost is load-bearing — that is the control.
//
// Reduced units: k = T = 1 throughout the engines, so kT·ln2 = ln2 = 0.693147…
// A final SI block converts to the laboratory numbers the page quotes (300 K).
//
// Sources (every quantitative claim): Szilard, Z. Phys. 53 (1929) 840; Landauer,
// IBM J. Res. Dev. 5 (1961) 183; Bennett, Int. J. Theor. Phys. 21 (1982) 905;
// Bérut et al., Nature 483 (2012) 187 (the experimental confirmation); Earman &
// Norton, Stud. Hist. Phil. Mod. Phys. 29 (1998) 435 & 30 (1999) 1; Norton,
// Stud. Hist. Phil. Mod. Phys. 36 (2005) 375 ("Eaters of the Lotus").
//
// Run: `node research/maxwell-demon/verify.mjs`

const LN2 = Math.log(2);

let checks = 0, fails = 0;
const ok = (cond, msg) => { checks++; if (!cond) { fails++; console.log('  ✗ ' + msg); } };
const close = (a, b, tol, msg) => ok(Math.abs(a - b) <= tol, `${msg} (|${a} - ${b}| = ${Math.abs(a - b).toExponential(3)} > ${tol})`);
const fmt = (x, d = 6) => Number(x).toFixed(d);

// Shannon entropy of a fair-vs-biased bit, in nats. H(0)=H(1)=0, H(1/2)=ln2.
const H = (f) => {
  if (f <= 0 || f >= 1) return 0;
  return -f * Math.log(f) - (1 - f) * Math.log(1 - f);
};

console.log('THE PRICE OF FORGETTING — Maxwell’s demon, Szilard, Landauer');
console.log('  reduced units k = T = 1   →   kT·ln2 = ln2 = ' + fmt(LN2, 9) + '\n');

// ===================================================================
// ENGINE 1 — the Szilard engine (1929), EXACT.
// One ideal-gas molecule in a box of volume V at temperature T. A partition is
// inserted at fraction f (left chamber = fV). The molecule is found on the left
// with probability f. The demon then lets the gas expand isothermally back to V,
// extracting work. Ideal gas, N = 1: P = kT/V, so for an expansion a→b,
//   W = ∫_a^b (kT/V) dV = kT·ln(b/a).
// On the left (prob f): expand fV → V → W = kT·ln(1/f).
// On the right (prob 1−f): expand (1−f)V → V → W = kT·ln(1/(1−f)).
// Expected work  E[W] = f·ln(1/f) + (1−f)·ln(1/(1−f)) = H(f)   (kT = 1).
// ===================================================================
console.log('ENGINE 1 — the Szilard engine: information becomes work, exactly.');

// Isothermal work integral by Simpson's rule (independent of the closed form).
function simpsonWork(a, b, n = 200000) {  // ∫_a^b dV/V  (kT = 1)
  const h = (b - a) / n; let s = 1 / a + 1 / b;
  for (let i = 1; i < n; i++) s += (i % 2 ? 4 : 2) / (a + i * h);
  return s * h / 3;
}
// fair bit: partition at the middle, molecule certainly on one side, expand V/2 → V.
const Wfair_closed = Math.log(1 / 0.5);          // = ln2
const Wfair_simpson = simpsonWork(0.5, 1.0);     // ∫_{1/2}^{1} dV/V
close(Wfair_closed, LN2, 1e-12, 'fair Szilard work (closed form) should equal ln2');
close(Wfair_simpson, LN2, 1e-7, 'fair Szilard work (Simpson ∫P dV) should equal ln2');
console.log('  fair bit (f = 1/2): W = ln2 = ' + fmt(LN2) + '   (∫P dV by quadrature = ' + fmt(Wfair_simpson) + ')');

// general partition: E[W] = H(f); the expected work is the Shannon entropy of the bit.
for (const f of [0.1, 0.25, 0.5, 0.75, 0.9]) {
  const expectedW = f * Math.log(1 / f) + (1 - f) * Math.log(1 / (1 - f));
  close(expectedW, H(f), 1e-12, `Szilard E[W] should equal H(${f})`);
}
// the fair bit is the MOST you can get; any unfair partition extracts strictly less.
ok(H(0.5) > H(0.25) && H(0.25) > H(0.1), 'fair bit must extract the most work (H peaks at 1/2)');
ok(Math.abs(H(0.5) - LN2) < 1e-12, 'the peak of H is exactly ln2 (one full bit)');
console.log('  E[W] = H(f) (the outcome’s Shannon entropy): H(.1)=' + fmt(H(.1), 4) +
            ' H(.25)=' + fmt(H(.25), 4) + ' H(.5)=' + fmt(H(.5), 4) + ' — peak at f=1/2 = one bit.');
// work extracted PER BIT of information acquired is exactly kT·ln2 for the fair bit.
close(H(0.5) / Math.log2(2), LN2, 1e-12, 'work per bit (fair) = kT·ln2');
console.log('  → one measured bit is worth exactly kT·ln2 of work.\n');

// ===================================================================
// ENGINE 2 — Landauer erasure (1961) as a two-state master equation.
// The memory is a bit: state L or R, energies E_L(t), E_R = 0. RESET-to-R protocol:
//   phase 1  hold at equilibrium (E_L = 0, p_L = p_R = 1/2)            [1 bit stored]
//   phase 2  raise E_L: 0 → Emax, barrier low so population flows L→R   [the work step]
//   phase 3  E_L = Emax held; population now ≈ entirely in R           [bit known]
//   restore  raise barrier (freeze), lower E_L: Emax → 0, p_L ≈ 0       [≈ no work]
// Glauber rates obey detailed balance: k_{L→R}/k_{R→L} = exp(−(E_R−E_L)) = exp(E_L).
// Work increment dW = p_L·dE_L + p_R·dE_R = p_L·dE_L.
// Free energy F = −ln(e^{−E_L} + e^{−E_R}); ΔF over phases 1→3 = ln2 − ln(1+e^{−Emax}).
// Quasistatic ramp work tends to ΔF; restoration adds -Emax*p_Lfinal.
// Complete reset of an initially fair bit has mean floor ln2; finite reset
// instead has mean floor ln2 - H(p_Lfinal). L/R are state names here, not
// drawing coordinates: the page draws the retained R state as left well 0.
// ===================================================================
console.log('ENGINE 2: mean erasure work for an initially unbiased bit.');

const Emax = 20;                       // E_L ramp height; correction = ln(1+e^{-20}) ~ 2e-9
const Fqs = LN2 - Math.log(1 + Math.exp(-Emax));   // exact quasistatic ramp work (approaches ln2 as Emax grows)

// equilibrium occupancy of L for given E_L (E_R = 0)
const pLeq = (EL) => Math.exp(-EL) / (Math.exp(-EL) + 1);
// quasistatic work as the equilibrium integral ∫_0^{Emax} pLeq dE_L  (independent check of Fqs)
function workQuasistatic(n = 400000) {
  const dE = Emax / n; let w = 0;
  for (let i = 0; i < n; i++) { const EL = (i + 0.5) * dE; w += pLeq(EL) * dE; }
  return w;
}
close(workQuasistatic(), Fqs, 1e-6, 'quasistatic ramp work (∫ pLeq dE_L) should equal ΔF');
close(Fqs, LN2, 1e-8, 'finite-ramp ΔF differs from ln2 by less than 1e-8 at Emax=20');
console.log('  quasistatic ramp  ΔF = ' + fmt(Fqs, 9) + '  (= ln2 to ' + (LN2 - Fqs).toExponential(2) + ')');

// deterministic master-equation integration of the FINITE-time protocol.
// rate prefactor Gamma sets how fast the bit can hop while the barrier is low.
function erasureWork(tau, Gamma = 5.0, steps = 60000) {
  const dt = tau / steps;
  let pL = 0.5;                  // start at equilibrium, E_L = 0
  let W = 0, prevEL = 0;
  for (let i = 1; i <= steps; i++) {
    const s = i / steps;
    // E_L ramps 0→Emax over the middle third of the protocol, then holds.
    let EL;
    if (s < 1 / 3) EL = 0;
    else if (s < 2 / 3) EL = Emax * (s - 1 / 3) * 3;
    else EL = Emax;
    // work increment p_L·dE_L (trapezoidal in E_L)
    W += pL * (EL - prevEL); prevEL = EL;
    // Glauber rates (k=T=1): k_{L→R} = G/(1+e^{(E_R-E_L)}) = G/(1+e^{-EL}); detailed balance.
    const kLR = Gamma / (1 + Math.exp(-EL));
    const kRL = Gamma / (1 + Math.exp(EL));
    // dp_L/dt = -kLR pL + kRL (1-pL)
    pL += dt * (-kLR * pL + kRL * (1 - pL));
  }
  // restore phase (E_L: Emax→0 with population frozen in R, p_L≈0) adds ≈ p_L·(0-Emax) ≈ 0
  W += pL * (0 - Emax);
  return { W, pLfinal: pL };
}

// At the sampled durations, the nearly complete reset costs more than ln2
// on average. This finite sample does not establish a bound at every speed.
// Incomplete reset has a lower entropy bound, ln2 - H(p_Lfinal).
const taus = [2, 4, 8, 16, 32, 64, 128, 256];
let prevW = Infinity, allAboveFloor = true, monotone = true;
console.log('  finite-time erasure (master equation):');
for (const tau of taus) {
  const { W, pLfinal } = erasureWork(tau);
  ok(pLfinal < 0.02, `residual occupation must be below 2% at τ = ${tau}`);
  if (W < LN2) allAboveFloor = false;
  if (W > prevW + 1e-9) monotone = false;
  prevW = W;
  console.log('    τ = ' + String(tau).padStart(5) + '   W = ' + fmt(W, 6) +
              '   excess over fair-bit floor = ' + (W - LN2).toExponential(3) + (W >= LN2 ? '' : '  << BELOW REFERENCE'));
}
ok(allAboveFloor, 'mean erasure work is at least kT·ln2 at each of the eight tested durations');
ok(monotone, 'mean erasure work decreases across the eight tested durations');

// the finite-time penalty scales as 1/τ (the geodesic / Sekimoto–Aurell dissipation law):
// excess(τ)·τ → a constant. Check it holds across a decade of slow protocols.
const scaling = [64, 128, 256, 512].map((t) => (erasureWork(t).W - Fqs) * t);
const sMean = scaling.reduce((a, b) => a + b, 0) / scaling.length;
const sSpread = Math.max(...scaling) - Math.min(...scaling);
ok(sSpread / sMean < 0.05, 'finite-time penalty obeys the 1/τ dissipation law (excess·τ ≈ const)');
console.log('  excess·τ across τ=64..512: ' + scaling.map((s) => fmt(s, 3)).join(', ') +
            '  → ≈ ' + fmt(sMean, 2) + ' (constant ⇒ excess ∝ 1/τ)');

const slow = erasureWork(4096).W;     // deep into the quasistatic limit
close(slow, Fqs, 5e-3, 'mean work at tau=4096 is within 0.005 kT of the finite-ramp reference');
console.log('  slow limit τ=4096:  W = ' + fmt(slow, 6) + '   (floor ' + fmt(Fqs, 6) + ')');
console.log('  → these tested durations approach kT·ln2 from above in mean work.\n');

// ===================================================================
// ENGINE 3 — independent stochastic simulation of the SAME erasure.
// A two-state continuous-time Markov jump process with the identical Glauber
// rates and protocol; trajectory-averaged work must match Engine 2.
// ===================================================================
console.log('ENGINE 3 — stochastic cross-check (independent Markov-jump simulation).');
function erasureWorkMC(tau, trajectories = 40000, Gamma = 5.0, dt = tau / 4000, seed = 987654321) {
  // mulberry32 PRNG — reproducible
  let a = seed >>> 0;
  const rnd = () => { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
  const ELof = (s) => (s < 1 / 3 ? 0 : s < 2 / 3 ? Emax * (s - 1 / 3) * 3 : Emax);
  let Wsum = 0, finishedR = 0;
  const nsteps = Math.round(tau / dt);
  for (let tr = 0; tr < trajectories; tr++) {
    let state = rnd() < 0.5 ? 'L' : 'R';   // 1 bit, uniformly random
    let W = 0, prevEL = 0;
    for (let i = 1; i <= nsteps; i++) {
      const s = i / nsteps, EL = ELof(s);
      if (state === 'L') W += (EL - prevEL);   // work = ΔE_L only while in L
      prevEL = EL;
      const kLR = Gamma / (1 + Math.exp(-EL));
      const kRL = Gamma / (1 + Math.exp(EL));
      const rate = state === 'L' ? kLR : kRL;
      if (rnd() < rate * dt) state = state === 'L' ? 'R' : 'L';
    }
    if (state === 'L') W += (0 - Emax);        // restore phase
    Wsum += W;
    if (state === 'R') finishedR++;
  }
  return { W: Wsum / trajectories, fracR: finishedR / trajectories };
}
for (const tau of [4, 16, 64]) {
  const det = erasureWork(tau).W;
  const mc = erasureWorkMC(tau);
  close(mc.W, det, 0.02, `MC erasure work should match the master equation at τ = ${tau}`);
  ok(mc.W >= Fqs - 0.02, `MC erasure work respects the Landauer floor at τ = ${tau}`);
  console.log('  τ = ' + String(tau).padStart(3) + '   master-eq W = ' + fmt(det, 4) +
              '   stochastic ⟨W⟩ = ' + fmt(mc.W, 4) + '   (erased→R: ' + (100 * mc.fracR).toFixed(1) + '%)');
}
console.log('');

// ===================================================================
// THE LEDGER — the demon's books, per full cycle. Extract by Engine 1, pay by
// the ideal entropy floor H(f). Engine 2 separately simulates an initially fair
// bit. With the erasure honoured the net is ≤ 0 in this ledger; let the
// demon forget for free and you get a perpetuum mobile of the second kind.
// ===================================================================
console.log('THE LEDGER — the demon’s books per cycle (and the control).');
for (const f of [0.5, 0.25]) {
  const extract = H(f);          // Engine 1: work won from one measured bit
  const eraseFloor = H(f);       // ideal mean erasure floor from entropy H(f), not a biased Engine 2 run
  const netHonest = extract - eraseFloor;          // reversible: exactly 0; real: < 0
  const netCheat = extract - 0;                    // "forgetting is free" — the fallacy
  close(netHonest, 0, 1e-12, `honest cycle (f=${f}) nets ≤ 0 — no free lunch`);
  ok(netCheat > 0, `the "free forgetting" fallacy (f=${f}) would net > 0 — a perpetuum mobile`);
  console.log('  f = ' + f + ':  extract +' + fmt(extract, 4) + '   erase −' + fmt(eraseFloor, 4) +
              '   net (honest) = ' + fmt(netHonest, 4) + '   net (if erasing were free) = +' + fmt(netCheat, 4));
}
const resetQs = Fqs - Emax * pLeq(Emax);
close(resetQs, LN2 - H(pLeq(Emax)), 1e-12,
  'finite-reset quasistatic work includes restoration and residual entropy');
console.log('  finite-reset quasistatic work = ' + fmt(resetQs, 12) +
  ' kT; residual occupation = ' + pLeq(Emax).toExponential(3));
console.log('  → in this ideal reversible ledger, mean erasure cost cancels mean extracted work.\n');

// ===================================================================
// SI BLOCK — the laboratory numbers the page quotes, from CODATA constants.
// ===================================================================
console.log('SI — the bill, in laboratory units (T = 300 K).');
const kB = 1.380649e-23;          // J/K (exact, SI 2019)
const NA = 6.02214076e23;         // /mol (exact)
const eV = 1.602176634e-19;       // J (exact)
const T = 300;
const ktln2_J = kB * T * LN2;
const ktln2_zJ = ktln2_J * 1e21;
const ktln2_meV = (ktln2_J / eV) * 1e3;
const RTln2_kJmol = (kB * T * LN2 * NA) / 1e3;
const dS = kB * LN2;              // entropy of one bit, J/K
close(ktln2_zJ, 2.8709, 1e-3, 'kT·ln2 at 300 K should be ≈ 2.871 zJ');
close(ktln2_meV, 17.92, 0.02, 'kT·ln2 at 300 K should be ≈ 17.9 meV');
close(RTln2_kJmol, 1.729, 2e-3, 'RT·ln2 at 300 K should be ≈ 1.729 kJ/mol');
close(dS / kB, LN2, 1e-12, 'one bit of memory carries entropy k·ln2');
console.log('  kT·ln2 (300 K) = ' + ktln2_J.toExponential(4) + ' J = ' + fmt(ktln2_zJ, 4) + ' zJ = ' +
            fmt(ktln2_meV, 2) + ' meV   |   RT·ln2 = ' + fmt(RTln2_kJmol, 4) + ' kJ/mol');
console.log('  complete reset of an initially unbiased bit → ΔS_memory = −k·ln2 = ' + (-dS).toExponential(3) + ' J/K (the environment gains at least as much)\n');

console.log(`${fails === 0 ? '✓ ALL' : '✗ ' + (checks - fails) + '/'} ${checks} checks ${fails === 0 ? 'PASS' : 'FAIL (' + fails + ' failed)'}`);
process.exit(fails === 0 ? 0 : 1);
