// research/the-bike-that-rights-itself/verify.mjs
// ----------------------------------------------------------------------------
// Reproduce the canonical self-stability result of the benchmark bicycle.
//
//   Meijaard, Papadopoulos, Ruina & Schwab (2007),
//   "Linearized dynamics equations for the balance and steer of a bicycle:
//    a benchmark and review," Proc. R. Soc. A 463:1955–1982.
//   Kooijman, Meijaard, Papadopoulos, Ruina & Schwab (2011),
//   "A bicycle can be self-stable without gyroscopic or caster effects,"
//    Science 332:339–342.
//
// The four constant matrices below ARE the benchmark's defining constants
// (Table 1 / Appendix of the 2007 paper) — they are INPUTS we cite, not
// outputs we claim. Everything else (eigenvalues, the weave and capsize
// speeds, the self-stable window) is COMPUTED here from scratch and checked
// against the paper's published numbers.
//
//   run:  node research/the-bike-that-rights-itself/verify.mjs
// ----------------------------------------------------------------------------
'use strict';

const g = 9.81;

// q = [phi (lean), delta (steer)]^T ;  M q'' + v C1 q' + (g K0 + v^2 K2) q = 0
const M  = [[80.81722,            2.31941332208709 ],
            [ 2.31941332208709,   0.29784188199686 ]];
const C1 = [[ 0,                 33.86641391492494 ],
            [-0.85035641456978,   1.68540397397560 ]];
const K0 = [[-80.95,             -2.59951685249872 ],
            [-2.59951685249872,  -0.80329488458618 ]];
const K2 = [[ 0,                 76.59734589573222 ],
            [ 0,                  2.65431523794604 ]];

// ---- polynomial helpers (coeffs ascending in lambda) -----------------------
const pmul = (p, q) => { const r = Array(p.length + q.length - 1).fill(0);
  for (let i = 0; i < p.length; i++) for (let j = 0; j < q.length; j++) r[i + j] += p[i] * q[j];
  return r; };
const psub = (p, q) => { const n = Math.max(p.length, q.length), r = Array(n).fill(0);
  for (let i = 0; i < n; i++) r[i] = (p[i] || 0) - (q[i] || 0); return r; };

// each matrix entry is a quadratic in lambda:  M*l^2 + v*C1*l + (g*K0 + v^2*K2)
const entry = (i, j, v) => [g * K0[i][j] + v * v * K2[i][j], v * C1[i][j], M[i][j]];

// characteristic quartic = det( M l^2 + v C1 l + K )
const charpoly = (v) => psub(
  pmul(entry(0, 0, v), entry(1, 1, v)),
  pmul(entry(0, 1, v), entry(1, 0, v)),
);

// ---- Durand–Kerner: roots of a real-coeff polynomial (complex allowed) -----
function roots(asc) {
  const a = asc.slice();
  while (a.length > 1 && Math.abs(a[a.length - 1]) < 1e-14) a.pop();
  const n = a.length - 1, lead = a[n];
  const desc = a.map(x => x / lead).reverse();             // monic, descending
  const ev = (zr, zi) => { let r = desc[0], i = 0;
    for (let k = 1; k < desc.length; k++) { const nr = r * zr - i * zi + desc[k]; i = r * zi + i * zr; r = nr; }
    return [r, i]; };
  const zr = Array(n), zi = Array(n);
  for (let k = 0; k < n; k++) { const a0 = 2 * Math.PI * k / n + 0.5; zr[k] = 1.2 * Math.cos(a0); zi[k] = 1.2 * Math.sin(a0); }
  for (let it = 0; it < 5000; it++) { let mx = 0;
    for (let k = 0; k < n; k++) { const [fr, fi] = ev(zr[k], zi[k]); let dr = 1, di = 0;
      for (let j = 0; j < n; j++) { if (j === k) continue; const xr = zr[k] - zr[j], xi = zi[k] - zi[j];
        const nr = dr * xr - di * xi; di = dr * xi + di * xr; dr = nr; }
      const den = dr * dr + di * di, qr = (fr * dr + fi * di) / den, qi = (fi * dr - fr * di) / den;
      zr[k] -= qr; zi[k] -= qi; mx = Math.max(mx, Math.hypot(qr, qi)); }
    if (mx < 1e-13) break; }
  return zr.map((r, k) => [r, zi[k]]);
}
const maxRe = (v) => Math.max(...roots(charpoly(v)).map(z => z[0]));

// bisection on a sign change of maxRe(v)
function cross(lo, hi) { let flo = maxRe(lo);
  for (let i = 0; i < 200; i++) { const m = (lo + hi) / 2, fm = maxRe(m);
    if (Math.sign(fm) === Math.sign(flo)) { lo = m; flo = fm; } else hi = m; }
  return (lo + hi) / 2; }

// ---- find the self-stable window (maxRe < 0) -------------------------------
let enter = null, exit = null, prev = maxRe(0);
for (let v = 0.001; v <= 10.0001; v += 0.001) { const m = maxRe(v);
  if (prev >= 0 && m < 0 && enter === null) enter = cross(v - 0.001, v);
  if (prev < 0 && m >= 0 && enter !== null && exit === null) exit = cross(v - 0.001, v);
  prev = m; }

// ---- assertions ------------------------------------------------------------
let fails = 0;
const ok = (name, cond, got, want) => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${got !== undefined ? `   got ${got}  want ${want}` : ''}`);
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;

console.log('Benchmark bicycle — computed self-stability\n');

// published weave speed v_w = 4.292 m/s, capsize speed v_c = 6.024 m/s
ok('weave speed reproduces 4.292 m/s',  near(enter, 4.292, 5e-3), enter.toFixed(4), '4.292');
ok('capsize speed reproduces 6.024 m/s', near(exit, 6.024, 5e-3), exit.toFixed(4), '6.024');
ok('window is exactly [weave, capsize]', enter < exit && exit - enter > 1, `${enter.toFixed(3)}..${exit.toFixed(3)}`, '~4.29..6.02');

// at v = 0 (pure inverted-pendulum), all motion diverges: two real ± pairs
const r0 = roots(charpoly(0)).map(z => z[0]).sort((a, b) => a - b);
ok('v=0 has a positive (toppling) real root', r0[r0.length - 1] > 2, r0[r0.length - 1].toFixed(4), '>2');
ok('v=0 eigenvalues are real (Im≈0)', roots(charpoly(0)).every(z => Math.abs(z[1]) < 1e-6), 'all real', 'all real');

// inside the window every eigenvalue decays
ok('v=5.0 m/s is self-stable (all Re<0)', maxRe(5.0) < 0, maxRe(5.0).toFixed(4), '<0');
// the gyroscope-myth point, made numeric: MORE speed past 6.024 DESTABILISES
ok('v=8.0 m/s is unstable (capsizes)', maxRe(8.0) > 0, maxRe(8.0).toFixed(4), '>0');
ok('faster is not safer: maxRe(8) > maxRe(5)', maxRe(8.0) > maxRe(5.0), undefined);

// weave onset is an oscillatory (Hopf-like) crossing: Im ≠ 0 at v_w
const rw = roots(charpoly(enter));
ok('weave crossing is oscillatory (Im≠0)', rw.some(z => Math.abs(z[0]) < 1e-2 && Math.abs(z[1]) > 1), undefined);
// capsize is a real (monotonic) crossing: a near-zero real root at v_c
const rc = roots(charpoly(exit));
ok('capsize crossing is monotonic (a real root ≈ 0)', rc.some(z => Math.abs(z[0]) < 1e-2 && Math.abs(z[1]) < 1e-3), undefined);

// ---------------------------------------------------------------------------
// GYROSCOPE DECOMPOSITION — assemble the four matrices from the physical
// parameters (Meijaard 2007, Table 1 + Appendix A) and verify: (a) at gamma=1
// they reproduce the published matrices above to 14 digits; (b) a scalar gamma
// on the wheel-spin momenta S_R,S_F,S_T moves exactly the four gyroscopic
// entries; (c) the self-stable window responds as the immersive page claims.
// ---------------------------------------------------------------------------
{
  const lam = Math.PI/10, wb = 1.02, tr = 0.08, sinL = Math.sin(lam), cosL = Math.cos(lam);
  const bR={m:2,x:0,z:-0.3,Ixx:0.0603,Ixz:0,Iyy:0.12,Izz:0.0603};
  const bB={m:85,x:0.3,z:-0.9,Ixx:9.2,Ixz:2.4,Iyy:11,Izz:2.8};
  const bH={m:4,x:0.9,z:-0.7,Ixx:0.05892,Ixz:-0.00756,Iyy:0.06,Izz:0.00708};
  const bF={m:3,x:1.02,z:-0.35,Ixx:0.1405,Ixz:0,Iyy:0.28,Izz:0.1405};
  const rR=0.3, rF=0.35, all=[bR,bB,bH,bF], sm=f=>all.reduce((a,b)=>a+f(b),0);
  const mT=sm(b=>b.m), xT=sm(b=>b.m*b.x)/mT, zT=sm(b=>b.m*b.z)/mT;
  const ITxx=sm(b=>b.Ixx+b.m*b.z*b.z), ITxz=sm(b=>b.Ixz-b.m*b.x*b.z), ITzz=sm(b=>b.Izz+b.m*b.x*b.x);
  const mA=bH.m+bF.m, xA=(bH.m*bH.x+bF.m*bF.x)/mA, zA=(bH.m*bH.z+bF.m*bF.z)/mA;
  const sA=f=>f(bH)+f(bF);
  const IAxx=sA(b=>b.Ixx+b.m*(b.z-zA)**2), IAxz=sA(b=>b.Ixz-b.m*(b.x-xA)*(b.z-zA)), IAzz=sA(b=>b.Izz+b.m*(b.x-xA)**2);
  const uA=(xA-wb-tr)*cosL-zA*sinL;
  const IAll=mA*uA*uA+IAxx*sinL*sinL+2*IAxz*sinL*cosL+IAzz*cosL*cosL;
  const IAlx=-mA*uA*zA+IAxx*sinL+IAxz*cosL, IAlz=mA*uA*xA+IAxz*sinL+IAzz*cosL;
  const mu=(tr/wb)*cosL, SR=bR.Iyy/rR, SF=bF.Iyy/rF, ST=SR+SF, SAc=mA*uA+mu*mT*xT;
  const mats=(gm)=>{ const gST=gm*ST, gSF=gm*SF;
    return { M:[[ITxx,IAlx+mu*ITxz],[IAlx+mu*ITxz,IAll+2*mu*IAlz+mu*mu*ITzz]],
      K0:[[mT*zT,-SAc],[-SAc,-SAc*sinL]],
      C1:[[0,mu*gST+gSF*cosL+(ITxz/wb)*cosL-mu*mT*zT],[-(mu*gST+gSF*cosL),(IAlz/wb)*cosL+mu*(SAc+(ITzz/wb)*cosL)]],
      K2:[[0,((gST-mT*zT)/wb)*cosL],[0,((SAc+gSF*sinL)/wb)*cosL]] }; };
  const emax=(P,Q)=>Math.max(Math.abs(P[0][0]-Q[0][0]),Math.abs(P[0][1]-Q[0][1]),Math.abs(P[1][0]-Q[1][0]),Math.abs(P[1][1]-Q[1][1]));
  const R1=mats(1), R0=mats(0);
  ok('assembled M reproduces published (14 digits)',  emax(R1.M,M)<1e-9,  emax(R1.M,M).toExponential(2), '<1e-9');
  ok('assembled C1 reproduces published (14 digits)', emax(R1.C1,C1)<1e-9, emax(R1.C1,C1).toExponential(2), '<1e-9');
  ok('assembled K0 reproduces published (14 digits)', emax(R1.K0,K0)<1e-9, emax(R1.K0,K0).toExponential(2), '<1e-9');
  ok('assembled K2 reproduces published (14 digits)', emax(R1.K2,K2)<1e-9, emax(R1.K2,K2).toExponential(2), '<1e-9');
  ok('spin momenta S_R=0.4, S_F=0.8 (I_yy/r)', near(SR,0.4,1e-12)&&near(SF,0.8,1e-12), `${SR},${SF}`, '0.4,0.8');
  ok('gamma=0 leaves M unchanged (mass — gyro-free)', emax(R0.M,R1.M)<1e-12, undefined);
  ok('gamma=0 leaves K0 unchanged (gravity — gyro-free)', emax(R0.K0,R1.K0)<1e-12, undefined);
  ok('gamma zeroes C1[1][0] (fully gyroscopic)', Math.abs(R0.C1[1][0])<1e-12, R0.C1[1][0].toExponential(2), '0');
  ok('C1[1][1] is NOT gyroscopic (its S_A is static)', Math.abs(R0.C1[1][1]-R1.C1[1][1])<1e-12, undefined);
  const cpoly=(v,MM)=>{ const e=(i,j)=>[g*MM.K0[i][j]+v*v*MM.K2[i][j], v*MM.C1[i][j], MM.M[i][j]];
    return psub(pmul(e(0,0),e(1,1)), pmul(e(0,1),e(1,0))); };
  const mre=(v,MM)=>Math.max(...roots(cpoly(v,MM)).map(z=>z[0]));
  const win=(gm)=>{ const MM=mats(gm); let en=null,ex=null,pv=mre(0,MM);
    const cr=(lo,hi)=>{let fl=mre(lo,MM);for(let i=0;i<80;i++){const m=(lo+hi)/2,fm=mre(m,MM);if((fm<0)===(fl<0)){lo=m;fl=fm;}else hi=m;}return(lo+hi)/2;};
    for(let v=0.01;v<=14;v+=0.01){const m=mre(v,MM); if(pv>=0&&m<0&&en===null)en=cr(v-0.01,v); if(pv<0&&m>=0&&en!==null&&ex===null)ex=cr(v-0.01,v); pv=m;} return {en,ex}; };
  const w1=win(1), w0=win(0), wLo=win(0.5), wHi=win(1.5);
  ok('gamma=1 window is [4.292, 6.024]', near(w1.en,4.292,5e-3)&&near(w1.ex,6.024,5e-3), `${w1.en.toFixed(3)}..${w1.ex.toFixed(3)}`, '4.292..6.024');
  ok('gamma=0: NO self-stable window (gyroscope removed)', w0.en===null, `${w0.en}`, 'null');
  ok('gamma=0: unstable at EVERY speed to 40 m/s', (()=>{const MM=mats(0);for(let v=0.1;v<=40;v+=0.1)if(mre(v,MM)<0)return false;return true;})(), undefined);
  ok('more gyro shifts window DOWN (v_weave falls with gamma)', wHi.en<w1.en&&w1.en<wLo.en, `${wHi.en.toFixed(2)}<${w1.en.toFixed(2)}<${wLo.en.toFixed(2)}`, 'monotone');
  ok('more gyro NARROWS the window', (wHi.ex-wHi.en)<(w1.ex-w1.en)&&(w1.ex-w1.en)<(wLo.ex-wLo.en), `${(wHi.ex-wHi.en).toFixed(2)}<${(w1.ex-w1.en).toFixed(2)}<${(wLo.ex-wLo.en).toFixed(2)}`, 'monotone');
}

console.log('\nSample spectra (real ± imag i):');
for (const v of [0, 3, +enter.toFixed(3), 5, +exit.toFixed(3), 8]) {
  const s = roots(charpoly(v)).map(z => `${z[0] >= 0 ? ' ' : ''}${z[0].toFixed(3)}${z[1] >= 0 ? '+' : '-'}${Math.abs(z[1]).toFixed(3)}i`).join('   ');
  console.log(`  v=${String(v).padEnd(6)} ${s}`);
}

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