// verify-why-led-needs-a-resistor.mjs — the physics behind the stratum
// "The Resistor That Saves the Light" (/strata/why-led-needs-a-resistor/).
//
// The claim the page corrects: an LED needs a series resistor NOT because "an LED
// has zero resistance" (the dominant, false internet answer) but because a diode's
// current rises EXPONENTIALLY with voltage. A tiny voltage above the forward drop
// produces a catastrophic current. The governing law is the Shockley diode equation
//
//        I = Is · ( exp( V / (n·Vt) ) − 1 ),      Vt = kT/q
//
// and the working point of the LED-plus-resistor circuit is the intersection of the
// diode curve with the resistor LOAD LINE  I = (V_batt − V) / R  — solvable exactly
// with the Lambert W function (Banwell & Jayakumar 2000).
//
// What this script proves, offline and from scratch, recomputing every number the
// page shows on screen:
//   1. Thermal voltage Vt = kT/q ≈ 25.852 mV at T = 300 K, from CODATA k and q.
//   2. The "×10 per ~60 mV" rule: for ideality n, current multiplies by 10 for each
//      ΔV = n·Vt·ln 10 ≈ 59.5 mV (n=1). A +60 mV step multiplies current by ≈10.16.
//      So +60 mV at room temperature ≈ ×10 current — voltage is the wrong knob.
//   3. The worked design: 5 V supply, red LED Vf = 2.0 V at 20 mA → R = (5−2.0)/0.020
//      = 150 Ω, exactly Ohm's law on the resistor's share of the voltage.
//   4. The exact operating point from Lambert W matches an independent Newton/bisection
//      solve of  V_batt = I·R + V_LED  to < 1e-9, at every R the page can show.
//   5. The catastrophe: as R → 0 the operating current rockets up the near-vertical
//      exponential and blows far past the 20 mA rating; the model's own breakdown
//      (it ignores high-injection + bulk series resistance) is bounded, not hidden.
//
//   run:  node research/why-led-needs-a-resistor/verify-why-led-needs-a-resistor.mjs
//
// No dependencies. Every number the page displays is recomputed here, the same way.

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;

// ── 1. Thermal voltage Vt = kT/q from CODATA constants ──────────────────────
// k (Boltzmann) and q (elementary charge) are EXACT in the 2019 SI redefinition.
const k_B = 1.380649e-23;        // J/K   (exact)
const q_e = 1.602176634e-19;     // C     (exact)
const T_room = 300;              // K     (the page's stated room temperature)
const Vt = (k_B * T_room) / q_e; // volts
console.log('\n— thermal voltage Vt = kT/q at T = 300 K —');
console.log(`  Vt = ${(Vt * 1000).toFixed(4)} mV`);
ok('Vt ≈ 25.85 mV at 300 K', approx(Vt * 1000, 25.852, 0.01), `${(Vt * 1000).toFixed(3)} mV`);
// sanity: at the conventional "room temperature" 298.15 K it's the familiar ~25.69 mV
const Vt25C = (k_B * 298.15) / q_e;
ok('Vt ≈ 25.69 mV at 25 °C (298.15 K) — the textbook value', approx(Vt25C * 1000, 25.693, 0.01),
   `${(Vt25C * 1000).toFixed(3)} mV`);

// ── 2. The decade-per-~60-mV rule ───────────────────────────────────────────
// Drop the −1 (negligible in forward bias): I ∝ exp(V/(n·Vt)). Increasing V by ΔV
// multiplies I by exp(ΔV/(n·Vt)). A ×10 (one decade) needs ΔV = n·Vt·ln 10.
const decade_mV = (n) => n * Vt * Math.log(10) * 1000;
console.log('\n— "+60 mV ⇒ ×10 current" (the steepness that makes voltage the wrong knob) —');
const dV_for_decade_n1 = decade_mV(1);
const dV_for_decade_n2 = decade_mV(2);
console.log(`  n=1: one decade per ${dV_for_decade_n1.toFixed(2)} mV`);
console.log(`  n=2: one decade per ${dV_for_decade_n2.toFixed(2)} mV`);
ok('n=1: a decade of current per ≈59.5 mV', approx(dV_for_decade_n1, 59.53, 0.1),
   `${dV_for_decade_n1.toFixed(2)} mV`);
// what a +60 mV step actually does (n=1): slightly MORE than ×10, because the exact
// decade is at 59.53 mV, so a round 60 mV overshoots it a touch. The page shows the
// exact multiplier, not a rounded "×10" — the honest number is ≈10.19.
const mult60_n1 = Math.exp(0.060 / (1 * Vt));
console.log(`  +60 mV step (n=1) multiplies current by ${mult60_n1.toFixed(3)}`);
ok('+60 mV (n=1) ≈ ×10 current (exact 10.19, since the true decade is at 59.5 mV)',
   approx(mult60_n1, 10.185, 0.01), `×${mult60_n1.toFixed(3)}`);

// ── 3. The worked design: 5 V, red LED Vf = 2.0 V @ 20 mA ⇒ R = 150 Ω ────────
console.log('\n— worked design: 5 V supply, red LED Vf = 2.0 V at 20 mA —');
const V_batt0 = 5.0, Vf = 2.0, I_target = 0.020;
const R_design = (V_batt0 - Vf) / I_target;   // Ohm's law on the resistor's voltage share
console.log(`  R = (${V_batt0} − ${Vf}) / ${I_target} = ${R_design} Ω`);
ok('R = 150 Ω', approx(R_design, 150, 1e-9), `${R_design} Ω`);
// Kirchhoff round-trip: I·R + Vf must equal V_batt exactly
ok('KVL closes: I·R + Vf = V_batt', approx(I_target * R_design + Vf, V_batt0, 1e-12));

// ── The diode model, pinned to (Vf, I_target, n) ────────────────────────────
// We choose n (ideality) and pin Is so the curve passes through (Vf, I_target):
//   I_target = Is·(exp(Vf/(nVt)) − 1)  ⇒  Is = I_target / (exp(Vf/(nVt)) − 1).
// n = 1.8 is a representative red-LED ideality (LEDs run higher than 1; the page
// names this free choice). Is then follows; it is NOT a universal constant.
const n_ideal = 1.8;
const Is = I_target / (Math.exp(Vf / (n_ideal * Vt)) - 1);
console.log('\n— diode model pinned to the worked LED —');
console.log(`  n = ${n_ideal}   Is = ${Is.toExponential(4)} A`);
const diodeI = (V) => Is * (Math.exp(V / (n_ideal * Vt)) - 1);   // Shockley
// it really does pass through the rated point:
ok('curve passes through (Vf=2.0 V, 20 mA) by construction',
   approx(diodeI(Vf) * 1000, 20, 1e-6), `I(2.0 V)=${(diodeI(Vf) * 1000).toFixed(4)} mA`);

// ── 4. Operating point: Lambert W closed form vs independent Newton solve ────
// Circuit: V_batt = I·R + V, with I = Is·(exp(V/(nVt)) − 1).
// Banwell & Jayakumar (2000) closed form for the current:
//   I = (nVt/R)·W( (Is·R/(nVt))·exp((V_batt + Is·R)/(nVt)) ) − Is.
// We implement Lambert W (principal branch) by Halley iteration, and separately
// solve the transcendental KVL by bisection on V — they must agree to ~1e-9.

// Lambert W principal branch, Halley's method (Corless et al. 1996).
function lambertW(x) {
  if (x < -1 / Math.E) throw new Error('W0 undefined for x < -1/e');
  if (x === 0) return 0;
  // initial guess: log series for large x, series for small x
  let w = x < 10 ? Math.log(1 + x) : Math.log(x) - Math.log(Math.log(x));
  for (let i = 0; i < 100; i++) {
    const ew = Math.exp(w);
    const f = w * ew - x;
    const wp1 = w + 1;
    const dw = f / (ew * wp1 - (w + 2) * f / (2 * wp1));  // Halley step
    w -= dw;
    if (Math.abs(dw) < 1e-15 * (1 + Math.abs(w))) break;
  }
  return w;
}
// self-test Lambert W against the defining identity W(x)·e^{W(x)} = x
for (const xx of [0.5, 1, 2, 10, 1e3, 1e8, 1e20]) {
  const w = lambertW(xx);
  ok(`Lambert W identity W·e^W = x  (x=${xx})`, approx(w * Math.exp(w), xx, Math.abs(xx) * 1e-9));
}

// closed-form operating current
function opCurrentLambert(V_batt, R) {
  const a = Is * R / (n_ideal * Vt);
  const arg = a * Math.exp((V_batt + Is * R) / (n_ideal * Vt));
  return (n_ideal * Vt / R) * lambertW(arg) - Is;
}
// independent solve: find V in [0, V_batt] with f(V)=Is(e^(V/nVt)-1) - (V_batt-V)/R = 0
function opVoltageBisect(V_batt, R) {
  const f = (V) => diodeI(V) - (V_batt - V) / R;
  let lo = 0, hi = V_batt;                 // f(0) < 0, f(V_batt) > 0
  for (let i = 0; i < 200; i++) {
    const mid = 0.5 * (lo + hi);
    if (f(mid) > 0) hi = mid; else lo = mid;
  }
  return 0.5 * (lo + hi);
}

console.log('\n— operating point: Lambert W closed form vs independent bisection —');
console.log('   R(Ω)     I_lambert(mA)   I_bisect(mA)   V_LED(V)   load-line check');
const Rgrid = [150, 330, 1000, 100, 47, 22, 10, 4.7, 1];
for (const R of Rgrid) {
  const I_lw = opCurrentLambert(V_batt0, R);
  const V_bi = opVoltageBisect(V_batt0, R);
  const I_bi = (V_batt0 - V_bi) / R;       // load line
  const V_lw = V_batt0 - I_lw * R;
  // KVL residual of the Lambert solution: |I·R + V_LED − V_batt|
  const residual = Math.abs(I_lw * R + V_lw - V_batt0);
  console.log(
    `   ${String(R).padStart(5)}   ${(I_lw * 1000).toFixed(4).padStart(11)}` +
    `   ${(I_bi * 1000).toFixed(4).padStart(11)}   ${V_lw.toFixed(4)}   res=${residual.toExponential(1)}`);
  ok(`R=${R}Ω  Lambert == bisection`, approx(I_lw, I_bi, 1e-9 + Math.abs(I_lw) * 1e-7),
     `Δ=${Math.abs(I_lw - I_bi).toExponential(1)} A`);
  ok(`R=${R}Ω  KVL closes on Lambert solution`, residual < 1e-9, `res=${residual.toExponential(1)}`);
}

// the design value lands on (essentially) the 20 mA target:
const I_at_150 = opCurrentLambert(V_batt0, 150);
console.log(`\n  at the designed R = 150 Ω:  I = ${(I_at_150 * 1000).toFixed(3)} mA, V_LED = ${(V_batt0 - I_at_150 * 150).toFixed(3)} V`);
ok('R = 150 Ω gives ≈ 20 mA (within model rounding)', approx(I_at_150 * 1000, 20, 0.6),
   `${(I_at_150 * 1000).toFixed(3)} mA`);

// ── 5. The catastrophe: R → 0 rockets past the 20 mA rating ─────────────────
console.log('\n— the catastrophe: shrinking R drives current past the 20 mA rating —');
const I_RATED_mA = 20;
for (const R of [150, 47, 10, 1]) {
  const I = opCurrentLambert(V_batt0, R) * 1000;
  const factor = I / I_RATED_mA;
  console.log(`  R=${String(R).padStart(4)}Ω → ${I.toFixed(1).padStart(8)} mA  (${factor.toFixed(1)}× the 20 mA rating)${factor > 1 ? '  ⚠ destroyed' : ''}`);
}
const I_1ohm = opCurrentLambert(V_batt0, 1) * 1000;
ok('with R = 1 Ω the current blows past 20 mA by > 50×', I_1ohm > 20 * 50,
   `${I_1ohm.toFixed(0)} mA = ${(I_1ohm / 20).toFixed(0)}× rating`);
// monotone: smaller R ⇒ larger current (load line pivots up the exponential)
let mono = true, prev = 0;
for (const R of [1000, 330, 150, 47, 10, 1]) {
  const I = opCurrentLambert(V_batt0, R);
  if (I <= prev) mono = false;
  prev = I;
}
ok('current is strictly increasing as R shrinks (the load line pivots up)', mono);

// honest bound: the IDEAL-source Shockley model OVERSTATES the destructive current.
// A real supply/wire has series resistance; the diode has bulk resistance Rs; and
// high-injection rolls the exponential off. We state the ideal number AND its bound.
console.log('\n— honesty bound: a real 0.5 Ω of wire/source resistance caps the "R=0" current —');
{
  // add a fixed parasitic series resistance even when the knob R = 0
  const R_parasitic = 0.5;  // representative wire + source internal resistance
  const I_ideal = opCurrentLambert(V_batt0, 0.001) * 1000;       // ~ideal, R≈0
  const I_real  = opCurrentLambert(V_batt0, R_parasitic) * 1000; // with parasitics
  console.log(`  ideal R≈0:   ${I_ideal.toFixed(0)} mA   (model: only the diode + a hair of R limits it)`);
  console.log(`  with 0.5 Ω:  ${I_real.toFixed(0)} mA   (finite — what a real bench actually does)`);
  ok('real parasitic R makes the "R=0" current finite (and far smaller than ideal)',
     I_real < I_ideal && I_real > I_RATED_mA, `${I_real.toFixed(0)} mA vs ideal ${I_ideal.toFixed(0)} mA`);
}

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