#!/usr/bin/env node
// verify.mjs — "Why No River Runs Straight" (river meandering)
//
// WHAT THE PAGE CLAIMS, AND WHAT THIS FILE CHECKS
// -----------------------------------------------
// The page settles two things and shows the working for both.
//
//  (1) THE MECHANISM (cited, not computed). A river bend curves because of the
//      same secondary "helical" flow that gathers tea leaves at the centre of a
//      stirred cup: fast surface water is flung to the OUTER bank (it erodes — the
//      cut bank), the slow bed-current sweeps inward to the INNER bank (it deposits
//      — the point bar), so any tiny bend amplifies itself. Einstein wrote this down
//      in 1926. The Coriolis "Baer's law" story is a real effect but orders of
//      magnitude too weak to steer ordinary rivers. These are historical / physical
//      claims, SOURCED in sources.md — this file does not "prove" them.
//
//  (2) THE SELF-ORGANISED SINUOSITY (computed here, recomputed live on the page).
//      The page runs a faithful curvature-driven kinematic meander model (the
//      Ikeda-Parker-Sawai / Howard-Knutson form, as implemented in meanderpy,
//      Sylvester et al. 2019): each centreline node migrates sideways in proportion
//      to an exponentially-weighted sum of the curvature UPSTREAM of it; loops that
//      touch are cut off into oxbows. The model self-organises into a *fluctuating*
//      sinuosity — bend growth pushes it up, cutoffs knock it down — and this file
//      shows three things about that:
//        2a. The model self-organises (mean sinuosity sits in a steady band, well
//            above the straight-line 1.0, with many cutoffs).
//        2b. The steady mean is PARAMETER-DEPENDENT, not a universal constant: make
//            cutoffs happen sooner and the mean drops; let loops grow and it rises.
//            This is the page's record-correction — the famous "rivers' sinuosity is
//            pi (3.14)" (Stolum 1996) is the mean of ONE parameter choice in this
//            same model, not a law of rivers. Real rivers sit far lower (global
//            median ~1.4; the meandering threshold is 1.5).
//        2c. The geometry behind the "pi" claim, checked exactly: a single
//            semicircular bend has sinuosity pi/2 = 1.5708..., NOT pi. Pi only
//            appears from a hand-fitted hierarchical-bend sum (Stolum 1996, note 14).
//
// Deterministic: a seeded PRNG, so every number below is reproducible.
//   Run:  node research/meandering-rivers/verify.mjs
// Exits non-zero if any asserted number drifts.

// ----------------------------- seeded PRNG -----------------------------
function mulberry32(a){return function(){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;};}

// ----------------------------- geometry helpers -----------------------------
function arclen(x,y){let L=0;for(let i=1;i<x.length;i++)L+=Math.hypot(x[i]-x[i-1],y[i]-y[i-1]);return L;}
function sinuosity(x,y){
  const L=arclen(x,y);
  const straight=Math.hypot(x[x.length-1]-x[0], y[y.length-1]-y[0]);
  return L/straight;
}
function curvature(x,y){
  const n=x.length,k=new Array(n).fill(0);
  for(let i=1;i<n-1;i++){
    const dx1=x[i]-x[i-1],dy1=y[i]-y[i-1],dx2=x[i+1]-x[i],dy2=y[i+1]-y[i];
    const a1=Math.atan2(dy1,dx1),a2=Math.atan2(dy2,dx2);
    let da=a2-a1;while(da>Math.PI)da-=2*Math.PI;while(da<-Math.PI)da+=2*Math.PI;
    const ds=(Math.hypot(dx1,dy1)+Math.hypot(dx2,dy2))/2;
    k[i]=da/(ds||1e-9);
  }
  k[0]=k[1];k[n-1]=k[n-2];return k;
}
function resample(x,y,ds){
  const n=x.length,s=[0];
  for(let i=1;i<n;i++)s.push(s[i-1]+Math.hypot(x[i]-x[i-1],y[i]-y[i-1]));
  const L=s[n-1],m=Math.max(2,Math.round(L/ds)),nx=[],ny=[];let j=0;
  for(let i=0;i<=m;i++){
    const target=i/m*L;
    while(j<n-2&&s[j+1]<target)j++;
    const seg=s[j+1]-s[j]||1e-9,t=(target-s[j])/seg;
    nx.push(x[j]+t*(x[j+1]-x[j]));ny.push(y[j]+t*(y[j+1]-y[j]));
  }
  return [nx,ny];
}

// migration rate: omega*local + gamma*(exponentially-weighted upstream curvature)
// (meanderpy form; constants omega=-1, gamma=2.5, alpha=2*Cf/D)
function migrationRate(x,y,curv,P,ds0){
  const n=x.length;
  const R0=curv.map(c=>P.kl*P.W*c);
  const alpha=2*P.Cf/P.D;
  // nodes are uniformly spaced (~ds0) after resample, so the exponential weight
  // decays geometrically: weight at k nodes upstream = decay^k. Compute it
  // incrementally (no Math.exp in the inner loop) and stop after ~5 e-foldings.
  const decay=Math.exp(-alpha*ds0);
  const kmax=Math.min(n,Math.ceil(5/(alpha*ds0)));
  const R1=new Array(n).fill(0);
  for(let i=0;i<n;i++){
    let num=0,den=0,g=1;
    const jlo=Math.max(0,i-kmax);
    for(let j=i;j>=jlo;j--){num+=g*R0[j];den+=g;g*=decay;}
    R1[i]=den>0?num/den:0;
  }
  const omega=-1.0,gamma=2.5;
  return R0.map((r,i)=>omega*r+gamma*R1[i]);
}

// neck cutoff: non-adjacent nodes within cutDist -> excise the loop between them
function doCutoffs(x,y,cutDist,minSep){
  let count=0;
  for(let i=0;i<x.length;i++){
    for(let j=i+minSep;j<x.length;j++){
      if(Math.hypot(x[i]-x[j],y[i]-y[j])<cutDist){
        x.splice(i+1,j-i-1);y.splice(i+1,j-i-1);count++;break; // continue from i
      }
    }
  }
  return count;
}

// ----------------------------- the simulation -----------------------------
function run(P){
  const rng=mulberry32(P.seed);
  const ds0=P.W*0.5;
  let x=[],y=[];
  for(let i=0;i<P.N0;i++){x.push(i*ds0);y.push((rng()-0.5)*0.6+0.8*Math.sin(i*2*Math.PI/40));}
  const minSep=Math.ceil((P.cutDist*1.0+8*P.W)/ds0);
  const hist=[];let cutoffs=0;
  for(let step=0;step<P.steps;step++){
    const curv=curvature(x,y);
    const R=migrationRate(x,y,curv,P,ds0);
    const n=x.length,nx=x.slice(),ny=y.slice();
    for(let i=1;i<n-1;i++){
      const tx=x[i+1]-x[i-1],ty=y[i+1]-y[i-1],tl=Math.hypot(tx,ty)||1e-9;
      nx[i]=x[i]+R[i]*P.dt*(-ty/tl);
      ny[i]=y[i]+R[i]*P.dt*(tx/tl);
    }
    x=nx;y=ny;
    [x,y]=resample(x,y,ds0);
    cutoffs+=doCutoffs(x,y,P.cutDist,minSep);
    if(step>=P.burn&&step%P.sample===0)hist.push(sinuosity(x,y));
  }
  const mean=hist.reduce((a,b)=>a+b,0)/hist.length;
  return {mean,min:Math.min(...hist),max:Math.max(...hist),cutoffs,samples:hist.length,nodes:x.length};
}

// base parameters (meanderpy-style: Cf=0.011, D=6, W width units, kl erodibility)
const BASE={seed:12345,W:10,Cf:0.011,D:6,kl:20,dt:0.02,N0:380,steps:3000,burn:1000,sample:25,cutDist:12};

// ----------------------------- run + assertions -----------------------------
let fails=0;
const A=(name,cond,got)=>{const ok=!!cond;console.log(`  ${ok?'✓':'✗'} ${name}${got!==undefined?'  ('+got+')':''}`);if(!ok)fails++;return ok;};
const round=(v,d=3)=>Number(v.toFixed(d));

console.log('\nWHY NO RIVER RUNS STRAIGHT — verify.mjs\n');

// --- 2c. geometry behind the "pi" claim, checked exactly ---
console.log('Geometry of a single bend (the root of the "pi" story):');
{
  // a discretised semicircle: channel length pi*r, valley (chord) length 2*r
  const r=100,seg=2000,sx=[],sy=[];
  for(let i=0;i<=seg;i++){const th=Math.PI*i/seg;sx.push(r*Math.cos(th));sy.push(r*Math.sin(th));}
  const semi=sinuosity(sx,sy);
  A('a semicircular bend has sinuosity pi/2 = 1.5708 (NOT pi)', Math.abs(semi-Math.PI/2)<1e-3, round(semi,4));
  A('pi/2 is below pi and even below Stolum\'s 3.14', Math.PI/2 < 3.14, round(Math.PI/2,4));
}

// --- 2a. the model self-organises ---
console.log('\nSelf-organisation of the kinematic model (seed '+BASE.seed+'):');
const base=run(BASE);
console.log(`    mean=${round(base.mean)}  band=[${round(base.min)}, ${round(base.max)}]  cutoffs=${base.cutoffs}  samples=${base.samples}`);
A('mean sinuosity self-organises into a steady meandering band (>1.5)', base.mean>1.5&&base.mean<3.0, round(base.mean));
A('it genuinely fluctuates (min well below mean, max well above)', base.min<base.mean-0.15&&base.max>base.mean+0.1, `[${round(base.min)},${round(base.max)}]`);
A('neck cutoffs keep firing in the thousands (guards the page\'s "4,531")', base.cutoffs>2000&&base.cutoffs<8000, base.cutoffs);
A('the self-organised mean is NOT pi (3.14): it sits clearly below', Math.PI-base.mean>0.6, `pi - ${round(base.mean)} = ${round(Math.PI-base.mean,2)}`);

// --- 2b. the steady mean is parameter-dependent (the record-correction) ---
console.log('\nThe steady mean shifts with the cutoff dial alone (so 3.14 is no constant):');
const early=run({...BASE,cutDist:16});   // cut sooner -> shorter loops -> lower sinuosity
const late =run({...BASE,cutDist:9});    // let loops grow -> higher sinuosity
console.log(`    cut-sooner (1.6W): mean=${round(early.mean)} | base (1.2W): ${round(base.mean)} | let-grow (0.9W): mean=${round(late.mean)}`);
A('cutting sooner LOWERS the self-organised mean', early.mean<base.mean, `${round(early.mean)} < ${round(base.mean)}`);
A('letting loops grow RAISES it', late.mean>base.mean, `${round(late.mean)} > ${round(base.mean)}`);
A('the mean is a tunable parameter, not a universal pi', (late.mean-early.mean)>0.2, `spread ${round(late.mean-early.mean)}`);
A('every regime stays below Stolum\'s 3.14 AND above real rivers\' ~1.4', early.mean>1.4&&late.mean<3.14, `${round(early.mean)}..${round(late.mean)}`);

// --- determinism check: same seed -> same number ---
console.log('\nDeterminism:');
const rerun=run(BASE);
A('a second run with the same seed reproduces the mean exactly', Math.abs(rerun.mean-base.mean)<1e-12, round(rerun.mean,6));

// ----------------------------- the numbers the page prints -----------------------------
console.log('\nNUMBERS THE PAGE QUOTES (keep page text in sync with these):');
console.log(`    self-organised mean sinuosity ........ ${round(base.mean,2)}`);
console.log(`    fluctuation band ..................... ${round(base.min,2)} to ${round(base.max,2)}`);
console.log(`    oxbow cutoffs over the run ........... ${base.cutoffs}`);
console.log(`    cut-sooner / base / let-grow mean .... ${round(early.mean,2)} / ${round(base.mean,2)} / ${round(late.mean,2)}`);
console.log(`    semicircle sinuosity (exact) ......... ${round(Math.PI/2,4)} (= pi/2)`);
console.log(`    Stolum 1996 reported mean ............ 3.14 +/- 0.34  (his free-meandering params; cited)`);
console.log(`    real-river global median (cited) ..... ~1.4 ; meandering threshold 1.5`);

console.log('\n'+(fails?`FAIL — ${fails} assertion(s) drifted.`:'ALL GREEN.')+'\n');
process.exit(fails?1:0);
