SPB Git

Repository Public

sim.kinds.test.ts 27.4 KB 422 lines typescript

1import { describe, expect, it } from "vitest";2import { SIM_KINDS, type SimKind } from "@/schema";3import { normalCdf, studentTQuantile } from "@/sim/core";4import { paramDefs, resolveParams, SIMULATIONS, snapParam, validateSimulation, describeParams, type SimBlock } from "@/sim/registry";5import { computeMoe } from "@/sim/kinds/moe-routing";6import { activate, computeNeural } from "@/sim/kinds/neural-forward";7import { computeKv } from "@/sim/kinds/kv-cache";8import { computeAttention } from "@/sim/kinds/attention";9import { computeDistribution } from "@/sim/kinds/distribution";10import { simulateIntervals } from "@/sim/kinds/confidence-interval";11import { computeRegression } from "@/sim/kinds/regression";12import { computeCorrelation } from "@/sim/kinds/correlation";13import { computeGarch } from "@/sim/kinds/garch";14import { computeWalk, walkMoments, WALK_STEPS } from "@/sim/kinds/random-walk";15import { computeIrf } from "@/sim/kinds/impulse-response";16import { computeEventStudy } from "@/sim/kinds/event-study";17import { computeFunctionPlot, functionPlotParams } from "@/sim/kinds/function-plot";1819const block = (kind: SimKind, params: Record<string, number> = {}, config: SimBlock["config"] = {}, seed = 1): SimBlock =>20  ({ id: "s1", type: "simulation", span: 12, kind, params, seed, config });21const total = (xs: number[]) => xs.reduce((a, b) => a + b, 0);22const EXAMPLE_CONFIG: Partial<Record<SimKind, SimBlock["config"]>> = { "function-plot": { expr: "a * sin(w * x)" } };2324describe("registry", () => {25  it("defines every kind of the schema, with bilingual labels and 2–5 sliders", () => {26    expect(Object.keys(SIMULATIONS).sort()).toEqual([...SIM_KINDS].sort());27    for (const kind of SIM_KINDS) {28      const def = SIMULATIONS[kind];29      expect(def.kind).toBe(kind);30      for (const l of ["fr", "en"] as const) { expect(def.title[l].length).toBeGreaterThan(3); expect(def.description[l].length).toBeGreaterThan(40); }31      const defs = paramDefs(kind, EXAMPLE_CONFIG[kind] ?? {});32      expect(defs.length).toBeGreaterThanOrEqual(2); expect(defs.length).toBeLessThanOrEqual(5);33      expect(new Set(defs.map((d) => d.key)).size).toBe(defs.length);34      for (const d of defs) {35        expect(d.key).toMatch(/^[a-zA-Z][a-zA-Z0-9]{0,23}$/);36        expect(d.min).toBeLessThan(d.max); expect(d.step).toBeGreaterThan(0);37        expect(d.default).toBeGreaterThanOrEqual(d.min); expect(d.default).toBeLessThanOrEqual(d.max);38        expect(snapParam(d, d.default)).toBeCloseTo(d.default, 9);39        expect(d.label.fr && d.label.en).toBeTruthy();40      }41    }42  });43  it("every compute is deterministic, sensitive to the seed when stochastic, and fast at the upper bounds", () => {44    for (const kind of SIM_KINDS) {45      const def = SIMULATIONS[kind], config = EXAMPLE_CONFIG[kind] ?? {};46      const p = resolveParams(block(kind, {}, config));47      const a = JSON.stringify(def.compute(p, 5, config));48      expect(JSON.stringify(def.compute(p, 5, config))).toBe(a);49      if (def.stochastic) expect(JSON.stringify(def.compute(p, 6, config))).not.toBe(a);50      else expect(JSON.stringify(def.compute(p, 6, config))).toBe(a);51      const top = Object.fromEntries(paramDefs(kind, config).map((d) => [d.key, d.max]));52      def.compute(top, 1, config);53      const t0 = performance.now();54      for (let i = 0; i < 5; i++) def.compute(top, i, config);55      expect((performance.now() - t0) / 5).toBeLessThan(20);56      const bottom = Object.fromEntries(paramDefs(kind, config).map((d) => [d.key, d.min]));57      expect(() => def.compute(bottom, 1, config)).not.toThrow();58    }59  });60  it("resolveParams fills defaults, clamps and rounds to the step", () => {61    expect(resolveParams(block("moe-routing"))).toEqual({ experts: 6, topK: 2, tokens: 8, temperature: 1 });62    const r = resolveParams(block("moe-routing", { experts: 99, topK: -3, temperature: 0.1234, bogus: 4 }));63    expect(r).toEqual({ experts: 8, topK: 1, tokens: 8, temperature: 0.1 });64    expect(resolveParams(block("garch", { alpha: 0.123456, n: 333 }))).toMatchObject({ alpha: 0.12, n: 350 });65    expect(resolveParams(block("regression", { slope: Number.NaN })).slope).toBe(1.5);66    expect(resolveParams({ kind: "confidence-interval", params: { level: 2 } }).level).toBe(0.99);67    expect(resolveParams(block("distribution", { df: 3.4 }, { family: "student" }))).toEqual({ df: 3, a: -2, b: 2 });68    expect(resolveParams(block("function-plot", { a: 50 }, { expr: "a*x", aMax: 10 }))).toEqual({ a: 10 });69  });70  it("validateSimulation reports unknown keys, out-of-range values and config errors", () => {71    for (const kind of SIM_KINDS) expect(validateSimulation(block(kind, {}, EXAMPLE_CONFIG[kind] ?? {}))).toEqual([]);72    expect(validateSimulation(block("garch", { gamma: 1 }))[0]).toMatch(/params\.gamma: unknown parameter.*omega, alpha, beta, n/);73    expect(validateSimulation(block("garch", { alpha: 3 }))[0]).toMatch(/params\.alpha = 3 is outside 0 … 0\.5/);74    expect(validateSimulation(block("garch", {}, { foo: 1 }))[0]).toMatch(/config\.foo: unknown option/);75    expect(validateSimulation(block("neural-forward", {}, { activation: "gelu" }))[0]).toMatch(/config\.activation: expected one of tanh, relu, sigmoid/);76    expect(validateSimulation(block("distribution", {}, { family: "poisson" }))[0]).toMatch(/config\.family/);77    expect(validateSimulation(block("random-walk", { reversion: 1 }, { process: "gbm" }))[0]).toMatch(/params\.reversion: unknown parameter/);78    expect(validateSimulation(block("random-walk", { reversion: 1 }, { process: "ou" }))).toEqual([]);79    expect(validateSimulation(block("attention", {}, { tokens: "a,b,c,d,e,f,g,h,i,j,k" }))[0]).toMatch(/at most 10 tokens/);80    expect(validateSimulation(block("event-study", {}, { window: 50 }))[0]).toMatch(/config\.window/);81    expect(validateSimulation(block("impulse-response", {}, { shock: 3 }))[0]).toMatch(/config\.shock/);82    expect(validateSimulation(block("function-plot"))[0]).toMatch(/config\.expr is required/);83    expect(validateSimulation(block("function-plot", {}, { expr: "x.constructor" }))[0]).toMatch(/config\.expr: .*(property access|not allowed)/);84    expect(validateSimulation(block("function-plot", {}, { expr: "sin(x", expr2: "foo(x)" }))).toHaveLength(2);85    expect(validateSimulation(block("function-plot", {}, { expr: "a*x", bMin: 0 }))[0]).toMatch(/config\.bMin: unknown option/);86    expect(validateSimulation(block("function-plot", { b: 1 }, { expr: "a*x" }))[0]).toMatch(/params\.b: unknown parameter/);87    expect(validateSimulation(block("function-plot", {}, { expr: "a+b+c+d+f+g+x" }))[0]).toMatch(/too many parameters/);88    expect(validateSimulation({ ...block("garch"), kind: "nope" } as unknown as SimBlock)[0]).toMatch(/unknown simulation kind/);89  });90  it("describes parameters in one line", () => {91    expect(describeParams(block("correlation", { rho: 0.5 }), "fr")).toBe("Corrélation vraie ρ = 0,5 ; Observations n = 150");92    expect(describeParams(block("correlation", { rho: 0.5 }), "en")).toBe("True correlation ρ = 0.5; Observations n = 150");93  });94});9596describe("moe-routing", () => {97  it("gate sums to 1, exactly k experts are selected, weights are renormalised", () => {98    for (const [experts, topK] of [[2, 1], [4, 2], [6, 3], [8, 8], [8, 1]]) {99      const m = computeMoe({ experts, topK, tokens: 12, temperature: 0.7 }, 3);100      expect(m.tokens).toHaveLength(12);101      m.gate.forEach((g, t) => {102        expect(g).toHaveLength(experts);103        expect(total(g)).toBeCloseTo(1, 12);104        expect(m.selected[t]).toHaveLength(topK);105        expect(new Set(m.selected[t]).size).toBe(topK);106        expect(total(m.weights[t])).toBeCloseTo(1, 12);107        expect(m.weights[t].filter((w) => w > 0)).toHaveLength(topK);108        const worstKept = Math.min(...m.selected[t].map((e) => g[e]));109        g.forEach((p, e) => { if (!m.selected[t].includes(e)) { expect(p).toBeLessThanOrEqual(worstKept); expect(m.weights[t][e]).toBe(0); } });110        for (const e of m.selected[t]) expect(m.weights[t][e]).toBeCloseTo(g[e] / m.kept[t], 12);111        expect(total(m.loadCum[t])).toBe((t + 1) * topK);112      });113    }114  });115  it("caps k at N, and temperature controls the sharpness of the gate", () => {116    expect(computeMoe({ experts: 3, topK: 8, tokens: 4, temperature: 1 }, 1).k).toBe(3);117    const cold = computeMoe({ experts: 6, topK: 2, tokens: 12, temperature: 0.1 }, 1), hot = computeMoe({ experts: 6, topK: 2, tokens: 12, temperature: 3 }, 1);118    expect(total(cold.entropy)).toBeLessThan(total(hot.entropy));119    expect(cold.logits).toEqual(hot.logits); // temperature rescales the same logits120    expect(computeMoe({ experts: 4, topK: 4, tokens: 8, temperature: 1 }, 9).imbalance).toBe(1);121  });122});123124describe("neural-forward", () => {125  it("each activation is f(Σ w·a + b); the output layer is linear", () => {126    for (const activation of ["tanh", "relu", "sigmoid"] as const) {127      const m = computeNeural({ layers: 3, width: 5, inputs: 4, scale: 1.5 }, 2, { activation });128      expect(m.sizes).toEqual([4, 5, 5, 5, 2]);129      for (let l = 1; l < m.sizes.length; l++) for (let j = 0; j < m.sizes[l]; j++) {130        const z = m.weights[l - 1][j].reduce((s, w, i) => s + w * m.a[l - 1][i], m.biases[l - 1][j]);131        expect(m.z[l][j]).toBeCloseTo(z, 12);132        expect(m.a[l][j]).toBeCloseTo(l === m.sizes.length - 1 ? z : activate(activation, z), 12);133      }134      const hidden = m.a.slice(1, -1).flat();135      if (activation === "relu") expect(hidden.every((v) => v >= 0)).toBe(true);136      if (activation === "tanh") expect(hidden.every((v) => v > -1 && v < 1)).toBe(true);137      if (activation === "sigmoid") expect(hidden.every((v) => v > 0 && v < 1)).toBe(true);138      expect(m.a[0].every((v) => v >= -1 && v < 1)).toBe(true);139    }140    expect(activate("relu", -2)).toBe(0); expect(activate("sigmoid", 0)).toBe(0.5); expect(activate("tanh", 0)).toBe(0);141  });142});143144describe("kv-cache", () => {145  it("matches the hand count for a prompt of 4 and 8 generated tokens", () => {146    const m = computeKv({ prompt: 4, newTokens: 8, layers: 1 });147    // contexts n = 4…11 ; without cache Σ n(n+1)/2 = 10+15+21+28+36+45+55+66 = 276 ; with cache 10 + (5+…+11) = 66148    expect(m.cumPlainScores.at(-1)).toBe(276);149    expect(m.cumCacheScores.at(-1)).toBe(66);150    expect(m.cumPlainKv.at(-1)).toBe(60); // 4+5+…+11151    expect(m.cumCacheKv.at(-1)).toBe(11); // 4 for the prompt, then one per step152    expect(m.steps[0]).toEqual({ n: 4, plainKv: 4, plainScores: 10, cacheKv: 4, cacheReused: 0, cacheScores: 10 });153    expect(m.steps[3]).toEqual({ n: 7, plainKv: 7, plainScores: 28, cacheKv: 1, cacheReused: 6, cacheScores: 7 });154  });155  it("matches the closed forms for any size, and scales with the number of layers", () => {156    for (const [P, G, L] of [[1, 2, 1], [8, 16, 12], [3, 5, 2]]) {157      const m = computeKv({ prompt: P, newTokens: G, layers: L });158      const N = P + G - 1;159      const tetra = (n: number) => (n * (n + 1) * (n + 2)) / 6; // Σ_{i≤n} i(i+1)/2160      expect(m.cumPlainScores.at(-1)).toBe(L * (tetra(N) - tetra(P - 1)));161      expect(m.cumCacheScores.at(-1)).toBe(L * ((P * (P + 1)) / 2 + (N * (N + 1)) / 2 - (P * (P + 1)) / 2));162      expect(m.cumCacheKv.at(-1)).toBe(L * N);163      for (const s of m.steps) { expect(s.cacheKv + s.cacheReused).toBe(L * s.n); expect(s.plainScores).toBeGreaterThanOrEqual(s.cacheScores); }164    }165  });166});167168describe("attention", () => {169  it("rows sum to 1 and weights are probabilities", () => {170    const configs: SimBlock["config"][] = [{}, { locale: "en" }, { tokens: "a,b,c,d,e,f,g,h,i,j" }, { causal: true }];171    for (const config of configs) {172      const m = computeAttention({ temperature: 0.7, dim: 16, locality: 0.5 }, 4, config);173      expect(m.weights).toHaveLength(m.tokens.length);174      for (const row of m.weights) { expect(total(row)).toBeCloseTo(1, 12); expect(row.every((w) => w >= 0 && w <= 1)).toBe(true); }175    }176  });177  it("uses the tokens of the config, the locale default otherwise, at most 10", () => {178    expect(computeAttention({ temperature: 1, dim: 8, locality: 0 }, 1, {}).tokens).toEqual(["le", "chat", "dort", "sur", "le", "tapis"]);179    expect(computeAttention({ temperature: 1, dim: 8, locality: 0 }, 1, { locale: "en" }).tokens).toEqual(["the", "cat", "sleeps", "on", "the", "mat"]);180    expect(computeAttention({ temperature: 1, dim: 8, locality: 0 }, 1, { tokens: " a, b ,,c " }).tokens).toEqual(["a", "b", "c"]);181    expect(computeAttention({ temperature: 1, dim: 8, locality: 0 }, 1, { tokens: "a,b,c,d,e,f,g,h,i,j,k,l" }).tokens).toHaveLength(10);182  });183  it("causal mask zeroes the future; temperature and locality act as documented", () => {184    const c = computeAttention({ temperature: 1, dim: 8, locality: 0 }, 1, { causal: true });185    c.weights.forEach((row, i) => row.forEach((w, j) => { if (j > i) expect(w).toBe(0); }));186    expect(c.weights[0][0]).toBe(1);187    const sharp = computeAttention({ temperature: 0.1, dim: 16, locality: 0 }, 1, {}), flat = computeAttention({ temperature: 5, dim: 16, locality: 0 }, 1, {});188    expect(sharp.meanEntropy).toBeLessThan(flat.meanEntropy);189    const local = computeAttention({ temperature: 1, dim: 16, locality: 3 }, 1, {}), free = computeAttention({ temperature: 1, dim: 16, locality: 0 }, 1, {});190    expect(local.selfWeight).toBeGreaterThan(free.selfWeight);191  });192});193194describe("distribution", () => {195  it("normal interval probability matches Φ", () => {196    const m = computeDistribution({ mu: 0, sigma: 1, a: -1.96, b: 1.96 }, {});197    expect(m.probability).toBeCloseTo(0.950004209703559, 12);198    const g = computeDistribution({ mu: 1, sigma: 2, a: 0, b: 3 }, { family: "normal" });199    expect(g.probability).toBeCloseTo(normalCdf(1) - normalCdf(-0.5), 14);200    expect(g.mean).toBe(1); expect(g.sd).toBe(2);201    expect(computeDistribution({ mu: 0, sigma: 1, a: 1, b: -1 }, {}).probability).toBeCloseTo(0.6826894921370859, 12); // bounds are ordered202  });203  it("other families use their closed-form distribution function", () => {204    expect(computeDistribution({ df: 1, a: -1, b: 1 }, { family: "student" }).probability).toBeCloseTo(0.5, 12);205    const t = computeDistribution({ df: 10, a: -2.2281388519649385, b: 2.2281388519649385 }, { family: "student" });206    expect(t.probability).toBeCloseTo(0.95, 9); expect(t.sd).toBeCloseTo(Math.sqrt(10 / 8), 12);207    const cauchy = computeDistribution({ df: 1, a: 0, b: 1 }, { family: "student" });208    expect(cauchy.mean).toBeNull(); expect(cauchy.sd).toBeNull();209    const ln = computeDistribution({ mu: 0, sigma: 1, a: 0, b: 1 }, { family: "lognormal" });210    expect(ln.probability).toBeCloseTo(0.5, 12); expect(ln.mean).toBeCloseTo(Math.exp(0.5), 12);211    const ex = computeDistribution({ lambda: 2, a: 0, b: 1 }, { family: "exponential" });212    expect(ex.probability).toBeCloseTo(1 - Math.exp(-2), 14); expect(ex.mean).toBe(0.5); expect(ex.sd).toBe(0.5);213    const u = computeDistribution({ low: 0, width: 4, a: 1, b: 2 }, { family: "uniform" });214    expect(u.probability).toBeCloseTo(0.25, 14); expect(u.mean).toBe(2); expect(u.sd).toBeCloseTo(4 / Math.sqrt(12), 12);215  });216  it("the plotted density integrates to the reported probability", () => {217    for (const [family, p] of [["normal", { mu: 0.5, sigma: 1.2, a: -1, b: 2 }], ["student", { df: 4, a: -2, b: 2 }], ["lognormal", { mu: 0.5, sigma: 0.5, a: 1, b: 3 }], ["exponential", { lambda: 1, a: 0.5, b: 2 }]] as const) {218      const m = computeDistribution(p, { family });219      let area = 0;220      for (let i = 1; i < m.shade.length; i++) area += 0.5 * (m.shade[i].hi + m.shade[i - 1].hi) * (m.shade[i].x - m.shade[i - 1].x);221      expect(area).toBeCloseTo(m.probability, 3);222    }223  });224});225226describe("confidence-interval", () => {227  it("coverage is near nominal over many samples", () => {228    for (const [level, n] of [[0.9, 10], [0.95, 5], [0.5, 30]]) {229      const m = simulateIntervals({ mu: 2, sigma: 3, n, m: 6000, level }, 17);230      expect(Math.abs(m.coverage - level)).toBeLessThan(0.02);231      expect(m.misses).toBe(m.intervals.filter((i) => !i.covers).length);232    }233  });234  it("builds x̄ ± t·s/√n", () => {235    const m = simulateIntervals({ mu: 0, sigma: 1, n: 12, m: 20, level: 0.95 }, 1);236    expect(m.critical).toBeCloseTo(studentTQuantile(0.975, 11), 12);237    for (const iv of m.intervals) {238      expect((iv.hi - iv.lo) / 2).toBeCloseTo((m.critical * iv.sd) / Math.sqrt(12), 12);239      expect((iv.hi + iv.lo) / 2).toBeCloseTo(iv.mean, 12);240      expect(iv.covers).toBe(iv.lo <= 0 && 0 <= iv.hi);241    }242    const wide = simulateIntervals({ mu: 0, sigma: 1, n: 12, m: 20, level: 0.99 }, 1);243    expect(wide.meanWidth).toBeGreaterThan(m.meanWidth);244  });245});246247describe("regression", () => {248  it("recovers the true coefficients exactly on noiseless data", () => {249    const m = computeRegression({ slope: -1.3, intercept: 2.5, sigma: 0, n: 30 }, 8);250    expect(m.fit.slope).toBeCloseTo(-1.3, 10); expect(m.fit.intercept).toBeCloseTo(2.5, 10); expect(m.fit.r2).toBeCloseTo(1, 12);251    for (const b of m.band) { expect(b.hi - b.lo).toBeLessThan(1e-9); expect(b.y).toBeCloseTo(2.5 - 1.3 * b.x, 9); }252  });253  it("with noise: estimates near the truth, band narrowest at x̄ and built with t(n−2)", () => {254    const m = computeRegression({ slope: 1.5, intercept: 1, sigma: 2, n: 200 }, 3);255    expect(Math.abs(m.fit.slope - 1.5)).toBeLessThan(4 * m.fit.seSlope);256    expect(m.fit.s).toBeGreaterThan(1.6); expect(m.fit.s).toBeLessThan(2.4);257    expect(m.critical).toBeCloseTo(studentTQuantile(0.975, 198), 12);258    const widths = m.band.map((b) => b.hi - b.lo);259    const narrowest = m.band[widths.indexOf(Math.min(...widths))].x;260    expect(Math.abs(narrowest - m.fit.xBar)).toBeLessThanOrEqual(0.25);261    expect(Math.min(...widths)).toBeCloseTo((2 * m.critical * m.fit.s) / Math.sqrt(200), 1);262  });263});264265describe("correlation", () => {266  it("sample r is near ρ and inside its Fisher interval most of the time", () => {267    let inside = 0;268    for (let seed = 1; seed <= 200; seed++) {269      const m = computeCorrelation({ rho: 0.6, n: 100 }, seed);270      expect(m.r).toBeGreaterThan(0.2); expect(m.ciLo).toBeLessThan(m.r); expect(m.ciHi).toBeGreaterThan(m.r);271      if (m.ciLo <= 0.6 && 0.6 <= m.ciHi) inside++;272    }273    expect(inside / 200).toBeGreaterThan(0.9);274    expect(computeCorrelation({ rho: -0.99, n: 500 }, 2).r).toBeLessThan(-0.985);275    expect(Math.abs(computeCorrelation({ rho: 0, n: 500 }, 2).r)).toBeLessThan(0.12);276  });277});278279describe("garch", () => {280  it("reports the unconditional variance ω/(1−α−β) and the persistence", () => {281    const m = computeGarch({ omega: 0.05, alpha: 0.1, beta: 0.85, n: 600 }, 1);282    expect(m.unconditionalVariance).toBeCloseTo(1, 12); expect(m.persistence).toBeCloseTo(0.95, 12); expect(m.clamped).toBe(false);283    expect(m.halfLife).toBeCloseTo(Math.log(0.5) / Math.log(0.95), 12);284    expect(m.sigma[0]).toBeCloseTo(1, 12);285    expect(m.returns).toHaveLength(600);286    for (let t = 1; t < 600; t++) expect(m.sigma[t] ** 2).toBeCloseTo(0.05 + 0.1 * m.returns[t - 1] ** 2 + 0.85 * m.sigma[t - 1] ** 2, 10);287  });288  it("clamps β so that α + β < 1", () => {289    const m = computeGarch({ omega: 0.1, alpha: 0.5, beta: 0.99, n: 100 }, 1);290    expect(m.clamped).toBe(true); expect(m.beta).toBeCloseTo(0.499, 12); expect(m.persistence).toBeLessThan(1);291    expect(m.unconditionalVariance).toBeCloseTo(0.1 / (1 - 0.999), 6);292    expect(m.returns.every(Number.isFinite)).toBe(true);293  });294  it("the sample variance averages to the unconditional variance", () => {295    let s = 0;296    for (let seed = 1; seed <= 60; seed++) s += computeGarch({ omega: 0.2, alpha: 0.1, beta: 0.5, n: 600 }, seed).sampleVariance;297    expect(s / 60).toBeCloseTo(0.5, 1);298    const arch0 = computeGarch({ omega: 0.25, alpha: 0, beta: 0, n: 100 }, 1);299    expect(arch0.sigma.every((v) => Math.abs(v - 0.5) < 1e-12)).toBe(true);300  });301});302303describe("random-walk", () => {304  it("starts at x0 and reports the closed-form moments", () => {305    const b = computeWalk({ drift: 0.5, volatility: 2, paths: 3, horizon: 4 }, 1, {});306    expect(b.process).toBe("brownian"); expect(b.paths).toHaveLength(3);307    for (const path of b.paths) { expect(path).toHaveLength(WALK_STEPS + 1); expect(path[0]).toBe(0); }308    expect(b.mean.at(-1)).toBeCloseTo(2, 12); expect(b.sd.at(-1)).toBeCloseTo(4, 12); expect(b.sd[0]).toBe(0);309    const g = walkMoments("gbm", 100, 0.05, 0.2, 0, 2);310    expect(g.mean).toBeCloseTo(100 * Math.exp(0.1), 10); expect(g.sd).toBeCloseTo(100 * Math.exp(0.1) * Math.sqrt(Math.exp(0.08) - 1), 10);311    const o = walkMoments("ou", 2, 0.5, 0.4, 1.5, 1);312    expect(o.mean).toBeCloseTo(0.5 + 1.5 * Math.exp(-1.5), 12); expect(o.sd).toBeCloseTo(0.4 * Math.sqrt((1 - Math.exp(-3)) / 3), 12);313    expect(walkMoments("ou", 2, 0.5, 0.4, 1.5, 1000).sd).toBeCloseTo(0.4 / Math.sqrt(3), 12);314  });315  it("simulated terminal values agree with the theory", () => {316    for (const process of ["brownian", "gbm", "ou"] as const) {317      const p: Record<string, number> = process === "gbm" ? { drift: 0.08, volatility: 0.2, paths: 20, horizon: 5 } : { drift: 0.5, volatility: 1, reversion: 1, paths: 20, horizon: 5 };318      const ends: number[] = [];319      let model = computeWalk(p, 1, { process });320      for (let seed = 1; seed <= 100; seed++) { model = computeWalk(p, seed, { process }); ends.push(...model.paths.map((q) => q[WALK_STEPS])); }321      const m = ends.reduce((a, c) => a + c, 0) / ends.length;322      const sdv = Math.sqrt(ends.reduce((a, c) => a + (c - m) ** 2, 0) / (ends.length - 1));323      const se = model.sd[WALK_STEPS] / Math.sqrt(ends.length);324      expect(Math.abs(m - model.mean[WALK_STEPS])).toBeLessThan(4 * se);325      expect(sdv / model.sd[WALK_STEPS]).toBeGreaterThan(0.9); expect(sdv / model.sd[WALK_STEPS]).toBeLessThan(1.1);326      if (process === "gbm") { expect(model.x0).toBe(100); expect(model.paths.flat().every((v) => v > 0)).toBe(true); }327    }328    expect(computeWalk({ drift: 0, volatility: 0.5, reversion: 1, paths: 1, horizon: 5 }, 1, { process: "ou", x0: -3 }).paths[0][0]).toBe(-3);329  });330});331332describe("impulse-response", () => {333  const mul = (A: number[][], v: number[]) => [A[0][0] * v[0] + A[0][1] * v[1], A[1][0] * v[0] + A[1][1] * v[1]];334  it("IRF at h = 0 is the unit shock and equals A^h·e afterwards", () => {335    const p = { a11: 0.6, a12: 0.2, a21: 0.3, a22: 0.5, horizon: 20 };336    const m = computeIrf(p, {});337    expect(m.irf).toHaveLength(21);338    expect(m.irf[0]).toEqual([1, 0]);339    expect(m.irf[1]).toEqual([0.6, 0.3]);340    expect(m.irf[2][0]).toBeCloseTo(0.42, 12); expect(m.irf[2][1]).toBeCloseTo(0.33, 12);341    let v = [1, 0];342    for (let h = 0; h <= 20; h++) { expect(m.irf[h][0]).toBeCloseTo(v[0], 12); expect(m.irf[h][1]).toBeCloseTo(v[1], 12); v = mul(m.a, v); }343    const m2 = computeIrf(p, { shock: 2 });344    expect(m2.irf[0]).toEqual([0, 1]); expect(m2.irf[1]).toEqual([0.2, 0.5]);345  });346  it("reports eigenvalue moduli and flags non-stationarity", () => {347    const m = computeIrf({ a11: 0.6, a12: 0.2, a21: 0.3, a22: 0.5, horizon: 5 }, {});348    expect(m.moduli[0]).toBeCloseTo(0.8, 12); expect(m.moduli[1]).toBeCloseTo(0.3, 12); expect(m.complex).toBe(false); expect(m.stationary).toBe(true);349    const rot = computeIrf({ a11: 0, a12: -1, a21: 1, a22: 0, horizon: 8 }, {});350    expect(rot.complex).toBe(true); expect(rot.moduli).toEqual([1, 1]); expect(rot.stationary).toBe(false);351    expect(rot.irf[4]).toEqual([1, 0]); // a quarter turn per period352    const spiral = computeIrf({ a11: 0.5, a12: -0.5, a21: 0.5, a22: 0.5, horizon: 8 }, {});353    expect(spiral.moduli[0]).toBeCloseTo(Math.SQRT1_2, 12); expect(spiral.stationary).toBe(true);354    expect(computeIrf({ a11: 1.1, a12: 0, a21: 0, a22: 0.2, horizon: 5 }, {}).stationary).toBe(false);355    expect(computeIrf({ a11: 1, a12: 0, a21: 0, a22: 0.5, horizon: 5 }, {}).stationary).toBe(false); // unit root356  });357});358359describe("event-study", () => {360  it("without noise, AR is the jump then the drift and CAR accumulates them", () => {361    const m = computeEventStudy({ jump: 2, drift: 0.1, sigma: 0, events: 10 }, 1, { window: 5 });362    expect(m.t).toEqual([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]);363    expect(m.ar.slice(0, 5).every((v) => v === 0)).toBe(true);364    expect(m.ar[5]).toBe(2);365    expect(m.ar.slice(6).every((v) => Math.abs(v - 0.1) < 1e-12)).toBe(true);366    expect(m.car.at(-1)).toBeCloseTo(2.5, 12); expect(m.expectedCar).toBeCloseTo(2.5, 12);367    expect(m.arSe.every((v) => v < 1e-9)).toBe(true);368  });369  it("with noise, estimates are within their standard errors and SE(AR) ≈ σ/√N", () => {370    const m = computeEventStudy({ jump: 2, drift: 0.1, sigma: 2, events: 200 }, 4, {});371    expect(m.window).toBe(10); expect(m.t).toHaveLength(21);372    expect(Math.abs(m.ar[10] - 2)).toBeLessThan(4 * m.arSe[10]);373    expect(Math.abs(m.car[20] - 3)).toBeLessThan(4 * m.carSe[20]);374    const meanSe = m.arSe.reduce((a, b) => a + b, 0) / 21;375    expect(meanSe).toBeCloseTo(2 / Math.sqrt(200), 1);376    expect(m.carSe[20]).toBeGreaterThan(m.carSe[0]); // CAR uncertainty grows like √(number of days)377    expect(m.carSe[20] / (2 * Math.sqrt(21 / 200))).toBeGreaterThan(0.8);378    expect(m.carSe[20] / (2 * Math.sqrt(21 / 200))).toBeLessThan(1.2);379    expect(m.tEvent).toBeCloseTo(m.ar[10] / m.arSe[10], 12);380  });381});382383describe("function-plot", () => {384  it("derives one slider per name other than x, with bounds from the config", () => {385    const defs = functionPlotParams({ expr: "a * sin(w * x) + c", expr2: "c + pi", wMin: 0, wMax: 10, cMin: 2, cMax: 3, cStep: 0.5 });386    expect(defs.map((d) => d.key)).toEqual(["a", "w", "c"]);387    expect(defs[0]).toMatchObject({ min: -5, max: 5, step: 0.1, default: 1 });388    expect(defs[1]).toMatchObject({ min: 0, max: 10, step: 0.1, default: 1 });389    expect(defs[2]).toMatchObject({ min: 2, max: 3, step: 0.5, default: 2 });390  });391  it("evaluates the curves on the x grid with the parameter values", () => {392    const m = computeFunctionPlot({ a: 2, b: -1 }, { expr: "a * x ^ 2 + b", expr2: "x", xMin: 0, xMax: 4, xLabel: "t", yLabel: "f" });393    expect(m.curves).toHaveLength(2);394    expect(m.curves[0].points).toHaveLength(241);395    expect(m.curves[0].points[0]).toEqual({ x: 0, y: -1 });396    expect(m.curves[0].points[240]).toEqual({ x: 4, y: 31 });397    expect(m.curves[0].points[120].y).toBeCloseTo(7, 12);398    expect(m.curves[1].points[60].y).toBeCloseTo(1, 12);399    expect(m.xLabel).toBe("t"); expect(m.yLabel).toBe("f"); expect(m.xDomain).toEqual([0, 4]);400    expect(m.values).toEqual([{ name: "a", value: 2, step: 0.1 }, { name: "b", value: -1, step: 0.1 }]);401    expect(m.curves[0].label).toBe("y = a * x ^ 2 + b");402    expect(computeFunctionPlot({}, { expr: "a * x", label: "droite" }).curves[0]).toMatchObject({ label: "droite" });403    expect(computeFunctionPlot({}, { expr: "a * x" }).curves[0].points[240].y).toBe(5); // a defaults to 1404  });405  it("leaves gaps where the function is not finite and keeps poles out of the frame", () => {406    const m = computeFunctionPlot({}, { expr: "1 / x" });407    expect(m.curves[0].points[120]).toEqual({ x: 0, y: null });408    expect(m.yDomain[1]).toBeLessThan(10); expect(m.yDomain[0]).toBeGreaterThan(-10);409    const log = computeFunctionPlot({}, { expr: "log(x)" });410    expect(log.curves[0].points.slice(0, 121).every((q) => q.y === null)).toBe(true);411    expect(log.curves[0].points[240].y).toBeCloseTo(Math.log(5), 12);412    const tan = computeFunctionPlot({}, { expr: "tan(x)" });413    expect(tan.curves[0].points.some((q) => q.y === null)).toBe(true); // pole crossings are cut414    expect(computeFunctionPlot({}, { expr: "x", yMin: -2, yMax: 2 }).yDomain).toEqual([-2, 2]);415  });416  it("throws a readable error on a bad expression", () => {417    expect(() => computeFunctionPlot({}, {})).toThrow(/config\.expr is required/);418    expect(() => computeFunctionPlot({}, { expr: "x +" })).toThrow(/config\.expr: unexpected end/);419    expect(() => computeFunctionPlot({}, { expr: "x", expr3: "window" })).toThrow(/config\.expr3: "window" is not allowed/);420  });421});422
Files main
Menu

Theme