<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Econometrics</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600&family=Space+Grotesk:wght@500;700&display=swap" rel="stylesheet">
<style>
/* ============ tokens ============ */
:root{
/* paper — white, with a faint neutral stripe for the fanfold rows */
--paper:#FFFFFF; --bar:#F1F3F5; --ink:#15171A; --ink-soft:#5B626A; --ink-faint:#6A7178;
--rule:#DBDFE4; --rule-soft:#EBEEF1;
/* chrome — the frame around the paper */
--chrome:#F7F8FA; --chrome-2:#F2F4F6; --chrome-ink:#15171A; --chrome-soft:#6C737B;
--chrome-line:#E2E6EA; --chrome-edge:#D2D7DD; --chrome-edge-2:#98A0A9;
--chrome-hover:#F0F2F5; --chrome-field:#F4F6F8;
--accent:#1B4D8F; --accent-soft:#EAF1F9; --flag:#B3402B; --on-accent:#FFFFFF;
--plot-bg:#FFFFFF; --plot-grid:#E7EAEE; --plot-axis:#8A9199; --plot-ink:#15171A;
--plot-fit:#B3402B; --plot-fit2:#1B4D8F; --plot-band:#C9DCEF;
--s1:#1B4D8F; --s2:#B3402B; --s3:#2F7D4F; --s4:#8A6D1F; --s5:#6B4A87; --s6:#1F7A83;
--mono:"IBM Plex Mono",ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
--sans:"IBM Plex Sans",system-ui,-apple-system,Segoe UI,sans-serif;
--disp:"Space Grotesk","IBM Plex Sans",system-ui,sans-serif;
--sh:0 1px 2px rgba(15,20,25,.07),0 8px 26px rgba(15,20,25,.07);
}
[data-theme="dark"]{
--paper:#0B0B0C; --bar:#151517; --ink:#E4E6E9; --ink-soft:#949AA1; --ink-faint:#828990;
--rule:#2A2C30; --rule-soft:#1D1E21;
--chrome:#000000; --chrome-2:#060607; --chrome-ink:#E8EAEC; --chrome-soft:#8B9298;
--chrome-line:#1E1F22; --chrome-edge:#303338; --chrome-edge-2:#5C6167;
--chrome-hover:#17181B; --chrome-field:#121315;
--accent:#7FB6EE; --accent-soft:#121B26; --flag:#EE9070; --on-accent:#06121C;
--plot-bg:#0E0E10; --plot-grid:#232529; --plot-axis:#7C848C; --plot-ink:#E4E6E9;
--plot-fit:#EE9070; --plot-fit2:#7FB6EE; --plot-band:#1E3348;
--s1:#7FB6EE; --s2:#EE9070; --s3:#7CC28E; --s4:#D9BC63; --s5:#B79BD4; --s6:#66C2C9;
--sh:0 1px 2px rgba(0,0,0,.5),0 8px 26px rgba(0,0,0,.45);
}
*{box-sizing:border-box}
html,body{height:100%}
body{margin:0;background:var(--chrome);color:var(--ink);font-family:var(--sans);
font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;overflow:hidden}
button,input,select,textarea{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
/* ============ frame ============ */
.app{display:grid;grid-template-rows:auto minmax(0,1fr) auto;height:100dvh}
/* ---- top bar ---- */
.topbar{display:flex;align-items:center;gap:18px;padding:0 16px;height:52px;
background:var(--chrome);border-bottom:1px solid var(--chrome-line);color:var(--chrome-ink)}
.brand{font-family:var(--disp);font-weight:700;font-size:17px;letter-spacing:-.02em;
display:flex;align-items:baseline;gap:9px;white-space:nowrap}
.brand .mk{color:var(--chrome-ink)}
.brand .ver{font-family:var(--mono);font-size:10px;font-weight:400;color:var(--chrome-soft);
letter-spacing:.08em;text-transform:uppercase}
.dsinfo{display:flex;gap:0;align-items:stretch;font-family:var(--mono);font-size:11.5px;
color:var(--chrome-soft);overflow:hidden}
.dsinfo b{color:var(--chrome-ink);font-weight:500}
.dsinfo span{padding:0 12px;border-left:1px solid var(--chrome-line);white-space:nowrap}
.dsinfo span:first-child{border-left:0}
.spacer{flex:1}
.tbtn{background:transparent;border:1px solid var(--chrome-edge);color:var(--chrome-ink);
padding:5px 11px;border-radius:5px;cursor:pointer;font-size:12.5px;white-space:nowrap}
.tbtn:hover{background:var(--chrome-hover);border-color:var(--chrome-edge-2)}
/* ---- body split ---- */
.main{display:grid;grid-template-columns:262px minmax(0,1fr);min-height:0;background:var(--chrome)}
.side{background:var(--chrome-2);border-right:1px solid var(--chrome-line);
overflow-y:auto;color:var(--chrome-ink);min-height:0}
.side::-webkit-scrollbar,.stage::-webkit-scrollbar,.dtwrap::-webkit-scrollbar{width:10px;height:10px}
.side::-webkit-scrollbar-thumb,.stage::-webkit-scrollbar-thumb,.dtwrap::-webkit-scrollbar-thumb{
background:var(--ink-faint);border-radius:6px}
.sec{border-bottom:1px solid var(--chrome-line)}
.sec>h2{margin:0;font-family:var(--mono);font-size:10px;letter-spacing:.13em;text-transform:uppercase;
color:var(--chrome-soft);padding:13px 14px 7px}
.vsearch{width:calc(100% - 24px);margin:0 12px 8px;padding:5px 8px;border-radius:5px;
background:var(--chrome-field);border:1px solid var(--chrome-edge);color:var(--chrome-ink);font-size:12.5px}
.vsearch::placeholder{color:var(--chrome-soft)}
.vlist{list-style:none;margin:0;padding:0 6px 12px;max-height:230px;overflow-y:auto}
.vlist li{display:flex;gap:8px;align-items:baseline;padding:3px 8px;border-radius:4px;cursor:pointer;
font-family:var(--mono);font-size:12px}
.vlist li:hover{background:var(--chrome-hover)}
.vlist .vn{color:var(--chrome-ink);font-weight:500}
.vlist .vt{color:var(--chrome-soft);font-size:10px;text-transform:uppercase;letter-spacing:.05em}
.vlist .vl{color:var(--chrome-soft);font-family:var(--sans);font-size:11px;
overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;text-align:right}
.empty{padding:6px 14px 14px;color:var(--chrome-soft);font-size:12.5px;line-height:1.55}
.menu{padding:0 8px 10px}
.mgroup{margin-bottom:2px}
.mhead{width:100%;text-align:left;background:transparent;border:0;color:var(--chrome-ink);
padding:7px 8px;border-radius:5px;cursor:pointer;font-size:13px;font-weight:500;
display:flex;align-items:center;gap:8px}
.mhead:hover{background:var(--chrome-line)}
.mhead .ar{color:var(--chrome-soft);font-size:9px;transition:transform .16s}
.mgroup.open .mhead .ar{transform:rotate(90deg)}
.mitems{display:none;padding:2px 0 6px 8px;margin-left:8px;border-left:1px solid var(--chrome-edge)}
.mgroup.open .mitems{display:block}
.mitems button{display:block;width:100%;text-align:left;background:transparent;border:0;
color:var(--chrome-soft);padding:4px 8px;border-radius:4px;cursor:pointer;font-size:12.5px}
.mitems button:hover{background:var(--chrome-hover);color:var(--chrome-ink)}
/* ---- stage ---- */
.stagewrap{display:flex;flex-direction:column;min-width:0;min-height:0;background:var(--paper)}
.tabs{display:flex;align-items:center;gap:2px;padding:0 12px;background:var(--chrome-2);
border-bottom:1px solid var(--rule);height:38px;flex:none}
.tab{background:transparent;border:0;border-bottom:2px solid transparent;color:var(--chrome-soft);
padding:8px 14px 7px;cursor:pointer;font-size:13px}
.tab:hover{color:var(--chrome-ink)}
.tab[aria-selected="true"]{color:var(--chrome-ink);border-bottom-color:var(--accent)}
.stage{flex:1;overflow-y:auto;min-height:0;background:var(--paper)}
.pane{display:none}
.pane.on{display:block}
/* ---- the log: fanfold greenbar paper ---- */
#log{padding:0 0 40px}
.entry{display:grid;grid-template-columns:44px minmax(0,1fr);border-bottom:1px solid var(--rule-soft)}
.entry:nth-child(even){background:var(--bar)}
.gutter{font-family:var(--mono);font-size:10.5px;color:var(--ink-faint);text-align:right;
padding:12px 10px 0 0;border-right:1px solid var(--rule);user-select:none;letter-spacing:.03em}
.ebody{padding:10px 18px 14px;min-width:0;overflow-x:auto}
.cmdline{font-family:var(--mono);font-size:13px;color:var(--accent);font-weight:500;
padding-bottom:6px;white-space:pre-wrap;word-break:break-word}
.cmdline::before{content:". ";color:var(--ink-faint)}
pre.out{font-family:var(--mono);font-size:12.2px;line-height:1.42;margin:0;color:var(--ink);
white-space:pre;overflow-x:auto;letter-spacing:0}
pre.err{color:var(--flag);white-space:pre-wrap}
pre.err::before{content:"r(198); ";color:var(--ink-faint)}
.note{font-size:12.5px;color:var(--ink-soft);margin:4px 0 0}
.warn{color:var(--flag);font-family:var(--mono);font-size:12.5px;margin:6px 0}
/* welcome block */
.welcome{padding:34px 30px 30px;max-width:860px}
.welcome h1{font-family:var(--disp);font-size:31px;font-weight:700;letter-spacing:-.025em;
margin:0 0 6px;color:var(--ink)}
.welcome .lede{font-size:15px;color:var(--ink-soft);margin:0 0 22px;max-width:60ch;line-height:1.6}
.startgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(215px,1fr));gap:9px;margin-bottom:26px}
.startcard{text-align:left;background:transparent;border:1px solid var(--rule);border-radius:7px;
padding:11px 13px;cursor:pointer}
.startcard:hover{border-color:var(--accent);background:var(--accent-soft)}
.startcard b{display:block;font-family:var(--mono);font-size:12.5px;color:var(--accent);margin-bottom:3px}
.startcard span{font-size:12px;color:var(--ink-soft);line-height:1.45}
.welcome h3{font-family:var(--mono);font-size:10.5px;letter-spacing:.13em;text-transform:uppercase;
color:var(--ink-faint);margin:0 0 9px;font-weight:500}
.welcome code{font-family:var(--mono);font-size:12.5px;background:var(--bar);
border:1px solid var(--rule-soft);border-radius:4px;padding:1px 5px;color:var(--ink)}
.tryline{font-family:var(--mono);font-size:12.5px;color:var(--ink-soft);padding:2px 0;cursor:pointer}
.tryline:hover{color:var(--accent)}
.tryline::before{content:". ";color:var(--ink-faint)}
/* ---- plots ---- */
figure.plot{margin:12px 0 4px;max-width:760px;border:1px solid var(--rule);border-radius:7px;
background:var(--plot-bg);padding:6px 6px 2px}
figure.plot svg{display:block;width:100%;height:auto}
figure.plot figcaption{font-family:var(--mono);font-size:10.5px;color:var(--ink-faint);
padding:4px 8px 6px;border-top:1px solid var(--rule-soft);margin-top:4px}
.ptick{font-family:var(--mono);font-size:10.5px;fill:var(--plot-axis)}
.plab{font-family:var(--sans);font-size:12px;fill:var(--ink-soft)}
.ptitle{font-family:var(--sans);font-size:13.5px;font-weight:600;fill:var(--ink)}
.psub,.pleg{font-family:var(--mono);font-size:11px;fill:var(--ink-soft)}
.pdiag{font-family:var(--mono);font-size:12px;font-weight:600;fill:var(--ink)}
.pcorr{font-family:var(--mono);font-size:10px;fill:var(--ink-soft)}
/* ---- data browser ---- */
.dtbar{display:flex;gap:10px;align-items:center;padding:9px 14px;border-bottom:1px solid var(--rule);
font-family:var(--mono);font-size:11.5px;color:var(--ink-soft);position:sticky;top:0;
background:var(--paper);z-index:2;flex-wrap:wrap}
.dtbar button{background:transparent;border:1px solid var(--rule);color:var(--ink-soft);
border-radius:5px;padding:3px 9px;cursor:pointer;font-size:11.5px}
.dtbar button:hover{border-color:var(--accent);color:var(--accent)}
.dtwrap{overflow:auto;max-height:calc(100dvh - 200px)}
table.dt{border-collapse:collapse;font-family:var(--mono);font-size:11.8px;white-space:nowrap}
table.dt th,table.dt td{border-right:1px solid var(--rule-soft);border-bottom:1px solid var(--rule-soft);
padding:3px 10px;text-align:right}
table.dt th{position:sticky;top:0;background:var(--bar);color:var(--ink);font-weight:600;
border-bottom:1px solid var(--rule);cursor:pointer;z-index:1}
table.dt th:hover{color:var(--accent)}
table.dt td.s{text-align:left;color:var(--ink-soft)}
table.dt td.rn{position:sticky;left:0;background:var(--paper);color:var(--ink-faint);
border-right:1px solid var(--rule);text-align:right}
table.dt tr:nth-child(even) td{background:var(--bar)}
table.dt tr:nth-child(even) td.rn{background:var(--bar)}
table.dt td.miss{color:var(--ink-faint)}
/* ---- help ---- */
.help{padding:26px 30px 60px;max-width:900px}
.help h2{font-family:var(--disp);font-size:22px;margin:30px 0 4px;letter-spacing:-.02em}
.help h2:first-child{margin-top:0}
.help p{color:var(--ink-soft);margin:0 0 14px;max-width:70ch}
table.ref{border-collapse:collapse;width:100%;margin:6px 0 18px}
table.ref td{border-bottom:1px solid var(--rule-soft);padding:6px 10px 6px 0;vertical-align:top;font-size:13px}
table.ref td:first-child{font-family:var(--mono);font-size:12.2px;color:var(--accent);
white-space:nowrap;width:37%;cursor:pointer}
table.ref td:first-child:hover{text-decoration:underline}
table.ref td:last-child{color:var(--ink-soft)}
/* ---- command bar ---- */
.cmdbar{display:flex;align-items:center;gap:10px;padding:9px 14px;background:var(--chrome);
border-top:1px solid var(--chrome-hover)}
.prompt{font-family:var(--mono);color:var(--chrome-soft);font-size:15px;padding-left:2px}
#cmd{flex:1;background:var(--chrome-2);border:1px solid var(--chrome-edge);border-radius:6px;
padding:8px 12px;font-family:var(--mono);font-size:13.5px;color:var(--chrome-ink)}
#cmd::placeholder{color:var(--chrome-soft)}
#cmd:focus{border-color:var(--accent);outline:none}
.runbtn{background:var(--accent);border:0;color:var(--on-accent);padding:8px 18px;border-radius:6px;
cursor:pointer;font-weight:500;font-size:13px}
.runbtn:hover{filter:brightness(1.12)}
/* ---- modal ---- */
.mask{position:fixed;inset:0;background:rgba(8,14,11,.55);display:none;align-items:center;
justify-content:center;padding:20px;z-index:50;backdrop-filter:blur(2px)}
.mask.on{display:flex}
.modal{background:var(--paper);border-radius:10px;box-shadow:var(--sh);width:min(560px,100%);
max-height:88dvh;display:flex;flex-direction:column;border:1px solid var(--rule)}
.modal header{padding:16px 20px 12px;border-bottom:1px solid var(--rule)}
.modal h3{font-family:var(--disp);font-size:18px;margin:0;letter-spacing:-.015em}
.modal .sub{color:var(--ink-soft);font-size:12.5px;margin-top:3px}
.mbody{padding:16px 20px;overflow-y:auto;flex:1}
.fld{margin-bottom:14px}
.fld>label{display:block;font-size:12px;color:var(--ink-soft);margin-bottom:5px;font-weight:500}
.fld input[type=text],.fld input[type=number],.fld select{width:100%;padding:7px 9px;border-radius:6px;
border:1px solid var(--rule);background:var(--plot-bg);color:var(--ink);font-family:var(--mono);font-size:13px}
.fld select[multiple]{height:132px;font-size:12.5px}
.chk{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink);margin-bottom:7px;cursor:pointer}
.chk input{accent-color:var(--accent);width:15px;height:15px}
.chkgrid{display:grid;grid-template-columns:1fr 1fr;gap:0 14px}
.preview{font-family:var(--mono);font-size:12.5px;background:var(--bar);border:1px solid var(--rule);
border-radius:6px;padding:9px 11px;color:var(--ink);word-break:break-word;margin-top:2px}
.preview b{color:var(--ink-faint);font-weight:400}
.modal footer{padding:12px 20px;border-top:1px solid var(--rule);display:flex;gap:9px;
justify-content:flex-end;align-items:center}
.ghost{background:transparent;border:1px solid var(--rule);color:var(--ink-soft);padding:7px 15px;
border-radius:6px;cursor:pointer;font-size:13px}
.ghost:hover{border-color:var(--ink-soft);color:var(--ink)}
.hint{font-size:11.5px;color:var(--ink-faint);margin-right:auto;font-family:var(--mono)}
/* ---- responsive ---- */
.mobtoggle{display:none}
@media (max-width:860px){
.main{grid-template-columns:1fr}
.side{position:fixed;top:52px;bottom:0;left:0;width:270px;z-index:30;transform:translateX(-100%);
transition:transform .2s ease;box-shadow:var(--sh)}
.side.open{transform:none}
.mobtoggle{display:inline-flex}
.dsinfo span.hidesm{display:none}
.brand .ver{display:none}
.welcome{padding:22px 18px}
.welcome h1{font-size:25px}
.ebody{padding:10px 12px 14px}
.entry{grid-template-columns:32px minmax(0,1fr)}
pre.out{font-size:10.6px}
.help{padding:20px 18px 50px}
table.ref td:first-child{width:auto}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<button class="tbtn mobtoggle" id="btnSide" aria-label="Toggle panel">☰</button>
<div class="brand"><span class="mk">Econometrics</span><span class="ver">workbench</span></div>
<div class="dsinfo" id="dsinfo"></div>
<div class="spacer"></div>
<button class="tbtn" id="btnImport">Import CSV</button>
<button class="tbtn" id="btnExport">Export</button>
<button class="tbtn" id="btnTheme">Black</button>
<input type="file" id="fileIn" accept=".csv,.tsv,.txt" style="display:none">
</header>
<div class="main">
<aside class="side" id="side">
<div class="sec">
<h2>Variables</h2>
<input class="vsearch" id="vsearch" placeholder="Filter variables" aria-label="Filter variables">
<ul class="vlist" id="vlist"></ul>
<div class="empty" id="vempty">No data in memory. Open the Data menu below, or type
<b>use auto</b> in the command bar.</div>
</div>
<div class="sec">
<h2>Commands</h2>
<div class="menu" id="menu"></div>
</div>
</aside>
<div class="stagewrap">
<div class="tabs" role="tablist">
<button class="tab" id="tabResults" role="tab" aria-selected="true">Results</button>
<button class="tab" id="tabData" role="tab" aria-selected="false">Data</button>
<button class="tab" id="tabHelp" role="tab" aria-selected="false">Reference</button>
<div class="spacer"></div>
<button class="tab" id="btnClear" title="Clear the results log">Clear log</button>
<button class="tab" id="btnSaveLog">Save log</button>
</div>
<div class="stage" id="stage">
<div class="pane on" id="paneResults"><div id="log"></div></div>
<div class="pane" id="paneData"></div>
<div class="pane" id="paneHelp"></div>
</div>
</div>
</div>
<div class="cmdbar">
<span class="prompt">.</span>
<input id="cmd" placeholder="Type a command — e.g. regress price mpg weight, robust" autocomplete="off"
spellcheck="false" aria-label="Command line">
<button class="runbtn" id="btnRun">Run</button>
</div>
</div>
<div class="mask" id="mask"><div class="modal" role="dialog" aria-modal="true">
<header><h3 id="mTitle"></h3><div class="sub" id="mSub"></div></header>
<div class="mbody" id="mBody"></div>
<footer>
<span class="hint" id="mHint"></span>
<button class="ghost" id="mCancel">Cancel</button>
<button class="runbtn" id="mRun">Run command</button>
</footer>
</div></div>
<script>
/* ============================================================
NUMERIC CORE — matrices, distributions, special functions
============================================================ */
const NA = NaN;
const isNum = v => typeof v === 'number' && isFinite(v);
/* ---------- Matrix ---------- */
function zeros(r, c) { const A = []; for (let i = 0; i < r; i++) A.push(new Array(c).fill(0)); return A; }
function eye(n) { const A = zeros(n, n); for (let i = 0; i < n; i++) A[i][i] = 1; return A; }
function mmul(A, B) {
const r = A.length, m = B.length, c = B[0].length, C = zeros(r, c);
for (let i = 0; i < r; i++) { const Ai = A[i], Ci = C[i];
for (let k = 0; k < m; k++) { const a = Ai[k]; if (a === 0) continue; const Bk = B[k];
for (let j = 0; j < c; j++) Ci[j] += a * Bk[j]; } }
return C;
}
function mtrans(A) { const r = A.length, c = A[0].length, T = zeros(c, r);
for (let i = 0; i < r; i++) for (let j = 0; j < c; j++) T[j][i] = A[i][j]; return T; }
function mvec(A, v) { const r = A.length, c = v.length, o = new Array(r).fill(0);
for (let i = 0; i < r; i++) { let s = 0; for (let j = 0; j < c; j++) s += A[i][j] * v[j]; o[i] = s; } return o; }
function madd(A, B) { return A.map((r, i) => r.map((x, j) => x + B[i][j])); }
function mscale(A, s) { return A.map(r => r.map(x => x * s)); }
function outer(a, b) { return a.map(x => b.map(y => x * y)); }
/* Cholesky-based symmetric inverse with rank detection.
Returns {inv, keep, drop} where inv is full k x k with zeros in dropped rows/cols. */
function symInv(A, tol) {
tol = tol || 1e-11;
const k = A.length, d0 = [];
for (let i = 0; i < k; i++) d0.push(Math.abs(A[i][i]) > 0 ? Math.abs(A[i][i]) : 1);
const keep = [], drop = [];
// pass 1: pivoted-in-order Cholesky to find dependent columns
const L = zeros(k, k);
for (let j = 0; j < k; j++) {
let s = A[j][j];
for (let m = 0; m < j; m++) s -= L[j][m] * L[j][m];
if (s <= tol * d0[j] || !isFinite(s)) { drop.push(j); continue; }
keep.push(j);
L[j][j] = Math.sqrt(s);
for (let i = j + 1; i < k; i++) {
let t = A[i][j];
for (let m = 0; m < j; m++) t -= L[i][m] * L[j][m];
L[i][j] = t / L[j][j];
}
}
// pass 2: invert the kept submatrix
const p = keep.length, S = zeros(p, p);
for (let i = 0; i < p; i++) for (let j = 0; j < p; j++) S[i][j] = A[keep[i]][keep[j]];
const Li = zeros(p, p);
for (let j = 0; j < p; j++) {
let s = S[j][j];
for (let m = 0; m < j; m++) s -= Li[j][m] * Li[j][m];
s = Math.max(s, 1e-300);
Li[j][j] = Math.sqrt(s);
for (let i = j + 1; i < p; i++) {
let t = S[i][j];
for (let m = 0; m < j; m++) t -= Li[i][m] * Li[j][m];
Li[i][j] = t / Li[j][j];
}
}
// invert lower triangular
const Inv = zeros(p, p);
for (let i = 0; i < p; i++) Inv[i][i] = 1 / Li[i][i];
for (let i = 1; i < p; i++) for (let j = 0; j < i; j++) {
let s = 0; for (let m = j; m < i; m++) s += Li[i][m] * Inv[m][j];
Inv[i][j] = -s / Li[i][i];
}
const R = zeros(p, p); // S^-1 = Inv' Inv
for (let i = 0; i < p; i++) for (let j = 0; j < p; j++) {
let s = 0; for (let m = Math.max(i, j); m < p; m++) s += Inv[m][i] * Inv[m][j];
R[i][j] = s;
}
const full = zeros(k, k);
for (let i = 0; i < p; i++) for (let j = 0; j < p; j++) full[keep[i]][keep[j]] = R[i][j];
return { inv: full, keep, drop };
}
function genInv(A) { // general square inverse, Gauss-Jordan w/ partial pivot
const n = A.length, M = A.map((r, i) => r.concat(eye(n)[i]));
for (let c = 0; c < n; c++) {
let p = c; for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
if (Math.abs(M[p][c]) < 1e-14) return null;
[M[c], M[p]] = [M[p], M[c]];
const pv = M[c][c];
for (let j = 0; j < 2 * n; j++) M[c][j] /= pv;
for (let r = 0; r < n; r++) { if (r === c) continue; const f = M[r][c]; if (!f) continue;
for (let j = 0; j < 2 * n; j++) M[r][j] -= f * M[c][j]; }
}
return M.map(r => r.slice(n));
}
/* ---------- Descriptive ---------- */
function mean(a) { let s = 0, n = 0; for (const x of a) if (isNum(x)) { s += x; n++; } return n ? s / n : NA; }
function variance(a, ddof) { ddof = ddof === undefined ? 1 : ddof;
const m = mean(a); let s = 0, n = 0;
for (const x of a) if (isNum(x)) { s += (x - m) * (x - m); n++; }
return n > ddof ? s / (n - ddof) : NA; }
function sd(a, d) { return Math.sqrt(variance(a, d)); }
function moment(a, p) { const m = mean(a); let s = 0, n = 0;
for (const x of a) if (isNum(x)) { s += Math.pow(x - m, p); n++; } return n ? s / n : NA; }
function skewness(a) { return moment(a, 3) / Math.pow(moment(a, 2), 1.5); }
function kurtosis(a) { return moment(a, 4) / Math.pow(moment(a, 2), 2); }
function quantile(a, q) {
const v = a.filter(isNum).sort((x, y) => x - y), n = v.length;
if (!n) return NA;
if (q <= 0) return v[0]; if (q >= 1) return v[n - 1];
const h = q * n - 0.5, lo = Math.floor(h), hi = Math.ceil(h);
if (lo < 0) return v[0]; if (hi >= n) return v[n - 1];
return v[lo] + (h - lo) * (v[hi] - v[lo]);
}
function median(a) { return quantile(a, 0.5); }
function corr(a, b) {
let sx = 0, sy = 0, n = 0;
for (let i = 0; i < a.length; i++) if (isNum(a[i]) && isNum(b[i])) { sx += a[i]; sy += b[i]; n++; }
if (n < 2) return NA;
const mx = sx / n, my = sy / n; let cxy = 0, cxx = 0, cyy = 0;
for (let i = 0; i < a.length; i++) if (isNum(a[i]) && isNum(b[i])) {
const dx = a[i] - mx, dy = b[i] - my; cxy += dx * dy; cxx += dx * dx; cyy += dy * dy; }
return cxy / Math.sqrt(cxx * cyy);
}
function ranks(a) { // average ranks, ignoring non-numeric (returns array aligned to input)
const idx = []; for (let i = 0; i < a.length; i++) if (isNum(a[i])) idx.push(i);
idx.sort((i, j) => a[i] - a[j]);
const r = new Array(a.length).fill(NA);
let i = 0;
while (i < idx.length) {
let j = i; while (j + 1 < idx.length && a[idx[j + 1]] === a[idx[i]]) j++;
const avg = (i + j) / 2 + 1;
for (let m = i; m <= j; m++) r[idx[m]] = avg;
i = j + 1;
}
return r;
}
/* ---------- Special functions ---------- */
const LG_C = [76.18009172947146, -86.50532032941677, 24.01409824083091,
-1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5];
function lgamma(x) {
let y = x, tmp = x + 5.5;
tmp -= (x + 0.5) * Math.log(tmp);
let ser = 1.000000000190015;
for (let j = 0; j < 6; j++) ser += LG_C[j] / ++y;
return -tmp + Math.log(2.5066282746310005 * ser / x);
}
function lbeta(a, b) { return lgamma(a) + lgamma(b) - lgamma(a + b); }
function gammainc_P(a, x) { // regularized lower incomplete gamma
if (x < 0 || a <= 0) return NA;
if (x === 0) return 0;
if (x < a + 1) { // series
let ap = a, sum = 1 / a, del = sum;
for (let n = 0; n < 500; n++) { ap++; del *= x / ap; sum += del; if (Math.abs(del) < Math.abs(sum) * 1e-15) break; }
return sum * Math.exp(-x + a * Math.log(x) - lgamma(a));
} else { // continued fraction for Q
let b = x + 1 - a, c = 1e300, d = 1 / b, h = d;
for (let i = 1; i < 500; i++) {
const an = -i * (i - a); b += 2; d = an * d + b; if (Math.abs(d) < 1e-300) d = 1e-300;
c = b + an / c; if (Math.abs(c) < 1e-300) c = 1e-300;
d = 1 / d; const del = d * c; h *= del;
if (Math.abs(del - 1) < 1e-15) break;
}
return 1 - Math.exp(-x + a * Math.log(x) - lgamma(a)) * h;
}
}
function betacf(a, b, x) {
const MAXIT = 500, EPS = 3e-16, FPMIN = 1e-300;
let qab = a + b, qap = a + 1, qam = a - 1, c = 1, d = 1 - qab * x / qap;
if (Math.abs(d) < FPMIN) d = FPMIN; d = 1 / d; let h = d;
for (let m = 1; m <= MAXIT; m++) {
const m2 = 2 * m;
let aa = m * (b - m) * x / ((qam + m2) * (a + m2));
d = 1 + aa * d; if (Math.abs(d) < FPMIN) d = FPMIN;
c = 1 + aa / c; if (Math.abs(c) < FPMIN) c = FPMIN;
d = 1 / d; h *= d * c;
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
d = 1 + aa * d; if (Math.abs(d) < FPMIN) d = FPMIN;
c = 1 + aa / c; if (Math.abs(c) < FPMIN) c = FPMIN;
d = 1 / d; const del = d * c; h *= del;
if (Math.abs(del - 1) < EPS) break;
}
return h;
}
function ibeta(x, a, b) { // regularized incomplete beta I_x(a,b)
if (x <= 0) return 0; if (x >= 1) return 1;
const bt = Math.exp(-lbeta(a, b) + a * Math.log(x) + b * Math.log(1 - x));
return x < (a + 1) / (a + b + 2) ? bt * betacf(a, b, x) / a : 1 - bt * betacf(b, a, 1 - x) / b;
}
/* ---------- Distributions ---------- */
function normpdf(z) { return Math.exp(-0.5 * z * z) / 2.5066282746310002; }
function normcdf(z) {
if (!isFinite(z)) return z > 0 ? 1 : 0;
// Cody-style erfc via continued fraction of incomplete gamma
const x = Math.abs(z) / Math.SQRT2;
const p = 0.5 * (1 + (x < 8 ? erf(x) : 1));
return z >= 0 ? p : 1 - p;
}
function erf(x) {
const t = 1 / (1 + 0.5 * Math.abs(x));
const y = t * Math.exp(-x * x - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 +
t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 +
t * (-0.82215223 + t * 0.17087277)))))))));
return x >= 0 ? 1 - y : y - 1;
}
function norminv(p) {
if (p <= 0) return -Infinity; if (p >= 1) return Infinity;
const a = [-3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02,
1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00];
const b = [-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02,
6.680131188771972e+01, -1.328068155288572e+01];
const c = [-7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00,
-2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00];
const d = [7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00];
const pl = 0.02425; let q, r, x;
if (p < pl) { q = Math.sqrt(-2 * Math.log(p));
x = (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
} else if (p <= 1 - pl) { q = p - 0.5; r = q * q;
x = (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q /
(((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
} else { q = Math.sqrt(-2 * Math.log(1 - p));
x = -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
}
// one Halley refinement
const e = normcdf(x) - p, u = e * 2.5066282746310002 * Math.exp(x * x / 2);
return x - u / (1 + x * u / 2);
}
function tcdf(t, v) {
if (!isFinite(t)) return t > 0 ? 1 : 0;
const p = 0.5 * ibeta(v / (v + t * t), v / 2, 0.5);
return t > 0 ? 1 - p : p;
}
function tinv(p, v) { return bisect(x => tcdf(x, v) - p, -1e4, 1e4); }
function chi2cdf(x, k) { return x <= 0 ? 0 : gammainc_P(k / 2, x / 2); }
function chi2inv(p, k) { return bisect(x => chi2cdf(x, k) - p, 0, 1e7); }
function fcdf(f, d1, d2) { return f <= 0 ? 0 : ibeta(d1 * f / (d1 * f + d2), d1 / 2, d2 / 2); }
function finv(p, d1, d2) { return bisect(x => fcdf(x, d1, d2) - p, 0, 1e7); }
function bisect(f, lo, hi) {
let flo = f(lo), fhi = f(hi);
if (flo > 0 || fhi < 0) return NA;
for (let i = 0; i < 300; i++) { const m = (lo + hi) / 2, fm = f(m);
if (fm < 0) { lo = m; flo = fm; } else { hi = m; fhi = fm; }
if (hi - lo < 1e-12 * Math.max(1, Math.abs(lo))) break; }
return (lo + hi) / 2;
}
/* tail probabilities used everywhere */
const pT = (t, v) => 2 * (1 - tcdf(Math.abs(t), v));
const pZ = z => 2 * (1 - normcdf(Math.abs(z)));
const pF = (f, d1, d2) => 1 - fcdf(f, d1, d2);
const pChi2 = (x, k) => 1 - chi2cdf(x, k);
/* ---------- RNG (seeded, reproducible) ---------- */
function makeRNG(seed) {
let s = seed >>> 0 || 12345;
const u = () => { s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0; return s / 4294967296; };
return {
unif: u,
norm: () => { let a = 0, b = 0; while (a === 0) a = u(); while (b === 0) b = u();
return Math.sqrt(-2 * Math.log(a)) * Math.cos(2 * Math.PI * b); },
pick: arr => arr[Math.floor(u() * arr.length)],
int: (lo, hi) => lo + Math.floor(u() * (hi - lo + 1))
};
}
/* ============================================================
ESTIMATION ENGINE
============================================================ */
/* Build a sandwich variance: bread * meat * bread */
function sandwich(XXi, meat) { return mmul(mmul(XXi, meat), XXi); }
/* ---------- Ordinary least squares (the workhorse) ----------
opts = { vce:'ols'|'robust'|'hc2'|'hc3'|'cluster'|'hac', cluster:[], lags:L,
weights:[], names:[], noCons:bool, level:95, boot:reps } */
function ols(y, X, opts) {
opts = opts || {};
const n = y.length, k = X[0].length;
const w = opts.weights || null;
let Xw = X, yw = y;
if (w) { Xw = X.map((r, i) => r.map(v => v * Math.sqrt(w[i]))); yw = y.map((v, i) => v * Math.sqrt(w[i])); }
const Xt = mtrans(Xw);
const XX = mmul(Xt, Xw), Xy = mvec(Xt, yw);
const { inv: XXi, keep, drop } = symInv(XX);
const b = mvec(XXi, Xy);
for (const j of drop) b[j] = 0;
const fitted = mvec(X, b), resid = y.map((v, i) => v - fitted[i]);
const kk = keep.length;
const dfr = n - kk, dfm = opts.noCons ? kk : kk - 1;
let rss = 0, wsum = 0;
for (let i = 0; i < n; i++) { const wi = w ? w[i] : 1; rss += wi * resid[i] * resid[i]; wsum += wi; }
const ybar = w ? y.reduce((s, v, i) => s + w[i] * v, 0) / wsum : mean(y);
let tss = 0;
for (let i = 0; i < n; i++) { const wi = w ? w[i] : 1;
tss += wi * (opts.noCons ? y[i] * y[i] : (y[i] - ybar) * (y[i] - ybar)); }
const mss = tss - rss;
const s2 = rss / dfr, rmse = Math.sqrt(s2);
const r2 = 1 - rss / tss, r2a = 1 - (1 - r2) * (n - (opts.noCons ? 0 : 1)) / dfr;
// hat values (needed for HC2/HC3 and diagnostics)
const hat = new Array(n).fill(0);
for (let i = 0; i < n; i++) { let h = 0;
for (let a = 0; a < k; a++) { if (!XXi[a][a] && drop.includes(a)) continue;
for (let bq = 0; bq < k; bq++) h += Xw[i][a] * XXi[a][bq] * Xw[i][bq]; }
hat[i] = Math.min(Math.max(h, 0), 0.9999); }
const vce = opts.vce || 'ols';
let V, vceLabel = 'OLS', dfrUse = dfr, useT = true, nclust = null;
if (vce === 'ols') { V = mscale(XXi, s2); }
else if (vce === 'cluster') {
const g = opts.cluster, groups = new Map();
for (let i = 0; i < n; i++) { const key = String(g[i]);
if (!groups.has(key)) groups.set(key, []); groups.get(key).push(i); }
const G = groups.size, meat = zeros(k, k);
for (const idx of groups.values()) {
const s = new Array(k).fill(0);
for (const i of idx) { const wi = w ? w[i] : 1;
for (let a = 0; a < k; a++) s[a] += Xw[i][a] * resid[i] * (w ? Math.sqrt(wi) : 1); }
for (let a = 0; a < k; a++) for (let bq = 0; bq < k; bq++) meat[a][bq] += s[a] * s[bq];
}
const c = (G / (G - 1)) * ((n - 1) / (n - kk));
V = mscale(sandwich(XXi, meat), c);
vceLabel = 'Cluster-robust'; dfrUse = G - 1; nclust = G;
}
else if (vce === 'hac') {
const L = opts.lags === undefined ? Math.floor(4 * Math.pow(n / 100, 2 / 9)) : opts.lags;
const meat = zeros(k, k);
const u = X.map((r, i) => r.map(v => v * resid[i]));
for (let i = 0; i < n; i++) for (let a = 0; a < k; a++) for (let bq = 0; bq < k; bq++)
meat[a][bq] += u[i][a] * u[i][bq];
for (let l = 1; l <= L; l++) { const wl = 1 - l / (L + 1);
for (let i = l; i < n; i++) for (let a = 0; a < k; a++) for (let bq = 0; bq < k; bq++)
meat[a][bq] += wl * (u[i][a] * u[i - l][bq] + u[i - l][a] * u[i][bq]); }
V = mscale(sandwich(XXi, meat), n / (n - kk));
vceLabel = 'Newey-West HAC (lag ' + L + ')';
}
else { // heteroskedasticity-robust family
const meat = zeros(k, k);
for (let i = 0; i < n; i++) {
let u2 = resid[i] * resid[i];
if (vce === 'hc2') u2 /= (1 - hat[i]);
else if (vce === 'hc3') u2 /= (1 - hat[i]) * (1 - hat[i]);
const wi = w ? w[i] : 1;
for (let a = 0; a < k; a++) for (let bq = 0; bq < k; bq++) meat[a][bq] += wi * u2 * X[i][a] * X[i][bq];
}
const c = vce === 'robust' ? n / (n - kk) : 1;
V = mscale(sandwich(XXi, meat), c);
vceLabel = vce === 'robust' ? 'Robust (HC1)' : vce.toUpperCase();
}
if (opts.boot) { // bootstrap replacement variance
const rng = makeRNG(opts.bootseed || 20250);
const reps = opts.boot, B = [];
for (let r = 0; r < reps; r++) {
const yi = [], Xi = [];
for (let i = 0; i < n; i++) { const j = Math.floor(rng.unif() * n); yi.push(y[j]); Xi.push(X[j]); }
const Xti = mtrans(Xi), s = symInv(mmul(Xti, Xi));
B.push(mvec(s.inv, mvec(Xti, yi)));
}
const bm = new Array(k).fill(0);
for (const bb of B) for (let a = 0; a < k; a++) bm[a] += bb[a] / reps;
V = zeros(k, k);
for (const bb of B) for (let a = 0; a < k; a++) for (let c2 = 0; c2 < k; c2++)
V[a][c2] += (bb[a] - bm[a]) * (bb[c2] - bm[c2]) / (reps - 1);
vceLabel = 'Bootstrap (' + reps + ' reps)';
}
const se = [], tv = [], pv = [], lo = [], hi = [];
const level = opts.level || 95, alpha = (1 - level / 100) / 2;
const crit = useT ? Math.abs(tinv(alpha, dfrUse)) : Math.abs(norminv(alpha));
for (let a = 0; a < k; a++) {
if (drop.includes(a)) { se.push(NA); tv.push(NA); pv.push(NA); lo.push(NA); hi.push(NA); continue; }
const s = Math.sqrt(Math.max(V[a][a], 0));
se.push(s); const t = b[a] / s; tv.push(t); pv.push(pT(t, dfrUse));
lo.push(b[a] - crit * s); hi.push(b[a] + crit * s);
}
// model F test
let F, pFv, dfn = dfm;
if (vce === 'ols' && !opts.boot) { F = dfm > 0 ? (mss / dfm) / s2 : NA; }
else { const idx = keep.filter(j => !(opts.consIdx !== undefined && j === opts.consIdx));
F = idx.length ? waldF(b, V, idx, dfrUse) : NA; dfn = idx.length; }
pFv = isNum(F) ? pF(F, dfn, dfrUse) : NA;
const ll = -0.5 * n * (Math.log(2 * Math.PI) + Math.log(rss / n) + 1);
return { type: 'ols', b, se, t: tv, p: pv, ci_lo: lo, ci_hi: hi, V, XXi, n, k: kk, keep, drop,
df_r: dfrUse, df_m: dfn, resid, fitted, hat, rss, tss, mss, s2, rmse, r2, r2a, F, pF: pFv,
ll, aic: -2 * ll + 2 * (kk + 1), bic: -2 * ll + Math.log(n) * (kk + 1),
names: opts.names, vce: vceLabel, nclust, level, ybar, X, y, noCons: !!opts.noCons };
}
/* Wald F for a set of coefficient indices being jointly zero */
function waldF(b, V, idx, dfr) {
const q = idx.length, sub = zeros(q, q);
for (let i = 0; i < q; i++) for (let j = 0; j < q; j++) sub[i][j] = V[idx[i]][idx[j]];
const Si = genInv(sub); if (!Si) return NA;
const bs = idx.map(i => b[i]);
let s = 0;
for (let i = 0; i < q; i++) for (let j = 0; j < q; j++) s += bs[i] * Si[i][j] * bs[j];
return s / q;
}
/* Wald test of general restrictions R b = r */
function waldR(b, V, R, r, dfr) {
const q = R.length;
const Rb = R.map((row, i) => row.reduce((s, v, j) => s + v * b[j], 0) - r[i]);
const RV = mmul(mmul(R, V), mtrans(R));
const Si = genInv(RV); if (!Si) return null;
let s = 0;
for (let i = 0; i < q; i++) for (let j = 0; j < q; j++) s += Rb[i] * Si[i][j] * Rb[j];
return { chi2: s, F: s / q, df: q, df_r: dfr, p_F: pF(s / q, q, dfr), p_chi2: pChi2(s, q) };
}
/* ---------- Maximum-likelihood binary / count models ---------- */
function glm(y, X, family, opts) {
opts = opts || {};
const n = y.length, k = X[0].length;
let b = new Array(k).fill(0);
// sensible start: constant at link of mean
const ybar = mean(y);
if (opts.consIdx !== undefined) {
b[opts.consIdx] = family === 'poisson' ? Math.log(Math.max(ybar, 1e-3))
: family === 'logit' ? Math.log(ybar / (1 - ybar)) : norminv(Math.min(Math.max(ybar, .01), .99));
}
const link = xb => {
if (family === 'logit') { const p = 1 / (1 + Math.exp(-Math.max(-500, Math.min(500, xb)))); return p; }
if (family === 'probit') return normcdf(xb);
return Math.exp(Math.max(-500, Math.min(500, xb)));
};
let ll = -Infinity, iter = 0, conv = false, XXi = null, drop = [];
const scores = zeros(n, k);
for (iter = 1; iter <= 100; iter++) {
const g = new Array(k).fill(0), H = zeros(k, k);
let llNew = 0;
for (let i = 0; i < n; i++) {
let xb = 0; for (let a = 0; a < k; a++) xb += X[i][a] * b[a];
let sc, wt;
if (family === 'poisson') {
const mu = link(xb);
llNew += y[i] * xb - mu - lgamma(y[i] + 1);
sc = y[i] - mu; wt = mu;
} else if (family === 'logit') {
const p = link(xb);
llNew += y[i] ? Math.log(Math.max(p, 1e-300)) : Math.log(Math.max(1 - p, 1e-300));
sc = y[i] - p; wt = p * (1 - p);
} else {
const P = Math.min(Math.max(link(xb), 1e-12), 1 - 1e-12), phi = normpdf(xb);
llNew += y[i] ? Math.log(P) : Math.log(1 - P);
const lam = phi / (P * (1 - P));
sc = lam * (y[i] - P); wt = phi * phi / (P * (1 - P));
}
for (let a = 0; a < k; a++) { g[a] += sc * X[i][a]; scores[i][a] = sc * X[i][a];
for (let c = 0; c < k; c++) H[a][c] += wt * X[i][a] * X[i][c]; }
}
const r = symInv(H); XXi = r.inv; drop = r.drop;
const step = mvec(XXi, g);
let lam = 1, ok = false;
for (let h = 0; h < 25; h++) { // step halving
const bt = b.map((v, a) => v + lam * step[a]);
let llt = 0;
for (let i = 0; i < n; i++) { let xb = 0; for (let a = 0; a < k; a++) xb += X[i][a] * bt[a];
if (family === 'poisson') llt += y[i] * xb - link(xb) - lgamma(y[i] + 1);
else if (family === 'logit') { const p = link(xb);
llt += y[i] ? Math.log(Math.max(p, 1e-300)) : Math.log(Math.max(1 - p, 1e-300)); }
else { const P = Math.min(Math.max(link(xb), 1e-12), 1 - 1e-12);
llt += y[i] ? Math.log(P) : Math.log(1 - P); } }
if (llt >= llNew - 1e-9 || h === 24) { b = bt; ll = llt; ok = true; break; }
lam /= 2;
}
if (Math.abs(ll - llNew) < 1e-10 * (Math.abs(ll) + 1) && iter > 1) { conv = true; break; }
if (Math.max(...step.map(Math.abs)) < 1e-10) { conv = true; break; }
}
for (const j of drop) b[j] = 0;
let V = XXi;
let vceLabel = 'OIM';
if (opts.vce === 'robust' || opts.vce === 'cluster') {
const meat = zeros(k, k);
if (opts.vce === 'cluster') {
const groups = new Map();
for (let i = 0; i < n; i++) { const key = String(opts.cluster[i]);
if (!groups.has(key)) groups.set(key, []); groups.get(key).push(i); }
for (const idx of groups.values()) { const s = new Array(k).fill(0);
for (const i of idx) for (let a = 0; a < k; a++) s[a] += scores[i][a];
for (let a = 0; a < k; a++) for (let c = 0; c < k; c++) meat[a][c] += s[a] * s[c]; }
const G = groups.size;
V = mscale(sandwich(XXi, meat), G / (G - 1));
vceLabel = 'Cluster-robust (' + G + ' clusters)';
} else {
for (let i = 0; i < n; i++) for (let a = 0; a < k; a++) for (let c = 0; c < k; c++)
meat[a][c] += scores[i][a] * scores[i][c];
V = sandwich(XXi, meat); vceLabel = 'Robust';
}
}
const se = [], zv = [], pv = [], lo = [], hi = [];
const crit = Math.abs(norminv((1 - (opts.level || 95) / 100) / 2));
for (let a = 0; a < k; a++) {
if (drop.includes(a)) { se.push(NA); zv.push(NA); pv.push(NA); lo.push(NA); hi.push(NA); continue; }
const s = Math.sqrt(Math.max(V[a][a], 0));
se.push(s); const z = b[a] / s; zv.push(z); pv.push(pZ(z));
lo.push(b[a] - crit * s); hi.push(b[a] + crit * s);
}
// null model log-likelihood
let ll0;
if (family === 'poisson') { const m = mean(y);
ll0 = y.reduce((s, v) => s + v * Math.log(m) - m - lgamma(v + 1), 0); }
else { const p = mean(y);
ll0 = y.reduce((s, v) => s + (v ? Math.log(p) : Math.log(1 - p)), 0); }
const kk = k - drop.length;
const dfm = opts.consIdx !== undefined ? kk - 1 : kk;
const lr = 2 * (ll - ll0);
const xb = X.map(r => r.reduce((s, v, a) => s + v * b[a], 0));
const mu = xb.map(link);
return { type: family, b, se, t: zv, p: pv, ci_lo: lo, ci_hi: hi, V, n, k: kk, drop,
ll, ll0, lr, p_lr: pChi2(lr, dfm), r2p: 1 - ll / ll0, df_m: dfm, iter, conv,
aic: -2 * ll + 2 * kk, bic: -2 * ll + Math.log(n) * kk,
xb, mu, fitted: mu, resid: y.map((v, i) => v - mu[i]), names: opts.names,
vce: vceLabel, level: opts.level || 95, X, y, family, consIdx: opts.consIdx };
}
/* Average marginal effects via numeric delta method */
function margins(m) {
const k = m.b.length, n = m.n;
const ame = bv => {
const out = new Array(k).fill(0);
for (let i = 0; i < n; i++) {
let xb = 0; for (let a = 0; a < k; a++) xb += m.X[i][a] * bv[a];
let d;
if (m.family === 'logit') { const p = 1 / (1 + Math.exp(-xb)); d = p * (1 - p); }
else if (m.family === 'probit') d = normpdf(xb);
else d = Math.exp(Math.max(-500, Math.min(500, xb)));
for (let a = 0; a < k; a++) out[a] += d * bv[a] / n;
}
return out;
};
const m0 = ame(m.b), J = zeros(k, k);
for (let a = 0; a < k; a++) {
const h = Math.max(1e-6, Math.abs(m.b[a]) * 1e-6);
const bp = m.b.slice(); bp[a] += h;
const mp = ame(bp);
for (let r = 0; r < k; r++) J[r][a] = (mp[r] - m0[r]) / h;
}
const V = mmul(mmul(J, m.V), mtrans(J));
const se = m0.map((_, a) => Math.sqrt(Math.max(V[a][a], 0)));
const z = m0.map((v, a) => v / se[a]);
const crit = Math.abs(norminv(0.025));
return { dy: m0, se, z, p: z.map(pZ), lo: m0.map((v, a) => v - crit * se[a]),
hi: m0.map((v, a) => v + crit * se[a]), names: m.names, consIdx: m.consIdx };
}
/* ---------- Instrumental variables / 2SLS ---------- */
function ivreg(y, Xexog, Xendo, Zinst, opts) {
opts = opts || {};
const n = y.length;
const X = Xexog.map((r, i) => r.concat(Xendo[i]));
const Z = Xexog.map((r, i) => r.concat(Zinst[i]));
const k = X[0].length;
const Zt = mtrans(Z), ZZ = mmul(Zt, Z);
const ZZi = symInv(ZZ).inv;
const ZX = mmul(Zt, X), Zy = mvec(Zt, y);
const A = mmul(mmul(mtrans(ZX), ZZi), ZX);
const rA = symInv(A);
const bhat = mvec(rA.inv, mvec(mmul(mtrans(ZX), ZZi), Zy));
const fitted = mvec(X, bhat), resid = y.map((v, i) => v - fitted[i]);
const rss = resid.reduce((s, v) => s + v * v, 0);
const dfr = n - k, s2 = rss / dfr;
let V;
if (opts.vce === 'robust' || opts.vce === 'cluster') {
// sandwich on the 2SLS estimator using Xhat
const Xhat = mmul(mmul(Z, ZZi), ZX);
const XhXh = mmul(mtrans(Xhat), Xhat), Bi = symInv(XhXh).inv;
const meat = zeros(k, k);
if (opts.vce === 'cluster') {
const groups = new Map();
for (let i = 0; i < n; i++) { const key = String(opts.cluster[i]);
if (!groups.has(key)) groups.set(key, []); groups.get(key).push(i); }
for (const idx of groups.values()) { const s = new Array(k).fill(0);
for (const i of idx) for (let a = 0; a < k; a++) s[a] += Xhat[i][a] * resid[i];
for (let a = 0; a < k; a++) for (let c = 0; c < k; c++) meat[a][c] += s[a] * s[c]; }
const G = groups.size;
V = mscale(sandwich(Bi, meat), (G / (G - 1)) * ((n - 1) / (n - k)));
} else {
for (let i = 0; i < n; i++) for (let a = 0; a < k; a++) for (let c = 0; c < k; c++)
meat[a][c] += resid[i] * resid[i] * Xhat[i][a] * Xhat[i][c];
V = mscale(sandwich(Bi, meat), n / (n - k));
}
} else V = mscale(rA.inv, s2);
const se = [], t = [], p = [], lo = [], hi = [];
const crit = Math.abs(tinv(0.025, dfr));
for (let a = 0; a < k; a++) { const s = Math.sqrt(Math.max(V[a][a], 0));
se.push(s); const tt = bhat[a] / s; t.push(tt); p.push(pT(tt, dfr));
lo.push(bhat[a] - crit * s); hi.push(bhat[a] + crit * s); }
const ybar = mean(y);
const tss = y.reduce((s, v) => s + (v - ybar) * (v - ybar), 0);
const nEndo = Xendo[0] ? Xendo[0].length : 0, nInst = Zinst[0] ? Zinst[0].length : 0;
// first-stage F on excluded instruments, per endogenous regressor
const first = [];
for (let e = 0; e < nEndo; e++) {
const ye = Xendo.map(r => r[e]);
const f = ols(ye, Z, { names: [] });
const nx = Xexog[0].length;
const idx = []; for (let a = nx; a < Z[0].length; a++) idx.push(a);
first.push({ F: waldF(f.b, f.V, idx, f.df_r), df1: idx.length, df_r: f.df_r, r2: f.r2,
p: pF(waldF(f.b, f.V, idx, f.df_r), idx.length, f.df_r) });
}
// Sargan overidentification test
let sargan = null;
if (nInst > nEndo) {
const aux = ols(resid, Z, { names: [] });
const st = n * aux.r2;
sargan = { chi2: st, df: nInst - nEndo, p: pChi2(st, nInst - nEndo) };
}
return { type: 'ivreg', b: bhat, se, t, p, ci_lo: lo, ci_hi: hi, V, n, k, df_r: dfr,
resid, fitted, rss, tss, r2: 1 - rss / tss,
r2a: 1 - (1 - (1 - rss / tss)) * (n - 1) / dfr, rmse: Math.sqrt(s2),
names: opts.names, first, sargan, nEndo, nInst,
vce: opts.vce === 'robust' ? 'Robust' : opts.vce === 'cluster' ? 'Cluster-robust' : '2SLS',
F: waldF(bhat, V, opts.consIdx !== undefined ? bhat.map((_, i) => i).filter(i => i !== opts.consIdx)
: bhat.map((_, i) => i), dfr), X, y, level: 95 };
}
/* ---------- Panel: fixed / random effects ---------- */
function panelFE(y, X, id, opts) {
opts = opts || {};
const n = y.length, k = X[0].length;
const groups = new Map();
for (let i = 0; i < n; i++) { const key = String(id[i]);
if (!groups.has(key)) groups.set(key, []); groups.get(key).push(i); }
const G = groups.size;
const yd = y.slice(), Xd = X.map(r => r.slice());
const ybarG = new Map();
for (const [g, idx] of groups) {
const my = mean(idx.map(i => y[i]));
ybarG.set(g, my);
const mx = new Array(k).fill(0);
for (const i of idx) for (let a = 0; a < k; a++) mx[a] += X[i][a] / idx.length;
for (const i of idx) { yd[i] = y[i] - my; for (let a = 0; a < k; a++) Xd[i][a] = X[i][a] - mx[a]; }
}
const gm = mean(y);
const m = ols(yd, Xd, { names: opts.names, noCons: true, vce: opts.vce, cluster: opts.cluster });
// correct degrees of freedom for the absorbed effects
const dfr = n - G - k;
const s2 = m.rss / dfr;
const V = mscale(m.XXi, s2);
const se = [], t = [], p = [], lo = [], hi = [];
const dfUse = opts.vce === 'cluster' ? G - 1 : dfr;
const Vuse = opts.vce ? mscale(m.V, m.df_r / dfr) : V;
const crit = Math.abs(tinv(0.025, dfUse));
for (let a = 0; a < k; a++) { const s = Math.sqrt(Math.max(Vuse[a][a], 0));
se.push(s); const tt = m.b[a] / s; t.push(tt); p.push(pT(tt, dfUse));
lo.push(m.b[a] - crit * s); hi.push(m.b[a] + crit * s); }
// constant = grand mean of y minus grand mean X * b
let cons = gm;
for (let a = 0; a < k; a++) { let mx = 0; for (let i = 0; i < n; i++) mx += X[i][a] / n; cons -= mx * m.b[a]; }
// variance components
const ui = [];
for (const [g, idx] of groups) { let s = ybarG.get(g);
for (let a = 0; a < k; a++) { let mx = 0; for (const i of idx) mx += X[i][a] / idx.length; s -= mx * m.b[a]; }
ui.push(s - cons); }
const sigma_u = sd(ui), sigma_e = Math.sqrt(s2);
const rho = sigma_u * sigma_u / (sigma_u * sigma_u + sigma_e * sigma_e);
const idxAll = []; for (let a = 0; a < k; a++) idxAll.push(a);
const F = waldF(m.b, Vuse, idxAll, dfUse);
// between / overall R2
const fitted = X.map(r => cons + r.reduce((s, v, a) => s + v * m.b[a], 0));
const r2o = Math.pow(corr(fitted, y), 2);
const Fu = ((m.rss === 0) ? NA : null);
return { type: 'fe', b: m.b, se, t, p, ci_lo: lo, ci_hi: hi, V: Vuse, n, k, G, df_r: dfUse,
df_m: k, resid: m.resid, fitted, rss: m.rss, r2: m.r2, r2_within: m.r2, r2_overall: r2o,
rmse: sigma_e, sigma_u, sigma_e, rho, cons, F, pF: pF(F, k, dfUse),
names: opts.names, vce: opts.vce ? m.vce : 'OLS', level: 95, X, y };
}
/* Random effects (Swamy-Arora style GLS) */
function panelRE(y, X, id, opts) {
opts = opts || {};
const n = y.length, k = X[0].length;
const groups = new Map();
for (let i = 0; i < n; i++) { const key = String(id[i]);
if (!groups.has(key)) groups.set(key, []); groups.get(key).push(i); }
const G = groups.size;
const fe = panelFE(y, X, id, { names: opts.names });
const sigma_e2 = fe.sigma_e * fe.sigma_e;
// between regression
const yb = [], Xb = [], Tb = [];
for (const [, idx] of groups) {
yb.push(mean(idx.map(i => y[i])));
const mx = new Array(k).fill(0);
for (const i of idx) for (let a = 0; a < k; a++) mx[a] += X[i][a] / idx.length;
Xb.push(mx.concat([1])); Tb.push(idx.length);
}
const be = ols(yb, Xb, { names: [] });
const Tbar = n / G;
let sigma_u2 = Math.max(be.s2 - sigma_e2 / Tbar, 0);
// GLS transform
const yg = [], Xg = [];
for (const [, idx] of groups) {
const T = idx.length;
const theta = 1 - Math.sqrt(sigma_e2 / (T * sigma_u2 + sigma_e2));
const my = mean(idx.map(i => y[i]));
const mx = new Array(k).fill(0);
for (const i of idx) for (let a = 0; a < k; a++) mx[a] += X[i][a] / T;
for (const i of idx) {
yg.push(y[i] - theta * my);
const row = []; for (let a = 0; a < k; a++) row.push(X[i][a] - theta * mx[a]);
row.push(1 - theta); Xg.push(row);
}
}
const m = ols(yg, Xg, { names: (opts.names || []).concat(['_cons']), consIdx: k, vce: opts.vce, cluster: opts.cluster });
const su = Math.sqrt(sigma_u2), se_ = Math.sqrt(sigma_e2);
const fitted = X.map((r, i) => r.reduce((s, v, a) => s + v * m.b[a], 0) + m.b[k]);
const wald = waldF(m.b, m.V, Array.from({ length: k }, (_, i) => i), 1e6) * k;
return Object.assign({}, m, { type: 're', G, sigma_u: su, sigma_e: se_,
rho: sigma_u2 / (sigma_u2 + sigma_e2), theta: 1 - Math.sqrt(sigma_e2 / (Tbar * sigma_u2 + sigma_e2)),
fitted, resid: y.map((v, i) => v - fitted[i]), chi2: wald, p_chi2: pChi2(wald, k),
r2_within: fe.r2_within, r2_overall: Math.pow(corr(fitted, y), 2), names: m.names });
}
/* Hausman test FE vs RE */
function hausman(fe, re, k) {
const d = [], Vd = zeros(k, k);
for (let a = 0; a < k; a++) { d.push(fe.b[a] - re.b[a]);
for (let c = 0; c < k; c++) Vd[a][c] = fe.V[a][c] - re.V[a][c]; }
const Vi = genInv(Vd); if (!Vi) return null;
let s = 0;
for (let a = 0; a < k; a++) for (let c = 0; c < k; c++) s += d[a] * Vi[a][c] * d[c];
return { chi2: s, df: k, p: pChi2(s, k) };
}
/* ---------- Quantile regression (IRLS on the check function) ---------- */
function qreg(y, X, tau, opts) {
opts = opts || {};
const n = y.length, k = X[0].length;
let b = ols(y, X, {}).b;
for (let it = 0; it < 200; it++) {
const w = [];
for (let i = 0; i < n; i++) {
let xb = 0; for (let a = 0; a < k; a++) xb += X[i][a] * b[a];
const u = y[i] - xb;
const wt = (u > 0 ? tau : 1 - tau) / Math.max(Math.abs(u), 1e-6);
w.push(wt);
}
const nb = ols(y, X, { weights: w }).b;
const diff = Math.max(...nb.map((v, a) => Math.abs(v - b[a])));
b = nb;
if (diff < 1e-8) break;
}
const resid = y.map((v, i) => v - X[i].reduce((s, x, a) => s + x * b[a], 0));
// sparsity-function (Powell) kernel estimate of the asymptotic variance
const h = Math.pow(n, -1 / 5) * Math.min(sd(resid), (quantile(resid, .75) - quantile(resid, .25)) / 1.34);
const J = zeros(k, k), H = zeros(k, k);
for (let i = 0; i < n; i++) {
const f = normpdf(resid[i] / h) / h;
const psi = tau - (resid[i] < 0 ? 1 : 0);
for (let a = 0; a < k; a++) for (let c = 0; c < k; c++) {
H[a][c] += f * X[i][a] * X[i][c];
J[a][c] += psi * psi * X[i][a] * X[i][c];
}
}
const Hi = symInv(H).inv;
const V = mmul(mmul(Hi, J), Hi);
const se = [], t = [], p = [], lo = [], hi = [];
const dfr = n - k, crit = Math.abs(tinv(0.025, dfr));
for (let a = 0; a < k; a++) { const s = Math.sqrt(Math.max(V[a][a], 0));
se.push(s); const tt = b[a] / s; t.push(tt); p.push(pT(tt, dfr));
lo.push(b[a] - crit * s); hi.push(b[a] + crit * s); }
const absdev = resid.reduce((s, u) => s + (u > 0 ? tau * u : (tau - 1) * u), 0);
const y0 = quantile(y, tau);
const absdev0 = y.reduce((s, v) => { const u = v - y0; return s + (u > 0 ? tau * u : (tau - 1) * u); }, 0);
return { type: 'qreg', b, se, t, p, ci_lo: lo, ci_hi: hi, V, n, k, df_r: dfr, tau,
resid, fitted: y.map((v, i) => v - resid[i]), absdev, r2: 1 - absdev / absdev0,
names: opts.names, vce: 'Powell kernel', level: 95, X, y };
}
/* ============================================================
DIAGNOSTIC TESTS
============================================================ */
function bpTest(m, koenker) {
const n = m.n, u2 = m.resid.map(v => v * v);
const s2 = m.rss / n;
const g = koenker ? u2 : u2.map(v => v / s2);
const aux = ols(g, m.X, { names: [] });
const df = m.k - 1;
let stat, p;
if (koenker) { stat = n * aux.r2; p = pChi2(stat, df); }
else { stat = (aux.tss - aux.rss) / 2; p = pChi2(stat, df); }
return { chi2: stat, df, p };
}
function whiteTest(m) {
const n = m.n, X = m.X, k = X[0].length;
// build squares and cross-products of non-constant regressors
const varCols = [];
for (let a = 0; a < k; a++) { const col = X.map(r => r[a]);
if (sd(col) > 1e-12) varCols.push(a); }
const rows = [];
for (let i = 0; i < n; i++) {
const r = [1];
for (const a of varCols) r.push(X[i][a]);
for (let x = 0; x < varCols.length; x++) for (let y2 = x; y2 < varCols.length; y2++)
r.push(X[i][varCols[x]] * X[i][varCols[y2]]);
rows.push(r);
}
const u2 = m.resid.map(v => v * v);
const aux = ols(u2, rows, { names: [] });
const df = aux.k - 1, stat = n * aux.r2;
return { chi2: stat, df, p: pChi2(stat, df) };
}
function dwStat(m) {
let num = 0, den = 0;
for (let i = 1; i < m.resid.length; i++) num += Math.pow(m.resid[i] - m.resid[i - 1], 2);
for (const u of m.resid) den += u * u;
return num / den;
}
function bgTest(m, p) {
const n = m.n, u = m.resid;
const rows = [], yv = [];
for (let i = p; i < n; i++) {
const r = m.X[i].slice();
for (let l = 1; l <= p; l++) r.push(u[i - l]);
rows.push(r); yv.push(u[i]);
}
const aux = ols(yv, rows, { names: [] });
const stat = (n - p) * aux.r2;
return { chi2: stat, df: p, p: pChi2(stat, p), lags: p };
}
function archTest(u, p) {
const n = u.length, rows = [], yv = [];
for (let i = p; i < n; i++) {
const r = [1];
for (let l = 1; l <= p; l++) r.push(u[i - l] * u[i - l]);
rows.push(r); yv.push(u[i] * u[i]);
}
const aux = ols(yv, rows, { names: [] });
const stat = (n - p) * aux.r2;
return { chi2: stat, df: p, p: pChi2(stat, p), lags: p };
}
function resetTest(m) {
const rows = m.X.map((r, i) => r.concat([Math.pow(m.fitted[i], 2), Math.pow(m.fitted[i], 3),
Math.pow(m.fitted[i], 4)]));
const aux = ols(m.y, rows, { names: [] });
const k0 = m.X[0].length;
const idx = [k0, k0 + 1, k0 + 2];
const F = waldF(aux.b, aux.V, idx, aux.df_r);
return { F, df1: 3, df2: aux.df_r, p: pF(F, 3, aux.df_r) };
}
function jbTest(a) {
const v = a.filter(isNum), n = v.length;
const s = skewness(v), kk = kurtosis(v);
const jb = n / 6 * (s * s + Math.pow(kk - 3, 2) / 4);
return { jb, skew: s, kurt: kk, p: pChi2(jb, 2), n };
}
function skTest(a) { // D'Agostino-Pearson style skewness/kurtosis test
const v = a.filter(isNum), n = v.length;
const b1 = skewness(v), b2 = kurtosis(v);
const Y = b1 * Math.sqrt((n + 1) * (n + 3) / (6 * (n - 2)));
const b2s = 3 * (n * n + 27 * n - 70) * (n + 1) * (n + 3) / ((n - 2) * (n + 5) * (n + 7) * (n + 9));
const W2 = -1 + Math.sqrt(2 * (b2s - 1)), d = 1 / Math.sqrt(Math.log(Math.sqrt(W2)));
const al = Math.sqrt(2 / (W2 - 1));
const Z1 = d * Math.log(Y / al + Math.sqrt(Math.pow(Y / al, 2) + 1));
const Eb2 = 3 * (n - 1) / (n + 1);
const Vb2 = 24 * n * (n - 2) * (n - 3) / ((n + 1) * (n + 1) * (n + 3) * (n + 5));
const X2 = (b2 - Eb2) / Math.sqrt(Vb2);
const B = 6 * (n * n - 5 * n + 2) / ((n + 7) * (n + 9)) * Math.sqrt(6 * (n + 3) * (n + 5) / (n * (n - 2) * (n - 3)));
const A = 6 + 8 / B * (2 / B + Math.sqrt(1 + 4 / (B * B)));
const Z2 = ((1 - 2 / (9 * A)) - Math.pow((1 - 2 / A) / (1 + X2 * Math.sqrt(2 / (A - 4))), 1 / 3)) / Math.sqrt(2 / (9 * A));
const K2 = Z1 * Z1 + Z2 * Z2;
return { n, pSkew: pZ(Z1), pKurt: pZ(Z2), chi2: K2, p: pChi2(K2, 2), skew: b1, kurt: b2 };
}
function vif(m) {
const X = m.X, k = X[0].length, out = [];
for (let a = 0; a < k; a++) {
const col = X.map(r => r[a]);
if (sd(col) < 1e-12) continue; // constant
const others = X.map(r => r.filter((_, j) => j !== a));
const r = ols(col, others, { names: [] });
out.push({ name: m.names[a], vif: 1 / (1 - r.r2), tol: 1 - r.r2 });
}
return out;
}
/* ---------- Time series ---------- */
function acf(x, maxlag) {
const v = x.filter(isNum), n = v.length, m = mean(v);
const c0 = v.reduce((s, u) => s + (u - m) * (u - m), 0) / n;
const out = [];
for (let l = 1; l <= maxlag; l++) {
let s = 0;
for (let i = l; i < n; i++) s += (v[i] - m) * (v[i - l] - m);
out.push(s / n / c0);
}
return out;
}
function pacf(r) { // Durbin-Levinson from acf
const p = r.length, phi = zeros(p + 1, p + 1), out = [];
phi[1][1] = r[0]; out.push(r[0]);
for (let k = 2; k <= p; k++) {
let num = r[k - 1], den = 1;
for (let j = 1; j < k; j++) { num -= phi[k - 1][j] * r[k - j - 1]; den -= phi[k - 1][j] * r[j - 1]; }
phi[k][k] = num / den; out.push(phi[k][k]);
for (let j = 1; j < k; j++) phi[k][j] = phi[k - 1][j] - phi[k][k] * phi[k - 1][k - j];
}
return out;
}
function ljungBox(r, n) {
const out = []; let s = 0;
for (let l = 0; l < r.length; l++) { s += r[l] * r[l] / (n - l - 1);
const q = n * (n + 2) * s; out.push({ lag: l + 1, q, p: pChi2(q, l + 1) }); }
return out;
}
const DF_Q = {
nc: [[.01, -2.58], [.025, -2.23], [.05, -1.95], [.10, -1.62], [.50, -0.50], [.90, 0.89], [.95, 1.28], [.99, 2.00]],
c: [[.01, -3.43], [.025, -3.12], [.05, -2.86], [.10, -2.57], [.50, -1.57], [.90, -0.44], [.95, -0.07], [.99, 0.60]],
ct: [[.01, -3.96], [.025, -3.66], [.05, -3.41], [.10, -3.12], [.50, -2.18], [.90, -1.25], [.95, -0.94], [.99, -0.32]]
};
function dfPvalue(t, kind) {
const q = DF_Q[kind];
if (t <= q[0][1]) return 0.005;
if (t >= q[q.length - 1][1]) return 0.995;
for (let i = 1; i < q.length; i++) if (t <= q[i][1]) {
const [p0, t0] = q[i - 1], [p1, t1] = q[i];
return p0 + (p1 - p0) * (t - t0) / (t1 - t0);
}
return NA;
}
function adf(x, lags, kind) { // kind: 'nc' | 'c' | 'ct'
const v = x.filter(isNum), n = v.length;
const yv = [], rows = [];
for (let i = lags + 1; i < n; i++) {
const r = [];
if (kind !== 'nc') r.push(1);
if (kind === 'ct') r.push(i);
r.push(v[i - 1]);
for (let l = 1; l <= lags; l++) r.push(v[i - l] - v[i - l - 1]);
rows.push(r); yv.push(v[i] - v[i - 1]);
}
const m = ols(yv, rows, { names: [] });
const pos = (kind === 'nc' ? 0 : kind === 'ct' ? 2 : 1);
const t = m.b[pos] / m.se[pos];
const q = DF_Q[kind];
return { t, rho: m.b[pos], lags, kind, n: yv.length,
crit: { '1%': q[0][1], '5%': q[2][1], '10%': q[3][1] }, p: dfPvalue(t, kind), model: m };
}
/* ---------- Classic hypothesis tests ---------- */
function ttest1(x, mu0) {
const v = x.filter(isNum), n = v.length, m = mean(v), s = sd(v);
const semean = s / Math.sqrt(n), t = (m - mu0) / semean, df = n - 1;
const c = Math.abs(tinv(0.025, df));
return { n, mean: m, sd: s, se: semean, t, df, mu0,
p2: pT(t, df), pl: tcdf(t, df), pu: 1 - tcdf(t, df),
lo: m - c * semean, hi: m + c * semean };
}
function ttest2(x1, x2, welch) {
const a = x1.filter(isNum), b = x2.filter(isNum);
const n1 = a.length, n2 = b.length, m1 = mean(a), m2 = mean(b), v1 = variance(a), v2 = variance(b);
let t, df, se;
if (welch) { se = Math.sqrt(v1 / n1 + v2 / n2);
df = Math.pow(v1 / n1 + v2 / n2, 2) / (Math.pow(v1 / n1, 2) / (n1 - 1) + Math.pow(v2 / n2, 2) / (n2 - 1));
} else { const sp2 = ((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2);
se = Math.sqrt(sp2 * (1 / n1 + 1 / n2)); df = n1 + n2 - 2; }
t = (m1 - m2) / se;
const c = Math.abs(tinv(0.025, df));
return { n1, n2, m1, m2, sd1: Math.sqrt(v1), sd2: Math.sqrt(v2),
se1: Math.sqrt(v1 / n1), se2: Math.sqrt(v2 / n2), diff: m1 - m2, se, t, df,
p2: pT(t, df), pl: tcdf(t, df), pu: 1 - tcdf(t, df),
lo: m1 - m2 - c * se, hi: m1 - m2 + c * se, welch: !!welch };
}
function ttestPaired(x1, x2) {
const d = [];
for (let i = 0; i < x1.length; i++) if (isNum(x1[i]) && isNum(x2[i])) d.push(x1[i] - x2[i]);
const r = ttest1(d, 0);
r.m1 = mean(x1.filter(isNum)); r.m2 = mean(x2.filter(isNum));
return r;
}
function okGroup(v) {
return v !== undefined && v !== null && v !== '' && !(typeof v === 'number' && isNaN(v));
}
function anova1(vals, groups) {
const g = new Map();
for (let i = 0; i < vals.length; i++) if (isNum(vals[i]) && okGroup(groups[i])) {
const key = String(groups[i]); if (!g.has(key)) g.set(key, []); g.get(key).push(vals[i]); }
const all = [].concat(...g.values()), N = all.length, gm = mean(all), K = g.size;
let ssb = 0, ssw = 0;
const rows = [];
for (const [key, arr] of g) { const m = mean(arr);
ssb += arr.length * (m - gm) * (m - gm);
for (const v of arr) ssw += (v - m) * (v - m);
rows.push({ key, n: arr.length, mean: m, sd: sd(arr) }); }
rows.sort((a, b) => cmpKey(a.key, b.key));
const df1 = K - 1, df2 = N - K, F = (ssb / df1) / (ssw / df2);
// Bartlett test for equal variances
let sp2 = ssw / df2, num = df2 * Math.log(sp2), den = 0, cc = 0;
for (const [, arr] of g) { num -= (arr.length - 1) * Math.log(variance(arr));
cc += 1 / (arr.length - 1); }
const C = 1 + (cc - 1 / df2) / (3 * (K - 1));
const bart = num / C;
return { rows, N, K, ssb, ssw, sst: ssb + ssw, df1, df2, F, p: pF(F, df1, df2),
r2: ssb / (ssb + ssw), rmse: Math.sqrt(sp2), bartlett: bart, pBart: pChi2(bart, K - 1) };
}
function ranksum(vals, groups) {
const pairs = [];
for (let i = 0; i < vals.length; i++) if (isNum(vals[i]) && okGroup(groups[i]))
pairs.push([vals[i], String(groups[i])]);
const keys = [...new Set(pairs.map(p => p[1]))].sort(cmpKey);
if (keys.length !== 2) return null;
const r = ranks(pairs.map(p => p[0]));
let n1 = 0, n2 = 0, R1 = 0;
const counts = new Map();
for (const [v] of pairs) counts.set(v, (counts.get(v) || 0) + 1);
for (let i = 0; i < pairs.length; i++) { if (pairs[i][1] === keys[0]) { n1++; R1 += r[i]; } else n2++; }
const N = n1 + n2, ER = n1 * (N + 1) / 2;
let tieAdj = 0; for (const c of counts.values()) tieAdj += c * c * c - c;
const V = n1 * n2 / 12 * ((N + 1) - tieAdj / (N * (N - 1)));
const z = (R1 - ER) / Math.sqrt(V);
return { keys, n1, n2, R1, ER, z, p: pZ(z), U: R1 - n1 * (n1 + 1) / 2 };
}
function signrank(x, mu0) {
const d = [];
for (const v of x) if (isNum(v) && v !== mu0) d.push(v - mu0);
const ad = d.map(Math.abs), r = ranks(ad);
let Wp = 0, Wn = 0;
for (let i = 0; i < d.length; i++) { if (d[i] > 0) Wp += r[i]; else Wn += r[i]; }
const n = d.length, E = n * (n + 1) / 4;
const counts = new Map(); for (const v of ad) counts.set(v, (counts.get(v) || 0) + 1);
let tie = 0; for (const c of counts.values()) tie += c * c * c - c;
const V = n * (n + 1) * (2 * n + 1) / 24 - tie / 48;
const z = (Wp - E) / Math.sqrt(V);
return { n, Wp, Wn, E, z, p: pZ(z) };
}
function kwallis(vals, groups) {
const pairs = [];
for (let i = 0; i < vals.length; i++) if (isNum(vals[i]) && okGroup(groups[i]))
pairs.push([vals[i], String(groups[i])]);
const r = ranks(pairs.map(p => p[0])), N = pairs.length;
const g = new Map();
for (let i = 0; i < pairs.length; i++) { const k = pairs[i][1];
if (!g.has(k)) g.set(k, { n: 0, R: 0 }); const o = g.get(k); o.n++; o.R += r[i]; }
let H = 0;
for (const o of g.values()) H += o.R * o.R / o.n;
H = 12 / (N * (N + 1)) * H - 3 * (N + 1);
const counts = new Map(); for (const [v] of pairs) counts.set(v, (counts.get(v) || 0) + 1);
let tie = 0; for (const c of counts.values()) tie += c * c * c - c;
const Hc = H / (1 - tie / (N * N * N - N));
const df = g.size - 1;
return { rows: [...g.entries()].map(([k, o]) => ({ key: k, n: o.n, R: o.R })), N,
H, Hc, df, p: pChi2(Hc, df) };
}
function spearman(a, b) {
const idx = [];
for (let i = 0; i < a.length; i++) if (isNum(a[i]) && isNum(b[i])) idx.push(i);
const ra = ranks(idx.map(i => a[i])), rb = ranks(idx.map(i => b[i]));
const r = corr(ra, rb), n = idx.length;
const t = r * Math.sqrt((n - 2) / (1 - r * r));
return { rho: r, n, p: pT(t, n - 2) };
}
function chi2table(rows, cols) {
const rk = [...new Set(rows)].sort(cmpKey), ck = [...new Set(cols)].sort(cmpKey);
const T = zeros(rk.length, ck.length);
for (let i = 0; i < rows.length; i++) {
const a = rk.indexOf(rows[i]), b = ck.indexOf(cols[i]);
if (a >= 0 && b >= 0) T[a][b]++;
}
const rt = T.map(r => r.reduce((s, v) => s + v, 0));
const ct = ck.map((_, j) => T.reduce((s, r) => s + r[j], 0));
const N = rt.reduce((s, v) => s + v, 0);
let chi2 = 0, lr = 0;
for (let i = 0; i < rk.length; i++) for (let j = 0; j < ck.length; j++) {
const e = rt[i] * ct[j] / N;
if (e > 0) { chi2 += Math.pow(T[i][j] - e, 2) / e;
if (T[i][j] > 0) lr += 2 * T[i][j] * Math.log(T[i][j] / e); }
}
const df = (rk.length - 1) * (ck.length - 1);
const V = Math.sqrt(chi2 / (N * Math.min(rk.length - 1, ck.length - 1)));
return { rk, ck, T, rt, ct, N, chi2, lr, df, p: pChi2(chi2, df), pLR: pChi2(lr, df),
cramer: V, gamma: null };
}
function cmpKey(a, b) {
const na = parseFloat(a), nb = parseFloat(b);
if (!isNaN(na) && !isNaN(nb)) return na - nb;
return String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
}
/* Gaussian kernel density */
function kdensity(x, n) {
const v = x.filter(isNum).sort((a, b) => a - b), N = v.length;
if (N < 2) return { x: [], y: [] };
const s = sd(v), iqr = quantile(v, .75) - quantile(v, .25);
const h = 0.9 * Math.min(s, iqr / 1.349 || s) * Math.pow(N, -0.2) || 1;
const lo = v[0] - 3 * h, hi = v[N - 1] + 3 * h, pts = n || 100;
const xs = [], ys = [];
for (let i = 0; i < pts; i++) {
const xx = lo + (hi - lo) * i / (pts - 1);
let d = 0; for (const u of v) d += normpdf((xx - u) / h);
xs.push(xx); ys.push(d / (N * h));
}
return { x: xs, y: ys, h };
}
/* ============================================================
DATA ENGINE
============================================================ */
const DB = {
name: null, n: 0, vars: [], col: {}, labels: {},
tsvar: null, panelvar: null, timevar: null,
last: null, // most recent estimation result
stored: {}, // estimates store
sorted: null
};
function varNames() { return DB.vars.map(v => v.name); }
function hasVar(v) { return DB.vars.some(x => x.name === v); }
function getVar(v) { return DB.vars.find(x => x.name === v); }
function isStr(v) { const o = getVar(v); return o && o.type === 'str'; }
function addVar(name, values, type, label) {
if (!hasVar(name)) DB.vars.push({ name, type: type || 'num', label: label || '' });
else { const o = getVar(name); if (type) o.type = type; if (label) o.label = label; }
DB.col[name] = values;
}
function dropVars(list) {
DB.vars = DB.vars.filter(v => !list.includes(v.name));
for (const v of list) delete DB.col[v];
}
function clearData() {
DB.name = null; DB.n = 0; DB.vars = []; DB.col = {};
DB.tsvar = null; DB.panelvar = null; DB.timevar = null; DB.last = null; DB.stored = {};
}
/* ---------- Expression compiler ----------
Compiles a Stata-ish expression into f(i) over observation index i. */
const AGG_FN = ['mean', 'sd', 'total', 'count', 'median', 'r_min', 'r_max', 'r_sum'];
function tokenize(s) {
const t = [], re = /\s*([A-Za-z_][A-Za-z0-9_]*|\d*\.\d+(?:[eE][+-]?\d+)?|\d+(?:\.\d*)?(?:[eE][+-]?\d+)?|>=|<=|==|!=|~=|&&|\|\||[-+*\/^()<>=!~,&|.])/g;
let m, last = 0;
while ((m = re.exec(s)) !== null) {
if (m.index > last && s.slice(last, m.index).trim()) throw new Error('unrecognized token near "' + s.slice(last, m.index).trim() + '"');
t.push(m[1]); last = re.lastIndex;
}
if (s.slice(last).trim()) throw new Error('unrecognized token near "' + s.slice(last).trim() + '"');
return t;
}
function compileExpr(src) {
const tk = tokenize(src);
let pos = 0;
const peek = () => tk[pos], next = () => tk[pos++];
const expect = c => { if (tk[pos] !== c) throw new Error('expected "' + c + '" in expression'); pos++; };
function primary() {
let t = next();
if (t === undefined) throw new Error('unexpected end of expression');
if (t === '(') { const e = orExpr(); expect(')'); return e; }
if (t === '-') { const e = primary(); return i => -e(i); }
if (t === '+') return primary();
if (t === '!' || t === '~') { const e = primary(); return i => (e(i) ? 0 : 1); }
if (t === '.') return () => NaN;
if (/^[\d.]/.test(t)) { const v = parseFloat(t); return () => v; }
if (/^[A-Za-z_]/.test(t)) {
if (peek() === '(') { // function call
next();
const args = [];
if (peek() !== ')') { args.push(orExpr()); while (peek() === ',') { next(); args.push(orExpr()); } }
expect(')');
return makeFn(t.toLowerCase(), args, tk, pos);
}
if (t === '_n') return i => i + 1;
if (t === '_N') return () => DB.n;
if (t === '_pi') return () => Math.PI;
if (!hasVar(t)) throw new Error('variable ' + t + ' not found');
if (isStr(t)) { const c = DB.col[t]; return i => c[i]; }
const c = DB.col[t];
return i => { const v = c[i]; return v === null || v === undefined || v === '' ? NaN : +v; };
}
if (t === '"' ) throw new Error('string literals use double quotes only in comparisons');
throw new Error('unexpected "' + t + '"');
}
function power() { const l = primary();
if (peek() === '^') { next(); const r = power(); return i => Math.pow(l(i), r(i)); } return l; }
function unary() { if (peek() === '-') { next(); const e = unary(); return i => -e(i); }
if (peek() === '!' || peek() === '~') { next(); const e = unary(); return i => (e(i) ? 0 : 1); } return power(); }
function term() { let l = unary();
while (peek() === '*' || peek() === '/') { const op = next(), r = unary(), L = l;
l = op === '*' ? i => L(i) * r(i) : i => L(i) / r(i); } return l; }
function arith() { let l = term();
while (peek() === '+' || peek() === '-') { const op = next(), r = term(), L = l;
l = op === '+' ? i => L(i) + r(i) : i => L(i) - r(i); } return l; }
function rel() { let l = arith();
while (['<', '>', '<=', '>=', '==', '!=', '~=', '='].includes(peek())) {
const op = next(), r = arith(), L = l;
l = i => { const a = L(i), b = r(i);
const bad = (typeof a === 'number' && isNaN(a)) || (typeof b === 'number' && isNaN(b));
if (bad && op !== '==' && op !== '!=' && op !== '~=') return NaN;
switch (op) { case '<': return a < b ? 1 : 0; case '>': return a > b ? 1 : 0;
case '<=': return a <= b ? 1 : 0; case '>=': return a >= b ? 1 : 0;
case '==': case '=': return a === b || String(a) === String(b) ? 1 : 0;
default: return (a === b || String(a) === String(b)) ? 0 : 1; } };
} return l; }
function andExpr() { let l = rel();
while (peek() === '&' || peek() === '&&') { next(); const r = rel(), L = l;
l = i => (L(i) && r(i)) ? 1 : 0; } return l; }
function orExpr() { let l = andExpr();
while (peek() === '|' || peek() === '||') { next(); const r = andExpr(), L = l;
l = i => (L(i) || r(i)) ? 1 : 0; } return l; }
const f = orExpr();
if (pos < tk.length) throw new Error('trailing "' + tk.slice(pos).join(' ') + '" in expression');
return f;
}
let RNGSTATE = makeRNG(20250401);
function setSeed(s) { RNGSTATE = makeRNG(s); }
function makeFn(name, a, tk, pos) {
const one = f => { if (a.length < 1) throw new Error(name + '() needs an argument'); return f; };
switch (name) {
case 'abs': return one(i => Math.abs(a[0](i)));
case 'ln': case 'log': return one(i => Math.log(a[0](i)));
case 'log10': return one(i => Math.log10(a[0](i)));
case 'exp': return one(i => Math.exp(a[0](i)));
case 'sqrt': return one(i => Math.sqrt(a[0](i)));
case 'sin': return one(i => Math.sin(a[0](i)));
case 'cos': return one(i => Math.cos(a[0](i)));
case 'tan': return one(i => Math.tan(a[0](i)));
case 'atan': return one(i => Math.atan(a[0](i)));
case 'round': return i => a.length > 1 ? Math.round(a[0](i) / a[1](i)) * a[1](i) : Math.round(a[0](i));
case 'int': case 'trunc': return one(i => Math.trunc(a[0](i)));
case 'floor': return one(i => Math.floor(a[0](i)));
case 'ceil': return one(i => Math.ceil(a[0](i)));
case 'sign': return one(i => Math.sign(a[0](i)));
case 'mod': return i => a[0](i) % a[1](i);
case 'max': return i => Math.max(...a.map(f => f(i)));
case 'min': return i => Math.min(...a.map(f => f(i)));
case 'inrange': return i => (a[0](i) >= a[1](i) && a[0](i) <= a[2](i)) ? 1 : 0;
case 'cond': return i => a[0](i) ? a[1](i) : a[2](i);
case 'missing': return one(i => isNaN(a[0](i)) ? 1 : 0);
case 'normal': return one(i => normcdf(a[0](i)));
case 'normalden': return one(i => normpdf(a[0](i)));
case 'invnormal': return one(i => norminv(a[0](i)));
case 'logistic': return one(i => 1 / (1 + Math.exp(-a[0](i))));
case 'lngamma': return one(i => lgamma(a[0](i)));
case 'rnormal': return i => a.length === 2 ? a[0](i) + a[1](i) * RNGSTATE.norm() : RNGSTATE.norm();
case 'runiform': return () => RNGSTATE.unif();
case 'rbinomial': return i => (RNGSTATE.unif() < a[1](i) ? 1 : 0);
case 'rpoisson': return i => { const L = Math.exp(-a[0](i)); let k = 0, p = 1;
do { k++; p *= RNGSTATE.unif(); } while (p > L); return k - 1; };
// series operators
case 'l': case 'lag': return i => { const k = a.length > 1 ? a[1](i) : 1;
return i - k >= 0 ? a[0](i - k) : NaN; };
case 'f': case 'lead': return i => { const k = a.length > 1 ? a[1](i) : 1;
return i + k < DB.n ? a[0](i + k) : NaN; };
case 'd': case 'diff': return i => i > 0 ? a[0](i) - a[0](i - 1) : NaN;
case 's': case 'growth': return i => i > 0 ? (a[0](i) - a[0](i - 1)) / a[0](i - 1) : NaN;
case 'sum': return i => { let s = 0; for (let j = 0; j <= i; j++) { const v = a[0](j); if (isNum(v)) s += v; } return s; };
// aggregates over the whole sample
case 'mean': return memoAgg(a[0], arr => mean(arr));
case 'sd': return memoAgg(a[0], arr => sd(arr));
case 'total': return memoAgg(a[0], arr => arr.filter(isNum).reduce((s, v) => s + v, 0));
case 'count': return memoAgg(a[0], arr => arr.filter(isNum).length);
case 'median': return memoAgg(a[0], arr => median(arr));
case 'r_min': return memoAgg(a[0], arr => Math.min(...arr.filter(isNum)));
case 'r_max': return memoAgg(a[0], arr => Math.max(...arr.filter(isNum)));
default: throw new Error('unknown function ' + name + '()');
}
}
function memoAgg(f, agg) {
let cached = null;
return () => { if (cached === null) { const arr = [];
for (let j = 0; j < DB.n; j++) arr.push(f(j)); cached = agg(arr); } return cached; };
}
/* Sample selector from an `if` condition + `in` range */
function makeTouse(ifExpr, inRange) {
const t = new Array(DB.n).fill(1);
if (inRange) { for (let i = 0; i < DB.n; i++)
if (i + 1 < inRange[0] || i + 1 > inRange[1]) t[i] = 0; }
if (ifExpr) { const f = compileExpr(ifExpr);
for (let i = 0; i < DB.n; i++) { if (!t[i]) continue; const v = f(i);
t[i] = (typeof v === 'number' && !isNaN(v) && v !== 0) ? 1 : 0; } }
return t;
}
/* ---------- Number formatting (Stata-like) ---------- */
function fmtG(x, sig) {
if (x === null || x === undefined) return '.';
if (typeof x === 'string') return x;
if (isNaN(x)) return '.';
if (!isFinite(x)) return x > 0 ? '+inf' : '-inf';
sig = sig || 7;
if (x === 0) return '0';
const ax = Math.abs(x);
if (ax >= 1e8 || ax < 1e-5) return x.toExponential(Math.max(0, sig - 3))
.replace(/e([+-])(\d)$/, 'e$10$2');
const dec = Math.max(0, sig - 1 - Math.floor(Math.log10(ax)));
let s = x.toFixed(Math.min(dec, 12));
if (s.indexOf('.') >= 0) s = s.replace(/0+$/, '').replace(/\.$/, '');
return s;
}
function fmtF(x, d) {
if (x === null || x === undefined || (typeof x === 'number' && isNaN(x))) return '.';
if (typeof x === 'string') return x;
if (!isFinite(x)) return x > 0 ? '+inf' : '-inf';
return x.toFixed(d);
}
function padL(s, w) { s = String(s); return s.length >= w ? s.slice(-w) : ' '.repeat(w - s.length) + s; }
function padR(s, w) { s = String(s); return s.length >= w ? s.slice(0, w) : s + ' '.repeat(w - s.length); }
function padC(s, w) { s = String(s); if (s.length >= w) return s.slice(0, w);
const l = Math.floor((w - s.length) / 2); return ' '.repeat(l) + s + ' '.repeat(w - s.length - l); }
function abbrev(s, w) { s = String(s); return s.length <= w ? s : s.slice(0, w - 2) + '~' + s.slice(-1); }
function rule(w, ch) { return (ch || '-').repeat(w); }
/* ---------- Sample datasets (simulated, fixed seed => reproducible) ---------- */
const SAMPLES = {
auto: {
desc: '74 automobiles, 1978 — prices, mileage, and specifications (simulated)',
build() {
const r = makeRNG(1978), N = 74;
const price = [], mpg = [], weight = [], length_ = [], foreign = [], rep78 = [],
headroom = [], trunk = [], displacement = [], gear_ratio = [], make = [];
const dom = ['AMC', 'Buick', 'Cad.', 'Chev.', 'Dodge', 'Ford', 'Linc.', 'Merc.', 'Olds', 'Plym.', 'Pont.'];
const frn = ['Audi', 'BMW', 'Datsun', 'Fiat', 'Honda', 'Mazda', 'Peugeot', 'Renault', 'Subaru', 'Toyota', 'VW', 'Volvo'];
for (let i = 0; i < N; i++) {
const f = i >= 52 ? 1 : 0;
const w = f ? 2100 + r.norm() * 380 : 3300 + r.norm() * 600;
const wt = Math.max(1700, Math.round(w / 10) * 10);
const disp = Math.round(wt * 0.055 + r.norm() * 20 + (f ? -20 : 20));
const mp = Math.max(12, Math.round(58 - 0.0092 * wt + (f ? 1.8 : 0) + r.norm() * 2.2));
const p = Math.round(1800 + 1.42 * wt + (f ? 1300 : 0) + Math.max(0, r.norm()) * 1900 + r.norm() * 500);
price.push(Math.max(3291, p)); mpg.push(mp); weight.push(wt);
length_.push(Math.round(wt * 0.045 + 60 + r.norm() * 4));
foreign.push(f);
rep78.push(i === 3 || i === 40 ? NaN : Math.min(5, Math.max(1, Math.round(2.9 + f * 1.1 + r.norm() * 0.8))));
headroom.push(Math.round((2.0 + (1 - f) * 0.7 + r.unif() * 1.5) * 2) / 2);
trunk.push(Math.round(8 + (1 - f) * 5 + r.unif() * 8));
displacement.push(Math.max(79, disp));
gear_ratio.push(Math.round((2.4 + f * 0.6 + r.unif() * 0.9) * 100) / 100);
make.push((f ? r.pick(frn) : r.pick(dom)) + ' ' + ['Custom', 'DL', 'GL', 'LX', 'Sedan', 'Wagon', 'Coupe', 'Deluxe'][r.int(0, 7)]);
}
return { n: N, cols: { make, price, mpg, weight, length: length_, headroom, trunk,
displacement, gear_ratio, rep78, foreign },
types: { make: 'str' },
labels: { make: 'Make and model', price: 'Price ($)', mpg: 'Mileage (mpg)',
weight: 'Weight (lbs.)', length: 'Length (in.)', headroom: 'Headroom (in.)',
trunk: 'Trunk space (cu. ft.)', displacement: 'Displacement (cu. in.)',
gear_ratio: 'Gear ratio', rep78: 'Repair record 1978', foreign: 'Car origin (1=foreign)' } };
}
},
wage: {
desc: '526 workers — wages and schooling; schooling is endogenous (simulated)',
build() {
const r = makeRNG(1976), N = 526;
const c = { wage: [], lwage: [], educ: [], exper: [], tenure: [], female: [], married: [],
nonwhite: [], union: [], south: [], smsa: [], numdep: [], feduc: [] };
for (let i = 0; i < N; i++) {
const ability = r.norm(); /* unobserved; biases OLS on educ */
const feduc = Math.min(20, Math.max(0, Math.round(11 + r.norm() * 3)));
const educ = Math.min(20, Math.max(6,
Math.round(9.4 + 0.22 * feduc + 0.9 * ability + r.norm() * 1.4)));
const exper = Math.max(0, Math.round(17 - (educ - 12) * 0.9 + r.norm() * 12));
const tenure = Math.max(0, Math.round(Math.min(exper, Math.abs(r.norm()) * 6)));
const female = r.unif() < 0.48 ? 1 : 0;
const married = r.unif() < (0.6 + exper * 0.004) ? 1 : 0;
const nonwhite = r.unif() < 0.11 ? 1 : 0;
const union = r.unif() < 0.18 ? 1 : 0;
const south = r.unif() < 0.29 ? 1 : 0;
const smsa = r.unif() < 0.72 ? 1 : 0;
const lw = 0.28 + 0.082 * educ + 0.0295 * exper - 0.00058 * exper * exper
+ 0.0169 * tenure - 0.30 * female + 0.055 * married - 0.09 * nonwhite
+ 0.11 * union - 0.08 * south + 0.12 * smsa + 0.35 * ability + r.norm() * 0.32;
c.wage.push(Math.round(Math.exp(lw) * 100) / 100);
c.lwage.push(Math.round(lw * 10000) / 10000);
c.feduc.push(feduc);
c.educ.push(educ); c.exper.push(exper); c.tenure.push(tenure); c.female.push(female);
c.married.push(married); c.nonwhite.push(nonwhite); c.union.push(union);
c.south.push(south); c.smsa.push(smsa); c.numdep.push(Math.max(0, Math.round(r.norm() + 1)));
}
return { n: N, cols: c, types: {},
labels: { wage: 'Hourly earnings ($)', educ: 'Years of education',
exper: 'Years of potential experience', tenure: 'Years with current employer',
female: '=1 if female', married: '=1 if married', nonwhite: '=1 if nonwhite',
union: '=1 if union member', south: '=1 if lives in South',
smsa: '=1 if lives in metro area', numdep: 'Number of dependents',
lwage: 'Log hourly earnings', feduc: "Father's years of education" } };
}
},
growth: {
desc: '104 countries — long-run growth, investment, and human capital (simulated)',
build() {
const r = makeRNG(1992), N = 104;
const c = { country: [], growth: [], lgdp60: [], invest: [], school: [], popgrow: [],
openness: [], africa: [], latam: [], asia: [], inflation: [], instab: [] };
for (let i = 0; i < N; i++) {
const africa = i < 30 ? 1 : 0, latam = (i >= 30 && i < 52) ? 1 : 0, asia = (i >= 52 && i < 74) ? 1 : 0;
const lgdp60 = 6.4 + (africa ? -0.9 : 0) + (asia ? -0.4 : 0) + (latam ? 0.2 : 0) + r.norm() * 0.75;
const school = Math.max(0.5, 5.5 - africa * 3 + asia * 0.4 + r.norm() * 2.2);
const invest = Math.max(3, 18 + asia * 6 - africa * 4 + r.norm() * 6);
const popgrow = Math.max(0.1, 1.9 + africa * 0.9 - asia * 0.4 + r.norm() * 0.6);
const openness = Math.max(5, 55 + asia * 20 - africa * 5 + r.norm() * 28);
const inflation = Math.max(0.2, Math.exp(1.9 + latam * 1.1 + r.norm() * 0.8));
const instab = Math.max(0, r.unif() * 3 + africa * 0.8);
const g = 4.6 - 0.55 * lgdp60 + 0.11 * invest + 0.13 * school - 0.55 * popgrow
+ 0.008 * openness - 0.004 * inflation - 0.25 * instab + r.norm() * 1.05;
c.country.push('Country ' + String(i + 1).padStart(3, '0'));
c.growth.push(Math.round(g * 1000) / 1000); c.lgdp60.push(Math.round(lgdp60 * 1000) / 1000);
c.invest.push(Math.round(invest * 10) / 10); c.school.push(Math.round(school * 100) / 100);
c.popgrow.push(Math.round(popgrow * 100) / 100); c.openness.push(Math.round(openness * 10) / 10);
c.africa.push(africa); c.latam.push(latam); c.asia.push(asia);
c.inflation.push(Math.round(inflation * 10) / 10); c.instab.push(Math.round(instab * 100) / 100);
}
return { n: N, cols: c, types: { country: 'str' },
labels: { growth: 'Avg annual GDP growth, %', lgdp60: 'Log initial GDP per capita',
invest: 'Investment share of GDP, %', school: 'Avg years of schooling',
popgrow: 'Population growth, %', openness: 'Trade share of GDP, %',
africa: '=1 if Sub-Saharan Africa', latam: '=1 if Latin America', asia: '=1 if Asia',
inflation: 'Avg inflation, %', instab: 'Political instability index' } };
}
},
invest: {
desc: 'Panel: 12 firms observed over 20 years — investment, market value, capital (simulated)',
build() {
const r = makeRNG(1954), NF = 12, NT = 20;
const c = { firm: [], year: [], invest: [], mvalue: [], kstock: [], sales: [] };
for (let f = 1; f <= NF; f++) {
const a0 = r.norm();
const alpha = a0 * 42; /* firm effect */
const scale = Math.exp(0.42 * a0 + r.norm() * 0.34); /* larger firms have larger effects */
let mv = 900 * scale, ks = 550 * scale;
const kbar = ks;
for (let t = 0; t < NT; t++) {
mv = Math.max(50, mv * (1 + 0.02 + r.norm() * 0.14));
ks = Math.max(40, ks * 0.90 + 0.10 * kbar + 22 + r.norm() * 30);
const inv = Math.max(1, 55 + alpha + 0.062 * mv + 0.055 * ks + r.norm() * 42);
c.firm.push(f); c.year.push(1935 + t);
c.invest.push(Math.round(inv * 10) / 10);
c.mvalue.push(Math.round(mv * 10) / 10);
c.kstock.push(Math.round(ks * 10) / 10);
c.sales.push(Math.round((ks * 1.4 + r.norm() * 60) * 10) / 10);
}
}
return { n: NF * NT, cols: c, types: {},
labels: { firm: 'Firm identifier', year: 'Year', invest: 'Gross investment',
mvalue: 'Market value of firm', kstock: 'Stock of plant and equipment', sales: 'Net sales' },
panel: 'firm', time: 'year' };
}
},
macro: {
desc: 'Quarterly US-style macro series, 1960q1–2019q4 (simulated)',
build() {
const r = makeRNG(1960), N = 240;
const c = { qtr: [], year: [], gdp: [], gdpgrow: [], cpi: [], inflation: [],
unemp: [], ffr: [], m2grow: [], oil: [] };
let lgdp = 7.6, cpi = 29, u = 5.5, ff = 3.5, infl = 1.5;
for (let i = 0; i < N; i++) {
const shock = r.norm();
const g = 0.0078 + 0.35 * (i > 0 ? c.gdpgrow[i - 1] / 100 - 0.0078 : 0) + shock * 0.008;
lgdp += g;
infl = 0.85 * infl + 0.25 + (i > 100 && i < 140 ? 1.4 : 0) + r.norm() * 0.55;
infl = Math.max(-1.5, infl);
cpi *= 1 + infl / 400;
u = Math.max(2.8, 0.90 * u + 0.55 - 45 * (g - 0.0078) + r.norm() * 0.25);
ff = Math.max(0, 0.80 * ff + 0.35 + 0.55 * infl - 0.30 * (u - 5.5) + r.norm() * 0.5);
c.qtr.push(i + 1); c.year.push(1960 + Math.floor(i / 4));
c.gdp.push(Math.round(Math.exp(lgdp) * 10) / 10);
c.gdpgrow.push(Math.round(g * 400 * 100) / 100);
c.cpi.push(Math.round(cpi * 100) / 100);
c.inflation.push(Math.round(infl * 100) / 100);
c.unemp.push(Math.round(u * 100) / 100);
c.ffr.push(Math.round(ff * 100) / 100);
c.m2grow.push(Math.round((5.5 + 0.4 * infl + r.norm() * 1.8) * 100) / 100);
c.oil.push(Math.round(Math.max(2, 20 * Math.exp(0.004 * i + r.norm() * 0.22)) * 100) / 100);
}
return { n: N, cols: c, types: {},
labels: { qtr: 'Quarter index', year: 'Calendar year', gdp: 'Real GDP index',
gdpgrow: 'Real GDP growth, annualized %', cpi: 'Consumer price index',
inflation: 'CPI inflation, annualized %', unemp: 'Unemployment rate, %',
ffr: 'Policy interest rate, %', m2grow: 'Money growth, %', oil: 'Oil price ($/bbl)' },
time: 'qtr' };
}
},
health: {
desc: '900 adults — insurance take-up, a binary-outcome dataset (simulated)',
build() {
const r = makeRNG(2010), N = 900;
const c = { insured: [], age: [], income: [], educ: [], chronic: [], smoker: [],
female: [], famsize: [], employed: [], visits: [] };
for (let i = 0; i < N; i++) {
const age = Math.round(20 + r.unif() * 45);
const educ = Math.min(20, Math.max(6, Math.round(13 + r.norm() * 3)));
const income = Math.round(Math.exp(9.6 + 0.07 * educ + 0.02 * age + r.norm() * 0.55));
const chronic = r.unif() < 0.22 ? 1 : 0;
const smoker = r.unif() < 0.19 ? 1 : 0;
const female = r.unif() < 0.51 ? 1 : 0;
const employed = r.unif() < 0.74 ? 1 : 0;
const famsize = Math.max(1, Math.round(2.4 + r.norm() * 1.3));
const xb = -6.4 + 0.031 * age + 0.00003 * income + 0.11 * educ + 0.62 * chronic
- 0.34 * smoker + 0.15 * female + 0.85 * employed + r.norm() * 0.4;
const p = 1 / (1 + Math.exp(-xb));
c.insured.push(r.unif() < p ? 1 : 0);
const lam = Math.exp(-0.4 + 0.018 * age + 0.9 * chronic + 0.25 * female);
let k = 0, pp = 1, L = Math.exp(-lam);
do { k++; pp *= r.unif(); } while (pp > L);
c.visits.push(k - 1);
c.age.push(age); c.income.push(income); c.educ.push(educ); c.chronic.push(chronic);
c.smoker.push(smoker); c.female.push(female); c.famsize.push(famsize); c.employed.push(employed);
}
return { n: N, cols: c, types: {},
labels: { insured: '=1 if has health insurance', age: 'Age in years',
income: 'Annual household income ($)', educ: 'Years of education',
chronic: '=1 if chronic condition', smoker: '=1 if current smoker',
female: '=1 if female', famsize: 'Household size', employed: '=1 if employed',
visits: 'Doctor visits in past year' } };
}
}
};
function loadSample(key) {
const s = SAMPLES[key];
if (!s) throw new Error('no sample dataset named "' + key + '". Try: ' + Object.keys(SAMPLES).join(', '));
const d = s.build();
clearData();
DB.name = key; DB.n = d.n;
for (const k of Object.keys(d.cols))
addVar(k, d.cols[k], (d.types && d.types[k]) || 'num', (d.labels && d.labels[k]) || '');
if (d.panel) DB.panelvar = d.panel;
if (d.time) { DB.timevar = d.time; DB.tsvar = d.time; }
return { desc: s.desc, n: d.n, k: DB.vars.length };
}
/* ---------- CSV ---------- */
function parseCSV(text, sep) {
text = text.replace(/\r\n?/g, '\n').replace(/\n+$/, '');
if (!sep) { const head = text.split('\n')[0];
sep = (head.split('\t').length > head.split(',').length) ? '\t'
: (head.split(';').length > head.split(',').length ? ';' : ','); }
const rows = [];
let cur = '', row = [], q = false;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (q) { if (ch === '"') { if (text[i + 1] === '"') { cur += '"'; i++; } else q = false; } else cur += ch; }
else if (ch === '"') q = true;
else if (ch === sep) { row.push(cur); cur = ''; }
else if (ch === '\n') { row.push(cur); rows.push(row); row = []; cur = ''; }
else cur += ch;
}
row.push(cur); rows.push(row);
if (!rows.length) throw new Error('no rows found');
let header = rows[0].map(h => h.trim());
const numericHeader = header.every(h => h !== '' && !isNaN(parseFloat(h)));
let start = 1;
if (numericHeader) { header = header.map((_, j) => 'v' + (j + 1)); start = 0; }
header = header.map((h, j) => {
let s = h.replace(/[^A-Za-z0-9_]/g, '_').replace(/^(\d)/, 'v$1');
if (!s) s = 'v' + (j + 1);
return s;
});
const seen = {};
header = header.map(h => { if (seen[h] === undefined) { seen[h] = 0; return h; }
seen[h]++; return h + '_' + seen[h]; });
const cols = header.map(() => []);
let n = 0;
for (let i = start; i < rows.length; i++) {
const r = rows[i];
if (r.length === 1 && r[0].trim() === '') continue;
for (let j = 0; j < header.length; j++) cols[j].push(r[j] === undefined ? '' : r[j].trim());
n++;
}
clearData(); DB.n = n; DB.name = 'imported';
const miss = ['', '.', 'NA', 'N/A', 'na', 'NaN', 'null', 'NULL', '#N/A', '-'];
header.forEach((h, j) => {
const raw = cols[j];
const numeric = raw.every(v => miss.includes(v) || !isNaN(parseFloat(v)) && /^[-+]?[\d.,eE+\-]+$/.test(v.replace(/,/g, '')));
if (numeric) addVar(h, raw.map(v => miss.includes(v) ? NaN : parseFloat(v.replace(/,/g, ''))), 'num');
else addVar(h, raw.map(v => miss.includes(v) ? '' : v), 'str');
});
return { n, k: header.length };
}
function toCSV() {
const names = varNames();
const lines = [names.join(',')];
for (let i = 0; i < DB.n; i++) {
lines.push(names.map(v => {
const x = DB.col[v][i];
if (typeof x === 'string') return /[",\n]/.test(x) ? '"' + x.replace(/"/g, '""') + '"' : x;
return (x === null || x === undefined || isNaN(x)) ? '' : String(x);
}).join(','));
}
return lines.join('\n');
}
/* ============================================================
OUTPUT FORMATTING (fixed-width, 78 columns)
============================================================ */
const TW = 80, LW = 14;
function fmtCell(x, w) {
if (x === null || x === undefined || (typeof x === 'number' && isNaN(x))) return padL('.', w);
if (typeof x === 'string') return padL(x, w);
for (let s = 7; s >= 2; s--) { const t = fmtG(x, s); if (t.length <= w - 1) return padL(t, w); }
return padL(x.toExponential(2), w);
}
function statLine(pairs, offset, lw, vw) {
return pairs.map(([l, v]) => ' '.repeat(offset) + padR(l, lw) + ' = ' + padL(v, vw)).join('\n');
}
const HD = 52;
function SL(label, value) { return padR(label, 16) + ' = ' + padL(value, 9); }
function sigStars(p) { return p < 0.01 ? '***' : p < 0.05 ? '**' : p < 0.1 ? '*' : ''; }
/* Coefficient block shared by every estimator */
function coefBlock(m, depvar, tlab, useZ) {
const L = [];
L.push(rule(TW));
const vlab = { 'Robust (HC1)': 'Robust', 'HC2': 'Robust', 'HC3': 'Robust',
'Bootstrap': 'Bootstrap' }[m.vce] ||
(/^Cluster/.test(m.vce || '') ? 'Cluster' : (/Newey/.test(m.vce || '') ? 'Newey-West' :
(/^Powell/.test(m.vce || '') ? 'Kernel' : (m.vce === 'Robust' ? 'Robust' : ''))));
if (vlab) L.push(padL('', LW) + ' | ' + padL('', 13) + padC(vlab, 12));
L.push(padL(abbrev(depvar, LW), LW) + ' | ' + padL('Coefficient', 13) + padL('Std. err.', 12) +
padL(useZ ? 'z' : 't', 8) + padL(useZ ? 'P>|z|' : 'P>|t|', 8) +
padC('[' + (m.level || 95) + '% conf. interval]', 22));
L.push(rule(LW + 1) + '+' + rule(TW - LW - 2));
const names = m.names || [];
for (let a = 0; a < m.b.length; a++) {
const nm = abbrev(names[a] || ('x' + a), LW);
if (m.drop && m.drop.includes(a)) {
L.push(padL(nm, LW) + ' | ' + padL('0', 13) + padL('(omitted)', 12)); continue;
}
L.push(padL(nm, LW) + ' | ' + fmtCell(m.b[a], 13) + fmtCell(m.se[a], 12) +
padL(fmtF(m.t[a], 2), 8) + padL(fmtF(m.p[a], 3), 8) +
fmtCell(m.ci_lo[a], 11) + fmtCell(m.ci_hi[a], 11));
}
L.push(rule(TW));
return L.join('\n');
}
function outRegress(m, depvar) {
const L = [];
const N = String(m.n);
if (m.vce === 'OLS') {
const msq = m.df_m > 0 ? m.mss / m.df_m : NaN;
L.push(padL('Source', LW) + ' | ' + padC('SS', 13) + padC('df', 8) + padC('MS', 11) +
' ' + SL('Number of obs', N));
L.push(rule(LW + 1) + '+' + rule(33) + ' ' + SL('F(' + m.df_m + ', ' + m.df_r + ')', fmtF(m.F, 2)));
L.push(padL('Model', LW) + ' | ' + fmtCell(m.mss, 13) + padL(String(m.df_m), 8) + fmtCell(msq, 11) +
' ' + SL('Prob > F', fmtF(m.pF, 4)));
L.push(padL('Residual', LW) + ' | ' + fmtCell(m.rss, 13) + padL(String(m.df_r), 8) + fmtCell(m.s2, 11) +
' ' + SL('R-squared', fmtF(m.r2, 4)));
L.push(rule(LW + 1) + '+' + rule(33) + ' ' + SL('Adj R-squared', fmtF(m.r2a, 4)));
L.push(padL('Total', LW) + ' | ' + fmtCell(m.tss, 13) + padL(String(m.n - (m.noCons ? 0 : 1)), 8) +
fmtCell(m.tss / (m.n - (m.noCons ? 0 : 1)), 11) + ' ' + SL('Root MSE', fmtG(m.rmse, 6)));
} else {
L.push(padR('Linear regression', HD) + SL('Number of obs', N));
L.push(' '.repeat(HD) + padR('F(' + m.df_m + ', ' + m.df_r + ')', 15) + ' = ' + padL(fmtF(m.F, 2), 9));
L.push(' '.repeat(HD) + padR('Prob > F', 15) + ' = ' + padL(fmtF(m.pF, 4), 9));
L.push(' '.repeat(HD) + padR('R-squared', 15) + ' = ' + padL(fmtF(m.r2, 4), 9));
if (m.nclust) L.push(' '.repeat(HD) + padR('Number of clusters', 15) + ' = ' + padL(String(m.nclust), 9));
L.push(' '.repeat(HD) + padR('Root MSE', 15) + ' = ' + padL(fmtG(m.rmse, 6), 9));
L.push('');
L.push(padC('Std. err. adjusted: ' + m.vce, TW));
}
L.push('');
L.push(coefBlock(m, depvar, 't', false));
return L.join('\n');
}
function outGLM(m, depvar) {
const title = { logit: 'Logistic regression', probit: 'Probit regression',
poisson: 'Poisson regression' }[m.family];
const L = [];
L.push('Iteration ' + m.iter + ': log likelihood = ' + fmtG(m.ll, 9) +
(m.conv ? '' : ' (not converged)'));
L.push('');
L.push(padR(title, HD) + padR('Number of obs', 15) + ' = ' + padL(String(m.n), 9));
L.push(' '.repeat(HD) + padR('LR chi2(' + m.df_m + ')', 15) + ' = ' + padL(fmtF(m.lr, 2), 9));
L.push(' '.repeat(HD) + padR('Prob > chi2', 15) + ' = ' + padL(fmtF(m.p_lr, 4), 9));
L.push(padR('Log likelihood = ' + fmtG(m.ll, 9), HD) +
padR('Pseudo R2', 15) + ' = ' + padL(fmtF(m.r2p, 4), 9));
if (m.vce !== 'OIM') { L.push(''); L.push(padC('Std. err.: ' + m.vce, TW)); }
L.push('');
L.push(coefBlock(m, depvar, 'z', true));
return L.join('\n');
}
function outIV(m, depvar) {
const L = [];
L.push(padR('Instrumental variables (2SLS) regression', HD) +
padR('Number of obs', 15) + ' = ' + padL(String(m.n), 9));
L.push(' '.repeat(HD) + padR('Wald F(' + m.k + ', ' + m.df_r + ')', 15) + ' = ' + padL(fmtF(m.F, 2), 9));
L.push(' '.repeat(HD) + padR('R-squared', 15) + ' = ' + padL(fmtF(m.r2, 4), 9));
L.push(' '.repeat(HD) + padR('Root MSE', 15) + ' = ' + padL(fmtG(m.rmse, 6), 9));
L.push('');
L.push(coefBlock(m, depvar, 't', false));
L.push('');
L.push('First-stage diagnostics (excluded instruments)');
L.push(rule(TW));
m.first.forEach((f, i) => {
L.push(' Endogenous #' + (i + 1) + ': F(' + f.df1 + ', ' + f.df_r + ') = ' + fmtF(f.F, 2) +
' Prob > F = ' + fmtF(f.p, 4) + ' R2 = ' + fmtF(f.r2, 4));
if (f.F < 10) L.push(' Note: F < 10 suggests the instruments are weak.');
});
if (m.sargan) {
L.push(' Sargan overidentification: chi2(' + m.sargan.df + ') = ' + fmtF(m.sargan.chi2, 3) +
' Prob > chi2 = ' + fmtF(m.sargan.p, 4));
} else L.push(' Model is exactly identified — no overidentification test available.');
L.push(rule(TW));
return L.join('\n');
}
function outPanel(m, depvar, idvar) {
const L = [];
const isFE = m.type === 'fe';
L.push(padR(isFE ? 'Fixed-effects (within) regression' : 'Random-effects GLS regression', HD) +
padR('Number of obs', 15) + ' = ' + padL(String(m.n), 9));
L.push(padR('Group variable: ' + idvar, HD) + padR('Number of groups', 16) + ' = ' + padL(String(m.G), 9));
L.push('');
L.push(padR('R-squared:', HD) + padR('Obs per group:', 16));
L.push(padR(' Within = ' + fmtF(m.r2_within, 4), HD) +
padR(' avg', 15) + ' = ' + padL(fmtF(m.n / m.G, 1), 9));
L.push(padR(' Overall = ' + fmtF(m.r2_overall, 4), HD));
L.push('');
if (isFE) {
L.push(' '.repeat(HD) + padR('F(' + m.df_m + ', ' + m.df_r + ')', 15) + ' = ' + padL(fmtF(m.F, 2), 9));
L.push(' '.repeat(HD) + padR('Prob > F', 15) + ' = ' + padL(fmtF(m.pF, 4), 9));
} else {
L.push(' '.repeat(HD) + padR('Wald chi2(' + (m.b.length - 1) + ')', 15) + ' = ' + padL(fmtF(m.chi2, 2), 9));
L.push(' '.repeat(HD) + padR('Prob > chi2', 15) + ' = ' + padL(fmtF(m.p_chi2, 4), 9));
}
L.push('');
L.push(coefBlock(m, depvar, isFE ? 't' : 'z', !isFE));
L.push(padL('sigma_u', LW) + ' | ' + fmtCell(m.sigma_u, 12));
L.push(padL('sigma_e', LW) + ' | ' + fmtCell(m.sigma_e, 12));
L.push(padL('rho', LW) + ' | ' + fmtCell(m.rho, 12) + ' (fraction of variance due to u_i)');
L.push(rule(TW));
if (isFE) L.push('Note: the ' + m.G + ' group intercepts are absorbed; constant shown is the grand mean.');
return L.join('\n');
}
function outQreg(m, depvar) {
const L = [];
L.push(padR('Quantile regression (tau = ' + m.tau + ')', HD) +
padR('Number of obs', 15) + ' = ' + padL(String(m.n), 9));
L.push(' '.repeat(HD) + padR('Raw sum of dev.', 15) + ' = ' + padL(fmtG(m.absdev / (1 - m.r2), 7), 9));
L.push(' '.repeat(HD) + padR('Min sum of dev.', 15) + ' = ' + padL(fmtG(m.absdev, 7), 9));
L.push(' '.repeat(HD) + padR('Pseudo R2', 15) + ' = ' + padL(fmtF(m.r2, 4), 9));
L.push('');
L.push(coefBlock(m, depvar, 't', false));
return L.join('\n');
}
/* summarize */
function outSummarize(vars, touse, detail) {
const L = [];
if (!detail) {
L.push(rule(TW));
L.push(padL('Variable', LW) + ' | ' + padL('Obs', 9) + padL('Mean', 14) +
padL('Std. dev.', 14) + padL('Min', 13) + padL('Max', 13));
L.push(rule(LW + 1) + '+' + rule(TW - LW - 2));
for (const v of vars) {
const a = [];
for (let i = 0; i < DB.n; i++) if (touse[i] && isNum(DB.col[v][i])) a.push(DB.col[v][i]);
if (isStr(v)) { L.push(padL(abbrev(v, LW), LW) + ' | ' + padL('0', 9) +
' (string variable — use encode or tabulate)'); continue; }
L.push(padL(abbrev(v, LW), LW) + ' | ' + padL(String(a.length), 9) +
fmtCell(mean(a), 14) + fmtCell(sd(a), 14) +
fmtCell(a.length ? Math.min(...a) : NaN, 13) + fmtCell(a.length ? Math.max(...a) : NaN, 13));
}
L.push(rule(TW));
return L.join('\n');
}
for (const v of vars) {
if (isStr(v)) continue;
const a = [];
for (let i = 0; i < DB.n; i++) if (touse[i] && isNum(DB.col[v][i])) a.push(DB.col[v][i]);
const s = a.slice().sort((x, y) => x - y), n = s.length;
L.push(padC(v + (getVar(v).label ? ' (' + getVar(v).label + ')' : ''), TW));
L.push(rule(TW));
const pcts = [1, 5, 10, 25, 50, 75, 90, 95, 99];
const smallest = s.slice(0, 4), largest = s.slice(-4);
const right = [
['Obs', String(n)], ['Sum of wgt.', String(n)], ['Mean', fmtG(mean(a), 7)],
['Std. dev.', fmtG(sd(a), 7)], ['Variance', fmtG(variance(a), 7)],
['Skewness', fmtG(skewness(a), 7)], ['Kurtosis', fmtG(kurtosis(a), 7)]
];
const leftRows = [];
pcts.forEach((p, i) => {
let extra = '';
if (i === 0) extra = 'Smallest';
if (i >= 1 && i <= 4 && smallest[i - 1] !== undefined) extra = fmtG(smallest[i - 1], 7);
if (i === 5) extra = 'Largest';
if (i >= 6 && largest[i - 6] !== undefined) extra = fmtG(largest[i - 6], 7);
leftRows.push(padL(p + '%', 10) + padL(fmtG(quantile(a, p / 100), 7), 12) + ' ' + padR(extra, 12));
});
const rightRows = ['', '', '', ...right.map(([k, v2]) => padR(k, 14) + ' ' + padL(v2, 11)), '', ''];
for (let i = 0; i < 9; i++) {
L.push(padR(leftRows[i], 38) + ' ' + (rightRows[i] || ''));
}
L.push(rule(TW));
}
return L.join('\n');
}
function outTab1(v, touse) {
const counts = new Map();
let N = 0;
for (let i = 0; i < DB.n; i++) {
if (!touse[i]) continue;
const x = DB.col[v][i];
if (x === '' || x === null || x === undefined || (typeof x === 'number' && isNaN(x))) continue;
const k = String(x); counts.set(k, (counts.get(k) || 0) + 1); N++;
}
const keys = [...counts.keys()].sort(cmpKey);
const L = [];
const w1 = Math.max(12, Math.min(24, Math.max(...keys.map(k => k.length), v.length)));
L.push(rule(w1 + 36));
L.push(padL(abbrev(v, w1), w1) + ' | ' + padL('Freq.', 10) + padL('Percent', 12) + padL('Cum.', 10));
L.push(rule(w1 + 1) + '+' + rule(34));
let cum = 0;
for (const k of keys) {
const c = counts.get(k); cum += 100 * c / N;
L.push(padL(abbrev(k, w1), w1) + ' | ' + padL(String(c), 10) +
padL(fmtF(100 * c / N, 2), 12) + padL(fmtF(cum, 2), 10));
}
L.push(rule(w1 + 1) + '+' + rule(34));
L.push(padL('Total', w1) + ' | ' + padL(String(N), 10) + padL(fmtF(100, 2), 12));
L.push(rule(w1 + 36));
return L.join('\n');
}
function outTab2(v1, v2, touse, opts) {
const r = [], c = [];
for (let i = 0; i < DB.n; i++) {
if (!touse[i]) continue;
const a = DB.col[v1][i], b = DB.col[v2][i];
if (a === '' || b === '' || (typeof a === 'number' && isNaN(a)) || (typeof b === 'number' && isNaN(b))) continue;
r.push(String(a)); c.push(String(b));
}
const t = chi2table(r, c);
const L = [];
const w1 = Math.max(10, Math.min(16, v1.length + 2));
const cw = Math.max(9, ...t.ck.map(k => k.length + 2));
const total = w1 + 1 + 1 + (t.ck.length + 1) * cw;
L.push(padC(v2, total));
L.push(rule(total));
L.push(padL(abbrev(v1, w1), w1) + ' | ' + t.ck.map(k => padL(abbrev(k, cw - 1), cw)).join('') + padL('Total', cw));
L.push(rule(w1 + 1) + '+' + rule(total - w1 - 2));
t.rk.forEach((rk, i) => {
L.push(padL(abbrev(rk, w1), w1) + ' | ' + t.T[i].map(x => padL(String(x), cw)).join('') +
padL(String(t.rt[i]), cw));
if (opts.row) L.push(padL('', w1) + ' | ' + t.T[i].map(x => padL(fmtF(100 * x / t.rt[i], 2), cw)).join('') +
padL(fmtF(100, 2), cw));
if (opts.col) L.push(padL('', w1) + ' | ' + t.T[i].map((x, j) => padL(fmtF(100 * x / t.ct[j], 2), cw)).join('') +
padL(fmtF(100 * t.rt[i] / t.N, 2), cw));
if (opts.row || opts.col) L.push(padL('', w1) + ' | ');
});
L.push(rule(w1 + 1) + '+' + rule(total - w1 - 2));
L.push(padL('Total', w1) + ' | ' + t.ct.map(x => padL(String(x), cw)).join('') + padL(String(t.N), cw));
L.push(rule(total));
if (opts.chi2 || opts.all) {
L.push('');
L.push(' Pearson chi2(' + t.df + ') = ' + fmtF(t.chi2, 4) + ' Pr = ' + fmtF(t.p, 3));
if (opts.lr || opts.all) L.push(' Likelihood-ratio chi2(' + t.df + ') = ' + fmtF(t.lr, 4) + ' Pr = ' + fmtF(t.pLR, 3));
if (opts.V || opts.all) L.push(' Cramer\'s V = ' + fmtF(t.cramer, 4));
}
return L.join('\n');
}
function outCorr(vars, touse, pw, sig, star) {
const cols = vars.map(v => { const a = [];
for (let i = 0; i < DB.n; i++) a.push(touse[i] ? DB.col[v][i] : NaN); return a; });
const L = [];
const w1 = Math.max(9, Math.min(13, Math.max(...vars.map(v => v.length)) + 1));
const cw = Math.max(9, w1);
L.push(padL('', w1) + ' | ' + vars.map(v => padL(abbrev(v, cw - 1), cw)).join(''));
L.push(rule(w1 + 1) + '+' + rule(cw * vars.length + 1));
for (let i = 0; i < vars.length; i++) {
let line = padL(abbrev(vars[i], w1), w1) + ' | ';
let line2 = padL('', w1) + ' | ';
for (let j = 0; j <= i; j++) {
const r = corr(cols[i], cols[j]);
let cell = fmtF(r, 4);
if (star) { let nn = 0;
for (let q = 0; q < DB.n; q++) if (isNum(cols[i][q]) && isNum(cols[j][q])) nn++;
const t = r * Math.sqrt((nn - 2) / (1 - r * r)); const p = pT(t, nn - 2);
if (i !== j) cell += sigStars(p); }
line += padL(cell, cw);
if (sig && i !== j) { let nn = 0;
for (let q = 0; q < DB.n; q++) if (isNum(cols[i][q]) && isNum(cols[j][q])) nn++;
const t = r * Math.sqrt((nn - 2) / (1 - r * r));
line2 += padL(i === j ? '' : fmtF(pT(t, nn - 2), 4), cw);
} else if (sig) line2 += padL('', cw);
}
L.push(line);
if (sig) { L.push(line2); L.push(padL('', w1) + ' | '); }
}
return L.join('\n');
}
function outTtest1(r, v) {
const L = [];
L.push('One-sample t test');
L.push(rule(TW));
L.push(padL('Variable', 10) + ' | ' + padL('Obs', 6) + padL('Mean', 12) + padL('Std. err.', 12) +
padL('Std. dev.', 12) + padC('[95% conf. interval]', 24));
L.push(rule(11) + '+' + rule(TW - 12));
L.push(padL(abbrev(v, 10), 10) + ' | ' + padL(String(r.n), 6) + fmtCell(r.mean, 12) +
fmtCell(r.se, 12) + fmtCell(r.sd, 12) + fmtCell(r.lo, 12) + fmtCell(r.hi, 12));
L.push(rule(TW));
L.push('');
L.push(' mean = mean(' + v + ')' + ' '.repeat(28) + 't = ' + fmtF(r.t, 4));
L.push('H0: mean = ' + fmtG(r.mu0, 6) + ' '.repeat(30) + 'Degrees of freedom = ' + r.df);
L.push('');
L.push(' Ha: mean < ' + fmtG(r.mu0, 6) + ' Ha: mean != ' + fmtG(r.mu0, 6) + ' Ha: mean > ' + fmtG(r.mu0, 6));
L.push(' Pr(T < t) = ' + fmtF(r.pl, 4) + ' Pr(|T| > |t|) = ' + fmtF(r.p2, 4) +
' Pr(T > t) = ' + fmtF(r.pu, 4));
return L.join('\n');
}
function outTtest2(r, v, g1, g2, byvar) {
const L = [];
L.push('Two-sample t test with ' + (r.welch ? 'unequal' : 'equal') + ' variances');
L.push(rule(TW));
L.push(padL('Group', 10) + ' | ' + padL('Obs', 6) + padL('Mean', 12) + padL('Std. err.', 12) +
padL('Std. dev.', 12) + padC('[95% conf. interval]', 24));
L.push(rule(11) + '+' + rule(TW - 12));
const c = Math.abs(tinv(0.025, r.n1 - 1)), c2 = Math.abs(tinv(0.025, r.n2 - 1));
L.push(padL(abbrev(String(g1), 10), 10) + ' | ' + padL(String(r.n1), 6) + fmtCell(r.m1, 12) +
fmtCell(r.se1, 12) + fmtCell(r.sd1, 12) + fmtCell(r.m1 - c * r.se1, 12) + fmtCell(r.m1 + c * r.se1, 12));
L.push(padL(abbrev(String(g2), 10), 10) + ' | ' + padL(String(r.n2), 6) + fmtCell(r.m2, 12) +
fmtCell(r.se2, 12) + fmtCell(r.sd2, 12) + fmtCell(r.m2 - c2 * r.se2, 12) + fmtCell(r.m2 + c2 * r.se2, 12));
L.push(rule(11) + '+' + rule(TW - 12));
L.push(padL('diff', 10) + ' | ' + padL('', 6) + fmtCell(r.diff, 12) + fmtCell(r.se, 12) +
padL('', 12) + fmtCell(r.lo, 12) + fmtCell(r.hi, 12));
L.push(rule(TW));
L.push('');
L.push(' diff = mean(' + g1 + ') - mean(' + g2 + ')' + ' '.repeat(Math.max(1, 20 - String(g1).length - String(g2).length)) +
't = ' + fmtF(r.t, 4));
L.push('H0: diff = 0' + ' '.repeat(31) + 'Degrees of freedom = ' + fmtF(r.df, r.welch ? 2 : 0));
L.push('');
L.push(' Ha: diff < 0 Ha: diff != 0 Ha: diff > 0');
L.push(' Pr(T < t) = ' + fmtF(r.pl, 4) + ' Pr(|T| > |t|) = ' + fmtF(r.p2, 4) +
' Pr(T > t) = ' + fmtF(r.pu, 4));
return L.join('\n');
}
function outAnova(a, yv, gv) {
const L = [];
L.push(padC('Analysis of variance: ' + yv + ' by ' + gv, TW));
L.push(rule(TW));
L.push(padL('Source', 20) + ' | ' + padL('SS', 15) + padL('df', 8) + padL('MS', 15) +
padL('F', 9) + padL('Prob>F', 9));
L.push(rule(21) + '+' + rule(TW - 22));
L.push(padL('Between groups', 20) + ' | ' + fmtCell(a.ssb, 15) + padL(String(a.df1), 8) +
fmtCell(a.ssb / a.df1, 15) + padL(fmtF(a.F, 2), 9) + padL(fmtF(a.p, 4), 9));
L.push(padL('Within groups', 20) + ' | ' + fmtCell(a.ssw, 15) + padL(String(a.df2), 8) +
fmtCell(a.ssw / a.df2, 15));
L.push(rule(21) + '+' + rule(TW - 22));
L.push(padL('Total', 20) + ' | ' + fmtCell(a.sst, 15) + padL(String(a.N - 1), 8) +
fmtCell(a.sst / (a.N - 1), 15));
L.push(rule(TW));
L.push('');
L.push(padL('Group', 20) + ' | ' + padL('Obs', 8) + padL('Mean', 14) + padL('Std. dev.', 14));
L.push(rule(21) + '+' + rule(37));
for (const r of a.rows) L.push(padL(abbrev(r.key, 20), 20) + ' | ' + padL(String(r.n), 8) +
fmtCell(r.mean, 14) + fmtCell(r.sd, 14));
L.push(rule(58));
L.push('');
L.push('R-squared = ' + fmtF(a.r2, 4) + ' Root MSE = ' + fmtG(a.rmse, 6));
L.push("Bartlett's test for equal variances: chi2(" + (a.K - 1) + ') = ' + fmtF(a.bartlett, 4) +
' Prob>chi2 = ' + fmtF(a.pBart, 3));
return L.join('\n');
}
function outMargins(mg, m) {
const L = [];
L.push('Average marginal effects' + ' '.repeat(24) + padR('Number of obs', 15) + ' = ' + padL(String(m.n), 9));
L.push('Model: ' + m.family + ' dy/dx w.r.t. each covariate');
L.push('');
L.push(rule(TW));
L.push(padL('', LW) + ' | ' + padL('dy/dx', 12) + padL('Std. err.', 11) + padL('z', 8) +
padL('P>|z|', 8) + padC('[95% conf. interval]', 22));
L.push(rule(LW + 1) + '+' + rule(TW - LW - 2));
for (let a = 0; a < mg.dy.length; a++) {
if (a === mg.consIdx) continue;
L.push(padL(abbrev(mg.names[a], LW), LW) + ' | ' + fmtCell(mg.dy[a], 12) + fmtCell(mg.se[a], 11) +
padL(fmtF(mg.z[a], 2), 8) + padL(fmtF(mg.p[a], 3), 8) + fmtCell(mg.lo[a], 11) + fmtCell(mg.hi[a], 11));
}
L.push(rule(TW));
return L.join('\n');
}
function outEstTable(names) {
const models = names.map(n => DB.stored[n]).filter(Boolean);
if (!models.length) return 'No stored estimates. Use: estimates store <name>';
const allVars = [];
for (const m of models) for (const v of m.m.names) if (!allVars.includes(v)) allVars.push(v);
const cw = 14, w1 = 16;
const L = [];
L.push(rule(w1 + 1 + cw * models.length + 1));
L.push(padL('Variable', w1) + ' | ' + names.map(n => padC(abbrev(n, cw - 1), cw)).join(''));
L.push(rule(w1 + 1) + '+' + rule(cw * models.length + 1));
for (const v of allVars) {
let l1 = padL(abbrev(v, w1), w1) + ' | ', l2 = padL('', w1) + ' | ';
for (const s of models) {
const i = s.m.names.indexOf(v);
if (i < 0) { l1 += padC('', cw); l2 += padC('', cw); continue; }
l1 += padC(fmtG(s.m.b[i], 6) + sigStars(s.m.p[i]), cw);
l2 += padC('(' + fmtG(s.m.se[i], 5) + ')', cw);
}
L.push(l1); L.push(l2);
}
L.push(rule(w1 + 1) + '+' + rule(cw * models.length + 1));
L.push(padL('N', w1) + ' | ' + models.map(s => padC(String(s.m.n), cw)).join(''));
L.push(padL('R-sq / Pseudo', w1) + ' | ' + models.map(s =>
padC(fmtF(s.m.r2 !== undefined ? s.m.r2 : s.m.r2p, 4), cw)).join(''));
L.push(padL('Depvar', w1) + ' | ' + models.map(s => padC(abbrev(s.depvar, cw - 1), cw)).join(''));
L.push(rule(w1 + 1 + cw * models.length + 1));
L.push('Standard errors in parentheses. * p<0.1, ** p<0.05, *** p<0.01');
return L.join('\n');
}
/* ============================================================
GRAPHICS — hand-rolled SVG, theme aware
============================================================ */
const PW = 720, PH = 430;
const PAL = ['var(--s1)', 'var(--s2)', 'var(--s3)', 'var(--s4)', 'var(--s5)', 'var(--s6)'];
function esc(s) { return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); }
function niceTicks(lo, hi, n) {
if (!isFinite(lo) || !isFinite(hi)) return [0, 1];
if (lo === hi) { lo -= 0.5; hi += 0.5; }
const raw = (hi - lo) / (n || 6);
const mag = Math.pow(10, Math.floor(Math.log10(raw)));
const norm = raw / mag;
const step = (norm < 1.5 ? 1 : norm < 3 ? 2 : norm < 7 ? 5 : 10) * mag;
const start = Math.ceil(lo / step) * step;
const t = [];
for (let v = start; v <= hi + step * 1e-9; v += step) t.push(Math.abs(v) < step * 1e-9 ? 0 : v);
return t;
}
function tickLab(v) {
const a = Math.abs(v);
if (a === 0) return '0';
if (a >= 1e6 || a < 1e-3) return v.toExponential(1).replace('e+', 'e');
return String(Math.round(v * 1e6) / 1e6);
}
/* Frame builder: returns helpers + a finish() that wraps everything */
function frame(o) {
const ml = o.ml || 70, mr = o.mr || 22, mt = o.mt || 46, mb = o.mb || 54;
const w = PW - ml - mr, h = PH - mt - mb;
let xlo = o.xlo, xhi = o.xhi, ylo = o.ylo, yhi = o.yhi;
if (xlo === xhi) { xlo -= 1; xhi += 1; }
if (ylo === yhi) { ylo -= 1; yhi += 1; }
const px = v => ml + (v - xlo) / (xhi - xlo) * w;
const py = v => mt + h - (v - ylo) / (yhi - ylo) * h;
const xt = o.xticks || niceTicks(xlo, xhi, 6), yt = niceTicks(ylo, yhi, 5);
const parts = [];
parts.push('<rect x="' + ml + '" y="' + mt + '" width="' + w + '" height="' + h +
'" fill="var(--plot-bg)" stroke="none"/>');
for (const t of yt) parts.push('<line x1="' + ml + '" y1="' + py(t).toFixed(1) + '" x2="' + (ml + w) +
'" y2="' + py(t).toFixed(1) + '" stroke="var(--plot-grid)" stroke-width="1"/>');
for (const t of xt) if (typeof t === 'number') parts.push('<line x1="' + px(t).toFixed(1) + '" y1="' + mt +
'" x2="' + px(t).toFixed(1) + '" y2="' + (mt + h) + '" stroke="var(--plot-grid)" stroke-width="1"/>');
const axes = () => {
const a = [];
a.push('<rect x="' + ml + '" y="' + mt + '" width="' + w + '" height="' + h +
'" fill="none" stroke="var(--plot-axis)" stroke-width="1.2"/>');
for (const t of yt) a.push('<text x="' + (ml - 8) + '" y="' + (py(t) + 4).toFixed(1) +
'" text-anchor="end" class="ptick">' + esc(tickLab(t)) + '</text>');
if (o.xcat) o.xcat.forEach((c, i) => a.push('<text x="' + px(c.at).toFixed(1) + '" y="' + (mt + h + 18) +
'" text-anchor="middle" class="ptick">' + esc(c.lab) + '</text>'));
else for (const t of xt) a.push('<text x="' + px(t).toFixed(1) + '" y="' + (mt + h + 18) +
'" text-anchor="middle" class="ptick">' + esc(tickLab(t)) + '</text>');
a.push('<text x="' + (ml + w / 2) + '" y="' + (PH - 12) + '" text-anchor="middle" class="plab">' +
esc(o.xlab || '') + '</text>');
a.push('<text x="16" y="' + (mt + h / 2) + '" text-anchor="middle" class="plab" transform="rotate(-90 16 ' +
(mt + h / 2) + ')">' + esc(o.ylab || '') + '</text>');
a.push('<text x="' + ml + '" y="26" class="ptitle">' + esc(o.title || '') + '</text>');
if (o.sub) a.push('<text x="' + (PW - mr) + '" y="26" text-anchor="end" class="psub">' + esc(o.sub) + '</text>');
return a.join('');
};
return { px, py, ml, mr, mt, mb, w, h, parts, axes, xlo, xhi, ylo, yhi };
}
function wrapSVG(inner, cap) {
return '<figure class="plot"><svg viewBox="0 0 ' + PW + ' ' + PH +
'" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">' + inner + '</svg>' +
(cap ? '<figcaption>' + esc(cap) + '</figcaption>' : '') + '</figure>';
}
function pad(lo, hi, f) { const d = (hi - lo) || 1; return [lo - d * (f || 0.05), hi + d * (f || 0.05)]; }
function plotScatter(xs, ys, o) {
o = o || {};
const pts = [];
for (let i = 0; i < xs.length; i++) if (isNum(xs[i]) && isNum(ys[i]))
pts.push([xs[i], ys[i], o.grp ? o.grp[i] : null, o.lbl ? o.lbl[i] : null]);
if (!pts.length) return '<p class="warn">Nothing to plot — no observations with both variables present.</p>';
const [xlo, xhi] = pad(Math.min(...pts.map(p => p[0])), Math.max(...pts.map(p => p[0])));
const [ylo, yhi] = pad(Math.min(...pts.map(p => p[1])), Math.max(...pts.map(p => p[1])));
const f = frame(Object.assign({ xlo, xhi, ylo, yhi }, o));
const groups = o.grp ? [...new Set(pts.map(p => String(p[2])))].sort(cmpKey) : [null];
pts.forEach(p => {
const gi = o.grp ? groups.indexOf(String(p[2])) : 0;
f.parts.push('<circle cx="' + f.px(p[0]).toFixed(1) + '" cy="' + f.py(p[1]).toFixed(1) +
'" r="3.1" fill="' + PAL[gi % PAL.length] + '" fill-opacity="0.72" stroke="' + PAL[gi % PAL.length] +
'" stroke-width="0.7"><title>' + esc((p[3] ? p[3] + '\n' : '') + tickLab(p[0]) + ', ' + tickLab(p[1])) +
'</title></circle>');
});
if (o.fit) { // OLS line through the plotted points
const X = pts.map(p => [1, p[0]]), m = ols(pts.map(p => p[1]), X, {});
const y1 = m.b[0] + m.b[1] * xlo, y2 = m.b[0] + m.b[1] * xhi;
f.parts.push('<line x1="' + f.px(xlo) + '" y1="' + f.py(y1).toFixed(1) + '" x2="' + f.px(xhi) +
'" y2="' + f.py(y2).toFixed(1) + '" stroke="var(--plot-fit)" stroke-width="2.2"/>');
o.sub = 'fit: y = ' + fmtG(m.b[0], 4) + ' + ' + fmtG(m.b[1], 4) + '·x (R² = ' + fmtF(m.r2, 3) + ')';
f.parts.push('<text x="' + (PW - 22) + '" y="26" text-anchor="end" class="psub">' + esc(o.sub) + '</text>');
}
if (o.lowess) {
const sp = pts.slice().sort((a, b) => a[0] - b[0]);
const bw = Math.max(0.15, o.lowess);
const ln = [];
for (let i = 0; i < 60; i++) {
const x0 = xlo + (xhi - xlo) * i / 59;
let sw = 0, sy = 0;
const h = bw * (xhi - xlo);
for (const p of sp) { const u = (p[0] - x0) / h; const wgt = Math.exp(-0.5 * u * u);
sw += wgt; sy += wgt * p[1]; }
if (sw > 1e-8) ln.push(f.px(x0).toFixed(1) + ',' + f.py(sy / sw).toFixed(1));
}
f.parts.push('<polyline points="' + ln.join(' ') + '" fill="none" stroke="var(--plot-fit2)" stroke-width="2.2"/>');
}
if (o.grp) {
groups.forEach((g, i) => {
const y = f.mt + 14 + i * 17;
f.parts.push('<circle cx="' + (f.ml + f.w - 92) + '" cy="' + y + '" r="4" fill="' + PAL[i % PAL.length] + '"/>');
f.parts.push('<text x="' + (f.ml + f.w - 82) + '" y="' + (y + 4) + '" class="pleg">' +
esc(o.grpname ? o.grpname + '=' + g : g) + '</text>');
});
}
return wrapSVG(f.parts.join('') + f.axes(), o.cap);
}
function plotLine(series, o) {
o = o || {};
let xlo = Infinity, xhi = -Infinity, ylo = Infinity, yhi = -Infinity;
for (const s of series) for (let i = 0; i < s.y.length; i++) {
if (!isNum(s.y[i])) continue;
const x = s.x ? s.x[i] : i + 1;
xlo = Math.min(xlo, x); xhi = Math.max(xhi, x);
ylo = Math.min(ylo, s.y[i]); yhi = Math.max(yhi, s.y[i]);
}
if (!isFinite(xlo)) return '<p class="warn">Nothing to plot.</p>';
const yr = pad(ylo, yhi, 0.08);
const f = frame(Object.assign({ xlo, xhi, ylo: yr[0], yhi: yr[1] }, o));
if (o.zero && yr[0] < 0 && yr[1] > 0) f.parts.push('<line x1="' + f.ml + '" y1="' + f.py(0).toFixed(1) +
'" x2="' + (f.ml + f.w) + '" y2="' + f.py(0).toFixed(1) + '" stroke="var(--plot-axis)" stroke-width="1" stroke-dasharray="4 3"/>');
series.forEach((s, si) => {
let d = '', open = false;
for (let i = 0; i < s.y.length; i++) {
const x = s.x ? s.x[i] : i + 1;
if (!isNum(s.y[i]) || !isNum(x)) { open = false; continue; }
d += (open ? 'L' : 'M') + f.px(x).toFixed(1) + ' ' + f.py(s.y[i]).toFixed(1) + ' ';
open = true;
}
f.parts.push('<path d="' + d + '" fill="none" stroke="' + (s.color || PAL[si % PAL.length]) +
'" stroke-width="' + (s.w || 1.9) + '" stroke-linejoin="round"' +
(s.dash ? ' stroke-dasharray="5 4"' : '') + '/>');
if (s.dots) for (let i = 0; i < s.y.length; i++) { if (!isNum(s.y[i])) continue;
f.parts.push('<circle cx="' + f.px(s.x ? s.x[i] : i + 1).toFixed(1) + '" cy="' + f.py(s.y[i]).toFixed(1) +
'" r="2.4" fill="' + (s.color || PAL[si % PAL.length]) + '"/>'); }
});
if (series.length > 1 && series[0].label) series.forEach((s, i) => {
const y = f.mt + 14 + i * 17;
f.parts.push('<line x1="' + (f.ml + f.w - 104) + '" y1="' + y + '" x2="' + (f.ml + f.w - 86) +
'" y2="' + y + '" stroke="' + (s.color || PAL[i % PAL.length]) + '" stroke-width="2.4"/>');
f.parts.push('<text x="' + (f.ml + f.w - 80) + '" y="' + (y + 4) + '" class="pleg">' + esc(s.label) + '</text>');
});
return wrapSVG(f.parts.join('') + f.axes(), o.cap);
}
function plotHist(vals, o) {
o = o || {};
const v = vals.filter(isNum);
if (v.length < 2) return '<p class="warn">Nothing to plot.</p>';
const lo = Math.min(...v), hi = Math.max(...v);
const nb = o.bins || Math.max(5, Math.min(40, Math.round(Math.sqrt(v.length))));
const bw = (hi - lo) / nb || 1;
const counts = new Array(nb).fill(0);
for (const x of v) counts[Math.min(nb - 1, Math.floor((x - lo) / bw))]++;
const dens = counts.map(c => c / (v.length * bw));
const useD = o.density !== false;
const hgt = useD ? dens : counts;
let ymax = Math.max(...hgt);
let kd = null;
if (o.kdens) { kd = kdensity(v, 120); ymax = Math.max(ymax, Math.max(...kd.y)); }
let nd = null;
if (o.normal) { const m = mean(v), s = sd(v); nd = { x: [], y: [] };
for (let i = 0; i < 120; i++) { const x = lo - bw + (hi - lo + 2 * bw) * i / 119;
nd.x.push(x); nd.y.push(normpdf((x - m) / s) / s); }
ymax = Math.max(ymax, Math.max(...nd.y)); }
const f = frame(Object.assign({ xlo: lo - bw * 0.4, xhi: hi + bw * 0.4, ylo: 0, yhi: ymax * 1.1,
ylab: o.ylab || (useD ? 'Density' : 'Frequency') }, o));
for (let i = 0; i < nb; i++) {
if (!hgt[i]) continue;
const x0 = f.px(lo + i * bw), x1 = f.px(lo + (i + 1) * bw);
f.parts.push('<rect x="' + (x0 + 0.6).toFixed(1) + '" y="' + f.py(hgt[i]).toFixed(1) +
'" width="' + Math.max(0.8, x1 - x0 - 1.2).toFixed(1) + '" height="' + (f.py(0) - f.py(hgt[i])).toFixed(1) +
'" fill="var(--s1)" fill-opacity="0.62" stroke="var(--s1)" stroke-width="0.8"><title>' +
esc('[' + tickLab(lo + i * bw) + ', ' + tickLab(lo + (i + 1) * bw) + ') n=' + counts[i]) + '</title></rect>');
}
const overlay = (obj, color, dash) => {
let d = '';
for (let i = 0; i < obj.x.length; i++) d += (i ? 'L' : 'M') + f.px(obj.x[i]).toFixed(1) + ' ' + f.py(obj.y[i]).toFixed(1) + ' ';
f.parts.push('<path d="' + d + '" fill="none" stroke="' + color + '" stroke-width="2.2"' +
(dash ? ' stroke-dasharray="6 4"' : '') + '/>');
};
if (kd) overlay(kd, 'var(--plot-fit)');
if (nd) overlay(nd, 'var(--plot-fit2)', true);
return wrapSVG(f.parts.join('') + f.axes(), o.cap);
}
function plotBox(groups, o) {
o = o || {};
const stats = groups.map(g => {
const v = g.values.filter(isNum).sort((a, b) => a - b);
const q1 = quantile(v, .25), q2 = quantile(v, .5), q3 = quantile(v, .75), iqr = q3 - q1;
const lof = q1 - 1.5 * iqr, hif = q3 + 1.5 * iqr;
const inl = v.filter(x => x >= lof && x <= hif);
return { label: g.label, q1, q2, q3, lo: inl.length ? inl[0] : q1, hi: inl.length ? inl[inl.length - 1] : q3,
out: v.filter(x => x < lof || x > hif), n: v.length };
}).filter(s => s.n > 0);
if (!stats.length) return '<p class="warn">Nothing to plot.</p>';
let ylo = Infinity, yhi = -Infinity;
for (const s of stats) { ylo = Math.min(ylo, s.lo, ...s.out); yhi = Math.max(yhi, s.hi, ...s.out); }
const [a, b] = pad(ylo, yhi, 0.08);
const K = stats.length;
const f = frame(Object.assign({ xlo: 0, xhi: K, ylo: a, yhi: b,
xcat: stats.map((s, i) => ({ at: i + 0.5, lab: abbrev(s.label, 12) })) }, o));
stats.forEach((s, i) => {
const cx = f.px(i + 0.5), bw = Math.min(66, f.w / K * 0.5);
const col = PAL[i % PAL.length];
f.parts.push('<line x1="' + cx + '" y1="' + f.py(s.lo).toFixed(1) + '" x2="' + cx + '" y2="' +
f.py(s.hi).toFixed(1) + '" stroke="var(--plot-axis)" stroke-width="1.2"/>');
for (const w of [s.lo, s.hi]) f.parts.push('<line x1="' + (cx - bw / 3) + '" y1="' + f.py(w).toFixed(1) +
'" x2="' + (cx + bw / 3) + '" y2="' + f.py(w).toFixed(1) + '" stroke="var(--plot-axis)" stroke-width="1.2"/>');
f.parts.push('<rect x="' + (cx - bw / 2) + '" y="' + f.py(s.q3).toFixed(1) + '" width="' + bw +
'" height="' + Math.max(1, f.py(s.q1) - f.py(s.q3)).toFixed(1) + '" fill="' + col +
'" fill-opacity="0.45" stroke="' + col + '" stroke-width="1.3"><title>' +
esc(s.label + ' n=' + s.n + ' median=' + tickLab(s.q2)) + '</title></rect>');
f.parts.push('<line x1="' + (cx - bw / 2) + '" y1="' + f.py(s.q2).toFixed(1) + '" x2="' + (cx + bw / 2) +
'" y2="' + f.py(s.q2).toFixed(1) + '" stroke="var(--plot-ink)" stroke-width="2.2"/>');
for (const ov of s.out) f.parts.push('<circle cx="' + cx + '" cy="' + f.py(ov).toFixed(1) +
'" r="2.6" fill="none" stroke="' + col + '" stroke-width="1.2"/>');
});
return wrapSVG(f.parts.join('') + f.axes(), o.cap);
}
function plotQQ(vals, o) {
o = o || {};
const v = vals.filter(isNum).sort((a, b) => a - b), n = v.length;
if (n < 3) return '<p class="warn">Nothing to plot.</p>';
const m = mean(v), s = sd(v);
const th = v.map((_, i) => m + s * norminv((i + 0.625) / (n + 0.25)));
const lo = Math.min(...v, ...th), hi = Math.max(...v, ...th);
const [a, b] = pad(lo, hi, 0.05);
const f = frame(Object.assign({ xlo: a, xhi: b, ylo: a, yhi: b,
xlab: 'Theoretical normal quantiles', ylab: 'Sample quantiles' }, o));
f.parts.push('<line x1="' + f.px(a) + '" y1="' + f.py(a) + '" x2="' + f.px(b) + '" y2="' + f.py(b) +
'" stroke="var(--plot-fit)" stroke-width="1.8" stroke-dasharray="6 4"/>');
v.forEach((y, i) => f.parts.push('<circle cx="' + f.px(th[i]).toFixed(1) + '" cy="' + f.py(y).toFixed(1) +
'" r="3" fill="var(--s1)" fill-opacity="0.7"/>'));
return wrapSVG(f.parts.join('') + f.axes(), o.cap);
}
function plotACF(vals, ciBand, o) {
o = o || {};
const K = vals.length;
const ymax = Math.max(0.25, ...vals.map(Math.abs), ciBand) * 1.2;
const f = frame(Object.assign({ xlo: 0.3, xhi: K + 0.7, ylo: -ymax, yhi: ymax,
xlab: 'Lag', ylab: o.ylab || 'Autocorrelation' }, o));
f.parts.push('<rect x="' + f.ml + '" y="' + f.py(ciBand).toFixed(1) + '" width="' + f.w +
'" height="' + (f.py(-ciBand) - f.py(ciBand)).toFixed(1) +
'" fill="var(--plot-band)" fill-opacity="0.5"/>');
f.parts.push('<line x1="' + f.ml + '" y1="' + f.py(0).toFixed(1) + '" x2="' + (f.ml + f.w) +
'" y2="' + f.py(0).toFixed(1) + '" stroke="var(--plot-axis)" stroke-width="1.2"/>');
vals.forEach((v, i) => {
const x = f.px(i + 1);
f.parts.push('<line x1="' + x.toFixed(1) + '" y1="' + f.py(0).toFixed(1) + '" x2="' + x.toFixed(1) +
'" y2="' + f.py(v).toFixed(1) + '" stroke="var(--s1)" stroke-width="3.2" stroke-linecap="round">' +
'<title>' + esc('lag ' + (i + 1) + ': ' + fmtF(v, 4)) + '</title></line>');
});
return wrapSVG(f.parts.join('') + f.axes(), o.cap);
}
function plotBar(labels, values, o) {
o = o || {};
const K = labels.length;
const ymax = Math.max(...values) * 1.12, ymin = Math.min(0, ...values) * 1.12;
const f = frame(Object.assign({ xlo: 0, xhi: K, ylo: ymin, yhi: ymax,
xcat: labels.map((l, i) => ({ at: i + 0.5, lab: abbrev(l, 11) })) }, o));
values.forEach((v, i) => {
const cx = f.px(i + 0.5), bw = Math.min(70, f.w / K * 0.62);
f.parts.push('<rect x="' + (cx - bw / 2).toFixed(1) + '" y="' + f.py(Math.max(0, v)).toFixed(1) +
'" width="' + bw.toFixed(1) + '" height="' + Math.abs(f.py(v) - f.py(0)).toFixed(1) +
'" fill="' + PAL[i % PAL.length] + '" fill-opacity="0.72" stroke="' + PAL[i % PAL.length] +
'" stroke-width="1"><title>' + esc(labels[i] + ': ' + tickLab(v)) + '</title></rect>');
});
return wrapSVG(f.parts.join('') + f.axes(), o.cap);
}
function plotMatrix(vars, touse, o) {
o = o || {};
const K = vars.length, S = 150, M = 44;
const W = M + K * S + 14, H = M + K * S + 30;
const cols = vars.map(v => { const a = [];
for (let i = 0; i < DB.n; i++) a.push(touse[i] ? DB.col[v][i] : NaN); return a; });
const rng = cols.map(c => { const v = c.filter(isNum); return pad(Math.min(...v), Math.max(...v), 0.07); });
const p = [];
for (let r = 0; r < K; r++) for (let c = 0; c < K; c++) {
const x0 = M + c * S, y0 = M + r * S;
p.push('<rect x="' + x0 + '" y="' + y0 + '" width="' + (S - 6) + '" height="' + (S - 6) +
'" fill="var(--plot-bg)" stroke="var(--plot-axis)" stroke-width="1"/>');
if (r === c) {
p.push('<text x="' + (x0 + (S - 6) / 2) + '" y="' + (y0 + (S - 6) / 2 + 5) +
'" text-anchor="middle" class="pdiag">' + esc(abbrev(vars[r], 12)) + '</text>');
continue;
}
const [xa, xb] = rng[c], [ya, yb] = rng[r];
for (let i = 0; i < DB.n; i++) {
if (!isNum(cols[c][i]) || !isNum(cols[r][i])) continue;
const px = x0 + (cols[c][i] - xa) / (xb - xa) * (S - 6);
const py = y0 + (S - 6) - (cols[r][i] - ya) / (yb - ya) * (S - 6);
p.push('<circle cx="' + px.toFixed(1) + '" cy="' + py.toFixed(1) + '" r="1.7" fill="var(--s1)" fill-opacity="0.55"/>');
}
const rr = corr(cols[c], cols[r]);
p.push('<text x="' + (x0 + S - 12) + '" y="' + (y0 + 15) + '" text-anchor="end" class="pcorr">r=' +
fmtF(rr, 2) + '</text>');
}
for (let i = 0; i < K; i++) {
p.push('<text x="' + (M + i * S + (S - 6) / 2) + '" y="' + (M + K * S + 18) +
'" text-anchor="middle" class="ptick">' + esc(abbrev(vars[i], 12)) + '</text>');
p.push('<text x="' + (M - 8) + '" y="' + (M + i * S + (S - 6) / 2) + '" text-anchor="middle" class="ptick" ' +
'transform="rotate(-90 ' + (M - 8) + ' ' + (M + i * S + (S - 6) / 2) + ')">' + esc(abbrev(vars[i], 12)) + '</text>');
}
p.push('<text x="' + M + '" y="24" class="ptitle">' + esc(o.title || 'Scatterplot matrix') + '</text>');
return '<figure class="plot"><svg viewBox="0 0 ' + W + ' ' + H + '" xmlns="http://www.w3.org/2000/svg">' +
p.join('') + '</svg>' + (o.cap ? '<figcaption>' + esc(o.cap) + '</figcaption>' : '') + '</figure>';
}
/* ============================================================
COMMAND LANGUAGE
============================================================ */
function splitTop(s, ch) { // split on ch at paren depth 0, respecting quotes
const out = []; let cur = '', d = 0, q = false;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c === '"') q = !q;
if (!q) { if (c === '(') d++; else if (c === ')') d--;
else if (c === ch && d === 0) { out.push(cur); cur = ''; continue; } }
cur += c;
}
out.push(cur); return out;
}
function parseCmd(line) {
let s = line.trim();
const p = { raw: line, opts: {}, ifExpr: null, inRange: null };
const parts = splitTop(s, ',');
let body = parts[0].trim();
const optstr = parts.slice(1).join(',').trim();
if (optstr) {
const re = /([A-Za-z_][A-Za-z0-9_]*)(\(([^)]*)\))?/g;
let m;
while ((m = re.exec(optstr)) !== null) p.opts[m[1].toLowerCase()] = m[3] !== undefined ? m[3].trim() : true;
}
// in range
const inm = body.match(/\s+in\s+(\d+|f|F|l|L)\s*\/\s*(\d+|l|L|f|F)\s*$/);
if (inm) {
const lo = /^\d+$/.test(inm[1]) ? +inm[1] : (/f/i.test(inm[1]) ? 1 : DB.n);
const hi = /^\d+$/.test(inm[2]) ? +inm[2] : (/l/i.test(inm[2]) ? DB.n : 1);
p.inRange = [lo, hi]; body = body.slice(0, inm.index).trim();
}
// if clause
const ifm = body.match(/(^|\s)if\s+/);
if (ifm) { p.ifExpr = body.slice(ifm.index + ifm[0].length).trim();
body = body.slice(0, ifm.index).trim(); }
const tk = body.split(/\s+/).filter(Boolean);
p.cmd = (tk.shift() || '').toLowerCase();
p.args = tk;
p.body = body;
return p;
}
function expandVarlist(list) {
const out = [];
for (const t of list) {
if (t === '_all' || t === '*') { out.push(...varNames()); continue; }
if (t.includes('*')) {
const re = new RegExp('^' + t.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
const hit = varNames().filter(v => re.test(v));
if (!hit.length) throw new Error('no variables match "' + t + '"');
out.push(...hit); continue;
}
if (!hasVar(t)) throw new Error('variable ' + t + ' not found');
out.push(t);
}
return [...new Set(out)];
}
function numVarlist(list) { return expandVarlist(list).filter(v => !isStr(v)); }
/* ---------- Design-matrix construction (factors, interactions, ts operators) ---------- */
function seriesOp(name) { // returns {base, fn} or null
const m = name.match(/^([LFDS])(\d*)\.(.+)$/i);
if (!m) return null;
const op = m[1].toUpperCase(), k = m[2] ? +m[2] : 1, base = m[3];
return { base, op, k };
}
function colFor(name) {
const so = seriesOp(name);
if (so) {
if (!hasVar(so.base)) throw new Error('variable ' + so.base + ' not found');
const c = DB.col[so.base], o = new Array(DB.n).fill(NaN);
for (let i = 0; i < DB.n; i++) {
if (so.op === 'L') { if (i - so.k >= 0) o[i] = c[i - so.k]; }
else if (so.op === 'F') { if (i + so.k < DB.n) o[i] = c[i + so.k]; }
else if (so.op === 'D') { if (i - so.k >= 0) o[i] = c[i] - c[i - so.k]; }
else if (so.op === 'S') { if (i - so.k >= 0) o[i] = (c[i] - c[i - so.k]) / c[i - so.k]; }
}
return o;
}
if (!hasVar(name)) throw new Error('variable ' + name + ' not found');
return DB.col[name];
}
function termColumns(tok) {
const parts = tok.split('#');
let acc = [{ name: '', col: new Array(DB.n).fill(1) }];
for (const p0 of parts) {
let p = p0, factor = false;
if (/^i\./i.test(p)) { factor = true; p = p.slice(2); }
else if (/^c\./i.test(p)) p = p.slice(2);
const base = colFor(p);
let cols;
if (factor || (isStr(p) && !seriesOp(p))) {
const levels = [...new Set(base.filter(v => v !== '' && v !== null && v !== undefined &&
!(typeof v === 'number' && isNaN(v))).map(String))].sort(cmpKey);
if (levels.length > 40) throw new Error('i.' + p + ' has ' + levels.length + ' levels — too many');
cols = levels.slice(1).map(lv => ({ name: lv + '.' + p,
col: base.map(v => (v === '' || (typeof v === 'number' && isNaN(v))) ? NaN : (String(v) === lv ? 1 : 0)) }));
} else cols = [{ name: p, col: base.map(v => typeof v === 'string' ? (v === '' ? NaN : +v) : v) }];
const next = [];
for (const a of acc) for (const b of cols)
next.push({ name: a.name ? a.name + '#' + b.name : b.name,
col: a.col.map((v, i) => v * b.col[i]) });
acc = next;
}
return acc;
}
function buildDesign(depvar, xtoks, touse, noCons) {
const terms = [];
for (const t of xtoks) terms.push(...termColumns(t));
const yc = depvar ? colFor(depvar).map(v => typeof v === 'string' ? (v === '' ? NaN : +v) : v) : null;
const rows = [];
for (let i = 0; i < DB.n; i++) {
if (!touse[i]) continue;
if (yc && !isNum(yc[i])) continue;
let ok = true;
for (const t of terms) if (!isNum(t.col[i])) { ok = false; break; }
if (ok) rows.push(i);
}
const names = terms.map(t => t.name);
const X = rows.map(i => terms.map(t => t.col[i]));
let consIdx;
if (!noCons) { consIdx = names.length; names.push('_cons'); X.forEach(r => r.push(1)); }
const y = yc ? rows.map(i => yc[i]) : null;
if (!rows.length) throw new Error('no observations remain after dropping missing values');
return { X, y, names, rows, consIdx, nterms: terms.length };
}
/* ---------- helpers used by handlers ---------- */
function vceFromOpts(o) {
if (o.cluster) return { vce: 'cluster', cluster: o.cluster };
if (o.robust || o.vce === 'robust' || o.hc1) return { vce: 'robust' };
if (o.hc2) return { vce: 'hc2' };
if (o.hc3) return { vce: 'hc3' };
if (o.hac || o.newey) return { vce: 'hac' };
if (o.bootstrap) return { vce: 'boot' };
return { vce: 'ols' };
}
function need(cond, msg) { if (!cond) throw new Error(msg); }
function needData() { need(DB.n > 0, 'no data in memory. Load a sample with e.g. "use auto", or import a CSV.'); }
function needModel() { need(DB.last, 'no estimation results. Fit a model first (e.g. "regress y x").'); }
/* ============================================================
DISPATCH
============================================================ */
function runCommand(line, echo) {
const trimmed = line.trim();
if (!trimmed) return;
if (trimmed.startsWith('*') || trimmed.startsWith('//')) { if (echo !== false) logCmd(trimmed); return; }
// by-prefix
const bym = trimmed.match(/^(by|bysort)\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.+)$/i);
if (bym) {
if (echo !== false) logCmd(trimmed);
needData();
const gv = bym[2];
need(hasVar(gv), 'variable ' + gv + ' not found');
const levels = [...new Set(DB.col[gv].filter(okGroup).map(String))].sort(cmpKey);
for (const lv of levels) {
const q = isStr(gv) ? '"' + lv + '"' : lv;
out('\n' + rule(TW, '-') + '\n-> ' + gv + ' = ' + lv + '\n');
const sub = bym[3];
const p = parseCmd(sub);
const cond = p.ifExpr ? '(' + p.ifExpr + ') & ' + gv + '==' + q : gv + '==' + q;
const parts = splitTop(sub, ',');
let base = parts[0];
const ifm2 = base.match(/(^|\s)if\s+/);
if (ifm2) base = base.slice(0, ifm2.index);
const rebuilt = base.trim() + ' if ' + cond + (parts.length > 1 ? ',' + parts.slice(1).join(',') : '');
try { dispatch(parseCmd(rebuilt)); } catch (e) { outErr(e.message); }
}
return;
}
if (echo !== false) logCmd(trimmed);
try { dispatch(parseCmd(trimmed)); }
catch (e) { outErr(e.message); }
}
const ALIASES = { reg: 'regress', regr: 'regress', su: 'summarize', sum: 'summarize', summ: 'summarize',
tab: 'tabulate', ta: 'tabulate', corr: 'correlate', gen: 'generate', g: 'generate', d: 'describe',
desc: 'describe', di: 'display', l: 'list', hist: 'histogram', ivreg: 'ivregress', ivreg2: 'ivregress',
est: 'estimates', cls: 'clearresults', xi: 'regress', tsline: 'line', sc: 'scatter', twoway: 'scatter',
qui: 'quietly', ren: 'rename', lab: 'label', gr: 'graph', dfgls: 'dfuller' };
function dispatch(p) {
let c = ALIASES[p.cmd] || p.cmd;
const o = p.opts, A = p.args;
switch (c) {
/* ---------------- data management ---------------- */
case 'use': case 'sysuse': case 'webuse': {
need(A[0], 'specify a dataset: ' + Object.keys(SAMPLES).join(', '));
const r = loadSample(A[0].replace(/\.dta$/, ''));
out('(' + r.desc + ')');
out('\nDataset "' + DB.name + '" loaded: ' + r.n + ' observations, ' + r.k + ' variables.');
if (DB.panelvar) out('Panel structure detected — xtset ' + DB.panelvar + ' ' + DB.timevar + ' already applied.');
else if (DB.tsvar) out('Time series detected — tsset ' + DB.tsvar + ' already applied.');
refreshAll(); return; }
case 'clear': {
if (A[0] === 'results') { DB.last = null; DB.stored = {}; out('(estimation results cleared)'); return; }
clearData(); out('(data cleared from memory)'); refreshAll(); return; }
case 'clearresults': clearLog(); return;
case 'describe': {
needData();
const vars = A.length ? expandVarlist(A) : varNames();
out('Contains data from ' + (DB.name || 'memory'));
out(' Observations: ' + padL(String(DB.n), 10));
out(' Variables: ' + padL(String(DB.vars.length), 10));
out('');
out(rule(TW));
out(padR('Variable', 16) + padR('Storage', 10) + padR('Display', 10) + 'Variable label');
out(rule(TW));
for (const v of vars) {
const o2 = getVar(v);
out(padR(abbrev(v, 15), 16) + padR(o2.type === 'str' ? 'str' : 'double', 10) +
padR(o2.type === 'str' ? '%12s' : '%9.0g', 10) + (o2.label || ''));
}
out(rule(TW));
if (DB.panelvar) out('Panel: ' + DB.panelvar + ' Time: ' + (DB.timevar || 'n/a'));
else if (DB.tsvar) out('Time variable: ' + DB.tsvar);
return; }
case 'codebook': {
needData();
const vars = A.length ? expandVarlist(A) : varNames();
const touse = makeTouse(p.ifExpr, p.inRange);
for (const v of vars) {
out(rule(TW));
out(padR(v, 30) + (getVar(v).label || ''));
out(rule(TW));
const raw = [];
for (let i = 0; i < DB.n; i++) if (touse[i]) raw.push(DB.col[v][i]);
const miss = raw.filter(x => x === '' || x === null || x === undefined ||
(typeof x === 'number' && isNaN(x))).length;
const uniq = new Set(raw.map(String)).size;
if (isStr(v)) {
out(' type: string');
out(' unique: ' + uniq + ' missing: ' + miss + '/' + raw.length);
const counts = new Map();
for (const x of raw) if (x !== '') counts.set(x, (counts.get(x) || 0) + 1);
const top = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6);
out(' examples: ' + top.map(t => t[0] + ' (' + t[1] + ')').join(', '));
} else {
const a = raw.filter(isNum);
out(' type: numeric' + (uniq <= 10 ? ' (looks categorical: ' + uniq + ' levels)' : ''));
out(' range: [' + fmtG(Math.min(...a), 6) + ', ' + fmtG(Math.max(...a), 6) + ']' +
' units: ' + (a.every(x => Number.isInteger(x)) ? 'integer' : 'continuous'));
out(' unique: ' + uniq + ' missing: ' + miss + '/' + raw.length);
out(' mean: ' + fmtG(mean(a), 6) + ' std. dev.: ' + fmtG(sd(a), 6));
out(' percentiles: 10% ' + fmtG(quantile(a, .1), 5) + ' 25% ' + fmtG(quantile(a, .25), 5) +
' 50% ' + fmtG(quantile(a, .5), 5) + ' 75% ' + fmtG(quantile(a, .75), 5) +
' 90% ' + fmtG(quantile(a, .9), 5));
}
}
out(rule(TW));
return; }
case 'list': {
needData();
const vars = A.length ? expandVarlist(A) : varNames().slice(0, 8);
const touse = makeTouse(p.ifExpr, p.inRange);
const rows = []; for (let i = 0; i < DB.n; i++) if (touse[i]) rows.push(i);
const lim = o.n ? +o.n : 50;
const w = vars.map(v => Math.max(v.length, 8) + 2);
out(rule(6 + w.reduce((s, x) => s + x, 0)));
out(padL('obs', 5) + ' |' + vars.map((v, j) => padL(abbrev(v, w[j] - 1), w[j])).join(''));
out(rule(6) + '+' + rule(w.reduce((s, x) => s + x, 0) - 1));
for (const i of rows.slice(0, lim)) {
out(padL(String(i + 1), 5) + ' |' + vars.map((v, j) => {
const x = DB.col[v][i];
return padL(typeof x === 'string' ? abbrev(x, w[j] - 1) : fmtG(x, 6), w[j]);
}).join(''));
}
out(rule(6 + w.reduce((s, x) => s + x, 0)));
if (rows.length > lim) out('(showing ' + lim + ' of ' + rows.length + ' observations — use the Data tab for all)');
return; }
case 'count': {
needData();
const touse = makeTouse(p.ifExpr, p.inRange);
out(' ' + touse.reduce((s, v) => s + v, 0));
return; }
case 'generate': case 'replace': {
needData();
const eq = p.body.indexOf('=');
need(eq > 0, 'syntax: ' + c + ' newvar = expression');
const lhsTok = p.body.slice(p.cmd.length, eq).trim().split(/\s+/);
const name = lhsTok[lhsTok.length - 1];
need(/^[A-Za-z_][A-Za-z0-9_]*$/.test(name), '"' + name + '" is not a valid variable name');
const expr = p.body.slice(eq + 1).trim();
const f = compileExpr(expr);
const touse = makeTouse(p.ifExpr, p.inRange);
const isNew = !hasVar(name);
need(c === 'generate' ? true : !isNew, 'variable ' + name + ' not found — use generate to create it');
if (c === 'generate' && !isNew) throw new Error('variable ' + name + ' already exists — use replace');
const old = isNew ? new Array(DB.n).fill(NaN) : DB.col[name].slice();
let changed = 0, missing = 0, str = false;
for (let i = 0; i < DB.n; i++) {
if (!touse[i]) continue;
const v = f(i);
if (typeof v === 'string') str = true;
if (typeof v === 'number' && isNaN(v)) missing++;
if (old[i] !== v) changed++;
old[i] = v;
}
addVar(name, old, str ? 'str' : 'num');
if (c === 'generate') out('(' + missing + ' missing value' + (missing === 1 ? '' : 's') + ' generated)');
else out('(' + changed + ' real change' + (changed === 1 ? '' : 's') + ' made)');
refreshAll(); return; }
case 'egen': {
needData();
const eq = p.body.indexOf('=');
need(eq > 0, 'syntax: egen newvar = fcn(arguments) [, by(groupvar)]');
const name = p.body.slice(4, eq).trim().split(/\s+/).pop();
const rhs = p.body.slice(eq + 1).trim();
const m = rhs.match(/^([A-Za-z_]+)\s*\(([^)]*)\)$/);
need(m, 'syntax: egen newvar = fcn(arguments)');
const fn = m[1].toLowerCase(), argstr = m[2].trim();
const touse = makeTouse(p.ifExpr, p.inRange);
const by = o.by;
const out_ = new Array(DB.n).fill(NaN);
const rowFns = { rowmean: a => mean(a), rowtotal: a => a.filter(isNum).reduce((s, v) => s + v, 0),
rowmax: a => Math.max(...a.filter(isNum)), rowmin: a => Math.min(...a.filter(isNum)),
rowsd: a => sd(a), rowmiss: a => a.filter(x => !isNum(x)).length,
rownonmiss: a => a.filter(isNum).length };
if (rowFns[fn]) {
const vars = expandVarlist(argstr.split(/[\s,]+/).filter(Boolean));
for (let i = 0; i < DB.n; i++) { if (!touse[i]) continue;
out_[i] = rowFns[fn](vars.map(v => DB.col[v][i])); }
} else if (fn === 'group' || fn === 'rank' || fn === 'seq' || fn === 'tag') {
if (fn === 'seq') { let k = 0; for (let i = 0; i < DB.n; i++) if (touse[i]) out_[i] = ++k; }
else if (fn === 'group') {
const vars = argstr.split(/[\s,]+/).filter(Boolean);
const keys = []; const map = new Map();
for (let i = 0; i < DB.n; i++) { if (!touse[i]) continue;
const k = vars.map(v => String(DB.col[v][i])).join('\u0001');
if (!map.has(k)) { map.set(k, 0); keys.push(k); } }
keys.sort(cmpKey); keys.forEach((k, j) => map.set(k, j + 1));
for (let i = 0; i < DB.n; i++) { if (!touse[i]) continue;
out_[i] = map.get(vars.map(v => String(DB.col[v][i])).join('\u0001')); }
} else if (fn === 'tag') {
const vars = argstr.split(/[\s,]+/).filter(Boolean); const seen = new Set();
for (let i = 0; i < DB.n; i++) { if (!touse[i]) continue;
const k = vars.map(v => String(DB.col[v][i])).join('\u0001');
out_[i] = seen.has(k) ? 0 : 1; seen.add(k); }
} else { // rank
const f = compileExpr(argstr);
const vals = []; for (let i = 0; i < DB.n; i++) vals.push(touse[i] ? f(i) : NaN);
const r = ranks(vals);
for (let i = 0; i < DB.n; i++) out_[i] = r[i];
}
} else {
const agg = { mean, sd, median, max: a => Math.max(...a.filter(isNum)),
min: a => Math.min(...a.filter(isNum)), total: a => a.filter(isNum).reduce((s, v) => s + v, 0),
sum: a => a.filter(isNum).reduce((s, v) => s + v, 0), count: a => a.filter(isNum).length,
iqr: a => quantile(a, .75) - quantile(a, .25), std: null, pc: null };
need(agg[fn] !== undefined, 'egen function "' + fn + '" is not supported. Available: mean sd median ' +
'min max total count iqr std group rank seq tag rowmean rowtotal rowmax rowmin rowsd');
const f = compileExpr(argstr);
const vals = []; for (let i = 0; i < DB.n; i++) vals.push(touse[i] ? f(i) : NaN);
const groups = new Map();
for (let i = 0; i < DB.n; i++) { if (!touse[i]) continue;
if (by && !okGroup(DB.col[by][i])) continue;
const k = by ? String(DB.col[by][i]) : '_';
if (!groups.has(k)) groups.set(k, []); groups.get(k).push(i); }
for (const [k, idx] of groups) {
const a = idx.map(i => vals[i]);
if (fn === 'std') { const m2 = mean(a), s2 = sd(a);
for (const i of idx) out_[i] = (vals[i] - m2) / s2; }
else { const v = agg[fn](a); for (const i of idx) out_[i] = v; }
}
}
addVar(name, out_, 'num');
out('(' + out_.filter(x => !isNum(x)).length + ' missing values generated)');
refreshAll(); return; }
case 'drop': case 'keep': {
needData();
if (p.ifExpr || p.inRange) {
const touse = makeTouse(p.ifExpr, p.inRange);
const keepRow = i => c === 'keep' ? touse[i] : !touse[i];
const idx = []; for (let i = 0; i < DB.n; i++) if (keepRow(i)) idx.push(i);
const dropped = DB.n - idx.length;
for (const v of varNames()) DB.col[v] = idx.map(i => DB.col[v][i]);
DB.n = idx.length;
out('(' + dropped + ' observation' + (dropped === 1 ? '' : 's') + ' deleted)');
} else {
need(A.length, 'specify variables, or use "' + c + ' if <condition>"');
const vars = expandVarlist(A);
if (c === 'keep') dropVars(varNames().filter(v => !vars.includes(v)));
else dropVars(vars);
out('(' + (c === 'keep' ? varNames().length + ' variables kept' : vars.length + ' variables dropped') + ')');
}
refreshAll(); return; }
case 'rename': {
needData(); need(A.length === 2, 'syntax: rename oldname newname');
need(hasVar(A[0]), 'variable ' + A[0] + ' not found');
need(!hasVar(A[1]), 'variable ' + A[1] + ' already exists');
getVar(A[0]).name = A[1]; DB.col[A[1]] = DB.col[A[0]]; delete DB.col[A[0]];
out('(renamed ' + A[0] + ' to ' + A[1] + ')'); refreshAll(); return; }
case 'label': {
needData();
const m = p.body.match(/^label\s+var\w*\s+(\S+)\s+"([^"]*)"/i);
need(m, 'syntax: label variable varname "label text"');
need(hasVar(m[1]), 'variable ' + m[1] + ' not found');
getVar(m[1]).label = m[2]; out('(label set)'); refreshAll(); return; }
case 'order': {
needData(); const vars = expandVarlist(A);
DB.vars = vars.map(getVar).concat(DB.vars.filter(v => !vars.includes(v.name)));
out('(variables reordered)'); refreshAll(); return; }
case 'sort': case 'gsort': {
needData(); need(A.length, 'syntax: sort varlist | gsort -varname');
const specs = A.map(t => ({ v: t.replace(/^[-+]/, ''), desc: t.startsWith('-') }));
for (const s of specs) need(hasVar(s.v), 'variable ' + s.v + ' not found');
const idx = Array.from({ length: DB.n }, (_, i) => i);
idx.sort((a, b) => {
for (const s of specs) {
const x = DB.col[s.v][a], y = DB.col[s.v][b];
const xm = x === '' || (typeof x === 'number' && isNaN(x)), ym = y === '' || (typeof y === 'number' && isNaN(y));
if (xm && ym) continue; if (xm) return 1; if (ym) return -1;
let d = typeof x === 'string' ? (x < y ? -1 : x > y ? 1 : 0) : x - y;
if (s.desc) d = -d;
if (d) return d;
}
return a - b;
});
for (const v of varNames()) DB.col[v] = idx.map(i => DB.col[v][i]);
out('(data sorted by ' + A.join(' ') + ')'); refreshAll(); return; }
case 'encode': {
needData(); need(A[0] && o.gen, 'syntax: encode strvar, gen(newvar)');
need(hasVar(A[0]), 'variable ' + A[0] + ' not found');
const levels = [...new Set(DB.col[A[0]].filter(v => v !== '').map(String))].sort(cmpKey);
const map = new Map(levels.map((l, i) => [l, i + 1]));
addVar(o.gen, DB.col[A[0]].map(v => v === '' ? NaN : map.get(String(v))), 'num',
'Encoded from ' + A[0]);
out('(' + levels.length + ' levels encoded: ' + levels.slice(0, 8).map((l, i) => (i + 1) + '=' + l).join(', ') +
(levels.length > 8 ? ', ...' : '') + ')');
refreshAll(); return; }
case 'tsset': case 'xtset': {
needData(); need(A[0], 'syntax: tsset timevar | xtset panelvar timevar');
need(hasVar(A[0]), 'variable ' + A[0] + ' not found');
if (c === 'xtset') { DB.panelvar = A[0]; DB.timevar = A[1] || null; DB.tsvar = A[1] || null;
const G = new Set(DB.col[A[0]].map(String)).size;
out('Panel variable: ' + A[0] + ' (' + G + ' groups)');
if (A[1]) out('Time variable: ' + A[1]); }
else { DB.tsvar = A[0]; DB.timevar = A[0]; DB.panelvar = null;
out('Time variable: ' + A[0] + ', ' + fmtG(Math.min(...DB.col[A[0]].filter(isNum)), 6) + ' to ' +
fmtG(Math.max(...DB.col[A[0]].filter(isNum)), 6));
out(' Delta: 1 unit'); }
refreshAll(); return; }
case 'set': {
if (A[0] === 'seed') { setSeed(+A[1] || 1); out('(random-number seed set to ' + (+A[1] || 1) + ')'); return; }
out('(option ignored)'); return; }
case 'preserve': { DB.snapshot = JSON.parse(JSON.stringify({ n: DB.n, vars: DB.vars, col: DB.col,
name: DB.name })); out('(data preserved)'); return; }
case 'restore': {
need(DB.snapshot, 'nothing has been preserved');
DB.n = DB.snapshot.n; DB.vars = DB.snapshot.vars; DB.col = DB.snapshot.col; DB.name = DB.snapshot.name;
for (const v of DB.vars) if (v.type === 'num') DB.col[v.name] = DB.col[v.name].map(x => x === null ? NaN : x);
out('(data restored)'); refreshAll(); return; }
case 'display': {
const f = compileExpr(p.body.slice(p.cmd.length).trim());
out(' ' + fmtG(f(0), 9)); return; }
/* ---------------- descriptive ---------------- */
case 'summarize': {
needData();
const touse = makeTouse(p.ifExpr, p.inRange);
const vars = A.length ? expandVarlist(A) : varNames();
out(outSummarize(vars, touse, !!(o.detail || o.d)));
return; }
case 'tabstat': {
needData();
const touse = makeTouse(p.ifExpr, p.inRange);
const vars = numVarlist(A.length ? A : varNames());
const stats = (o.statistics || o.stats || 'mean sd min max n').split(/[\s,]+/).filter(Boolean);
const fns = { mean: a => mean(a), sd: a => sd(a), min: a => Math.min(...a), max: a => Math.max(...a),
n: a => a.length, count: a => a.length, median: a => median(a), p25: a => quantile(a, .25),
p50: a => median(a), p75: a => quantile(a, .75), sum: a => a.reduce((s, v) => s + v, 0),
var: a => variance(a), cv: a => sd(a) / mean(a), skewness: a => skewness(a), kurtosis: a => kurtosis(a),
iqr: a => quantile(a, .75) - quantile(a, .25), range: a => Math.max(...a) - Math.min(...a) };
for (const s of stats) need(fns[s], 'unknown statistic "' + s + '"');
const by = o.by;
const groups = new Map();
for (let i = 0; i < DB.n; i++) { if (!touse[i]) continue;
if (by && !okGroup(DB.col[by][i])) continue;
const k = by ? String(DB.col[by][i]) : 'Total';
if (!groups.has(k)) groups.set(k, []); groups.get(k).push(i); }
const keys = [...groups.keys()].sort(cmpKey);
const w1 = 14, cw = 12;
out(rule(w1 + 2 + cw * stats.length));
out(padL(by ? by : 'Variable', w1) + ' |' + (by ? '' : '') +
stats.map(s => padL(s, cw)).join('') + (by ? '' : ''));
out(rule(w1 + 1) + '+' + rule(cw * stats.length));
if (by) {
for (const v of vars) {
out(padL(abbrev(v, w1), w1) + ' |');
for (const k of keys) {
const a = groups.get(k).map(i => DB.col[v][i]).filter(isNum);
out(padL(abbrev(k, w1), w1) + ' |' + stats.map(s => fmtCell(a.length ? fns[s](a) : NaN, cw)).join(''));
}
out(rule(w1 + 1) + '+' + rule(cw * stats.length));
}
} else {
for (const v of vars) {
const a = groups.get('Total').map(i => DB.col[v][i]).filter(isNum);
out(padL(abbrev(v, w1), w1) + ' |' + stats.map(s => fmtCell(a.length ? fns[s](a) : NaN, cw)).join(''));
}
out(rule(w1 + 2 + cw * stats.length));
}
return; }
case 'tabulate': {
needData();
const touse = makeTouse(p.ifExpr, p.inRange);
need(A.length, 'syntax: tabulate var1 [var2] [, chi2 row col all]');
if (A.length === 1) out(outTab1(expandVarlist([A[0]])[0], touse));
else out(outTab2(A[0], A[1], touse, o));
return; }
case 'correlate': case 'pwcorr': {
needData();
const touse = makeTouse(p.ifExpr, p.inRange);
const vars = numVarlist(A.length ? A : varNames());
need(vars.length >= 2, 'specify at least two numeric variables');
if (c === 'correlate') {
// listwise deletion
const t2 = touse.slice();
for (let i = 0; i < DB.n; i++) if (t2[i]) for (const v of vars) if (!isNum(DB.col[v][i])) { t2[i] = 0; break; }
out('(obs=' + t2.reduce((s, v) => s + v, 0) + ')');
out('');
out(outCorr(vars, t2, false, false, false));
} else out(outCorr(vars, touse, true, !!o.sig, !!o.star));
return; }
/* ---------------- classical tests ---------------- */
case 'ttest': {
needData();
const touse = makeTouse(p.ifExpr, p.inRange);
const body = p.body.replace(/^ttest\s+/i, '');
if (o.by) {
const v = body.trim().split(/\s+/)[0];
need(hasVar(v), 'variable ' + v + ' not found');
const lev = [...new Set(DB.col[o.by].filter((x, i) => touse[i] && x !== '' &&
!(typeof x === 'number' && isNaN(x))).map(String))].sort(cmpKey);
need(lev.length === 2, o.by + ' takes ' + lev.length + ' values — ttest, by() needs exactly 2');
const g1 = [], g2 = [];
for (let i = 0; i < DB.n; i++) { if (!touse[i] || !isNum(DB.col[v][i])) continue;
(String(DB.col[o.by][i]) === lev[0] ? g1 : g2).push(DB.col[v][i]); }
out(outTtest2(ttest2(g1, g2, !!(o.unequal || o.welch)), v, o.by + '=' + lev[0], o.by + '=' + lev[1], o.by));
return;
}
if (body.includes('==')) {
const [a, b] = body.split('==').map(s => s.trim());
need(hasVar(a) && hasVar(b), 'both variables must exist for a paired test');
const x1 = [], x2 = [];
for (let i = 0; i < DB.n; i++) if (touse[i]) { x1.push(DB.col[a][i]); x2.push(DB.col[b][i]); }
const r = ttestPaired(x1, x2);
out('Paired t test: ' + a + ' vs ' + b);
out(outTtest1(r, a + ' - ' + b));
return;
}
const m = body.match(/^(\S+)\s*=\s*(\S+)$/);
need(m, 'syntax: ttest var = # | ttest var, by(group) | ttest var1 == var2');
const a = [];
for (let i = 0; i < DB.n; i++) if (touse[i]) a.push(DB.col[m[1]][i]);
out(outTtest1(ttest1(a, parseFloat(m[2])), m[1]));
return; }
case 'sdtest': {
needData(); const touse = makeTouse(p.ifExpr, p.inRange);
need(A[0] && o.by, 'syntax: sdtest var, by(group)');
const lev = [...new Set(DB.col[o.by].filter((x, i) => touse[i] && okGroup(x)).map(String))].sort(cmpKey);
need(lev.length === 2, 'by() must have exactly 2 groups');
const g = [[], []];
for (let i = 0; i < DB.n; i++) if (touse[i] && isNum(DB.col[A[0]][i]))
g[String(DB.col[o.by][i]) === lev[0] ? 0 : 1].push(DB.col[A[0]][i]);
const v1 = variance(g[0]), v2 = variance(g[1]);
const F = v1 / v2, d1 = g[0].length - 1, d2 = g[1].length - 1;
const pv = 2 * Math.min(fcdf(F, d1, d2), 1 - fcdf(F, d1, d2));
out('Variance ratio test: ' + A[0] + ' by ' + o.by);
out(rule(TW));
out(padL('Group', 14) + ' | ' + padL('Obs', 8) + padL('Mean', 13) + padL('Std. dev.', 13) + padL('Variance', 13));
out(rule(15) + '+' + rule(TW - 16));
[0, 1].forEach(k => out(padL(o.by + '=' + lev[k], 14) + ' | ' + padL(String(g[k].length), 8) +
fmtCell(mean(g[k]), 13) + fmtCell(sd(g[k]), 13) + fmtCell(variance(g[k]), 13)));
out(rule(TW));
out('');
out(' ratio = sd(' + lev[0] + ') / sd(' + lev[1] + ') f = ' + fmtF(F, 4));
out(' H0: ratio = 1 df = ' + d1 + ', ' + d2);
out(' Ha: ratio != 1 Pr(F < f) = ' + fmtF(fcdf(F, d1, d2), 4) + ' 2*min = ' + fmtF(pv, 4));
return; }
case 'oneway': case 'anova': {
needData(); need(A.length >= 2, 'syntax: oneway depvar groupvar');
const touse = makeTouse(p.ifExpr, p.inRange);
const y = [], g = [];
for (let i = 0; i < DB.n; i++) if (touse[i]) { y.push(DB.col[A[0]][i]); g.push(DB.col[A[1]][i]); }
out(outAnova(anova1(y, g), A[0], A[1]));
return; }
case 'ranksum': {
needData(); need(A[0] && o.by, 'syntax: ranksum var, by(groupvar)');
const touse = makeTouse(p.ifExpr, p.inRange);
const y = [], g = [];
for (let i = 0; i < DB.n; i++) if (touse[i]) { y.push(DB.col[A[0]][i]); g.push(DB.col[o.by][i]); }
const r = ranksum(y, g);
need(r, 'by() must have exactly two groups');
out('Two-sample Wilcoxon rank-sum (Mann-Whitney) test');
out(rule(56));
out(padL(o.by, 14) + ' | ' + padL('Obs', 8) + padL('Rank sum', 14) + padL('Expected', 14));
out(rule(15) + '+' + rule(40));
out(padL(String(r.keys[0]), 14) + ' | ' + padL(String(r.n1), 8) + fmtCell(r.R1, 14) + fmtCell(r.ER, 14));
out(padL(String(r.keys[1]), 14) + ' | ' + padL(String(r.n2), 8) +
fmtCell((r.n1 + r.n2) * (r.n1 + r.n2 + 1) / 2 - r.R1, 14) +
fmtCell(r.n2 * (r.n1 + r.n2 + 1) / 2, 14));
out(rule(56));
out('');
out(' H0: distributions are equal z = ' + fmtF(r.z, 3));
out(' Prob > |z| = ' + fmtF(r.p, 4));
out(' Mann-Whitney U = ' + fmtG(r.U, 8));
return; }
case 'signrank': {
needData();
const m = p.body.replace(/^signrank\s+/i, '').match(/^(\S+)\s*=\s*(\S+)$/);
need(m, 'syntax: signrank var = #');
const touse = makeTouse(p.ifExpr, p.inRange);
const a = []; for (let i = 0; i < DB.n; i++) if (touse[i]) a.push(DB.col[m[1]][i]);
const rhs = parseFloat(m[2]);
const r = signrank(a, isNaN(rhs) ? 0 : rhs);
out('Wilcoxon signed-rank test');
out('');
out(' Obs with nonzero difference = ' + r.n);
out(' Sum of positive ranks = ' + fmtG(r.Wp, 8));
out(' Sum of negative ranks = ' + fmtG(r.Wn, 8));
out(' Expected under H0 = ' + fmtG(r.E, 8));
out('');
out(' H0: median = ' + m[2] + ' z = ' + fmtF(r.z, 3) + ' Prob > |z| = ' + fmtF(r.p, 4));
return; }
case 'kwallis': {
needData(); need(A[0] && o.by, 'syntax: kwallis var, by(groupvar)');
const touse = makeTouse(p.ifExpr, p.inRange);
const y = [], g = [];
for (let i = 0; i < DB.n; i++) if (touse[i]) { y.push(DB.col[A[0]][i]); g.push(DB.col[o.by][i]); }
const r = kwallis(y, g);
out('Kruskal-Wallis equality-of-populations rank test');
out(rule(48));
out(padL(o.by, 16) + ' | ' + padL('Obs', 8) + padL('Rank sum', 16));
out(rule(17) + '+' + rule(30));
for (const row of r.rows) out(padL(abbrev(row.key, 16), 16) + ' | ' + padL(String(row.n), 8) + fmtCell(row.R, 16));
out(rule(48));
out('');
out(' chi2(' + r.df + ') = ' + fmtF(r.H, 4) + ' Prob = ' + fmtF(pChi2(r.H, r.df), 4));
out(' chi2(' + r.df + ') tie-adj. = ' + fmtF(r.Hc, 4) + ' Prob = ' + fmtF(r.p, 4));
return; }
case 'spearman': {
needData(); need(A.length >= 2, 'syntax: spearman var1 var2');
const touse = makeTouse(p.ifExpr, p.inRange);
const a = [], b = [];
for (let i = 0; i < DB.n; i++) if (touse[i]) { a.push(DB.col[A[0]][i]); b.push(DB.col[A[1]][i]); }
const r = spearman(a, b);
out('Spearman rank correlation: ' + A[0] + ' and ' + A[1]);
out('');
out(' Number of obs = ' + r.n);
out(" Spearman's rho = " + fmtF(r.rho, 4));
out(' Prob > |t| = ' + fmtF(r.p, 4));
return; }
case 'sktest': case 'jb': {
needData();
const touse = makeTouse(p.ifExpr, p.inRange);
const vars = numVarlist(A.length ? A : varNames());
out('Skewness and kurtosis tests for normality');
out(rule(TW));
out(padL('Variable', 14) + ' | ' + padL('Obs', 7) + padL('Pr(skew)', 11) + padL('Pr(kurt)', 11) +
padL('chi2(2)', 10) + padL('Prob>chi2', 11) + padL('Jarque-Bera', 12));
out(rule(15) + '+' + rule(TW - 16));
for (const v of vars) {
const a = []; for (let i = 0; i < DB.n; i++) if (touse[i]) a.push(DB.col[v][i]);
const cl = a.filter(isNum);
if (cl.length < 8) continue;
const s = skTest(cl), j = jbTest(cl);
out(padL(abbrev(v, 14), 14) + ' | ' + padL(String(s.n), 7) + padL(fmtF(s.pSkew, 4), 11) +
padL(fmtF(s.pKurt, 4), 11) + padL(fmtF(s.chi2, 2), 10) + padL(fmtF(s.p, 4), 11) +
padL(fmtF(j.jb, 2) + ' (' + fmtF(j.p, 3) + ')', 12));
}
out(rule(TW));
return; }
/* ---------------- estimation ---------------- */
case 'regress': case 'newey': {
needData();
need(A.length >= 1, 'syntax: regress depvar [indepvars] [if] [, robust cluster(v) ...]');
const touse = makeTouse(p.ifExpr, p.inRange);
const dep = A[0], xs = A.slice(1);
const noCons = !!(o.noconstant || o.nocons);
const D = buildDesign(dep, xs, touse, noCons);
const opt = { names: D.names, consIdx: D.consIdx, noCons, level: o.level ? +o.level : 95 };
const v = vceFromOpts(o);
if (c === 'newey') { opt.vce = 'hac'; opt.lags = o.lag !== undefined ? +o.lag : (o.lags !== undefined ? +o.lags : undefined); }
else if (v.vce === 'cluster') { need(hasVar(v.cluster), 'cluster variable ' + v.cluster + ' not found');
opt.vce = 'cluster'; opt.cluster = D.rows.map(i => DB.col[v.cluster][i]); }
else if (v.vce === 'boot') { opt.boot = +o.bootstrap || 200; opt.bootseed = o.seed ? +o.seed : 20250; }
else if (v.vce === 'hac') { opt.vce = 'hac'; opt.lags = o.lags !== undefined ? +o.lags : undefined; }
else opt.vce = v.vce;
if (o.weight && hasVar(o.weight)) opt.weights = D.rows.map(i => DB.col[o.weight][i]);
const m = ols(D.y, D.X, opt);
out(outRegress(m, dep));
if (m.drop.length) out('\nNote: ' + m.drop.map(i => D.names[i]).join(', ') +
' omitted because of collinearity.');
DB.last = { m, depvar: dep, xs, rows: D.rows, names: D.names, cmd: 'regress', touse, noCons };
return; }
case 'logit': case 'probit': case 'poisson': {
needData(); need(A.length >= 2, 'syntax: ' + c + ' depvar indepvars [if] [, robust cluster(v)]');
const touse = makeTouse(p.ifExpr, p.inRange);
const dep = A[0], D = buildDesign(dep, A.slice(1), touse, false);
if (c !== 'poisson') {
const u = [...new Set(D.y)];
need(u.every(v => v === 0 || v === 1), 'depvar must be 0/1 for ' + c +
' (values found: ' + u.slice(0, 5).join(', ') + '). Try: generate y01 = ' + dep + ' > 0');
need(u.length === 2, 'depvar does not vary — all values are ' + u[0]);
} else need(D.y.every(v => v >= 0 && Number.isInteger(v)),
'poisson requires a nonnegative integer count as depvar');
const opt = { names: D.names, consIdx: D.consIdx, level: o.level ? +o.level : 95 };
const v = vceFromOpts(o);
if (v.vce === 'cluster') { opt.vce = 'cluster'; opt.cluster = D.rows.map(i => DB.col[v.cluster][i]); }
else if (v.vce === 'robust') opt.vce = 'robust';
const m = glm(D.y, D.X, c, opt);
out(outGLM(m, dep));
DB.last = { m, depvar: dep, xs: A.slice(1), rows: D.rows, names: D.names, cmd: c, touse };
return; }
case 'qreg': {
needData(); need(A.length >= 2, 'syntax: qreg depvar indepvars [, quantile(.5)]');
const touse = makeTouse(p.ifExpr, p.inRange);
const dep = A[0], D = buildDesign(dep, A.slice(1), touse, false);
let tau = o.quantile !== undefined ? parseFloat(o.quantile) : (o.q !== undefined ? parseFloat(o.q) : 0.5);
if (tau > 1) tau /= 100;
need(tau > 0 && tau < 1, 'quantile must be between 0 and 1');
const m = qreg(D.y, D.X, tau, { names: D.names });
out(outQreg(m, dep));
DB.last = { m, depvar: dep, xs: A.slice(1), rows: D.rows, names: D.names, cmd: 'qreg', touse };
return; }
case 'ivregress': {
needData();
const body = p.body.replace(/^\S+\s+/, '').replace(/^2sls\s+/i, '').replace(/^liml\s+/i, '');
const m0 = body.match(/^([^(]*)\(([^=]+)=([^)]+)\)(.*)$/);
need(m0, 'syntax: ivregress 2sls depvar [exogenous] (endogenous = instruments)');
const pre = m0[1].trim().split(/\s+/).filter(Boolean);
const dep = pre[0], exog = pre.slice(1);
const endo = m0[2].trim().split(/\s+/).filter(Boolean);
const inst = m0[3].trim().split(/\s+/).filter(Boolean);
const post = m0[4].trim().split(/\s+/).filter(Boolean);
exog.push(...post);
need(inst.length >= endo.length, 'need at least as many instruments as endogenous regressors');
const touse = makeTouse(p.ifExpr, p.inRange);
const all = buildDesign(dep, exog.concat(endo).concat(inst), touse, false);
const rows = all.rows;
const colOf = t => { const cc = termColumns(t); return cc; };
const mk = toks => { const cols = []; for (const t of toks) cols.push(...termColumns(t));
return { names: cols.map(x => x.name), rows: rows.map(i => cols.map(x => x.col[i])) }; };
const E = mk(exog), N = mk(endo), Z = mk(inst);
const Xex = rows.map((r, i) => E.rows[i].concat([1]));
const names = E.names.concat(['_cons']).concat(N.names);
const y = rows.map(i => colFor(dep)[i]);
const opt = { names, consIdx: E.names.length };
const v = vceFromOpts(o);
if (v.vce === 'cluster') { opt.vce = 'cluster'; opt.cluster = rows.map(i => DB.col[v.cluster][i]); }
else if (v.vce === 'robust') opt.vce = 'robust';
const m = ivreg(y, Xex, N.rows, Z.rows, opt);
out(outIV(m, dep));
out('\nInstrumented: ' + endo.join(' '));
out('Instruments: ' + exog.concat(inst).join(' '));
DB.last = { m, depvar: dep, xs: exog.concat(endo), rows, names, cmd: 'ivregress', touse };
return; }
case 'xtreg': {
needData();
need(A.length >= 2, 'syntax: xtreg depvar indepvars, fe|re');
const id = o.i || DB.panelvar;
need(id, 'set the panel variable first: xtset panelvar timevar');
const touse = makeTouse(p.ifExpr, p.inRange);
const dep = A[0];
const D = buildDesign(dep, A.slice(1), touse, true); // no constant for within
const ids = D.rows.map(i => DB.col[id][i]);
const v = vceFromOpts(o);
const opt = { names: D.names };
if (v.vce === 'cluster') { opt.vce = 'cluster'; opt.cluster = D.rows.map(i => DB.col[v.cluster][i]); }
else if (v.vce === 'robust') { opt.vce = 'cluster'; opt.cluster = ids; }
if (o.re) {
const m = panelRE(D.y, D.X, ids, opt);
out(outPanel(m, dep, id));
DB.last = { m, depvar: dep, xs: A.slice(1), rows: D.rows, names: m.names, cmd: 'xtreg', touse, id };
DB.stored.__re = { m, depvar: dep };
} else {
const m = panelFE(D.y, D.X, ids, opt);
m.names = D.names;
out(outPanel(m, dep, id));
DB.last = { m, depvar: dep, xs: A.slice(1), rows: D.rows, names: D.names, cmd: 'xtreg', touse, id };
DB.stored.__fe = { m, depvar: dep };
}
return; }
case 'hausman': {
need(DB.stored.__fe && DB.stored.__re,
'run both "xtreg y x..., fe" and "xtreg y x..., re" first, then hausman');
const fe = DB.stored.__fe.m, re = DB.stored.__re.m;
const k = fe.b.length;
const h = hausman(fe, re, k);
need(h, 'the difference in covariance matrices is not invertible');
out('Hausman specification test: fixed effects vs. random effects');
out(rule(TW));
out(padL('Variable', 16) + ' | ' + padL('(b) fixed', 14) + padL('(B) random', 14) +
padL('(b-B) diff.', 14) + padL('sqrt(diag)', 14));
out(rule(17) + '+' + rule(TW - 18));
for (let i = 0; i < k; i++) {
const d = fe.V[i][i] - re.V[i][i];
out(padL(abbrev(fe.names[i], 16), 16) + ' | ' + fmtCell(fe.b[i], 14) + fmtCell(re.b[i], 14) +
fmtCell(fe.b[i] - re.b[i], 14) + fmtCell(d > 0 ? Math.sqrt(d) : NaN, 14));
}
out(rule(TW));
out('');
out(' H0: the random-effects estimator is consistent (differences not systematic)');
out(' chi2(' + h.df + ') = ' + fmtF(h.chi2, 2) + ' Prob > chi2 = ' + fmtF(h.p, 4));
out(' ' + (h.p < 0.05 ? '=> Reject H0 at 5%: prefer fixed effects.'
: '=> Do not reject H0 at 5%: random effects is defensible and more efficient.'));
return; }
/* ---------------- postestimation ---------------- */
case 'predict': {
needModel(); need(A[0], 'syntax: predict newvar [, xb residuals stdp pr]');
const L = DB.last, m = L.m;
const col = new Array(DB.n).fill(NaN);
const what = o.residuals || o.resid || o.res ? 'resid' : (o.stdp ? 'stdp' : (o.pr ? 'pr' : 'xb'));
L.rows.forEach((r, j) => {
if (what === 'resid') col[r] = m.resid[j];
else if (what === 'stdp') { const x = m.X[j];
let s = 0; for (let a = 0; a < x.length; a++) for (let b = 0; b < x.length; b++)
s += x[a] * m.V[a][b] * x[b];
col[r] = Math.sqrt(Math.max(s, 0)); }
else if (what === 'pr' && m.mu) col[r] = m.mu[j];
else col[r] = m.fitted ? m.fitted[j] : NaN;
});
addVar(A[0], col, 'num', { xb: 'Linear prediction', resid: 'Residuals',
stdp: 'S.E. of prediction', pr: 'Predicted probability' }[what]);
out('(option ' + what + ' assumed; ' + col.filter(x => !isNum(x)).length + ' missing values generated)');
refreshAll(); return; }
case 'test': {
needModel();
const m = DB.last.m, names = DB.last.names;
const spec = p.body.replace(/^test\s+/i, '').trim();
need(spec, 'syntax: test x1 x2 | test x1 = x2 | test x1 = 0.5');
const R = [], r = [];
const idxOf = nm => { const i = names.indexOf(nm);
need(i >= 0, 'variable ' + nm + ' is not in the last model (available: ' + names.join(', ') + ')');
return i; };
const clauses = splitTop(spec, ',').map(s => s.trim()).filter(Boolean);
for (const cl of clauses) {
if (cl.includes('=')) {
const [lhs, rhs] = cl.split('=').map(s => s.trim());
const row = new Array(m.b.length).fill(0);
row[idxOf(lhs)] = 1;
if (/^[-+]?[\d.]+$/.test(rhs)) r.push(parseFloat(rhs));
else { row[idxOf(rhs)] = -1; r.push(0); }
R.push(row);
} else for (const t of cl.split(/\s+/)) {
const row = new Array(m.b.length).fill(0); row[idxOf(t)] = 1; R.push(row); r.push(0);
}
}
const w = waldR(m.b, m.V, R, r, m.df_r);
need(w, 'the restriction matrix is not of full rank (are the restrictions redundant?)');
out('Test of linear restrictions');
clauses.forEach((cl, i) => out(' (' + (i + 1) + ') ' + (cl.includes('=') ? cl : cl + ' = 0')));
out('');
const useZ = ['logit', 'probit', 'poisson'].includes(DB.last.cmd);
if (useZ) out(' chi2(' + w.df + ') = ' + fmtF(w.chi2, 2) + '\n Prob > chi2 = ' + fmtF(w.p_chi2, 4));
else out(' F(' + w.df + ', ' + w.df_r + ') = ' + fmtF(w.F, 2) + '\n Prob > F = ' + fmtF(w.p_F, 4));
return; }
case 'margins': {
needModel();
need(['logit', 'probit', 'poisson'].includes(DB.last.cmd),
'margins is available after logit, probit, or poisson');
out(outMargins(margins(DB.last.m), DB.last.m));
return; }
case 'estat': {
needModel();
const sub = (A[0] || '').toLowerCase(), m = DB.last.m;
const linear = () => need(DB.last.cmd === 'regress' || DB.last.cmd === 'newey',
'estat ' + sub + ' is available after regress');
if (sub === 'vif') { linear();
out('Variance inflation factors');
out(rule(44));
out(padL('Variable', 18) + ' | ' + padL('VIF', 10) + padL('1/VIF', 12));
out(rule(19) + '+' + rule(24));
const v = vif(m); let s = 0;
for (const r of v) { s += r.vif;
out(padL(abbrev(r.name, 18), 18) + ' | ' + padL(fmtF(r.vif, 2), 10) + padL(fmtF(r.tol, 6), 12)); }
out(rule(19) + '+' + rule(24));
out(padL('Mean VIF', 18) + ' | ' + padL(fmtF(s / v.length, 2), 10));
out(rule(44));
if (Math.max(...v.map(x => x.vif)) > 10) out('\nNote: a VIF above 10 is the usual flag for serious multicollinearity.');
return; }
if (sub === 'hettest') { linear();
const bp = bpTest(m, false), kk = bpTest(m, true);
out('Breusch-Pagan / Cook-Weisberg test for heteroskedasticity');
out(' H0: constant variance');
out(' Variables: fitted values of ' + DB.last.depvar);
out('');
out(' chi2(' + bp.df + ') = ' + fmtF(bp.chi2, 2) + ' Prob > chi2 = ' + fmtF(bp.p, 4) + ' (normality assumed)');
out(' chi2(' + kk.df + ') = ' + fmtF(kk.chi2, 2) + ' Prob > chi2 = ' + fmtF(kk.p, 4) + " (Koenker, robust)");
return; }
if (sub === 'imtest' || sub === 'white') { linear();
const w = whiteTest(m);
out("White's test for heteroskedasticity");
out(' H0: homoskedasticity Ha: unrestricted heteroskedasticity');
out('');
out(' chi2(' + w.df + ') = ' + fmtF(w.chi2, 2) + ' Prob > chi2 = ' + fmtF(w.p, 4));
return; }
if (sub === 'ovtest') { linear();
const r = resetTest(m);
out('Ramsey RESET test for omitted variables');
out(' H0: model has no omitted variables (powers of fitted values add nothing)');
out('');
out(' F(' + r.df1 + ', ' + r.df2 + ') = ' + fmtF(r.F, 2) + ' Prob > F = ' + fmtF(r.p, 4));
return; }
if (sub === 'dwatson' || sub === 'durbinalt') { linear();
const d = dwStat(m);
out('Durbin-Watson d-statistic (' + m.k + ', ' + m.n + ') = ' + fmtF(d, 6));
out(' Rule of thumb: d near 2 => no first-order serial correlation;');
out(' d < 1.5 suggests positive, d > 2.5 negative autocorrelation.');
return; }
if (sub === 'bgodfrey') { linear();
const L = o.lags ? +o.lags : 1;
const b = bgTest(m, L);
out("Breusch-Godfrey LM test for autocorrelation");
out(' H0: no serial correlation up to lag ' + L);
out('');
out(' chi2(' + b.df + ') = ' + fmtF(b.chi2, 3) + ' Prob > chi2 = ' + fmtF(b.p, 4));
return; }
if (sub === 'archlm') { linear();
const L = o.lags ? +o.lags : 1;
const a = archTest(m.resid, L);
out('LM test for autoregressive conditional heteroskedasticity (ARCH)');
out(' H0: no ARCH effects up to lag ' + L);
out('');
out(' chi2(' + a.df + ') = ' + fmtF(a.chi2, 3) + ' Prob > chi2 = ' + fmtF(a.p, 4));
return; }
if (sub === 'ic') {
out('Information criteria');
out(rule(64));
out(padL('Model', 12) + ' | ' + padL('N', 8) + padL('ll(model)', 14) + padL('df', 6) +
padL('AIC', 12) + padL('BIC', 12));
out(rule(13) + '+' + rule(50));
out(padL('.', 12) + ' | ' + padL(String(m.n), 8) + fmtCell(m.ll, 14) + padL(String(m.k), 6) +
fmtCell(m.aic, 12) + fmtCell(m.bic, 12));
out(rule(64));
return; }
if (sub === 'summarize') {
const vars = [DB.last.depvar].concat(DB.last.xs);
const t = new Array(DB.n).fill(0);
for (const r of DB.last.rows) t[r] = 1;
out('Estimation sample summary');
out(outSummarize(expandVarlist(vars), t, false));
return; }
throw new Error('estat subcommand "' + sub + '" not recognized. Available: vif, hettest, imtest, ' +
'ovtest, dwatson, bgodfrey, archlm, ic, summarize');
}
case 'estimates': {
const sub = (A[0] || '').toLowerCase();
if (sub === 'store') { needModel(); need(A[1], 'syntax: estimates store name');
DB.stored[A[1]] = { m: DB.last.m, depvar: DB.last.depvar, cmd: DB.last.cmd };
out('(estimates stored as "' + A[1] + '")'); return; }
if (sub === 'table') {
const nm = A.slice(1).filter(x => !x.startsWith('_'));
out(outEstTable(nm.length ? nm : Object.keys(DB.stored).filter(k => !k.startsWith('__'))));
return; }
if (sub === 'dir' || sub === 'list') {
const k = Object.keys(DB.stored).filter(x => !x.startsWith('__'));
out(k.length ? 'Stored estimates: ' + k.join(', ') : 'No stored estimates.');
return; }
if (sub === 'clear') { DB.stored = {}; out('(stored estimates cleared)'); return; }
throw new Error('syntax: estimates store <name> | estimates table [names] | estimates dir | estimates clear');
}
/* ---------------- time series ---------------- */
case 'ac': case 'pac': case 'corrgram': {
needData(); need(A[0], 'syntax: ' + c + ' varname [, lags(#)]');
const touse = makeTouse(p.ifExpr, p.inRange);
const v = []; for (let i = 0; i < DB.n; i++) if (touse[i]) v.push(DB.col[A[0]][i]);
const cl = v.filter(isNum), n = cl.length;
const L = o.lags ? +o.lags : Math.min(40, Math.max(5, Math.floor(n / 4)));
const r = acf(cl, L), pr = pacf(r), lb = ljungBox(r, n);
const ci = 1.96 / Math.sqrt(n);
if (c === 'corrgram') {
out('Correlogram for ' + A[0] + ' (n = ' + n + ')');
out(rule(72));
out(padL('LAG', 5) + ' ' + padL('AC', 10) + padL('PAC', 10) + padL('Q', 12) + padL('Prob>Q', 10) +
' ' + padC('[Autocorrelation]', 21));
out(rule(72));
for (let i = 0; i < L; i++) {
const bars = Math.round(Math.abs(r[i]) * 10);
const b = r[i] >= 0 ? padR(' '.repeat(10) + '|' + '#'.repeat(bars), 21)
: padR(' '.repeat(10 - bars) + '#'.repeat(bars) + '|', 21);
out(padL(String(i + 1), 5) + ' ' + padL(fmtF(r[i], 4), 10) + padL(fmtF(pr[i], 4), 10) +
padL(fmtF(lb[i].q, 3), 12) + padL(fmtF(lb[i].p, 4), 10) + ' ' + b);
}
out(rule(72));
out('Q is the Ljung-Box portmanteau statistic; H0: no autocorrelation up to that lag.');
return;
}
const isAC = c === 'ac';
outHTML(plotACF(isAC ? r : pr, ci, { title: (isAC ? 'Autocorrelations of ' : 'Partial autocorrelations of ') + A[0],
ylab: isAC ? 'Autocorrelation' : 'Partial autocorrelation',
sub: 'shaded band: ±1.96/√n', cap: (isAC ? 'ac ' : 'pac ') + A[0] + ' — n = ' + n }));
return; }
case 'dfuller': {
needData(); need(A[0], 'syntax: dfuller varname [, lags(#) trend noconstant]');
const touse = makeTouse(p.ifExpr, p.inRange);
const v = []; for (let i = 0; i < DB.n; i++) if (touse[i]) v.push(DB.col[A[0]][i]);
const lags = o.lags !== undefined ? +o.lags : 0;
const kind = (o.noconstant || o.nocons) ? 'nc' : (o.trend ? 'ct' : 'c');
const r = adf(v, lags, kind);
out((lags ? 'Augmented ' : '') + 'Dickey-Fuller test for a unit root' +
' Number of obs = ' + r.n);
out(' Model: ' + { nc: 'no constant, no trend', c: 'constant', ct: 'constant and trend' }[kind] +
(lags ? ', ' + lags + ' lagged difference' + (lags === 1 ? '' : 's') : ''));
out('');
out(rule(66));
out(padL('', 14) + ' | ' + padL('Test', 12) + padC('---- Interpolated critical values ----', 38));
out(padL('', 14) + ' | ' + padL('statistic', 12) + padL('1% ', 12) + padL('5% ', 12) + padL('10% ', 12));
out(rule(15) + '+' + rule(50));
out(padL('Z(t)', 14) + ' | ' + padL(fmtF(r.t, 3), 12) + padL(fmtF(r.crit['1%'], 3), 12) +
padL(fmtF(r.crit['5%'], 3), 12) + padL(fmtF(r.crit['10%'], 3), 12));
out(rule(66));
out('');
out(' H0: ' + A[0] + ' contains a unit root. Approx. MacKinnon p-value = ' + fmtF(r.p, 4));
out(' ' + (r.t < r.crit['5%'] ? '=> Reject H0 at 5%: the series looks stationary.'
: '=> Cannot reject H0 at 5%: a unit root is consistent with the data.'));
return; }
/* ---------------- graphics ---------------- */
case 'scatter': {
needData(); need(A.length >= 2, 'syntax: scatter yvar xvar [, fit lowess by(group)]');
const touse = makeTouse(p.ifExpr, p.inRange);
const yv = A[0], xv = A[1];
const xs = [], ys = [], gs = [], lb = [];
const lblVar = DB.vars.find(v => v.type === 'str');
for (let i = 0; i < DB.n; i++) if (touse[i]) {
xs.push(DB.col[xv][i]); ys.push(DB.col[yv][i]);
gs.push(o.by ? DB.col[o.by][i] : null);
lb.push(lblVar ? DB.col[lblVar.name][i] : null);
}
outHTML(plotScatter(xs, ys, { xlab: xv + (getVar(xv).label ? ' — ' + getVar(xv).label : ''),
ylab: yv + (getVar(yv).label ? ' — ' + getVar(yv).label : ''),
title: yv + ' against ' + xv, fit: !!(o.fit || o.lfit), lowess: o.lowess ? 0.3 : 0,
grp: o.by ? gs : null, grpname: o.by, lbl: lb,
cap: 'scatter ' + yv + ' ' + xv + (o.fit ? ', fit' : '') }));
return; }
case 'line': {
needData(); need(A.length >= 1, 'syntax: line yvar [yvar2 ...] [xvar]');
const touse = makeTouse(p.ifExpr, p.inRange);
let ys = A.slice(), xv = null;
if (A.length > 1 && (A[A.length - 1] === DB.tsvar || A[A.length - 1] === DB.timevar)) {
xv = A[A.length - 1]; ys = A.slice(0, -1);
} else if (DB.tsvar && hasVar(DB.tsvar)) xv = DB.tsvar;
const x = [];
for (let i = 0; i < DB.n; i++) if (touse[i]) x.push(xv ? DB.col[xv][i] : i + 1);
const series = ys.map(v => { const yy = [];
for (let i = 0; i < DB.n; i++) if (touse[i]) yy.push(DB.col[v][i]);
return { x, y: yy, label: v }; });
outHTML(plotLine(series, { xlab: xv || 'Observation', ylab: ys.length === 1 ? ys[0] : 'Value',
title: ys.join(', ') + (xv ? ' over ' + xv : ''), zero: true,
cap: 'line ' + A.join(' ') }));
return; }
case 'histogram': {
needData(); need(A[0], 'syntax: histogram var [, bins(#) normal kdensity frequency]');
const touse = makeTouse(p.ifExpr, p.inRange);
const v = []; for (let i = 0; i < DB.n; i++) if (touse[i]) v.push(DB.col[A[0]][i]);
outHTML(plotHist(v, { bins: o.bins ? +o.bins : (o.bin ? +o.bin : 0), normal: !!o.normal,
kdens: !!(o.kdensity || o.kdens), density: !(o.frequency || o.freq),
xlab: A[0] + (getVar(A[0]).label ? ' — ' + getVar(A[0]).label : ''),
title: 'Distribution of ' + A[0], cap: 'histogram ' + A[0] }));
return; }
case 'kdensity': {
needData(); need(A[0], 'syntax: kdensity var');
const touse = makeTouse(p.ifExpr, p.inRange);
const v = []; for (let i = 0; i < DB.n; i++) if (touse[i]) v.push(DB.col[A[0]][i]);
const k = kdensity(v, 200);
outHTML(plotLine([{ x: k.x, y: k.y, label: 'Kernel density' }], { xlab: A[0], ylab: 'Density',
title: 'Kernel density estimate of ' + A[0], sub: 'Gaussian kernel, bandwidth = ' + fmtG(k.h, 4),
cap: 'kdensity ' + A[0] }));
return; }
case 'qnorm': {
needData(); need(A[0], 'syntax: qnorm var');
const touse = makeTouse(p.ifExpr, p.inRange);
const v = []; for (let i = 0; i < DB.n; i++) if (touse[i]) v.push(DB.col[A[0]][i]);
outHTML(plotQQ(v, { title: 'Normal quantile plot: ' + A[0],
sub: 'points on the dashed line => normality', cap: 'qnorm ' + A[0] }));
return; }
case 'graph': {
needData();
const sub = (A[0] || '').toLowerCase();
const touse = makeTouse(p.ifExpr, p.inRange);
if (sub === 'box') {
const v = A[1]; need(v, 'syntax: graph box var [, over(groupvar)]');
let groups;
if (o.over) {
const lev = [...new Set(DB.col[o.over].filter((x, i) => touse[i] && okGroup(x)).map(String))].sort(cmpKey);
groups = lev.map(l => ({ label: String(l),
values: DB.col[v].filter((x, i) => touse[i] && String(DB.col[o.over][i]) === l) }));
} else groups = [{ label: v, values: DB.col[v].filter((x, i) => touse[i]) }];
outHTML(plotBox(groups, { title: 'Box plot of ' + v + (o.over ? ' by ' + o.over : ''),
ylab: v, xlab: o.over || '', cap: 'graph box ' + v + (o.over ? ', over(' + o.over + ')' : '') }));
return;
}
if (sub === 'matrix') {
const vars = numVarlist(A.slice(1));
need(vars.length >= 2 && vars.length <= 6, 'graph matrix needs between 2 and 6 numeric variables');
outHTML(plotMatrix(vars, touse, { title: 'Scatterplot matrix', cap: 'graph matrix ' + vars.join(' ') }));
return;
}
if (sub === 'bar') {
const v = A[1]; need(v && o.over, 'syntax: graph bar var, over(groupvar)');
const lev = [...new Set(DB.col[o.over].filter((x, i) => touse[i] && okGroup(x)).map(String))].sort(cmpKey);
const vals = lev.map(l => mean(DB.col[v].filter((x, i) => touse[i] && String(DB.col[o.over][i]) === l)));
outHTML(plotBar(lev.map(String), vals, { title: 'Mean of ' + v + ' by ' + o.over,
ylab: 'Mean of ' + v, xlab: o.over, cap: 'graph bar ' + v + ', over(' + o.over + ')' }));
return;
}
throw new Error('graph subcommands: box, bar, matrix');
}
case 'rvfplot': {
needModel();
const m = DB.last.m;
outHTML(plotScatter(m.fitted, m.resid, { xlab: 'Fitted values', ylab: 'Residuals',
title: 'Residuals against fitted values', lowess: 0.35,
sub: 'a funnel shape signals heteroskedasticity',
cap: 'rvfplot — after ' + DB.last.cmd + ' ' + DB.last.depvar }));
return; }
case 'rvpplot': {
needModel(); need(A[0], 'syntax: rvpplot varname');
const m = DB.last.m, i = DB.last.names.indexOf(A[0]);
need(i >= 0, A[0] + ' is not in the last model');
outHTML(plotScatter(m.X.map(r => r[i]), m.resid, { xlab: A[0], ylab: 'Residuals',
title: 'Residuals against ' + A[0], lowess: 0.35, cap: 'rvpplot ' + A[0] }));
return; }
/* ---------------- misc ---------------- */
case 'quietly': { const rest = p.raw.replace(/^\s*(qui|quietly)\s+/i, ''); runCommand(rest, false); return; }
case 'help': { showHelp(A[0]); return; }
case 'about': { showAbout(); return; }
default:
throw new Error('unrecognized command "' + p.cmd + '". Type "help" for the command list.');
}
}
/* ============================================================
INTERFACE
============================================================ */
const $ = id => document.getElementById(id);
let runNo = 0, curEntry = null, history = [], hIdx = -1, dtPage = 0, sortDir = {};
/* ---------- results log ---------- */
function killWelcome() { const w = $('log').querySelector('.welcome'); if (w) w.remove(); }
function logCmd(text) {
killWelcome();
runNo++;
const e = document.createElement('div');
e.className = 'entry';
e.innerHTML = '<div class="gutter">' + String(runNo).padStart(2, '0') + '</div>' +
'<div class="ebody"><div class="cmdline"></div></div>';
e.querySelector('.cmdline').textContent = text;
$('log').appendChild(e);
curEntry = e.querySelector('.ebody');
scrollLog();
}
function ensureEntry() {
if (curEntry) return;
killWelcome();
const e = document.createElement('div');
e.className = 'entry';
e.innerHTML = '<div class="gutter"></div><div class="ebody"></div>';
$('log').appendChild(e);
curEntry = e.querySelector('.ebody');
}
function out(text) {
ensureEntry();
const pre = document.createElement('pre');
pre.className = 'out';
pre.textContent = text;
curEntry.appendChild(pre);
scrollLog();
}
function outHTML(html) {
ensureEntry();
const d = document.createElement('div');
d.innerHTML = html;
curEntry.appendChild(d);
scrollLog();
}
function outErr(msg) {
ensureEntry();
const pre = document.createElement('pre');
pre.className = 'out err';
pre.textContent = msg;
curEntry.appendChild(pre);
scrollLog();
}
function scrollLog() { const s = $('stage'); s.scrollTop = s.scrollHeight; }
function clearLog() { $('log').innerHTML = ''; runNo = 0; curEntry = null; renderWelcome(); }
/* ---------- chrome ---------- */
function refreshAll() { renderVars(); renderInfo(); if (paneOn === 'Data') renderData(); }
function renderInfo() {
const d = $('dsinfo');
if (!DB.n) { d.innerHTML = '<span>no data in memory</span>'; return; }
let s = '<span><b>' + DB.name + '</b></span><span>N = <b>' + DB.n + '</b></span>' +
'<span class="hidesm">' + DB.vars.length + ' variables</span>';
if (DB.panelvar) s += '<span class="hidesm">panel: <b>' + DB.panelvar + '</b></span>';
else if (DB.tsvar) s += '<span class="hidesm">time: <b>' + DB.tsvar + '</b></span>';
d.innerHTML = s;
}
function renderVars() {
const ul = $('vlist'), q = ($('vsearch').value || '').toLowerCase();
ul.innerHTML = '';
const vs = DB.vars.filter(v => !q || v.name.toLowerCase().includes(q) ||
(v.label || '').toLowerCase().includes(q));
$('vempty').style.display = DB.vars.length ? 'none' : 'block';
$('vsearch').style.display = DB.vars.length ? 'block' : 'none';
for (const v of vs) {
const li = document.createElement('li');
li.innerHTML = '<span class="vn"></span><span class="vt"></span><span class="vl"></span>';
li.children[0].textContent = v.name;
li.children[1].textContent = v.type === 'str' ? 'str' : 'num';
li.children[2].textContent = v.label || '';
li.title = 'Insert ' + v.name + ' into the command line';
li.onclick = () => { const c = $('cmd');
c.value = (c.value + (c.value && !c.value.endsWith(' ') ? ' ' : '') + v.name); c.focus(); };
ul.appendChild(li);
}
}
/* ---------- data browser ---------- */
const PAGE = 250;
function renderData() {
const p = $('paneData');
if (!DB.n) { p.innerHTML = '<div class="welcome"><h1>No data</h1><p class="lede">Load one of the ' +
'example datasets from the Data menu, or import a CSV file from the top bar.</p></div>'; return; }
const maxPage = Math.max(0, Math.ceil(DB.n / PAGE) - 1);
dtPage = Math.min(dtPage, maxPage);
const lo = dtPage * PAGE, hi = Math.min(DB.n, lo + PAGE);
const names = varNames();
let h = '<div class="dtbar"><span>Observations ' + (lo + 1) + '–' + hi + ' of ' + DB.n + '</span>' +
'<button id="dtPrev"' + (dtPage === 0 ? ' disabled' : '') + '>◀ Previous</button>' +
'<button id="dtNext"' + (dtPage >= maxPage ? ' disabled' : '') + '>Next ▶</button>' +
'<span>Click a column heading to sort the dataset.</span></div>' +
'<div class="dtwrap"><table class="dt"><thead><tr><th>obs</th>';
for (const v of names) h += '<th data-v="' + v + '" title="' + (getVar(v).label || v) + '">' + v + '</th>';
h += '</tr></thead><tbody>';
for (let i = lo; i < hi; i++) {
h += '<tr><td class="rn">' + (i + 1) + '</td>';
for (const v of names) {
const x = DB.col[v][i];
const missing = x === '' || x === null || x === undefined || (typeof x === 'number' && isNaN(x));
h += '<td class="' + (isStr(v) ? 's' : '') + (missing ? ' miss' : '') + '">' +
(missing ? '.' : esc(typeof x === 'string' ? x : fmtG(x, 7))) + '</td>';
}
h += '</tr>';
}
p.innerHTML = h + '</tbody></table></div>';
const prev = $('dtPrev'), next = $('dtNext');
if (prev) prev.onclick = () => { dtPage--; renderData(); };
if (next) next.onclick = () => { dtPage++; renderData(); };
p.querySelectorAll('th[data-v]').forEach(th => th.onclick = () => {
const v = th.dataset.v;
sortDir[v] = !sortDir[v];
runCommand(sortDir[v] ? 'sort ' + v : 'gsort -' + v);
renderData();
});
}
/* ---------- tabs ---------- */
let paneOn = 'Results';
function showPane(name) {
paneOn = name;
['Results', 'Data', 'Help'].forEach(k => {
$('pane' + k).classList.toggle('on', k === name);
$('tab' + k).setAttribute('aria-selected', String(k === name));
});
if (name === 'Data') renderData();
if (name === 'Help') renderHelp();
}
/* ============================================================
MENU + DIALOGS
============================================================ */
function optstr(parts) { const p = parts.filter(Boolean); return p.length ? ', ' + p.join(' ') : ''; }
function ifstr(v) { return v && v.trim() ? ' if ' + v.trim() : ''; }
const MENUS = [
{ name: 'Data', items: [
{ label: 'Open example dataset', title: 'Open an example dataset',
sub: 'Simulated datasets with realistic structure, generated from a fixed seed.',
fields: [{ t: 'select', name: 'd', label: 'Dataset',
options: Object.keys(SAMPLES).map(k => [k, k + ' — ' + SAMPLES[k].desc]) }],
build: v => 'use ' + v.d, noData: true },
{ label: 'Describe variables', build: () => 'describe', noData: false, instant: true },
{ label: 'Codebook', title: 'Codebook',
fields: [{ t: 'vars', name: 'v', label: 'Variables (leave empty for all)' }],
build: v => 'codebook ' + v.v.join(' ') },
{ label: 'List observations', title: 'List observations',
fields: [{ t: 'vars', name: 'v', label: 'Variables (empty = first eight)' },
{ t: 'text', name: 'if', label: 'Restrict to (if condition)', ph: 'e.g. foreign==1 & price>5000' },
{ t: 'num', name: 'n', label: 'Maximum rows', def: 30 }],
build: v => 'list ' + v.v.join(' ') + ifstr(v.if) + optstr(['n(' + (v.n || 30) + ')']) },
{ label: 'Create a variable', title: 'Create a new variable',
sub: 'Functions: ln exp sqrt abs round int mod max min cond normal invnormal rnormal runiform, ' +
'series operators lag(x,1) lead(x,1) diff(x) sum(x), aggregates mean(x) sd(x) median(x) total(x).',
fields: [{ t: 'text', name: 'n', label: 'New variable name', ph: 'lprice' },
{ t: 'text', name: 'e', label: 'Expression', ph: 'ln(price)' },
{ t: 'text', name: 'if', label: 'Only where (optional)', ph: 'price > 0' }],
build: v => 'generate ' + v.n + ' = ' + v.e + ifstr(v.if) },
{ label: 'Replace values', title: 'Replace values in a variable',
fields: [{ t: 'var', name: 'n', label: 'Variable' },
{ t: 'text', name: 'e', label: 'New value (expression)', ph: '.' },
{ t: 'text', name: 'if', label: 'Only where', ph: 'price > 15000' }],
build: v => 'replace ' + v.n + ' = ' + v.e + ifstr(v.if) },
{ label: 'Group summary variable (egen)', title: 'Create a variable from a group summary',
fields: [{ t: 'text', name: 'n', label: 'New variable name', ph: 'mean_price' },
{ t: 'select', name: 'f', label: 'Function', options: [['mean', 'mean'], ['sd', 'standard deviation'],
['median', 'median'], ['min', 'minimum'], ['max', 'maximum'], ['total', 'total'],
['count', 'count of non-missing'], ['iqr', 'interquartile range'], ['std', 'standardised (z-score)'],
['rank', 'rank'], ['group', 'group index'], ['tag', 'tag first in group'],
['rowmean', 'row mean across variables'], ['rowtotal', 'row total across variables']] },
{ t: 'text', name: 'a', label: 'Argument (variable or expression)', ph: 'price' },
{ t: 'var', name: 'by', label: 'Compute within groups of (optional)', opt: true }],
build: v => 'egen ' + v.n + ' = ' + v.f + '(' + v.a + ')' + optstr([v.by ? 'by(' + v.by + ')' : '']) },
{ label: 'Keep or drop observations', title: 'Keep or drop observations',
fields: [{ t: 'select', name: 'k', label: 'Action', options: [['keep', 'Keep only rows where…'],
['drop', 'Drop rows where…']] },
{ t: 'text', name: 'if', label: 'Condition', ph: 'foreign == 1' }],
build: v => v.k + ' if ' + v.if },
{ label: 'Drop variables', title: 'Drop variables',
fields: [{ t: 'vars', name: 'v', label: 'Variables to remove' }],
build: v => 'drop ' + v.v.join(' ') },
{ label: 'Rename a variable', title: 'Rename a variable',
fields: [{ t: 'var', name: 'a', label: 'Existing name' },
{ t: 'text', name: 'b', label: 'New name' }],
build: v => 'rename ' + v.a + ' ' + v.b },
{ label: 'Sort the data', title: 'Sort observations',
fields: [{ t: 'vars', name: 'v', label: 'Sort by (in order)' },
{ t: 'check', name: 'desc', label: 'Descending' }],
build: v => v.desc ? 'gsort ' + v.v.map(x => '-' + x).join(' ') : 'sort ' + v.v.join(' ') },
{ label: 'Encode a text variable', title: 'Turn text into numeric codes',
fields: [{ t: 'var', name: 'v', label: 'Text variable', str: true },
{ t: 'text', name: 'g', label: 'New numeric variable' }],
build: v => 'encode ' + v.v + ', gen(' + v.g + ')' },
{ label: 'Declare time series or panel', title: 'Declare the data structure',
sub: 'Needed for lag operators, correlograms, and panel estimators.',
fields: [{ t: 'select', name: 'k', label: 'Structure',
options: [['tsset', 'Time series — one observation per period'],
['xtset', 'Panel — many units observed over time']] },
{ t: 'var', name: 'a', label: 'Panel identifier (panel only) or time variable' },
{ t: 'var', name: 'b', label: 'Time variable (panel only)', opt: true }],
build: v => v.k === 'tsset' ? 'tsset ' + v.a : 'xtset ' + v.a + (v.b ? ' ' + v.b : '') }
]},
{ name: 'Summaries', items: [
{ label: 'Summary statistics', title: 'Summary statistics',
fields: [{ t: 'vars', name: 'v', label: 'Variables (empty = all)', numeric: true },
{ t: 'text', name: 'if', label: 'Restrict to (optional)' },
{ t: 'check', name: 'detail', label: 'Full detail — percentiles, skewness, kurtosis' }],
build: v => 'summarize ' + v.v.join(' ') + ifstr(v.if) + optstr([v.detail ? 'detail' : '']) },
{ label: 'Statistics by group', title: 'Statistics by group',
fields: [{ t: 'vars', name: 'v', label: 'Variables', numeric: true },
{ t: 'var', name: 'by', label: 'Group by', opt: true },
{ t: 'text', name: 's', label: 'Statistics', ph: 'mean sd min max n' }],
build: v => 'tabstat ' + v.v.join(' ') + optstr([v.by ? 'by(' + v.by + ')' : '',
'stats(' + (v.s || 'mean sd min max n') + ')']) },
{ label: 'Frequency table', title: 'One-way frequency table',
fields: [{ t: 'var', name: 'v', label: 'Variable' },
{ t: 'text', name: 'if', label: 'Restrict to (optional)' }],
build: v => 'tabulate ' + v.v + ifstr(v.if) },
{ label: 'Cross-tabulation', title: 'Two-way table with chi-squared test',
fields: [{ t: 'var', name: 'a', label: 'Row variable' },
{ t: 'var', name: 'b', label: 'Column variable' },
{ t: 'check', name: 'row', label: 'Row percentages' },
{ t: 'check', name: 'col', label: 'Column percentages' },
{ t: 'check', name: 'chi2', label: 'Chi-squared and Cramér\'s V', def: true }],
build: v => 'tabulate ' + v.a + ' ' + v.b + optstr([v.row ? 'row' : '', v.col ? 'col' : '',
v.chi2 ? 'all' : '']) },
{ label: 'Correlation matrix', title: 'Correlation matrix',
fields: [{ t: 'vars', name: 'v', label: 'Variables', numeric: true },
{ t: 'check', name: 'pw', label: 'Pairwise deletion instead of listwise' },
{ t: 'check', name: 'sig', label: 'Show significance levels' },
{ t: 'check', name: 'star', label: 'Star significant correlations' }],
build: v => (v.pw || v.sig || v.star ? 'pwcorr ' : 'correlate ') + v.v.join(' ') +
optstr([v.sig ? 'sig' : '', v.star ? 'star' : '']) }
]},
{ name: 'Tests', items: [
{ label: 't test — one sample', title: 'One-sample t test',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'text', name: 'm', label: 'Hypothesised mean', ph: '0' }],
build: v => 'ttest ' + v.v + ' = ' + (v.m || 0) },
{ label: 't test — two groups', title: 'Two-group mean comparison',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'var', name: 'by', label: 'Group variable (two groups)' },
{ t: 'check', name: 'un', label: 'Allow unequal variances (Welch)' }],
build: v => 'ttest ' + v.v + ', by(' + v.by + ')' + (v.un ? ' unequal' : '') },
{ label: 't test — paired', title: 'Paired t test',
fields: [{ t: 'var', name: 'a', label: 'First variable', numeric: true },
{ t: 'var', name: 'b', label: 'Second variable', numeric: true }],
build: v => 'ttest ' + v.a + ' == ' + v.b },
{ label: 'Equality of variances', title: 'Variance ratio test',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'var', name: 'by', label: 'Group variable' }],
build: v => 'sdtest ' + v.v + ', by(' + v.by + ')' },
{ label: 'One-way ANOVA', title: 'One-way analysis of variance',
fields: [{ t: 'var', name: 'y', label: 'Outcome', numeric: true },
{ t: 'var', name: 'g', label: 'Group variable' }],
build: v => 'oneway ' + v.y + ' ' + v.g },
{ label: 'Rank-sum (Mann-Whitney)', title: 'Wilcoxon rank-sum test',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'var', name: 'by', label: 'Group variable (two groups)' }],
build: v => 'ranksum ' + v.v + ', by(' + v.by + ')' },
{ label: 'Signed-rank test', title: 'Wilcoxon signed-rank test',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'text', name: 'm', label: 'Hypothesised median', ph: '0' }],
build: v => 'signrank ' + v.v + ' = ' + (v.m || 0) },
{ label: 'Kruskal-Wallis', title: 'Kruskal-Wallis rank test',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'var', name: 'by', label: 'Group variable' }],
build: v => 'kwallis ' + v.v + ', by(' + v.by + ')' },
{ label: 'Spearman correlation', title: 'Spearman rank correlation',
fields: [{ t: 'var', name: 'a', label: 'First variable', numeric: true },
{ t: 'var', name: 'b', label: 'Second variable', numeric: true }],
build: v => 'spearman ' + v.a + ' ' + v.b },
{ label: 'Normality tests', title: 'Skewness, kurtosis and Jarque-Bera tests',
fields: [{ t: 'vars', name: 'v', label: 'Variables', numeric: true }],
build: v => 'sktest ' + v.v.join(' ') }
]},
{ name: 'Models', items: [
{ label: 'Linear regression', title: 'Linear regression (OLS)',
sub: 'Prefix a regressor with i. to expand it into dummies, or join two with # to interact them.',
fields: [{ t: 'var', name: 'y', label: 'Dependent variable', numeric: true },
{ t: 'vars', name: 'x', label: 'Independent variables' },
{ t: 'select', name: 'vce', label: 'Standard errors',
options: [['', 'Conventional (assumes homoskedasticity)'], ['robust', 'Robust (HC1)'],
['hc3', 'Robust HC3 — better in small samples'], ['cluster', 'Clustered by a group variable'],
['hac', 'Newey-West (serial correlation)'], ['bootstrap', 'Bootstrap']] },
{ t: 'var', name: 'cl', label: 'Cluster / lag variable (if clustering)', opt: true },
{ t: 'text', name: 'if', label: 'Restrict sample to (optional)' },
{ t: 'check', name: 'nocons', label: 'Suppress the constant' }],
build: v => 'regress ' + v.y + ' ' + v.x.join(' ') + ifstr(v.if) + optstr([
v.vce === 'cluster' ? 'cluster(' + v.cl + ')' : (v.vce === 'bootstrap' ? 'bootstrap(400)' : v.vce),
v.nocons ? 'noconstant' : '']) },
{ label: 'Instrumental variables (2SLS)', title: 'Two-stage least squares',
sub: 'Reports first-stage F statistics and, when overidentified, the Sargan test.',
fields: [{ t: 'var', name: 'y', label: 'Dependent variable', numeric: true },
{ t: 'vars', name: 'x', label: 'Exogenous regressors' },
{ t: 'vars', name: 'e', label: 'Endogenous regressors' },
{ t: 'vars', name: 'z', label: 'Excluded instruments' },
{ t: 'check', name: 'r', label: 'Robust standard errors' }],
build: v => 'ivregress 2sls ' + v.y + ' ' + v.x.join(' ') + ' (' + v.e.join(' ') + ' = ' +
v.z.join(' ') + ')' + optstr([v.r ? 'robust' : '']) },
{ label: 'Panel: fixed / random effects', title: 'Panel data regression',
sub: 'Declare the panel first with xtset.',
fields: [{ t: 'var', name: 'y', label: 'Dependent variable', numeric: true },
{ t: 'vars', name: 'x', label: 'Independent variables' },
{ t: 'select', name: 'm', label: 'Estimator', options: [['fe', 'Fixed effects (within)'],
['re', 'Random effects (GLS)']] },
{ t: 'check', name: 'r', label: 'Cluster standard errors by panel' }],
build: v => 'xtreg ' + v.y + ' ' + v.x.join(' ') + ', ' + v.m + (v.r ? ' robust' : '') },
{ label: 'Logit', title: 'Logistic regression',
fields: [{ t: 'var', name: 'y', label: 'Binary outcome (0/1)', numeric: true },
{ t: 'vars', name: 'x', label: 'Independent variables' },
{ t: 'check', name: 'r', label: 'Robust standard errors' }],
build: v => 'logit ' + v.y + ' ' + v.x.join(' ') + optstr([v.r ? 'robust' : '']) },
{ label: 'Probit', title: 'Probit regression',
fields: [{ t: 'var', name: 'y', label: 'Binary outcome (0/1)', numeric: true },
{ t: 'vars', name: 'x', label: 'Independent variables' },
{ t: 'check', name: 'r', label: 'Robust standard errors' }],
build: v => 'probit ' + v.y + ' ' + v.x.join(' ') + optstr([v.r ? 'robust' : '']) },
{ label: 'Poisson (counts)', title: 'Poisson regression',
fields: [{ t: 'var', name: 'y', label: 'Count outcome', numeric: true },
{ t: 'vars', name: 'x', label: 'Independent variables' },
{ t: 'check', name: 'r', label: 'Robust standard errors' }],
build: v => 'poisson ' + v.y + ' ' + v.x.join(' ') + optstr([v.r ? 'robust' : '']) },
{ label: 'Quantile regression', title: 'Quantile regression',
fields: [{ t: 'var', name: 'y', label: 'Dependent variable', numeric: true },
{ t: 'vars', name: 'x', label: 'Independent variables' },
{ t: 'text', name: 'q', label: 'Quantile', ph: '0.5' }],
build: v => 'qreg ' + v.y + ' ' + v.x.join(' ') + ', quantile(' + (v.q || 0.5) + ')' },
{ label: 'Newey-West regression', title: 'Regression with HAC standard errors',
fields: [{ t: 'var', name: 'y', label: 'Dependent variable', numeric: true },
{ t: 'vars', name: 'x', label: 'Independent variables' },
{ t: 'num', name: 'l', label: 'Maximum lag', def: 4 }],
build: v => 'newey ' + v.y + ' ' + v.x.join(' ') + ', lag(' + (v.l || 4) + ')' }
]},
{ name: 'After estimation', items: [
{ label: 'Save predictions or residuals', title: 'Predict after estimation',
fields: [{ t: 'text', name: 'n', label: 'New variable name', ph: 'yhat' },
{ t: 'select', name: 'k', label: 'Quantity', options: [['xb', 'Fitted values / linear prediction'],
['residuals', 'Residuals'], ['pr', 'Predicted probability (logit, probit)'],
['stdp', 'Standard error of the prediction']] }],
build: v => 'predict ' + v.n + ', ' + v.k },
{ label: 'Test linear restrictions', title: 'Wald test of restrictions',
sub: 'Separate several restrictions with commas: educ = exper, female = 0',
fields: [{ t: 'text', name: 's', label: 'Restriction(s)', ph: 'educ exper' }],
build: v => 'test ' + v.s },
{ label: 'Marginal effects', build: () => 'margins', instant: true },
{ label: 'Multicollinearity (VIF)', build: () => 'estat vif', instant: true },
{ label: 'Heteroskedasticity (Breusch-Pagan)', build: () => 'estat hettest', instant: true },
{ label: "Heteroskedasticity (White)", build: () => 'estat imtest', instant: true },
{ label: 'Omitted variables (RESET)', build: () => 'estat ovtest', instant: true },
{ label: 'Durbin-Watson', build: () => 'estat dwatson', instant: true },
{ label: 'Serial correlation (Breusch-Godfrey)', title: 'Breusch-Godfrey LM test',
fields: [{ t: 'num', name: 'l', label: 'Lags', def: 1 }],
build: v => 'estat bgodfrey, lags(' + (v.l || 1) + ')' },
{ label: 'ARCH effects', title: 'ARCH LM test',
fields: [{ t: 'num', name: 'l', label: 'Lags', def: 1 }],
build: v => 'estat archlm, lags(' + (v.l || 1) + ')' },
{ label: 'Information criteria (AIC/BIC)', build: () => 'estat ic', instant: true },
{ label: 'Store these estimates', title: 'Store estimation results',
fields: [{ t: 'text', name: 'n', label: 'Name', ph: 'm1' }],
build: v => 'estimates store ' + v.n },
{ label: 'Compare stored models', title: 'Side-by-side comparison table',
fields: [{ t: 'text', name: 'n', label: 'Model names (empty = all stored)', ph: 'm1 m2 m3' }],
build: v => 'estimates table ' + (v.n || '') },
{ label: 'Hausman test (FE vs RE)', build: () => 'hausman', instant: true }
]},
{ name: 'Time series', items: [
{ label: 'Correlogram table', title: 'Correlogram with Ljung-Box statistics',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'num', name: 'l', label: 'Lags', def: 12 }],
build: v => 'corrgram ' + v.v + ', lags(' + (v.l || 12) + ')' },
{ label: 'Autocorrelation plot', title: 'Autocorrelation function',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'num', name: 'l', label: 'Lags', def: 20 }],
build: v => 'ac ' + v.v + ', lags(' + (v.l || 20) + ')' },
{ label: 'Partial autocorrelation plot', title: 'Partial autocorrelation function',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'num', name: 'l', label: 'Lags', def: 20 }],
build: v => 'pac ' + v.v + ', lags(' + (v.l || 20) + ')' },
{ label: 'Unit root test', title: 'Augmented Dickey-Fuller test',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'num', name: 'l', label: 'Lagged differences', def: 1 },
{ t: 'select', name: 'k', label: 'Deterministic terms', options: [['', 'Constant'],
['trend', 'Constant and trend'], ['noconstant', 'Neither']] }],
build: v => 'dfuller ' + v.v + optstr(['lags(' + (v.l || 0) + ')', v.k]) }
]},
{ name: 'Graphs', items: [
{ label: 'Scatter plot', title: 'Scatter plot',
fields: [{ t: 'var', name: 'y', label: 'Y variable', numeric: true },
{ t: 'var', name: 'x', label: 'X variable', numeric: true },
{ t: 'var', name: 'by', label: 'Colour by group (optional)', opt: true },
{ t: 'check', name: 'fit', label: 'Add the fitted regression line' },
{ t: 'check', name: 'lo', label: 'Add a smoothed curve' }],
build: v => 'scatter ' + v.y + ' ' + v.x + optstr([v.fit ? 'fit' : '', v.lo ? 'lowess' : '',
v.by ? 'by(' + v.by + ')' : '']) },
{ label: 'Line plot', title: 'Line plot',
fields: [{ t: 'vars', name: 'y', label: 'Variables to plot', numeric: true },
{ t: 'var', name: 'x', label: 'X axis (optional — defaults to time)', opt: true }],
build: v => 'line ' + v.y.join(' ') + (v.x ? ' ' + v.x : '') },
{ label: 'Histogram', title: 'Histogram',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'num', name: 'b', label: 'Number of bins (0 = automatic)', def: 0 },
{ t: 'check', name: 'n', label: 'Overlay a normal density' },
{ t: 'check', name: 'k', label: 'Overlay a kernel density' }],
build: v => 'histogram ' + v.v + optstr([+v.b ? 'bins(' + v.b + ')' : '', v.n ? 'normal' : '',
v.k ? 'kdensity' : '']) },
{ label: 'Kernel density', title: 'Kernel density estimate',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true }],
build: v => 'kdensity ' + v.v },
{ label: 'Box plot', title: 'Box plot',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'var', name: 'o', label: 'Split by group (optional)', opt: true }],
build: v => 'graph box ' + v.v + optstr([v.o ? 'over(' + v.o + ')' : '']) },
{ label: 'Bar chart of means', title: 'Bar chart of group means',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true },
{ t: 'var', name: 'o', label: 'Group by' }],
build: v => 'graph bar ' + v.v + ', over(' + v.o + ')' },
{ label: 'Normal quantile plot', title: 'Normal Q-Q plot',
fields: [{ t: 'var', name: 'v', label: 'Variable', numeric: true }],
build: v => 'qnorm ' + v.v },
{ label: 'Residuals vs fitted', build: () => 'rvfplot', instant: true },
{ label: 'Scatterplot matrix', title: 'Scatterplot matrix',
fields: [{ t: 'vars', name: 'v', label: 'Variables (2 to 6)', numeric: true }],
build: v => 'graph matrix ' + v.v.join(' ') }
]}
];
function renderMenu() {
const m = $('menu');
m.innerHTML = '';
MENUS.forEach((g, gi) => {
const d = document.createElement('div');
d.className = 'mgroup' + (gi === 0 ? ' open' : '');
const h = document.createElement('button');
h.className = 'mhead';
h.innerHTML = '<span class="ar">▶</span>' + g.name;
h.onclick = () => d.classList.toggle('open');
const items = document.createElement('div');
items.className = 'mitems';
for (const it of g.items) {
const b = document.createElement('button');
b.textContent = it.label;
b.onclick = () => it.instant ? runCommand(it.build({})) : openDialog(it);
items.appendChild(b);
}
d.appendChild(h); d.appendChild(items);
m.appendChild(d);
});
}
/* ---------- generic dialog ---------- */
let dlgItem = null;
function openDialog(item) {
if (!DB.n && !item.noData) { runCommand('describe'); return; }
dlgItem = item;
$('mTitle').textContent = item.title || item.label;
$('mSub').textContent = item.sub || '';
$('mSub').style.display = item.sub ? 'block' : 'none';
const body = $('mBody');
body.innerHTML = '';
const numVars = DB.vars.filter(v => v.type !== 'str').map(v => v.name);
const allVars = varNames();
for (const f of item.fields) {
const d = document.createElement('div');
d.className = 'fld';
const pool = f.numeric ? numVars : (f.str ? DB.vars.filter(v => v.type === 'str').map(v => v.name) : allVars);
if (f.t === 'check') {
d.innerHTML = '<label class="chk"><input type="checkbox" data-n="' + f.name + '"' +
(f.def ? ' checked' : '') + '><span>' + f.label + '</span></label>';
} else if (f.t === 'vars') {
d.innerHTML = '<label>' + f.label + '</label><select multiple data-n="' + f.name + '">' +
pool.map(v => '<option value="' + v + '">' + v + (getVar(v).label ? ' — ' +
getVar(v).label : '') + '</option>').join('') + '</select>';
} else if (f.t === 'var') {
d.innerHTML = '<label>' + f.label + '</label><select data-n="' + f.name + '">' +
(f.opt ? '<option value="">(none)</option>' : '') +
pool.map(v => '<option value="' + v + '">' + v + (getVar(v).label ? ' — ' +
getVar(v).label : '') + '</option>').join('') + '</select>';
} else if (f.t === 'select') {
d.innerHTML = '<label>' + f.label + '</label><select data-n="' + f.name + '">' +
f.options.map(o => '<option value="' + o[0] + '">' + o[1] + '</option>').join('') + '</select>';
} else if (f.t === 'num') {
d.innerHTML = '<label>' + f.label + '</label><input type="number" data-n="' + f.name +
'" value="' + (f.def !== undefined ? f.def : '') + '">';
} else {
d.innerHTML = '<label>' + f.label + '</label><input type="text" data-n="' + f.name +
'" placeholder="' + (f.ph || '') + '">';
}
body.appendChild(d);
}
const pv = document.createElement('div');
pv.className = 'fld';
pv.innerHTML = '<label>This will run</label><div class="preview" id="mPrev"></div>';
body.appendChild(pv);
body.querySelectorAll('input,select').forEach(el => {
el.addEventListener('input', updatePreview);
el.addEventListener('change', updatePreview);
});
updatePreview();
$('mHint').textContent = 'Enter to run · Esc to cancel';
$('mask').classList.add('on');
const first = body.querySelector('input,select');
if (first) first.focus();
}
function dlgValues() {
const v = {};
$('mBody').querySelectorAll('[data-n]').forEach(el => {
if (el.type === 'checkbox') v[el.dataset.n] = el.checked;
else if (el.multiple) v[el.dataset.n] = [...el.selectedOptions].map(o => o.value);
else v[el.dataset.n] = el.value;
});
return v;
}
function updatePreview() {
let s;
try { s = dlgItem.build(dlgValues()).replace(/\s+/g, ' ').replace(/\s+,/g, ',').trim(); }
catch (e) { s = ''; }
const p = $('mPrev');
p.innerHTML = s ? '<b>. </b>' + esc(s) : '<b>fill in the fields above</b>';
}
function closeDialog() { $('mask').classList.remove('on'); dlgItem = null; }
function runDialog() {
let s;
try { s = dlgItem.build(dlgValues()).replace(/\s+/g, ' ').replace(/\s+,/g, ',').trim(); }
catch (e) { return; }
closeDialog();
showPane('Results');
runCommand(s);
$('cmd').focus();
}
/* ============================================================
REFERENCE
============================================================ */
const REF = [
{ h: 'Getting data in', p: 'Every menu action writes a command into the log, so the interface doubles as ' +
'a way to learn the syntax. Anything you can click, you can type.', rows: [
['use auto', 'Load an example dataset (auto, wage, growth, invest, macro, health)'],
['describe', 'List the variables, their types, and their labels'],
['codebook price mpg', 'Detailed report on each variable, including missing values'],
['list make price in 1/10', 'Show observations 1 to 10'],
['count if foreign==1', 'Count the observations meeting a condition'],
['clear', 'Empty the dataset from memory']
]},
{ h: 'Creating and reshaping variables', p: 'Expressions accept ln exp sqrt abs round int mod max min ' +
'cond normal invnormal logistic rnormal runiform, the series operators lag(x,1) lead(x,1) diff(x) ' +
'sum(x), and the sample aggregates mean(x) sd(x) median(x) total(x) count(x). A full stop means missing.', rows: [
['generate lprice = ln(price)', 'Create a variable from an expression'],
['generate big = price > 10000', 'Indicator variables come from comparisons'],
['replace mpg = . if mpg < 5', 'Overwrite values that meet a condition'],
['egen avg = mean(price), by(foreign)', 'Group summary attached to every row'],
['egen id = group(firm year)', 'Number the distinct combinations'],
['drop if price > 15000', 'Delete observations'],
['keep make price mpg', 'Keep only these variables'],
['rename mpg mileage', 'Rename a variable'],
['encode make, gen(makeid)', 'Turn text into numeric codes'],
['sort price', 'Sort ascending; gsort -price sorts descending'],
['tsset qtr', 'Declare a time series'],
['xtset firm year', 'Declare a panel']
]},
{ h: 'Describing the data', rows: [
['summarize', 'Mean, standard deviation, minimum and maximum for every variable'],
['summarize price, detail', 'Adds percentiles, skewness, and kurtosis'],
['tabstat price mpg, by(foreign) stats(mean sd p50)', 'A custom table of statistics'],
['tabulate rep78', 'Frequency table'],
['tabulate foreign rep78, all', 'Cross-tabulation with chi-squared and Cramér\'s V'],
['correlate price mpg weight', 'Correlation matrix, listwise deletion'],
['pwcorr price mpg, sig star', 'Pairwise correlations with significance levels'],
['by foreign: summarize price', 'Repeat any command within each group']
]},
{ h: 'Hypothesis tests', rows: [
['ttest mpg = 20', 'One-sample t test'],
['ttest mpg, by(foreign)', 'Two-group comparison; add unequal for Welch'],
['ttest price == mpg', 'Paired t test'],
['sdtest mpg, by(foreign)', 'Equality of variances'],
['oneway price rep78', 'One-way ANOVA with Bartlett\'s test'],
['ranksum mpg, by(foreign)', 'Wilcoxon rank-sum (Mann-Whitney)'],
['signrank mpg = 20', 'Wilcoxon signed-rank'],
['kwallis mpg, by(rep78)', 'Kruskal-Wallis'],
['spearman price mpg', 'Rank correlation'],
['sktest price mpg', 'Skewness, kurtosis, and Jarque-Bera normality tests']
]},
{ h: 'Estimation', p: 'In any regressor list, i.var expands a categorical variable into dummies, ' +
'and a#b interacts two terms. L.x, L2.x, D.x, and F.x are lag, second lag, difference, and lead.', rows: [
['regress price mpg weight', 'Ordinary least squares'],
['regress price mpg, robust', 'Heteroskedasticity-robust standard errors (HC1); hc2 and hc3 also work'],
['regress price mpg, cluster(rep78)', 'Cluster-robust standard errors'],
['regress price mpg, bootstrap(400)', 'Bootstrap standard errors'],
['regress wage educ i.rep78', 'Categorical variable expanded into dummies'],
['regress wage educ exper educ#exper', 'Interaction term'],
['newey gdpgrow L.gdpgrow, lag(4)', 'Newey-West HAC standard errors'],
['ivregress 2sls wage exper (educ = tenure)', 'Two-stage least squares with diagnostics'],
['xtreg invest mvalue kstock, fe', 'Panel fixed effects; use re for random effects'],
['logit insured age income', 'Logistic regression'],
['probit insured age income', 'Probit regression'],
['poisson visits age chronic', 'Poisson count model'],
['qreg price mpg, quantile(0.25)', 'Quantile regression']
]},
{ h: 'After estimation', rows: [
['predict yhat', 'Fitted values; add , residuals or , pr or , stdp'],
['test mpg weight', 'Joint test that both coefficients are zero'],
['test mpg = weight', 'Test a linear restriction between coefficients'],
['margins', 'Average marginal effects after logit, probit, or poisson'],
['estat vif', 'Variance inflation factors'],
['estat hettest', 'Breusch-Pagan test for heteroskedasticity'],
['estat imtest', 'White test for heteroskedasticity'],
['estat ovtest', 'Ramsey RESET test for functional form'],
['estat dwatson', 'Durbin-Watson statistic'],
['estat bgodfrey, lags(2)', 'Breusch-Godfrey test for serial correlation'],
['estat archlm, lags(1)', 'Test for ARCH effects'],
['estat ic', 'AIC and BIC'],
['estimates store m1', 'Save the current results under a name'],
['estimates table m1 m2', 'Compare stored models side by side'],
['hausman', 'Compare fixed and random effects']
]},
{ h: 'Time series', rows: [
['corrgram gdpgrow, lags(12)', 'Autocorrelations, partial autocorrelations, Ljung-Box Q'],
['ac gdpgrow, lags(20)', 'Autocorrelation plot with confidence band'],
['pac gdpgrow, lags(20)', 'Partial autocorrelation plot'],
['dfuller gdp, lags(2) trend', 'Augmented Dickey-Fuller unit root test']
]},
{ h: 'Graphs', rows: [
['scatter price mpg, fit', 'Scatter plot with a fitted line; lowess adds a smoothed curve'],
['scatter price mpg, by(foreign)', 'Colour the points by a group variable'],
['line gdp cpi', 'Line plot against the time variable'],
['histogram price, normal kdensity', 'Histogram with density overlays'],
['kdensity price', 'Kernel density estimate'],
['graph box price, over(foreign)', 'Box plot by group'],
['graph bar price, over(rep78)', 'Bar chart of group means'],
['graph matrix price mpg weight', 'Scatterplot matrix'],
['qnorm price', 'Normal quantile plot'],
['rvfplot', 'Residuals against fitted values']
]}
];
function renderHelp() {
const p = $('paneHelp');
if (p.dataset.done) return;
let h = '<div class="help"><h2>Command reference</h2><p>Click any command to load it into the ' +
'command bar. Most commands accept <code>if</code> conditions and <code>in</code> ranges, ' +
'and take options after a comma.</p>';
for (const s of REF) {
h += '<h2>' + s.h + '</h2>';
if (s.p) h += '<p>' + s.p + '</p>';
h += '<table class="ref">';
for (const r of s.rows) h += '<tr><td data-c="' + esc(r[0]) + '">' + esc(r[0]) + '</td><td>' +
esc(r[1]) + '</td></tr>';
h += '</table>';
}
h += '</div>';
p.innerHTML = h;
p.dataset.done = '1';
p.querySelectorAll('td[data-c]').forEach(td => td.onclick = () => {
$('cmd').value = td.dataset.c; showPane('Results'); $('cmd').focus();
});
}
function showHelp(topic) {
if (!topic) { showPane('Help'); out('(the full command reference is open in the Reference tab)'); return; }
const t = topic.toLowerCase();
const hits = [];
for (const s of REF) for (const r of s.rows)
if (r[0].toLowerCase().split(/[\s,]/)[0].startsWith(t) || r[0].toLowerCase().includes(t))
hits.push(r);
if (!hits.length) { out('No reference entry for "' + topic + '". Open the Reference tab for the full list.'); return; }
out('Reference entries matching "' + topic + '"\n' + rule(TW));
for (const r of hits) out(' ' + padR(r[0], 38) + r[1]);
out(rule(TW));
}
function showAbout() {
out('Econometrics — a self-contained statistical workbench.\n' + rule(TW) +
'\nEverything runs in this page: no server, no libraries. Estimators are implemented from\n' +
'scratch, with the linear algebra done by Cholesky factorisation and rank detection that\n' +
'drops collinear regressors the way a commercial package would.\n\n' +
'Verified against closed-form results: the within estimator reproduces least-squares dummy\n' +
'variables, exactly identified 2SLS reproduces the IV formula, HC1 matches the sandwich\n' +
'computed by hand, one-way ANOVA F equals the squared two-sample t, and Kruskal-Wallis\n' +
'equals the squared rank-sum z.\n\n' +
'Example datasets are simulated from fixed seeds, so every result here is reproducible,\n' +
'but they are not the real surveys they are patterned on. Use your own data for research.');
}
/* ---------- welcome ---------- */
function renderWelcome() {
const w = document.createElement('div');
w.className = 'welcome';
w.innerHTML =
'<h1>A statistics workbench that shows its work</h1>' +
'<p class="lede">Load a dataset and start estimating. Every menu action writes its command ' +
'into the log below, so you can read what just ran, edit it, and run it again.</p>' +
'<div class="startgrid">' +
Object.keys(SAMPLES).map(k => '<button class="startcard" data-c="use ' + k + '"><b>use ' + k +
'</b><span>' + esc(SAMPLES[k].desc.replace(/ \(simulated\)/, '')) + '</span></button>').join('') +
'</div>' +
'<h3>Try a first session</h3>' +
['use auto', 'summarize price mpg weight, detail', 'scatter price weight, fit',
'regress price mpg weight foreign, robust', 'estat vif', 'estat hettest', 'rvfplot']
.map(c => '<div class="tryline" data-c="' + esc(c) + '">' + esc(c) + '</div>').join('') +
'<p class="note" style="margin-top:20px">Datasets here are simulated from fixed seeds — realistic ' +
'in structure and reproducible, but not the real surveys they are patterned on.</p>';
$('log').appendChild(w);
w.querySelectorAll('[data-c]').forEach(el => el.onclick = () => runCommand(el.dataset.c));
}
/* ============================================================
WIRING
============================================================ */
function submitCmd() {
const c = $('cmd');
const v = c.value.trim();
if (!v) return;
history.push(v); hIdx = history.length;
c.value = '';
showPane('Results');
runCommand(v);
}
function download(name, text, type) {
const b = new Blob([text], { type: type || 'text/plain' });
const a = document.createElement('a');
a.href = URL.createObjectURL(b); a.download = name;
document.body.appendChild(a); a.click();
setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 0);
}
function init() {
renderMenu(); renderVars(); renderInfo(); renderWelcome();
$('btnRun').onclick = submitCmd;
$('cmd').addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); submitCmd(); }
else if (e.key === 'ArrowUp') { e.preventDefault();
if (hIdx > 0) { hIdx--; $('cmd').value = history[hIdx]; } }
else if (e.key === 'ArrowDown') { e.preventDefault();
if (hIdx < history.length - 1) { hIdx++; $('cmd').value = history[hIdx]; }
else { hIdx = history.length; $('cmd').value = ''; } }
});
$('vsearch').addEventListener('input', renderVars);
$('tabResults').onclick = () => showPane('Results');
$('tabData').onclick = () => showPane('Data');
$('tabHelp').onclick = () => showPane('Help');
$('btnClear').onclick = () => clearLog();
$('btnSaveLog').onclick = () => {
let t = 'Econometrics — session log\n' + new Date().toString() + '\n\n';
$('log').querySelectorAll('.entry').forEach(e => {
const c = e.querySelector('.cmdline');
if (c) t += '. ' + c.textContent + '\n';
e.querySelectorAll('pre').forEach(p => t += p.textContent + '\n');
t += '\n';
});
download('econometrics-log.txt', t);
};
$('btnTheme').onclick = () => {
const d = document.documentElement.getAttribute('data-theme') === 'dark';
document.documentElement.setAttribute('data-theme', d ? 'light' : 'dark');
$('btnTheme').textContent = d ? 'Black' : 'White';
};
$('btnImport').onclick = () => $('fileIn').click();
$('fileIn').addEventListener('change', e => {
const f = e.target.files[0];
if (!f) return;
const r = new FileReader();
r.onload = () => {
logCmd('import delimited "' + f.name + '"');
try {
const res = parseCSV(r.result);
DB.name = f.name.replace(/\.[^.]+$/, '');
out('(' + res.k + ' variables, ' + res.n + ' observations read)');
out('');
runCommand('describe', false);
refreshAll();
} catch (err) { outErr(err.message); }
};
r.readAsText(f);
e.target.value = '';
});
$('btnExport').onclick = () => {
if (!DB.n) { showPane('Results'); logCmd('export delimited'); outErr('no data in memory'); return; }
download((DB.name || 'data') + '.csv', toCSV(), 'text/csv');
};
$('btnSide').onclick = () => $('side').classList.toggle('open');
$('mCancel').onclick = closeDialog;
$('mRun').onclick = runDialog;
$('mask').addEventListener('click', e => { if (e.target === $('mask')) closeDialog(); });
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && $('mask').classList.contains('on')) closeDialog();
if (e.key === 'Enter' && $('mask').classList.contains('on') &&
e.target.tagName !== 'SELECT') { e.preventDefault(); runDialog(); }
});
$('menu').addEventListener('click', () => {
if (window.innerWidth <= 860) $('side').classList.remove('open');
});
$('cmd').focus();
}
document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>
Websites this page contacts when it runs — fonts, chart libraries, data. Found by reading its source.
Published on Globefin under the MIT License. You may copy, change, and reuse this page, including commercially — just keep the notice below with it.
Copyright © 2026 Shane Hadden. Licensed under the MIT License. Published on Globefin.
Provided as is, without warranty. Any external libraries it loads keep their own licences. Terms →
Scripts run, but the demo has its own throwaway origin. It can't read your session or cookies, can't reach the page around it, and can't navigate your tab. Don't enter real passwords or personal data into any demo.