unifying_electro_magnetism / Why-plotters /time-series-why-plotter-forecast.html
perrabyte's picture
Upload 1494 files
f8506a2 verified
Raw History Blame Contribute Delete
38.6 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Why is this forecast this value? — AR decomposition explorer</title> <style> :root { --bg: #0a0a12; --panel: #12121e; --border: #2a2a3a; --text: #e8e8f0; --dim: #8888a0; --accent: #6cf; --good: #6cdc78; --bad: #ff5566; --obs: #7ab8ff; } * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--text); font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; font-size: 14px; line-height: 1.55; } header { padding: 18px 24px; border-bottom: 1px solid var(--border); } header h1 { margin: 0 0 4px; font-size: 18px; font-weight: 600; } header p { margin: 0; color: var(--dim); font-size: 13px; max-width: 900px; } header code { background: #1e1e2e; padding: 1px 5px; border-radius: 3px; font-size: 12px; } main { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(0, 1fr); gap: 16px; padding: 16px; max-width: 1600px; margin: 0 auto; } @media (max-width: 1100px) { main { grid-template-columns: 1fr; } } .col { display: flex; flex-direction: column; gap: 16px; } .panel { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; } .panel-header { padding: 10px 14px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; } .panel-header h2 { margin: 0; font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; color: var(--dim); } .controls { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; font-size: 12px; } .controls label { display: flex; align-items: center; gap: 5px; color: var(--dim); } .controls input[type=range] { width: 80px; accent-color: var(--accent); } .controls select, .controls input[type=file] { background: #0e0e1a; color: var(--text); border: 1px solid var(--border); border-radius: 4px; padding: 3px 8px; font-size: 12px; font-family: inherit; } .controls input[type=file] { padding: 2px 6px; cursor: pointer; } .controls input[type=file]::file-selector-button { background: #1e1e2e; color: var(--text); border: 1px solid var(--border); border-radius: 3px; padding: 3px 8px; font-family: inherit; font-size: 11px; cursor: pointer; margin-right: 6px; } canvas { display: block; width: 100%; height: auto; background: #080810; } #mainCanvas { cursor: crosshair; } .hint { padding: 9px 14px; font-size: 11.5px; color: var(--dim); border-top: 1px solid var(--border); background: rgba(255,255,255,0.02); line-height: 1.5; } .hint b { color: var(--text); } #explanation { padding: 14px 16px; font-size: 13px; max-height: 400px; overflow-y: auto; } #explanation h3 { margin: 0 0 10px; font-size: 13px; color: var(--accent); font-weight: 600; } #explanation p { margin: 8px 0; } .verdict { padding: 8px 12px; border-radius: 4px; margin: 10px 0; font-weight: 600; font-size: 13px; } .verdict.bad { background: rgba(255,85,102,0.12); color: #ff8a99; border-left: 3px solid #ff5566; } .verdict.good { background: rgba(102, 204, 255, 0.12); color: #9ddcff; border-left: 3px solid #6cf; } #explanation table { width: 100%; border-collapse: collapse; font-family: ui-monospace, monospace; font-size: 11.5px; margin: 8px 0; } #explanation th, #explanation td { text-align: right; padding: 3px 6px; border-bottom: 1px solid var(--border); } #explanation th:first-child, #explanation td:first-child { text-align: left; } #explanation th { color: var(--dim); font-weight: 500; } .note { color: var(--dim); font-size: 12px; border-top: 1px solid var(--border); padding-top: 10px; margin-top: 14px; line-height: 1.6; } kbd { background: #1e1e2e; border: 1px solid var(--border); border-radius: 3px; padding: 1px 5px; font-size: 10.5px; font-family: ui-monospace, monospace; } </style> </head> <body> <header> <h1>Why is this forecast this value?</h1> <p> Hover over the time series to see how each forecast point decomposes into contributions from the clamped past. The dashed cyan line is the <code>F<sup>h</sup></code> leap; red bands are <b>voids</b> (unobserved times) that coast rather than decay. Upload any CSV, pick a numeric column, set the AR order <code>p</code> and the horizon <code>h</code>. </p> </header> <main> <div class="col"> <div class="panel"> <div class="panel-header"> <h2>Time series &amp; forecast</h2> <div class="controls"> <input type="file" id="fileInput" accept=".csv,.txt,.tsv"> <select id="colSelect" title="numeric column"></select> <label>p <input type="range" id="pSlider" min="1" max="6" value="2" step="1"><span id="pVal">2</span></label> <label>h <input type="range" id="hSlider" min="1" max="80" value="25" step="1"><span id="hVal">25</span></label> </div> </div> <canvas id="mainCanvas" width="960" height="460"></canvas> <div class="hint"> <b>Blue dots</b>: observed (clamp rows). <b>Dashed cyan</b>: forecast (free boundary coasting on <code>F<sup>h</sup></code>). <b>Red bands</b>: gaps — treated as voids, not zeros. Drop a CSV onto the window to load it. </div> </div> </div> <div class="col"> <div class="panel"> <div class="panel-header"><h2>Decomposition of the hovered point</h2></div> <canvas id="attrCanvas" width="520" height="300"></canvas> </div> <div class="panel"> <div class="panel-header"><h2>Spectrum — the arrow of time</h2></div> <canvas id="specCanvas" width="520" height="300"></canvas> </div> <div class="panel"> <div id="explanation"> <p style="color:var(--dim)">Hover over the time series to inspect a point.</p> </div> </div> </div> </main> <script> "use strict"; // ===================================================================== // State // ===================================================================== const state = { series: [], dataRows: null, header: null, numericCols: [], selectedCol: null, p: 2, horizon: 25, model: null, forecast: null, // { forecast: [...], startT, state: [...] } hoverIdx: null, }; // ===================================================================== // Canvas setup // ===================================================================== const mainCanvas = document.getElementById("mainCanvas"); const mainCtx = mainCanvas.getContext("2d"); const attrCanvas = document.getElementById("attrCanvas"); const attrCtx = attrCanvas.getContext("2d"); const specCanvas = document.getElementById("specCanvas"); const specCtx = specCanvas.getContext("2d"); const explanationEl = document.getElementById("explanation"); const COL = { obs: "#7ab8ff", fc: "#6cf", pos: "rgba(108, 220, 120, 0.85)", neg: "rgba(255, 110, 130, 0.85)", gap: "rgba(255, 85, 102, 0.10)", grid: "#14141f", axis: "#2a2a3a", }; // ===================================================================== // Small linear algebra (plain 2D arrays) // ===================================================================== function zeros(n, m) { return Array.from({length: n}, () => new Array(m).fill(0)); } function eye(n) { const I = zeros(n, n); for (let i = 0; i < n; i++) I[i][i] = 1; return I; } function matmul(A, B) { const n = A.length, m = B[0].length, k = B.length; const C = zeros(n, m); for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) { let s = 0; for (let q = 0; q < k; q++) s += A[i][q] * B[q][j]; C[i][j] = s; } return C; } function matpow(A, k) { const n = A.length; let R = eye(n), B = A.map(r => r.slice()); while (k > 0) { if (k & 1) R = matmul(R, B); B = matmul(B, B); k >>= 1; } return R; } function solveLinear(A, b) { const n = A.length; const M = A.map((row, i) => [...row, b[i]]); for (let col = 0; col < n; col++) { let pivot = col; for (let r = col + 1; r < n; r++) if (Math.abs(M[r][col]) > Math.abs(M[pivot][col])) pivot = r; if (Math.abs(M[pivot][col]) < 1e-12) return null; [M[col], M[pivot]] = [M[pivot], M[col]]; const pv = M[col][col]; for (let r = col + 1; r < n; r++) { const f = M[r][col] / pv; for (let c = col; c <= n; c++) M[r][c] -= f * M[col][c]; } } const x = new Array(n).fill(0); for (let i = n - 1; i >= 0; i--) { let s = M[i][n]; for (let j = i + 1; j < n; j++) s -= M[i][j] * x[j]; x[i] = s / M[i][i]; } return x; } // Complex helpers for polynomial roots const cx = (re, im = 0) => ({ re, im }); const cadd = (a, b) => ({ re: a.re + b.re, im: a.im + b.im }); const csub = (a, b) => ({ re: a.re - b.re, im: a.im - b.im }); const cmul = (a, b) => ({ re: a.re * b.re - a.im * b.im, im: a.re * b.im + a.im * b.re }); const cdiv = (a, b) => { const d = b.re * b.re + b.im * b.im; return { re: (a.re * b.re + a.im * b.im) / d, im: (a.im * b.re - a.re * b.im) / d }; }; function evalPoly(coeffs, z) { // coeffs descending: c[0] z^n + c[1] z^{n-1} + ... + c[n] let r = cx(coeffs[0]); for (let i = 1; i < coeffs.length; i++) r = cadd(cmul(r, z), cx(coeffs[i])); return r; } function polyRoots(arCoeffs) { // roots of z^p - a1 z^{p-1} - ... - ap const p = arCoeffs.length; const c = [1]; for (const a of arCoeffs) c.push(-a); // Durand–Kerner const n = p; let roots = []; for (let k = 0; k < n; k++) { const ang = (2 * Math.PI * k) / n + 0.4; roots.push(cx(Math.cos(ang), Math.sin(ang))); } for (let iter = 0; iter < 300; iter++) { let maxStep = 0; for (let i = 0; i < n; i++) { let num = evalPoly(c, roots[i]); let den = cx(1, 0); for (let j = 0; j < n; j++) if (j !== i) den = cmul(den, csub(roots[i], roots[j])); const d = cdiv(num, den); roots[i] = csub(roots[i], d); maxStep = Math.max(maxStep, Math.hypot(d.re, d.im)); } if (maxStep < 1e-12) break; } return roots; } // ===================================================================== // CSV parsing // ===================================================================== function parseLine(line) { const out = []; let cur = "", inQ = false; for (let i = 0; i < line.length; i++) { const ch = line[i]; if (ch === '"') { inQ = !inQ; continue; } if ((ch === ',' || ch === '\t' || ch === ';') && !inQ) { out.push(cur); cur = ""; continue; } cur += ch; } out.push(cur); return out; } function parseCSV(text) { const lines = text.replace(/^\uFEFF/, "").trim().split(/\r?\n/).filter(l => l.trim()); return lines.map(parseLine); } function analyzeColumns(rows) { if (!rows.length) return null; const first = rows[0]; const isHeader = first.some(v => v !== "" && isNaN(parseFloat(v))); let header, dataRows; if (isHeader) { header = first; dataRows = rows.slice(1); } else { header = first.map((_, i) => `col${i + 1}`); dataRows = rows; } const numeric = []; for (let j = 0; j < header.length; j++) { let ok = 0, tot = 0; for (const r of dataRows) { const v = r[j]; if (v === undefined || v === "") continue; tot++; if (isFinite(parseFloat(v))) ok++; } if (tot > 0 && ok / tot > 0.6) numeric.push(j); } return { header, dataRows, numeric }; } function extractColumn(dataRows, col) { return dataRows.map(r => { const v = parseFloat(r[col]); return isFinite(v) ? v : NaN; }); } // ===================================================================== // Model: AR(p) with intercept, OLS fit with tiny ridge // ===================================================================== function fitAR(series, p) { const X = [], y = []; for (let t = p; t < series.length; t++) { if (!isFinite(series[t])) continue; const row = [1]; let ok = true; for (let k = 1; k <= p; k++) { const v = series[t - k]; if (!isFinite(v)) { ok = false; break; } row.push(v); } if (!ok) continue; X.push(row); y.push(series[t]); } if (X.length < p + 4) return null; const n = p + 1; const XtX = zeros(n, n), Xty = new Array(n).fill(0); for (let i = 0; i < X.length; i++) { for (let a = 0; a < n; a++) { for (let b = 0; b < n; b++) XtX[a][b] += X[i][a] * X[i][b]; Xty[a] += X[i][a] * y[i]; } } // Ridge on AR coefficients (not intercept) let trace = 0; for (let i = 0; i < n; i++) trace += XtX[i][i]; for (let i = 1; i < n; i++) XtX[i][i] += 1e-8 * trace; const beta = solveLinear(XtX, Xty); if (!beta) return null; const intercept = beta[0]; const coeffs = beta.slice(1); const roots = polyRoots(coeffs); return { intercept, coeffs, roots, nPoints: X.length }; } function findLastValidWindow(series, p) { for (let t = series.length - 1; t >= p - 1; t--) { let ok = true; for (let k = 0; k < p; k++) if (!isFinite(series[t - k])) { ok = false; break; } if (ok) return t; } return -1; } function runForecast(series, model, h) { const p = model.coeffs.length; const startT = findLastValidWindow(series, p); if (startT < 0) return null; const s = []; for (let k = 0; k < p; k++) s.push(series[startT - k]); const out = []; const work = s.slice(); for (let i = 0; i < h; i++) { let nx = model.intercept; for (let k = 0; k < p; k++) nx += model.coeffs[k] * work[k]; out.push(nx); work.unshift(nx); work.pop(); } return { forecast: out, startT, state: s }; } // Attribution of x_{T+h} into (F^h s)_k contributions + bias function attribution(model, stateVec, h) { const p = model.coeffs.length; const F = zeros(p, p); for (let j = 0; j < p; j++) F[0][j] = model.coeffs[j]; for (let i = 1; i < p; i++) F[i][i - 1] = 1; const Fh = matpow(F, h); const contributions = []; for (let k = 0; k < p; k++) contributions.push(Fh[0][k] * stateVec[k]); // bias = c * sum_{j=0}^{h-1} (F^j)[0][0] let sum00 = 0; let Fj = eye(p); for (let j = 0; j < h; j++) { sum00 += Fj[0][0]; Fj = matmul(Fj, F); } const bias = model.intercept * sum00; return { contributions, bias }; } // Route multiplicity: p-bonacci at distance d function routeCount(d, p) { if (d < 0) return 0; if (d === 0) return 1; const R = [1]; for (let i = 1; i <= d; i++) { let s = 0; for (let k = 1; k <= Math.min(p, i); k++) s += R[i - k]; R.push(s); } return R[d]; } function totalRoutes(h, p) { let s = 0; for (let k = 0; k < p; k++) s += routeCount(h + k, p); return s; } // ===================================================================== // Demo series // ===================================================================== function generateDemo(n = 220) { const x = [0, 0.4]; for (let t = 2; t < n; t++) { x.push(0.75 * x[t - 1] - 0.25 * x[t - 2] + 0.25 * (Math.random() - 0.5)); } // introduce some void gaps const gaps = [[28, 34], [72, 88], [130, 137], [180, 183]]; for (const [a, b] of gaps) for (let i = a; i <= b; i++) x[i] = NaN; return x; } // ===================================================================== // Drawing — main time series // ===================================================================== let viewScale = 1; // for potential future use function drawMain() { const W = mainCanvas.width, H = mainCanvas.height; const ctx = mainCtx; ctx.clearRect(0, 0, W, H); ctx.fillStyle = "#080810"; ctx.fillRect(0, 0, W, H); const series = state.series; if (!series || series.length === 0) return; const N = series.length; const fc = state.forecast ? state.forecast.forecast : []; const NF = fc.length; const pad = { l: 60, r: 24, t: 28, b: 36 }; const plotW = W - pad.l - pad.r; const plotH = H - pad.t - pad.b; // y range let ymin = Infinity, ymax = -Infinity; for (const v of series) if (isFinite(v)) { if (v < ymin) ymin = v; if (v > ymax) ymax = v; } for (const v of fc) { if (v < ymin) ymin = v; if (v > ymax) ymax = v; } if (!isFinite(ymin)) { ymin = 0; ymax = 1; } if (ymax - ymin < 1e-9) { ymax = ymin + 1; } const yPad = (ymax - ymin) * 0.1; ymin -= yPad; ymax += yPad; const xmax = Math.max(N - 1, 1) + NF; const xToPx = t => pad.l + (t / xmax) * plotW; const yToPx = v => pad.t + (1 - (v - ymin) / (ymax - ymin)) * plotH; // grid ctx.strokeStyle = COL.grid; ctx.lineWidth = 1; ctx.font = "10px ui-monospace, monospace"; ctx.fillStyle = "#666"; ctx.textAlign = "right"; ctx.textBaseline = "middle"; const nY = 5; for (let i = 0; i <= nY; i++) { const y = pad.t + (i / nY) * plotH; ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(W - pad.r, y); ctx.stroke(); const v = ymax - (i / nY) * (ymax - ymin); ctx.fillText(v.toFixed(2), pad.l - 6, y); } // gap bands let gapStart = -1; for (let i = 0; i <= N; i++) { const isGap = i < N && !isFinite(series[i]); if (isGap && gapStart < 0) gapStart = i; if (!isGap && gapStart >= 0) { const x0 = xToPx(gapStart - 0.5); const x1 = xToPx(i - 0.5); ctx.fillStyle = COL.gap; ctx.fillRect(x0, pad.t, x1 - x0, plotH); ctx.strokeStyle = "rgba(255, 85, 102, 0.35)"; ctx.setLineDash([3, 3]); ctx.beginPath(); ctx.moveTo(x0, pad.t); ctx.lineTo(x0, pad.t + plotH); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x1, pad.t); ctx.lineTo(x1, pad.t + plotH); ctx.stroke(); ctx.setLineDash([]); gapStart = -1; } } // forecast band if (NF > 0 && state.forecast) { const xStart = xToPx(state.forecast.startT + 0.5); const xEnd = xToPx(N - 0.5 + NF); ctx.fillStyle = "rgba(102, 204, 255, 0.05)"; ctx.fillRect(xStart, pad.t, xEnd - xStart, plotH); ctx.strokeStyle = "rgba(102, 204, 255, 0.25)"; ctx.setLineDash([3, 5]); ctx.beginPath(); ctx.moveTo(xStart, pad.t); ctx.lineTo(xStart, pad.t + plotH); ctx.stroke(); ctx.setLineDash([]); } // observed line (broken at gaps) ctx.strokeStyle = COL.obs; ctx.lineWidth = 1.6; ctx.beginPath(); let pen = false; for (let i = 0; i < N; i++) { if (isFinite(series[i])) { const px = xToPx(i), py = yToPx(series[i]); if (!pen) { ctx.moveTo(px, py); pen = true; } else ctx.lineTo(px, py); } else pen = false; } ctx.stroke(); // forecast dashed line, connected to last valid observed if (NF > 0 && state.forecast) { const T = state.forecast.startT; ctx.strokeStyle = COL.fc; ctx.setLineDash([5, 4]); ctx.lineWidth = 1.9; ctx.beginPath(); ctx.moveTo(xToPx(T), yToPx(series[T])); for (let i = 0; i < NF; i++) { ctx.lineTo(xToPx(N + i), yToPx(fc[i])); } ctx.stroke(); ctx.setLineDash([]); for (let i = 0; i < NF; i++) { ctx.fillStyle = COL.fc; ctx.beginPath(); ctx.arc(xToPx(N + i), yToPx(fc[i]), 2.4, 0, Math.PI * 2); ctx.fill(); } } // observed dots for (let i = 0; i < N; i++) { if (isFinite(series[i])) { ctx.fillStyle = COL.obs; ctx.beginPath(); ctx.arc(xToPx(i), yToPx(series[i]), 2.1, 0, Math.PI * 2); ctx.fill(); } } // hover overlay if (state.hoverIdx != null) { const t = state.hoverIdx; // vertical line ctx.strokeStyle = "rgba(255,255,255,0.18)"; ctx.setLineDash([2, 4]); ctx.beginPath(); ctx.moveTo(xToPx(t), pad.t); ctx.lineTo(xToPx(t), pad.t + plotH); ctx.stroke(); ctx.setLineDash([]); // If hovering a forecast point, draw contribution arcs if (state.forecast && t >= N && t < N + NF && state.model) { const h = t - N + 1; const attr = attribution(state.model, state.forecast.state, h); const T = state.forecast.startT; const total = fc[h - 1]; const denom = Math.max(Math.abs(total), 1e-9); for (let k = 0; k < attr.contributions.length; k++) { const srcT = T - k; if (srcT < 0 || !isFinite(series[srcT])) continue; const c = attr.contributions[k]; const w = Math.abs(c) / denom; const alpha = Math.min(0.85, 0.15 + w * 1.2); const color = c >= 0 ? `rgba(108, 220, 120, ${alpha})` : `rgba(255, 110, 130, ${alpha})`; ctx.strokeStyle = color; ctx.lineWidth = Math.max(1, Math.min(4.5, 0.5 + w * 5)); const x0 = xToPx(srcT), y0 = yToPx(series[srcT]); const x1 = xToPx(t), y1 = yToPx(fc[h - 1]); const mx = (x0 + x1) / 2; const my = Math.min(y0, y1) - 30 - 8 * k; ctx.beginPath(); ctx.moveTo(x0, y0); ctx.quadraticCurveTo(mx, my, x1, y1); ctx.stroke(); } // ring around hovered forecast ctx.strokeStyle = "#6cf"; ctx.lineWidth = 1.6; ctx.beginPath(); ctx.arc(xToPx(t), yToPx(fc[h - 1]), 6, 0, Math.PI * 2); ctx.stroke(); } else if (t < N && isFinite(series[t])) { ctx.strokeStyle = "#ffffff"; ctx.lineWidth = 1.6; ctx.beginPath(); ctx.arc(xToPx(t), yToPx(series[t]), 5, 0, Math.PI * 2); ctx.stroke(); } else if (t < N) { // hovering a gap: mark void ctx.fillStyle = "#ff5566"; ctx.font = "10px ui-monospace, monospace"; ctx.textAlign = "center"; ctx.textBaseline = "bottom"; ctx.fillText("void", xToPx(t), pad.t + plotH - 4); } } // axis labels ctx.fillStyle = "#888"; ctx.font = "11px ui-monospace, monospace"; ctx.textAlign = "center"; ctx.textBaseline = "top"; ctx.fillText("t", pad.l + plotW / 2, H - 18); ctx.save(); ctx.translate(14, pad.t + plotH / 2); ctx.rotate(-Math.PI / 2); ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = "#888"; ctx.fillText("x_t", 0, 0); ctx.restore(); } // ===================================================================== // Drawing — attribution bars // ===================================================================== function drawAttribution() { const W = attrCanvas.width, H = attrCanvas.height; const ctx = attrCtx; ctx.clearRect(0, 0, W, H); ctx.fillStyle = "#0c0c16"; ctx.fillRect(0, 0, W, H); const N = state.series.length; const t = state.hoverIdx; if (t == null || !state.forecast || t < N) { ctx.fillStyle = "#555"; ctx.font = "13px ui-monospace, monospace"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText("Hover a forecast point", W / 2, H / 2 - 8); ctx.fillStyle = "#333"; ctx.font = "11px ui-monospace, monospace"; ctx.fillText("(dashed cyan region)", W / 2, H / 2 + 12); return; } const h = t - N + 1; const NF = state.forecast.forecast.length; if (h < 1 || h > NF) return; const attr = attribution(state.model, state.forecast.state, h); const total = state.forecast.forecast[h - 1]; const T = state.forecast.startT; const items = []; for (let k = 0; k < attr.contributions.length; k++) { items.push({ label: `a${k + 1}·x[${T - k}]`, value: attr.contributions[k], color: attr.contributions[k] >= 0 ? COL.pos : COL.neg, }); } if (Math.abs(attr.bias) > 1e-12 || true) { items.push({ label: "intercept", value: attr.bias, color: attr.bias >= 0 ? COL.pos : COL.neg, }); } const pad = { l: 110, r: 56, t: 44, b: 22 }; const plotW = W - pad.l - pad.r; const plotH = H - pad.t - pad.b; // scale let maxAbs = Math.abs(total); for (const it of items) maxAbs = Math.max(maxAbs, Math.abs(it.value)); if (maxAbs < 1e-9) maxAbs = 1; const spanW = plotW / 2; const xZero = pad.l + plotW / 2; const xOf = v => xZero + (v / maxAbs) * spanW; // header label ctx.fillStyle = "#888"; ctx.font = "11px ui-monospace, monospace"; ctx.textAlign = "left"; ctx.textBaseline = "top"; ctx.fillText(`forecast step h = ${h} (t = ${t})`, pad.l, 12); ctx.textAlign = "right"; ctx.fillStyle = COL.fc; ctx.font = "bold 13px ui-monospace, monospace"; ctx.fillText(`x̂ = ${total.toFixed(4)}`, W - pad.r, 10); // zero axis ctx.strokeStyle = "#333"; ctx.beginPath(); ctx.moveTo(xZero, pad.t); ctx.lineTo(xZero, pad.t + plotH); ctx.stroke(); // grid lines ctx.strokeStyle = "#181822"; for (let i = 1; i <= 2; i++) { const xp = xZero + (i / 2) * spanW; const xn = xZero - (i / 2) * spanW; ctx.beginPath(); ctx.moveTo(xp, pad.t); ctx.lineTo(xp, pad.t + plotH); ctx.stroke(); ctx.beginPath(); ctx.moveTo(xn, pad.t); ctx.lineTo(xn, pad.t + plotH); ctx.stroke(); } // bars const rowH = Math.min(30, (plotH - 12) / items.length); const gap = 4; ctx.font = "11px ui-monospace, monospace"; for (let i = 0; i < items.length; i++) { const it = items[i]; const y = pad.t + i * (rowH + gap); // label ctx.fillStyle = "#aaa"; ctx.textAlign = "right"; ctx.textBaseline = "middle"; ctx.fillText(it.label, pad.l - 8, y + rowH / 2); // bar const x0 = xZero; const x1 = xOf(it.value); ctx.fillStyle = it.color; ctx.fillRect(Math.min(x0, x1), y + 3, Math.abs(x1 - x0) || 1, rowH - 6); // value ctx.fillStyle = "#ddd"; ctx.textAlign = "left"; ctx.textBaseline = "middle"; const labelX = it.value >= 0 ? x1 + 6 : x1 - 6; ctx.textAlign = it.value >= 0 ? "left" : "right"; ctx.fillText(it.value.toFixed(3), labelX, y + rowH / 2); } // total indicator bar (below) const yTotal = pad.t + items.length * (rowH + gap) + 6; if (yTotal < H - 6) { ctx.strokeStyle = COL.fc; ctx.lineWidth = 1.4; ctx.beginPath(); ctx.moveTo(xZero, yTotal); ctx.lineTo(xOf(total), yTotal); ctx.stroke(); ctx.fillStyle = COL.fc; ctx.beginPath(); ctx.arc(xOf(total), yTotal, 3.5, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = "#666"; ctx.font = "10px ui-monospace, monospace"; ctx.textAlign = "left"; ctx.textBaseline = "middle"; ctx.fillText("total", xZero + 6, yTotal); } } // ===================================================================== // Drawing — spectrum // ===================================================================== function drawSpectrum() { const W = specCanvas.width, H = specCanvas.height; const ctx = specCtx; ctx.clearRect(0, 0, W, H); ctx.fillStyle = "#0c0c16"; ctx.fillRect(0, 0, W, H); if (!state.model) { ctx.fillStyle = "#555"; ctx.font = "13px ui-monospace, monospace"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText("no model", W / 2, H / 2); return; } const roots = state.model.roots; let maxR = 1.5; for (const r of roots) maxR = Math.max(maxR, Math.hypot(r.re, r.im) * 1.2); const cx0 = W / 2; const cy0 = H / 2; const scale = Math.min(W, H) / (2.4 * maxR); // unit circle ctx.strokeStyle = "rgba(102, 204, 255, 0.35)"; ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(cx0, cy0, scale, 0, Math.PI * 2); ctx.stroke(); // axes ctx.strokeStyle = "#1a1a2a"; ctx.beginPath(); ctx.moveTo(cx0 - W / 2, cy0); ctx.lineTo(cx0 + W / 2, cy0); ctx.moveTo(cx0, cy0 - H / 2); ctx.lineTo(cx0, cy0 + H / 2); ctx.stroke(); // roots for (const r of roots) { const px = cx0 + r.re * scale; const py = cy0 - r.im * scale; const mag = Math.hypot(r.re, r.im); let color, glow; if (mag > 1.005) { color = "#ff5566"; glow = "rgba(255,85,102,0.35)"; } else if (mag > 0.995) { color = "#ffcc44"; glow = "rgba(255,204,68,0.35)"; } else { color = "#6cf"; glow = "rgba(102,204,255,0.35)"; } // glow ctx.fillStyle = glow; ctx.beginPath(); ctx.arc(px, py, 11, 0, Math.PI * 2); ctx.fill(); // dot ctx.fillStyle = color; ctx.beginPath(); ctx.arc(px, py, 5, 0, Math.PI * 2); ctx.fill(); ctx.strokeStyle = "#fff"; ctx.lineWidth = 0.8; ctx.stroke(); } // text ctx.font = "10.5px ui-monospace, monospace"; ctx.textAlign = "left"; ctx.textBaseline = "top"; ctx.fillStyle = "#888"; ctx.fillText(`roots of z^${roots.length} − Σ aₖ z^${roots.length}⁻ᵏ = 0`, 8, 8); // legend ctx.textBaseline = "bottom"; ctx.fillStyle = "#6cf"; ctx.fillText("● |λ| < 1 damped — arrow of time", 8, H - 26); ctx.fillStyle = "#ffcc44"; ctx.fillText("● |λ| = 1 inertia — void", 8, H - 12); // spectral summary const inUnit = roots.filter(r => Math.hypot(r.re, r.im) < 0.995).length; const onUnit = roots.filter(r => Math.abs(Math.hypot(r.re, r.im) - 1) <= 0.005).length; const outUnit = roots.length - inUnit - onUnit; ctx.fillStyle = "#888"; ctx.textAlign = "right"; ctx.textBaseline = "top"; ctx.fillText(`in ${inUnit} · on ${onUnit} · out ${outUnit}`, W - 8, 8); } // ===================================================================== // Explanation panel // ===================================================================== function fmt(x, d = 4) { if (!isFinite(x)) return "—"; if (Math.abs(x) < 1e-9) return "0"; if (Math.abs(x) >= 1e6 || (Math.abs(x) < 1e-4 && x !== 0)) return x.toExponential(2); return x.toFixed(d); } function fmtC(z) { const re = fmt(z.re); const im = fmt(Math.abs(z.im)); const sign = z.im >= 0 ? "+" : "−"; return `${re} ${sign} ${im}i`; } function updateExplanation() { if (!state.model) { explanationEl.innerHTML = '<p style="color:var(--dim)">Load a CSV or use the demo to begin.</p>'; return; } const N = state.series.length; const t = state.hoverIdx; const p = state.model.coeffs.length; let html = ""; if (t == null) { html += `<h3>Model: AR(${p})</h3>`; html += `<p>Fit on <b>${state.model.nPoints}</b> valid lag-windows.</p>`; html += `<p>`; html += `c = ${fmt(state.model.intercept)}<br>`; for (let k = 0; k < p; k++) html += `a<sub>${k + 1}</sub> = ${fmt(state.model.coeffs[k])}<br>`; html += `</p>`; const r = state.model.roots; html += `<p style="color:var(--dim)">`; html += `Spectrum: ` + r.map(z => `|λ| = ${Math.hypot(z.re, z.im).toFixed(3)}`).join(", "); html += `</p>`; html += `<div class="note">Hover over the plot. If you hover a <b>forecast</b> point, this panel shows how the leap <code>F<sup>h</sup> s<sub>t</sub></code> decomposes into contributions from each clamped past value — the route sum is the answer, the routes themselves are the opaque residue.</div>`; } else if (t < N) { const v = state.series[t]; if (!isFinite(v)) { html += `<h3>t = ${t} — void</h3>`; html += `<div class="verdict bad">VOID — no observation here</div>`; html += `<p>This time is a <b>free boundary</b>. Under ⊗-resolution the void acts as identity transport: the state coasts through without damping or driving. No force is applied.</p>`; html += `<div class="note">A zero fill here would be an <em>absorbing wall</em>, not a gap. The void is the unique imputation whose contamination spectrum sits on the unit circle.</div>`; } else { html += `<h3>t = ${t} — observed</h3>`; html += `<div class="verdict good">x<sub>t</sub> = ${fmt(v)}</div>`; html += `<p>This point is a <b>clamp row</b> in the spacetime system: it pins the particle exactly here. Every clamp is a Dirichlet boundary condition.</p>`; } } else { const h = t - N + 1; const fc = state.forecast.forecast[h - 1]; const attr = attribution(state.model, state.forecast.state, h); const T = state.forecast.startT; html += `<h3>Forecast at t = ${t} (step h = ${h})</h3>`; html += `<div class="verdict good">x̂<sub>${t}</sub> = <b>${fmt(fc)}</b></div>`; html += `<p>Decomposition via <code>F<sup>${h}</sup> · s<sub>${T}</sub></code>:</p>`; html += `<table>`; html += `<tr><th>source</th><th>x</th><th>weight</th><th>contribution</th></tr>`; let sumCheck = 0; for (let k = 0; k < attr.contributions.length; k++) { const srcT = T - k; const x = state.series[srcT]; const c = attr.contributions[k]; sumCheck += c; const w = x !== 0 ? c / x : NaN; html += `<tr><td>x[${srcT}]</td><td>${fmt(x, 3)}</td><td>${fmt(w, 4)}</td><td>${fmt(c, 4)}</td></tr>`; } html += `<tr><td>intercept</td><td>—</td><td>—</td><td>${fmt(attr.bias, 4)}</td></tr>`; html += `<tr style="border-top:2px solid #2a2a3a"><td>Σ</td><td></td><td></td><td><b>${fmt(sumCheck + attr.bias)}</b></td></tr>`; html += `</table>`; const routes = totalRoutes(h, p); html += `<p style="color:var(--dim)">Causal route multiplicity: <b>${routes}</b> distinct lag-paths connect the past window to this forecast. The leap <code>F<sup>h</sup></code> sums them all; the individual routes are not recoverable from the sum — this is the <em>opaque residue 𝒪</em>.</p>`; // arrow-of-time note based on spectrum const roots = state.model.roots; const anyDamped = roots.some(r => Math.hypot(r.re, r.im) < 0.995); const anyVoid = roots.some(r => Math.abs(Math.hypot(r.re, r.im) - 1) < 0.005); if (anyDamped && !anyVoid) { html += `<div class="note"><b>Arrow of time present.</b> The spectrum has damped roots, so retrodiction amplifies noise as <code>|λ|<sup>−h</sup></code>. Information is destroyed going forward; the particle relaxes toward the fixed point.</div>`; } else if (anyVoid && !anyDamped) { html += `<div class="note"><b>Pure inertia.</b> All roots sit on the unit circle. The forecast is a bounded oscillation — modulus is conserved, only phase drifts. Retrodiction is exact in principle.</div>`; } else if (anyDamped && anyVoid) { html += `<div class="note"><b>Mixed spectrum.</b> Some directions damp (arrow of time) and some coast (void). Forward predictability is high; backward predictability splits by direction.</div>`; } } explanationEl.innerHTML = html; } // ===================================================================== // Main interaction // ===================================================================== function redraw() { drawMain(); drawAttribution(); drawSpectrum(); updateExplanation(); } function rebuildModel() { if (!state.series || !state.series.length) return; const p = state.p; const model = fitAR(state.series, p); state.model = model; if (model) { state.forecast = runForecast(state.series, model, state.horizon); } else { state.forecast = null; } redraw(); } mainCanvas.addEventListener("mousemove", e => { if (!state.series || !state.series.length) return; const rect = mainCanvas.getBoundingClientRect(); const px = (e.clientX - rect.left) / rect.width * mainCanvas.width; const W = mainCanvas.width; const pad = { l: 60, r: 24, t: 28, b: 36 }; const plotW = W - pad.l - pad.r; const N = state.series.length; const NF = state.forecast ? state.forecast.forecast.length : 0; const xmax = Math.max(N - 1, 1) + NF; // inverse of xToPx const tFrac = (px - pad.l) / plotW; let t = Math.round(tFrac * xmax); t = Math.max(0, Math.min(N - 1 + NF, t)); if (t !== state.hoverIdx) { state.hoverIdx = t; redraw(); } }); mainCanvas.addEventListener("mouseleave", () => { state.hoverIdx = null; redraw(); }); // ===================================================================== // Controls // ===================================================================== const fileInput = document.getElementById("fileInput"); const colSelect = document.getElementById("colSelect"); const pSlider = document.getElementById("pSlider"); const hSlider = document.getElementById("hSlider"); const pVal = document.getElementById("pVal"); const hVal = document.getElementById("hVal"); function loadCSVText(text) { const rows = parseCSV(text); if (!rows || rows.length < 3) { alert("CSV too short or empty."); return; } const info = analyzeColumns(rows); if (!info || info.numeric.length === 0) { alert("No numeric column detected."); return; } state.header = info.header; state.dataRows = info.dataRows; state.numericCols = info.numeric; colSelect.innerHTML = ""; for (const j of info.numeric) { const opt = document.createElement("option"); opt.value = j; opt.textContent = info.header[j] || `col${j + 1}`; colSelect.appendChild(opt); } state.selectedCol = info.numeric[info.numeric.length - 1]; colSelect.value = state.selectedCol; applyColumn(); } function applyColumn() { const col = parseInt(colSelect.value, 10); state.selectedCol = col; state.series = extractColumn(state.dataRows, col); // cap length for perf const MAX = 4000; if (state.series.length > MAX) { const step = Math.ceil(state.series.length / MAX); state.series = state.series.filter((_, i) => i % step === 0); } state.hoverIdx = null; rebuildModel(); } fileInput.addEventListener("change", e => { const f = e.target.files[0]; if (!f) return; const reader = new FileReader(); reader.onload = ev => loadCSVText(ev.target.result); reader.readAsText(f); }); colSelect.addEventListener("change", applyColumn); pSlider.addEventListener("input", () => { state.p = parseInt(pSlider.value, 10); pVal.textContent = state.p; rebuildModel(); }); hSlider.addEventListener("input", () => { state.horizon = parseInt(hSlider.value, 10); hVal.textContent = state.horizon; rebuildModel(); }); // Drag & drop ["dragenter", "dragover"].forEach(ev => window.addEventListener(ev, e => { e.preventDefault(); }) ); window.addEventListener("drop", e => { e.preventDefault(); const f = e.dataTransfer.files[0]; if (!f) return; const reader = new FileReader(); reader.onload = ev => loadCSVText(ev.target.result); reader.readAsText(f); }); // ===================================================================== // Boot // ===================================================================== function bootWithDemo() { state.series = generateDemo(220); state.header = ["t", "demo"]; state.numericCols = [1]; colSelect.innerHTML = '<option value="1">demo AR(2)</option>'; state.selectedCol = 1; state.p = 2; state.horizon = 25; pSlider.value = 2; pVal.textContent = "2"; hSlider.value = 25; hVal.textContent = "25"; rebuildModel(); } bootWithDemo(); </script> </body> </html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Why is this forecast this value? — AR decomposition explorer</title>
<style>
:root {
--bg: #0a0a12;
--panel: #12121e;
--border: #2a2a3a;
--text: #e8e8f0;
--dim: #8888a0;
--accent: #6cf;
--good: #6cdc78;
--bad: #ff5566;
--obs: #7ab8ff;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: ui-sans-serif, system-ui, -apple-system, sans-serif;
font-size: 14px;
line-height: 1.55;
}
header {
padding: 18px 24px;
border-bottom: 1px solid var(--border);
}
header h1 {
margin: 0 0 4px;
font-size: 18px;
font-weight: 600;
}
header p {
margin: 0;
color: var(--dim);
font-size: 13px;
max-width: 900px;
}
header code {
background: #1e1e2e;
padding: 1px 5px;
border-radius: 3px;
font-size: 12px;
}
main {
display: grid;
grid-template-columns: minmax(0, 1.55fr) minmax(0, 1fr);
gap: 16px;
padding: 16px;
max-width: 1600px;
margin: 0 auto;
}
@media (max-width: 1100px) {
main { grid-template-columns: 1fr; }
}
.col { display: flex; flex-direction: column; gap: 16px; }
.panel {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
overflow: hidden;
}
.panel-header {
padding: 10px 14px;
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.panel-header h2 {
margin: 0;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--dim);
}
.controls {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
font-size: 12px;
}
.controls label {
display: flex;
align-items: center;
gap: 5px;
color: var(--dim);
}
.controls input[type=range] {
width: 80px;
accent-color: var(--accent);
}