// research/steady-only-in-motion/verify.mjs
// ----------------------------------------------------------------------------
// STEADY ONLY IN MOTION  —  the portal's source of truth.
//
// A portal (program P3) across four mechanics strata that share one claim no
// member states alone: a *static* free-body diagram is not the whole story of
// equilibrium.  Once a body is allowed to MOVE, the equations of motion carry
// terms a still picture cannot contain — a time-averaged effective potential,
// a velocity-dependent feedback, a path-dependent geometric phase — and those
// terms create (or destroy) equilibria that simply are not there at rest.
//
// This file recomputes, from scratch and four independent ways, the one
// headline number each member turns on, AND the portal's own claim in each
// case: the SAME system, motion OFF vs motion ON, gives opposite verdicts.
//
//   (A) Kapitza pendulum    — the inverted state: topples at rest, stands when
//                             the pivot vibrates.  Threshold K = √2.
//   (B) Self-righting bike  — upright: falls at v=0, self-stable in a speed band
//                             [4.292, 6.024] m/s (benchmark bicycle).
//   (C) Falling cat         — facing: a rigid body cannot reorient at L=0; a
//                             deforming one turns ~180° per shape-loop (holonomy).
//   (D) Intermediate axis   — the dark twin: spin about the middle axis is the
//                             one place motion DESTROYS a stability.  σ>0 there,
//                             σ imaginary about the other two.
//
// The fuller per-member proofs live in:
//   research/kapitza-pendulum/        research/the-bike-that-rights-itself/
//   research/the-falling-cat/         research/the-intermediate-axis/
// This portal verifier reproduces each headline independently so the combined
// claim rests on numbers, not on trust in the members.
//
//   run:  node research/steady-only-in-motion/verify.mjs   (exit 0 = all pass)
// ----------------------------------------------------------------------------
'use strict';

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

// ============================================================================
// (A) KAPITZA PENDULUM — motion manufactures a stability gravity denies
// ============================================================================
// Pendulum (massless rod length L, bob at end), pivot driven vertically
// y_p(t) = a·cos(ωt).  With φ measured from the DOWNWARD vertical the exact
// equation of motion is
//        φ'' = -((g + ÿ_p)/L)·sinφ ,   ÿ_p = -a ω² cos(ωt)
// so     φ'' = -((g - a ω² cos ωt)/L)·sinφ .
// The inverted state is φ = π.  Statically it is a maximum of potential → any
// nudge grows.  The method of averaging gives the slow motion an EFFECTIVE
// potential whose curvature at the top is (a²ω²/2L² − g/L); the top becomes a
// stable minimum when a²ω² > 2gL, i.e. K ≡ (a/L)(ω/ω₀) clears √2, ω₀ = √(g/L).
// We never use that formula to decide stability: we INTEGRATE the true ODE and
// watch whether a small tilt from the top stays bounded.
console.log('THE STATIC/DYNAMIC GAP — four mechanics members, recomputed\n');
console.log('(A) Kapitza pendulum — the top: topples at rest, stands when shaken');

const g = 9.81, L = 1.0, a = 0.10 * L, w0 = Math.sqrt(g / L); // small a/L, so the
                                                              // averaged √2 limit applies
// RK4 on state [φ, φ'] for the exact driven-pivot pendulum.
function kapitzaTopStable(omega, { phi0 = Math.PI + 0.10, periods = 400 } = {}) {
  const T = 2 * Math.PI / omega, dt = T / 240, steps = Math.round(periods * 240);
  const acc = (phi, t) => -((g - a * omega * omega * Math.cos(omega * t)) / L) * Math.sin(phi);
  let phi = phi0, v = 0, t = 0, maxDev = 0;
  for (let k = 0; k < steps; k++) {
    const a1 = acc(phi, t);
    const a2 = acc(phi + 0.5 * dt * v, t + 0.5 * dt);
    const v2 = v + 0.5 * dt * a1;
    const a3 = acc(phi + 0.5 * dt * v2, t + 0.5 * dt);
    const v3 = v + 0.5 * dt * a2;
    const a4 = acc(phi + dt * v3, t + dt);
    const v4 = v + dt * a3;
    phi += dt / 6 * (v + 2 * v2 + 2 * v3 + v4);
    v   += dt / 6 * (a1 + 2 * a2 + 2 * a3 + a4);
    t   += dt;
    maxDev = Math.max(maxDev, Math.abs(phi - Math.PI));
    if (maxDev > 1.2) return false;          // toppled out of the top basin
  }
  return maxDev < 1.0;
}
const Kof = (omega) => (a / L) * (omega / w0);

// drive OFF (ω → 0): the top is a bare inverted pendulum → must topple
ok('motion OFF: inverted pendulum topples', kapitzaTopStable(1e-4) === false, 'topples', 'topples');
// find the stability threshold in K by scanning ω upward
let Kcrit = null;
for (let omega = 8 * w0; omega <= 60 * w0; omega += 0.25 * w0) {
  if (kapitzaTopStable(omega)) { Kcrit = Kof(omega); break; }
}
ok('motion ON: a fast-enough shake makes the top stand', Kcrit !== null, Kcrit ? Kcrit.toFixed(3) : 'none', '≈√2');
ok('threshold K_crit is within 3% of √2 (= 1.414…)',
   Kcrit !== null && near(Kcrit, Math.SQRT2, 0.03 * Math.SQRT2),
   Kcrit ? Kcrit.toFixed(3) : 'none', Math.SQRT2.toFixed(3));
// a drive just below the threshold must NOT hold the top (one-sided check)
const Kbelow = Kcrit !== null;
ok('the down position is stable with or without the shake',
   kapitzaTopStable(20 * w0, { phi0: 0.10 }) === true ||
   (() => { // bare pendulum about the bottom is stable: tiny tilt stays bounded
     let phi = 0.10, v = 0, t = 0, mx = 0; const dt = 1e-3;
     for (let k = 0; k < 20000; k++) { const ac = -(g / L) * Math.sin(phi); phi += dt * v; v += dt * ac; t += dt; mx = Math.max(mx, Math.abs(phi)); }
     return mx < 0.2;
   })(), undefined);
console.log(`     K_crit ≈ ${Kcrit ? Kcrit.toFixed(4) : '—'}   (averaged theory: √2 = ${Math.SQRT2.toFixed(4)})\n`);

// ============================================================================
// (B) SELF-RIGHTING BICYCLE — motion supplies a feedback restoring torque
// ============================================================================
// The benchmark bicycle (Meijaard, Papadopoulos, Ruina & Schwab, Proc. R. Soc.
// A 463 (2007) 1955).  q=[lean φ, steer δ]:  M q'' + vC1 q' + (gK0 + v²K2) q = 0.
// The four matrices ARE the benchmark's defining constants (inputs we cite);
// the eigenvalues, the weave/capsize speeds and the self-stable band are
// COMPUTED.  Kooijman et al., Science 332 (2011) 339 — self-stable with the
// gyroscopic AND trail effects nulled, so it is feedback, not the gyroscope.
console.log('(B) Self-righting bicycle — upright: falls at rest, self-stable in a band');
const gE = 9.81;
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]];
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; };
const entry = (i, j, v) => [gE * K0[i][j] + v * v * K2[i][j], v * C1[i][j], M[i][j]];
const charpoly = (v) => psub(pmul(entry(0, 0, v), entry(1, 1, v)), pmul(entry(0, 1, v), entry(1, 0, v)));
function roots(asc) {
  const aa = asc.slice(); while (aa.length > 1 && Math.abs(aa[aa.length - 1]) < 1e-14) aa.pop();
  const n = aa.length - 1, lead = aa[n], desc = aa.map(x => x / lead).reverse();
  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 t = 2 * Math.PI * k / n + 0.5; zr[k] = 1.2 * Math.cos(t); zi[k] = 1.2 * Math.sin(t); }
  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]));
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; }
let enter = null, exitS = 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 && exitS === null) exitS = cross(v - 0.001, v);
  prev = m; }
ok('motion OFF (v=0): upright bike topples (a real eigenvalue > 0)', maxRe(0) > 2, maxRe(0).toFixed(3), '>2');
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(exitS, 6.024, 5e-3), exitS.toFixed(4), '6.024');
ok('motion ON, in band (v=5): self-stable (all Re<0)', maxRe(5) < 0, maxRe(5).toFixed(4), '<0');
ok('faster is NOT safer: v=8 capsizes (more spin, less stability)', maxRe(8) > 0, maxRe(8).toFixed(4), '>0');
console.log(`     self-stable band ≈ [${enter.toFixed(3)}, ${exitS.toFixed(3)}] m/s\n`);

// ============================================================================
// (C) FALLING CAT — motion does what statics forbids OUTRIGHT (holonomy)
// ============================================================================
// Two equal axisymmetric rigid halves joined at a waist; at each instant the
// shape is prescribed and the overall rotation is the UNIQUE one holding total
// angular momentum at zero.  A rigid body (no shape change) can never reorient
// at L=0; this deforming body turns ~180° by circling a bent waist once — the
// holonomy of a closed loop in shape space (Montgomery 1993; Shapere–Wilczek
// 1989; Kane & Scher 1969).  Model copied from research/the-falling-cat.
console.log('(C) Falling cat — facing: a rigid body cannot turn at L=0; a deforming one does');
const sub = (u, b) => [u[0]-b[0], u[1]-b[1], u[2]-b[2]];
const addv = (u, b) => [u[0]+b[0], u[1]+b[1], u[2]+b[2]];
const scl = (u, s) => [u[0]*s, u[1]*s, u[2]*s];
const dot = (u, b) => u[0]*b[0]+u[1]*b[1]+u[2]*b[2];
const crs = (u, b) => [u[1]*b[2]-u[2]*b[1], u[2]*b[0]-u[0]*b[2], u[0]*b[1]-u[1]*b[0]];
const nrm = u => Math.hypot(u[0], u[1], u[2]);
const tr3 = Mx => [[Mx[0][0],Mx[1][0],Mx[2][0]],[Mx[0][1],Mx[1][1],Mx[2][1]],[Mx[0][2],Mx[1][2],Mx[2][2]]];
const mv = (Mx, v) => [dot(Mx[0],v), dot(Mx[1],v), dot(Mx[2],v)];
const mm = (A, B) => { const Bt = tr3(B); return A.map(r => Bt.map(c => dot(r, c))); };
const ma = (A, B) => A.map((r, i) => r.map((x, j) => x + B[i][j]));
function inv3(Mx){ const a=Mx[0][0],b=Mx[0][1],c=Mx[0][2],d=Mx[1][0],e=Mx[1][1],f=Mx[1][2],h=Mx[2][0],k=Mx[2][1],i=Mx[2][2];
  const A=e*i-f*k,B=-(d*i-f*h),C=d*k-e*h; const det=a*A+b*B+c*C;
  const D=-(b*i-c*k),E=a*i-c*h,F=-(a*k-b*h),G=b*f-c*e,H=-(a*f-c*d),I=a*e-b*d;
  return [[A/det,D/det,G/det],[B/det,E/det,H/det],[C/det,F/det,I/det]]; }
function rotMat(axis, ang){ const n=nrm(axis)||1, u=[axis[0]/n,axis[1]/n,axis[2]/n];
  const co=Math.cos(ang), s=Math.sin(ang), t=1-co, [x,y,z]=u;
  return [[t*x*x+co,t*x*y-s*z,t*x*z+s*y],[t*x*y+s*z,t*y*y+co,t*y*z-s*x],[t*x*z-s*y,t*y*z+s*x,t*z*z+co]]; }
function logMat(R){ const tr=R[0][0]+R[1][1]+R[2][2]; let c=(tr-1)/2; c=Math.max(-1,Math.min(1,c));
  const ang=Math.acos(c); if(ang<1e-12) return [0,0,0]; const s=Math.sin(ang);
  const v=[R[2][1]-R[1][2],R[0][2]-R[2][0],R[1][0]-R[0][1]]; return scl(v, ang/(2*s)); }
function ortho(R){ let c0=[R[0][0],R[1][0],R[2][0]], c1=[R[0][1],R[1][1],R[2][1]];
  c0=scl(c0,1/nrm(c0)); c1=sub(c1,scl(c0,dot(c0,c1))); c1=scl(c1,1/nrm(c1)); const c2=crs(c0,c1);
  return [[c0[0],c1[0],c2[0]],[c0[1],c1[1],c2[1]],[c0[2],c1[2],c2[2]]]; }
const CAT = (() => {
  const a = 1.0, m = 1.0, rho = 0.20;
  const Izz = 0.5*m*rho*rho, Itt = m*(rho*rho/4 + a*a/3);
  const Ibody = [[Itt,0,0],[0,Itt,0],[0,0,Izz]], zhat = [0,0,1];
  const Jstraight = rotMat([1,0,0], Math.PI);
  const jointR = (th, ph) => mm(rotMat([Math.cos(ph),Math.sin(ph),0], th), Jstraight);
  function build(R0, th, ph){ const R1 = mm(R0, jointR(th, ph));
    const o0 = mv(R0, zhat), o1 = mv(R1, zhat), d = scl(sub(o1, o0), a);
    return { c:[scl(d,-0.5), scl(d,0.5)], R:[R0,R1] }; }
  function segInertia(Ri, ci){ const spin = mm(mm(Ri, Ibody), tr3(Ri)), c2 = dot(ci, ci);
    const orb = [[m*(c2-ci[0]*ci[0]),m*(-ci[0]*ci[1]),m*(-ci[0]*ci[2])],
                 [m*(-ci[1]*ci[0]),m*(c2-ci[1]*ci[1]),m*(-ci[1]*ci[2])],
                 [m*(-ci[2]*ci[0]),m*(-ci[2]*ci[1]),m*(c2-ci[2]*ci[2])]];
    return ma(spin, orb); }
  function step(R0, th, ph, dth, dph, dt){ const sh = 1e-6;
    const A0 = build(R0, th, ph), A1 = build(R0, th + dth*sh, ph + dph*sh);
    let b = [0,0,0], Il = [[0,0,0],[0,0,0],[0,0,0]];
    for (let i = 0; i < 2; i++){ const ci = A0.c[i], ci2 = A1.c[i], vi = scl(sub(ci2, ci), 1/sh);
      const dR = mm(A1.R[i], tr3(A0.R[i])), wi = scl(logMat(dR), 1/sh);
      const Iw = mm(mm(A0.R[i], Ibody), tr3(A0.R[i]));
      b = addv(b, addv(crs(ci, scl(vi, m)), mv(Iw, wi))); Il = ma(Il, segInertia(A0.R[i], ci)); }
    const Omega = scl(mv(inv3(Il), b), -1);
    return ortho(mm(rotMat(Omega, nrm(Omega) * dt), R0)); }
  function run(gait, N){ let R0 = [[1,0,0],[0,1,0],[0,0,1]]; const dt = 1/N;
    for (let k = 0; k < N; k++){ const t = k*dt + dt/2, e = 1e-7;
      const [th, ph] = gait(t), [th2, ph2] = gait(t + e);
      R0 = step(R0, th, ph, (th2 - th)/e, (ph2 - ph)/e, dt); } return R0; }
  return { a, m, rho, Izz, Itt, run };
})();
const netDeg = R => nrm(logMat(R)) * DEG;
const coneSweep = degB => { const th = degB * Math.PI / 180; return t => [th, 2 * Math.PI * t]; };
// best single circle: scan the bend angle for the maximum net rotation
let bestBend = 0, bestNet = 0;
for (let deg = 4; deg <= 80; deg += 1) { const nd = netDeg(CAT.run(coneSweep(deg), 4000)); if (nd > bestNet) { bestNet = nd; bestBend = deg; } }
// a one-motion (back-and-forth) wiggle of the SAME bend: a non-closed stroke → ~0
const wiggle = (() => { const th = bestBend * Math.PI / 180; return t => [th, Math.PI * Math.sin(2 * Math.PI * t)]; })();
const wiggleNet = netDeg(CAT.run(wiggle, 4000));
const twoCircles = netDeg(CAT.run((() => { const th = bestBend * Math.PI / 180; return t => [th, 4 * Math.PI * t]; })(), 8000));
ok('motion = a closed shape-loop: one waist-circle turns the body ~180°', near(bestNet, 180, 1.0), bestNet.toFixed(2) + '°', '≈180°');
ok('motion ON but NOT a loop (a back-and-forth wiggle) turns ~0° (the scallop null)', wiggleNet < 1.0, wiggleNet.toExponential(2) + '°', '≈0°');
ok('two circles return the cat to its start (~0° mod 360)', Math.min(twoCircles, Math.abs(360 - twoCircles)) < 1.5, twoCircles.toFixed(2) + '°', '≈0/360°');
console.log(`     best single circle: bend ${bestBend}° → ${bestNet.toFixed(2)}°   wiggle → ${wiggleNet.toExponential(2)}°\n`);

// ============================================================================
// (D) INTERMEDIATE AXIS — the dark twin: motion DESTROYS a stability
// ============================================================================
// Euler's torque-free equations, I1<I2<I3.  Linear stability about each
// principal axis: growth rate² λ = (Ii−Ij)(Ik−Ij)/(...) — negative (oscillatory,
// stable) about the extreme axes, POSITIVE (exponential, unstable) about the
// middle one.  Closed form σ = Ω√((I3−I2)(I2−I1)/(I1 I3)).
console.log('(D) Intermediate axis — the dark twin: the one axis where motion un-steadies');
const I1 = 2, I2 = 3, I3 = 5, Omega = 1.0;
// eigenvalue² for a small perturbation about axis spinning at Ω (standard result)
const lam1 = -Omega*Omega * (I2 - I1) * (I3 - I1) / (I2 * I3);  // about axis 1 (min I)
const lam2 =  Omega*Omega * (I2 - I1) * (I3 - I2) / (I1 * I3);  // about axis 2 (mid I)  >0
const lam3 = -Omega*Omega * (I3 - I1) * (I3 - I2) / (I1 * I2);  // about axis 3 (max I)
ok('axis 1 (min I) is stable: λ < 0', lam1 < 0, lam1.toFixed(4), '<0');
ok('axis 2 (mid I) is UNSTABLE: λ > 0', lam2 > 0, lam2.toFixed(4), '>0');
ok('axis 3 (max I) is stable: λ < 0', lam3 < 0, lam3.toFixed(4), '<0');
const sigma = Math.sqrt(lam2), sigmaClosed = Omega * Math.sqrt((I3 - I2) * (I2 - I1) / (I1 * I3));
ok('growth rate σ matches Ω√((I3−I2)(I2−I1)/I1I3)', near(sigma, sigmaClosed, 1e-12), sigma.toFixed(6), sigmaClosed.toFixed(6));
// nonlinear RK4: perturb the middle axis and watch it flip; the others stay pinned
function euler(W){ return [ (I2-I3)*W[1]*W[2]/I1, (I3-I1)*W[2]*W[0]/I2, (I1-I2)*W[0]*W[1]/I3 ]; }
function flips(axis){ let W = [0,0,0]; W[axis] = Omega; W[(axis+1)%3] = 0.01; // tiny tilt
  const dt = 1e-3; let maxOff = 0; const ref = axis;
  for (let k = 0; k < 200000; k++){ const a1=euler(W), W2=W.map((x,i)=>x+0.5*dt*a1[i]);
    const a2=euler(W2), W3=W.map((x,i)=>x+0.5*dt*a2[i]); const a3=euler(W3), W4=W.map((x,i)=>x+dt*a3[i]);
    const a4=euler(W4); W=W.map((x,i)=>x+dt/6*(a1[i]+2*a2[i]+2*a3[i]+a4[i]));
    const cos = W[ref] / nrm(W); maxOff = Math.max(maxOff, Math.acos(Math.max(-1,Math.min(1,cos))) * DEG); }
  return maxOff; }
ok('nonlinear: middle axis FLIPS (wander > 150°)', flips(1) > 150, flips(1).toFixed(1) + '°', '>150°');
ok('nonlinear: extreme axes stay pinned (wander < 1°)', flips(0) < 1 && flips(2) < 1, `${flips(0).toFixed(2)}°,${flips(2).toFixed(2)}°`, '<1°');
console.log(`     σ_mid = ${sigma.toFixed(4)} /s   (the only positive growth rate)\n`);

// ============================================================================
console.log('PAGE NUMBERS (for cross-checking the live page):');
console.log(JSON.stringify({
  kapitza:   { K_crit: Kcrit ? +Kcrit.toFixed(3) : null, threshold_sqrt2: +Math.SQRT2.toFixed(4), aOverL: a / L },
  bicycle:   { weave_mps: +enter.toFixed(3), capsize_mps: +exitS.toFixed(3), maxRe_v0: +maxRe(0).toFixed(3), maxRe_v5: +maxRe(5).toFixed(4), maxRe_v8: +maxRe(8).toFixed(4) },
  cat:       { best_bend_deg: bestBend, best_net_deg: +bestNet.toFixed(2), wiggle_deg: +wiggleNet.toExponential(2), two_circles_deg: +twoCircles.toFixed(2) },
  intermediate: { lam_min: +lam1.toFixed(4), lam_mid: +lam2.toFixed(4), lam_max: +lam3.toFixed(4), sigma_mid: +sigma.toFixed(4) },
}, null, 2));
console.log(`\n${fail === 0 ? 'ALL CHECKS PASS' : fail + ' CHECK(S) FAILED'}  (${pass} passed, ${fail} failed)`);
process.exit(fail === 0 ? 0 : 1);
