// verify.mjs — recompute, from scratch, the summary statistics of Anscombe's
// quartet (1973) and the Datasaurus Dozen (Matejka & Fitzmaurice 2017), and
// assert that the famous claim holds: within each collection the datasets share
// their summary statistics to the stated precision while their shapes differ.
//
//   node research/anscombes-quartet/verify.mjs
//
// Anscombe's numbers are computed in EXACT rational (BigInt) arithmetic: the
// x-values are integers and the y-values have exactly two decimals, so every
// mean / variance / covariance / regression coefficient is an exact rational and
// is printed as such. Only the correlation (a square root) is irrational; we give
// its exact square and the decimal. The Datasaurus is high-precision float data,
// recomputed in IEEE-754 doubles and checked to two decimals (the paper's claim).
//
// Sources:
//   Anscombe, F. J. (1973). "Graphs in Statistical Analysis." The American
//     Statistician 27(1): 17–21. (The four datasets, Table, p. 19.)
//   Matejka, J. & Fitzmaurice, G. (2017). "Same Stats, Different Graphs: …"
//     Proc. CHI 2017. Data via the datasauRus R package (jumpingrivers, MIT),
//     inst/extdata/DatasaurusDozen-Long.tsv. The Datasaurus drawing: Alberto Cairo.

import { readFileSync, writeFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const HERE = dirname(fileURLToPath(import.meta.url));

let fails = 0;
const ok  = (name, cond, extra='') => { console.log((cond?'  ok   ':'  FAIL ')+name+(extra?'  '+extra:'')); if(!cond) fails++; };
const sec = (s) => console.log('\n=== '+s+' ===');

/* ───────────────────────── exact rational (BigInt) ───────────────────────── */
const gcd = (a,b)=>{ a=a<0n?-a:a; b=b<0n?-b:b; while(b){ [a,b]=[b,a%b]; } return a; };
class Q {
  constructor(n, d=1n){ if(d<0n){n=-n;d=-d;} const g=gcd(n,d)||1n; this.n=n/g; this.d=d/g; }
  add(o){ return new Q(this.n*o.d + o.n*this.d, this.d*o.d); }
  sub(o){ return new Q(this.n*o.d - o.n*this.d, this.d*o.d); }
  mul(o){ return new Q(this.n*o.n, this.d*o.d); }
  div(o){ return new Q(this.n*o.d, this.d*o.n); }
  toNumber(){ return Number(this.n)/Number(this.d); }
  toString(){ return this.d===1n ? `${this.n}` : `${this.n}/${this.d}`; }
}
const Qi = (n)=> new Q(BigInt(n));

/* exact stats over integer-scaled samples.  xs are integers; ys are integers ==
   real_y * 100 (two decimals).  Returns rationals in real (unscaled) units.    */
function exactStats(xsInt, ysIntScaled, yScale=100n){
  const n = BigInt(xsInt.length);
  const xs = xsInt.map(BigInt), ys = ysIntScaled.map(BigInt);
  const Y = new Q(yScale,1n);                 // divide y-sums by this to unscale
  let Sx=0n,Sy=0n,Sxx=0n,Syy=0n,Sxy=0n;
  for(let i=0;i<xs.length;i++){ Sx+=xs[i]; Sy+=ys[i]; Sxx+=xs[i]*xs[i]; Syy+=ys[i]*ys[i]; Sxy+=xs[i]*ys[i]; }
  const meanX = new Q(Sx,n);
  const meanY = new Q(Sy,n).div(Y);
  // sample (n-1) variance: (n*Sxx - Sx^2) / (n*(n-1))
  const varX = new Q(n*Sxx - Sx*Sx, n*(n-1n));
  const varY = new Q(n*Syy - Sy*Sy, n*(n-1n)).div(Y).div(Y);
  const covXY= new Q(n*Sxy - Sx*Sy, n*(n-1n)).div(Y);
  const slope = new Q(n*Sxy - Sx*Sy, n*Sxx - Sx*Sx).div(Y);   // cov/varX, y unscaled
  const intercept = meanY.sub(slope.mul(meanX));
  // correlation^2 = covXY^2 / (varX*varY) — exact rational; r = sqrt
  const r2 = covXY.mul(covXY).div(varX.mul(varY));
  const r  = Math.sqrt(r2.toNumber());
  return { n:xsInt.length, meanX, meanY, varX, varY, covXY, slope, intercept, r2, r };
}

/* ───────────────────────────── Anscombe's quartet ────────────────────────── */
// Anscombe (1973), Table on p. 19.  x123 shared by I,II,III; x4 for IV.
const x123 = [10,8,13,9,11,14,6,4,12,7,5];
const x4   = [8,8,8,8,8,8,8,19,8,8,8];
// y given to two decimals → store as integer hundredths (exact).
const yI   = [804,695,758,881,833,996,724,426,1084,482,568];
const yII  = [914,814,874,877,926,810,613,310,913,726,474];
const yIII = [746,677,1274,711,781,884,608,539,815,642,573];
const yIV  = [658,576,771,884,847,704,525,1250,556,791,689];

const quartet = [
  { id:'I',   x:x123, y:yI },
  { id:'II',  x:x123, y:yII },
  { id:'III', x:x123, y:yIII },
  { id:'IV',  x:x4,   y:yIV },
];

sec('Anscombe\'s quartet — exact recomputation (rational arithmetic)');
const Astats = quartet.map(d => ({ id:d.id, s:exactStats(d.x, d.y) }));
for(const {id,s} of Astats){
  console.log(`  [${id}]  mean(x)=${s.meanX}  var(x)=${s.varX}  mean(y)=${s.meanY} (${s.meanY.toNumber().toFixed(6)})`);
  console.log(`        var(y)=${s.varY} (${s.varY.toNumber().toFixed(6)})  cov=${s.covXY.toNumber().toFixed(6)}`);
  console.log(`        slope=${s.slope} (${s.slope.toNumber().toFixed(6)})  intercept=${s.intercept} (${s.intercept.toNumber().toFixed(6)})  r=${s.r.toFixed(6)}  r^2=${s.r2.toNumber().toFixed(6)}`);
}

sec('Anscombe — the claim: identical to the precision Anscombe stated');
// mean(x)=9 and var(x)=11 are claimed EXACT; the page must not overstate the rest.
for(const {id,s} of Astats){
  ok(`[${id}] mean(x) == 9 exactly`, s.meanX.n===9n && s.meanX.d===1n);
  ok(`[${id}] var(x)  == 11 exactly`, s.varX.n===11n && s.varX.d===1n);
}
// mean(y), slope, intercept agree to 2 dp; correlation to 3 sig figs; var(y) to ~4.12–4.13.
const round2 = (q)=> Math.round((q.toNumber?q.toNumber():q)*100)/100;
const rng = (arr)=>{const v=arr.map(x=>x.toNumber?x.toNumber():x);return Math.max(...v)-Math.min(...v);};
const meanY2 = Astats.map(a=>round2(a.s.meanY));
const slope2 = Astats.map(a=>round2(a.s.slope));
const int2   = Astats.map(a=>round2(a.s.intercept));
ok('mean(y) equal to 2 dp across I–IV (= 7.50)', new Set(meanY2).size===1 && meanY2[0]===7.50, JSON.stringify(meanY2));
ok('slope   equal to 2 dp across I–IV (= 0.50)', new Set(slope2).size===1 && slope2[0]===0.50, JSON.stringify(slope2));
ok('intercept equal to 2 dp across I–IV (= 3.00)', new Set(int2).size===1 && int2[0]===3.00,  JSON.stringify(int2));
// correlation: 0.8162–0.8165 — agree to 3 significant figures (~0.816), spread < 0.001.
ok('correlation agrees to 3 sig figs (spread < 0.001, ~0.816)', rng(Astats.map(a=>a.s.r))<0.001, 'spread='+rng(Astats.map(a=>a.s.r)).toExponential(2));
// var(y): 4.1226–4.1276 — agree to within 0.005 (~4.12–4.13), NOT to 2 dp.
ok('var(y) agrees to within 0.01 (~4.12–4.13)', rng(Astats.map(a=>a.s.varY))<0.01, 'spread='+rng(Astats.map(a=>a.s.varY)).toFixed(4));
// Honesty, made checkable: they are NOT bit-identical, and var(y)/corr are NOT
// equal at 2 dp — the page must say "to the precision Anscombe reported", not "identical".
const varY2set = new Set(Astats.map(a=>round2(a.s.varY)));
ok('var(y) is NOT identical at 2 dp (splits 4.12/4.13) — page must not overstate', varY2set.size>1, [...varY2set].join(','));
ok('mean(y) NOT bit-identical (spread > 0)', rng(Astats.map(a=>a.s.meanY))>0, 'spread='+rng(Astats.map(a=>a.s.meanY)).toExponential(2));

// The four shapes are genuinely different — prove with a shape statistic the
// summaries miss. II is an exact parabola; quantify curvature by fitting y=a+bx+cx^2
// and showing c is ~0 for I but large for II.  (Least squares via normal eqns.)
sec('Anscombe — the shapes differ (a statistic the summaries cannot see)');
function quadFit(xs,ys){ // returns c (the x^2 coefficient) via 3x3 normal equations
  const n=xs.length; let S0=n,S1=0,S2=0,S3=0,S4=0,T0=0,T1=0,T2=0;
  for(let i=0;i<n;i++){const x=xs[i],y=ys[i]/100;S1+=x;S2+=x*x;S3+=x*x*x;S4+=x*x*x*x;T0+=y;T1+=x*y;T2+=x*x*y;}
  // solve [[S0,S1,S2],[S1,S2,S3],[S2,S3,S4]] [a,b,c]^T = [T0,T1,T2]^T
  const A=[[S0,S1,S2,T0],[S1,S2,S3,T1],[S2,S3,S4,T2]];
  for(let i=0;i<3;i++){ let p=i; for(let k=i+1;k<3;k++) if(Math.abs(A[k][i])>Math.abs(A[p][i]))p=k; [A[i],A[p]]=[A[p],A[i]];
    for(let k=0;k<3;k++){ if(k===i)continue; const f=A[k][i]/A[i][i]; for(let j=i;j<4;j++)A[k][j]-=f*A[i][j]; } }
  return A[2][3]/A[2][2]; // c
}
const cI  = quadFit(x123,yI), cII = quadFit(x123,yII), cIII=quadFit(x123,yIII), cIV=quadFit(x4,yIV);
console.log(`  quadratic x^2 coefficient:  I=${cI.toFixed(4)}  II=${cII.toFixed(4)}  III=${cIII.toFixed(4)}  IV=${cIV.toFixed(4)}`);
ok('II is the curved one: a clean parabola the line cannot see (|c|>0.1)', Math.abs(cII)>0.1, 'c_II='+cII.toFixed(4));
ok('II is markedly more curved than I and III (≥3×)', Math.abs(cII) >= 3*Math.max(Math.abs(cI),Math.abs(cIII)), `|c_II|=${Math.abs(cII).toFixed(4)} vs |c_I|=${Math.abs(cI).toFixed(4)}, |c_III|=${Math.abs(cIII).toFixed(4)}`);
// III: one outlier. Remove the largest |residual| point and refit; slope should jump.
function lineFit(xs,ys){const n=xs.length;let sx=0,sy=0,sxx=0,sxy=0;for(let i=0;i<n;i++){sx+=xs[i];sy+=ys[i]/100;sxx+=xs[i]*xs[i];sxy+=xs[i]*ys[i]/100;}const b=(n*sxy-sx*sy)/(n*sxx-sx*sx);return {b,a:(sy-b*sx)/n};}
const fIII=lineFit(x123,yIII);
let worst=-1,wr=-1; for(let i=0;i<x123.length;i++){const r=Math.abs(yIII[i]/100-(fIII.a+fIII.b*x123[i])); if(r>wr){wr=r;worst=i;}}
const x3b=x123.filter((_,i)=>i!==worst), y3b=yIII.filter((_,i)=>i!==worst);
const fIIIb=lineFit(x3b,y3b);
console.log(`  III slope with all 11 pts = ${fIII.b.toFixed(4)}; drop the lone outlier (pt ${worst+1}) → slope = ${fIIIb.b.toFixed(4)}`);
ok('III without its outlier is almost perfectly linear (slope→~0.346, fit tightens)', Math.abs(fIIIb.b-0.3454)<0.01, 'slope='+fIIIb.b.toFixed(4));
// IV: all x equal except one — leverage. Variance of x is carried by a single point.
const xMode = 8; const nOff = x4.filter(v=>v!==xMode).length;
ok('IV: 10 of 11 points share one x (8); the slope rests on a single leverage point', nOff===1, 'off-mode pts='+nOff);

// IV leverage, computed EXACTLY — the anchor of the page's draggable instrument.
// Simple-regression leverage h_i = 1/n + (x_i - x̄)² / Σ(x_j - x̄)²  (diagonal of the hat matrix H).
// For Anscombe IV, x̄ = 9 exactly and Σ(x-9)² = 110, so every h_i is an exact rational.
sec('Anscombe IV — leverage is exact (the draggable instrument\'s claim)');
{
  const xbarIV = 9n;                         // exact: (10·8 + 19)/11 = 9
  let SxxN = 0n; for(const x of x4){ const d=BigInt(x)-xbarIV; SxxN += d*d; }
  const Sxx = new Q(SxxN);                    // 110
  const nIV = Qi(x4.length);                  // 11
  const lev = x4.map(x=>{ const d=new Q(BigInt(x)-xbarIV); return Qi(1).div(nIV).add(d.mul(d).div(Sxx)); });
  const far = lev[x4.indexOf(19)];
  const stacked = lev[x4.indexOf(8)];
  ok('IV: Σ(x-9)² = 110 exactly', Sxx.n===110n && Sxx.d===1n, Sxx.toString());
  ok('IV: leverage of the far point (x=19) is EXACTLY 1  (1/11 + 100/110)', far.n===1n && far.d===1n, 'h='+far);
  ok('IV: leverage of each stacked point (x=8) is EXACTLY 1/10', stacked.n===1n && stacked.d===10n, 'h='+stacked);
  ok('IV: all ten stacked points share leverage 1/10', x4.every((x,i)=> x!==8 || (lev[i].n===1n && lev[i].d===10n)));
  let sum=Qi(0); for(const h of lev) sum=sum.add(h);
  ok('IV: Σ leverages = 2 exactly  (trace of the hat matrix = # parameters: slope + intercept)', sum.n===2n && sum.d===1n, 'Σh='+sum);
  // drop the far point → every remaining x = 8 → zero x-spread → slope undefined
  const rest = x4.filter(x=>x!==19); const rn=BigInt(rest.length); let rs=0n; for(const x of rest) rs+=BigInt(x);
  let Sxx2=0n; for(const x of rest){ const d=BigInt(x)*rn - rs; Sxx2 += d*d; }   // n²·variance numerator
  ok('IV: remove the far point → the ten remaining x are identical (Σ(x-x̄)²=0) → slope UNDEFINED', Sxx2===0n, 'Sxx_num='+Sxx2);
  console.log(`  leverages:  far(x=19) = ${far}    each stacked(x=8) = ${stacked}    Σ = ${sum}`);
}

/* ───────────────────────────── Datasaurus Dozen ──────────────────────────── */
sec('Datasaurus Dozen — recomputation from primary data (datasauRus pkg)');
const tsv = readFileSync(join(HERE,'datasaurus.tsv'),'utf8').trim().split('\n');
const header = tsv[0].split('\t');
ok('TSV header is dataset/x/y', header[0]==='dataset'&&header[1]==='x'&&header[2]==='y', header.join(','));
const byDS = new Map();
for(const line of tsv.slice(1)){ const [ds,xs,ys]=line.split('\t'); if(!byDS.has(ds))byDS.set(ds,[]); byDS.get(ds).push([+xs,+ys]); }
ok('13 datasets parsed', byDS.size===13, '#='+byDS.size);
function fstats(pts){
  const n=pts.length; let sx=0,sy=0; for(const[x,y]of pts){sx+=x;sy+=y;} const mx=sx/n,my=sy/n;
  let sxx=0,syy=0,sxy=0; for(const[x,y]of pts){sxx+=(x-mx)**2;syy+=(y-my)**2;sxy+=(x-mx)*(y-my);}
  const vx=sxx/(n-1),vy=syy/(n-1); const sdx=Math.sqrt(vx),sdy=Math.sqrt(vy);
  const r=sxy/Math.sqrt(sxx*syy); return {n,mx,my,sdx,sdy,r};
}
const dStats=[...byDS.entries()].map(([ds,pts])=>({ds,...fstats(pts)}));
console.log('  dataset        n   mean(x)  mean(y)   sd(x)    sd(y)     corr');
for(const s of dStats) console.log(`  ${s.ds.padEnd(12)} ${String(s.n).padStart(3)}  ${s.mx.toFixed(4)} ${s.my.toFixed(4)}  ${s.sdx.toFixed(4)} ${s.sdy.toFixed(4)}  ${s.r.toFixed(4)}`);
// The paper's claim: all 13 share their summary stats "to two decimal places"
// (X̄≈54.26, Ȳ≈47.83, SDx≈16.76, SDy≈26.93, corr≈-0.06). Recomputed exactly, they
// agree to within ±0.01 — but the popular "identical to 2 dp" is slightly too
// strong: several statistics straddle a rounding boundary, so the 2-dp value is
// not unique. The page states this honestly. Verify the TRUE claim: spread < 0.011.
const range=(f)=>{const v=dStats.map(f);return Math.max(...v)-Math.min(...v);};
ok('mean(x) spread across 13 < 0.011', range(s=>s.mx)<0.011, 'spread='+range(s=>s.mx).toFixed(4));
ok('mean(y) spread across 13 < 0.011', range(s=>s.my)<0.011, 'spread='+range(s=>s.my).toFixed(4));
ok('sd(x)   spread across 13 < 0.011', range(s=>s.sdx)<0.011, 'spread='+range(s=>s.sdx).toFixed(4));
ok('sd(y)   spread across 13 < 0.011', range(s=>s.sdy)<0.011, 'spread='+range(s=>s.sdy).toFixed(4));
ok('corr    spread across 13 < 0.011', range(s=>s.r)<0.011,  'spread='+range(s=>s.r).toFixed(4));
// the published centroid values, matched to within 0.01
const mid=(f)=>{const v=dStats.map(f);return (Math.max(...v)+Math.min(...v))/2;};
ok('mean(x) midpoint ≈ 54.26 (±0.01)', Math.abs(mid(s=>s.mx)-54.26)<0.01, mid(s=>s.mx).toFixed(4));
ok('mean(y) midpoint ≈ 47.83 (±0.01)', Math.abs(mid(s=>s.my)-47.83)<0.01, mid(s=>s.my).toFixed(4));
ok('sd(x)   midpoint ≈ 16.76 (±0.01)', Math.abs(mid(s=>s.sdx)-16.765)<0.01, mid(s=>s.sdx).toFixed(4));
ok('sd(y)   midpoint ≈ 26.93 (±0.01)', Math.abs(mid(s=>s.sdy)-26.935)<0.01, mid(s=>s.sdy).toFixed(4));
ok('corr    midpoint ≈ -0.065 (±0.01)', Math.abs(mid(s=>s.r)+0.065)<0.01, mid(s=>s.r).toFixed(4));
// the honest record-correction, made checkable: "identical to 2 dp" is NOT exactly true.
const r2d=(v)=>Math.round(v*100)/100;
const mxs=new Set(dStats.map(s=>r2d(s.mx)));
ok('record-correction: recomputed mean(x) is NOT unique at 2 dp (54.26 AND 54.27 appear)', mxs.size>1, [...mxs].sort().join(' / '));
const nPts=new Set(dStats.map(s=>s.n));
ok('every dataset has 142 points', nPts.size===1 && [...nPts][0]===142, [...nPts].join(','));

/* ─────────────── emit a clean data.json for the page to embed ─────────────── */
const out = {
  anscombe: {
    source: 'Anscombe, F. J. (1973), The American Statistician 27(1):17–21',
    datasets: quartet.map(d=>({ id:d.id, points:d.x.map((x,i)=>[x, d.y[i]/100]) })),
    shared: { meanX:9, varX:11, meanY:7.50, varY:4.13, slope:0.50, intercept:3.00, corr:0.816 },
    exact: Astats.map(a=>({ id:a.id, meanX:a.s.meanX.toString(), varX:a.s.varX.toString(),
      meanY:a.s.meanY.toString(), varY:a.s.varY.toString(), slope:a.s.slope.toString(),
      intercept:a.s.intercept.toString(), r2:a.s.r2.toString(), r:a.s.r })),
  },
  datasaurus: {
    source: 'Matejka & Fitzmaurice (2017), CHI; data via datasauRus R package (MIT). Datasaurus drawing: Alberto Cairo.',
    shared: { meanX:54.26, meanY:47.83, sdX:16.76, sdY:26.93, corr:-0.06, n:142 },
    datasets: [...byDS.entries()].map(([ds,pts])=>({ id:ds, points:pts.map(([x,y])=>[+x.toFixed(4),+y.toFixed(4)]) })),
  },
};
writeFileSync(join(HERE,'data.json'), JSON.stringify(out));
console.log('\n  wrote data.json ('+ (JSON.stringify(out).length/1024).toFixed(0) +' KB)');

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