Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat(explain): model-based explainers with ridge holdout scoring (K-6/K-7)

Elwynn Chen783e0b92e029
diff --git a/packages/graphic-walker/src/lib/explain/explainers/contributingDim.ts b/packages/graphic-walker/src/lib/explain/explainers/contributingDim.ts
new file mode 100644
index 00000000..c48ac143
--- /dev/null
+++ b/packages/graphic-walker/src/lib/explain/explainers/contributingDim.ts
@@ -0,0 +1,135 @@
+import type { IRow, IViewField } from '../../../interfaces';
+import { getMeaAggKey } from '../../../utils';
+import { EXPLAIN_COUNT_KEY, complementaryDimensions, markLevelQuery } from '../queries';
+import { standardize } from '../stats/ridge';
+import {
+ MIN_SCORE,
+ PERMUTATION_P_THRESHOLD,
+ baseFeatures,
+ buildMarksTable,
+ markKeyOf,
+ modelStrength,
+ scatterSpec,
+ scoreCandidate,
+ seedFromString,
+ targetMeasure,
+} from './modelCommon';
+import type { IExplainContext, IExplainer, IExplanation } from '../types';
+
+/**
+ * B-class explainer: contributing dimensions.
+ *
+ * Does the composition of an unvisualized dimension (per-mark shares of its
+ * top values) help predict the target measure across marks? Shares the
+ * per-candidate markLevelQuery with the unique-mark explainer — the engine
+ * dedupes, so both run off one scan per candidate.
+ *
+ * SCORING-FROZEN for the executor agent (see docs/explain-data-worklog.md §1).
+ */
+
+const MAX_RESULTS = 5;
+const MAX_RATE_FEATURES = 6;
+
+export const contributingDimExplainer: IExplainer = {
+ type: 'contributing-dimension',
+
+ isApplicable(ctx) {
+ if (Object.keys(ctx.selectedMark).length === 0 || ctx.viewDimensions.length === 0) {
+ return { applicable: false, reason: 'explain.skip.noMark' };
+ }
+ if (!targetMeasure(ctx)) {
+ return { applicable: false, reason: 'explain.skip.noDerivableTarget' };
+ }
+ if (complementaryDimensions(ctx).length === 0) {
+ return { applicable: false, reason: 'explain.skip.noCandidates' };
+ }
+ return { applicable: true };
+ },
+
+ plan(ctx) {
+ // identical payloads to the unique-mark explainer → engine-level dedup
+ return complementaryDimensions(ctx).map((candidate) => markLevelQuery(ctx, candidate).payload);
+ },
+
+ analyze(ctx, results) {
+ const target = targetMeasure(ctx)!;
+ const candidates = complementaryDimensions(ctx);
+ const explanations: IExplanation[] = [];
+
+ candidates.forEach((candidate, index) => {
+ const rows = results[index];
+ if (!rows || rows.length === 0) return;
+ const table = buildMarksTable(ctx, rows, target);
+ if (!table) return;
+ const baseX = baseFeatures(ctx, table);
+ const { candidateKey } = markLevelQuery(ctx, candidate);
+
+ // global top categories by row count
+ const globalCounts = new Map<string, number>();
+ for (const row of rows) {
+ const cat = String(row[candidateKey]);
+ globalCounts.set(cat, (globalCounts.get(cat) ?? 0) + (Number(row[EXPLAIN_COUNT_KEY]) || 0));
+ }
+ const nTrain = table.markKeys.length - 1;
+ const maxFeatures = Math.min(MAX_RATE_FEATURES, Math.max(1, Math.floor(nTrain / 4)));
+ const topCategories = [...globalCounts.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, maxFeatures + 1) // +1: the last share is redundant (sums to ~1), drop it below
+ .map(([cat]) => cat)
+ .slice(0, Math.max(1, Math.min(maxFeatures, globalCounts.size - 1)));
+ if (topCategories.length === 0) return;
+
+ // per-mark rate of each top category
+ const rateOf = (markRows: IRow[], cat: string, total: number): number => {
+ if (total <= 0) return 0;
+ const catCount = markRows.reduce((acc, r) => acc + (String(r[candidateKey]) === cat ? Number(r[EXPLAIN_COUNT_KEY]) || 0 : 0), 0);
+ return catCount / total;
+ };
+ const rateCols = topCategories.map((cat) => table.rowsByMark.map((markRows, i) => rateOf(markRows, cat, table.counts[i])));
+ if (rateCols.every((col) => new Set(col).size < 2)) return; // composition constant across marks
+ const zCols = rateCols.map(standardize);
+ const candX = table.markKeys.map((_, r) => zCols.map((col) => col[r]));
+
+ const scored = scoreCandidate(baseX, candX, table.y, table.selectedIndex, seedFromString(`dim:${candidate.fid}`));
+ if (!scored || scored.score < MIN_SCORE || scored.pValue >= PERMUTATION_P_THRESHOLD) return;
+
+ // most associated category: largest |correlation-ish| via rate column vs y (on standardized cols)
+ const zy = standardize(table.y);
+ let bestCat = 0;
+ let bestAbs = -1;
+ zCols.forEach((col, c) => {
+ const corr = Math.abs(col.reduce((acc, v, i) => acc + v * zy[i], 0) / col.length);
+ if (corr > bestAbs) {
+ bestAbs = corr;
+ bestCat = c;
+ }
+ });
+
+ explanations.push({
+ type: 'contributing-dimension',
+ score: scored.score,
+ strength: modelStrength(scored.score),
+ field: candidate,
+ measure: target,
+ descriptionKey: 'explain.contributingDimension.desc',
+ descriptionParams: {
+ dimension: candidate.name ?? candidate.fid,
+ target: target.name ?? target.fid,
+ topCategory: topCategories[bestCat],
+ cvGainPercent: Math.round(Math.max(0, scored.fitGain) * 1000) / 10,
+ },
+ evidence: {
+ chartSpec: scatterSpec(
+ rateCols[bestCat],
+ table.y,
+ table.selectedIndex,
+ `share of "${topCategories[bestCat]}" in ${candidate.name ?? candidate.fid}`,
+ `${target.aggName ?? 'sum'} ${target.name ?? target.fid}`
+ ),
+ },
+ });
+ });
+
+ return explanations.sort((a, b) => b.score - a.score).slice(0, MAX_RESULTS);
+ },
+};
diff --git a/packages/graphic-walker/src/lib/explain/explainers/contributingMeasure.ts b/packages/graphic-walker/src/lib/explain/explainers/contributingMeasure.ts
new file mode 100644
index 00000000..ff0c71fd
--- /dev/null
+++ b/packages/graphic-walker/src/lib/explain/explainers/contributingMeasure.ts
@@ -0,0 +1,96 @@
+import type { IViewField } from '../../../interfaces';
+import { COUNT_FIELD_ID } from '../../../constants';
+import { getMeaAggKey } from '../../../utils';
+import { marksWithMeasuresQuery } from '../queries';
+import {
+ MIN_SCORE,
+ PERMUTATION_P_THRESHOLD,
+ baseFeatures,
+ buildMarksTable,
+ modelStrength,
+ scatterSpec,
+ scoreCandidate,
+ secondOrderFeatures,
+ seedFromString,
+ targetMeasure,
+} from './modelCommon';
+import type { IExplainContext, IExplainer, IExplanation } from '../types';
+
+/**
+ * C-class explainer: contributing measures.
+ *
+ * Does an unvisualized measure, aggregated to the view's level of detail,
+ * help predict the target measure across marks? Base model vs explain model
+ * with the selected mark held out; second-order term captures simple
+ * non-linear association (Tableau's "second-order modeling for measures").
+ *
+ * SCORING-FROZEN for the executor agent (see docs/explain-data-worklog.md §1).
+ */
+
+const MAX_RESULTS = 5;
+
+function candidateMeasures(ctx: IExplainContext): IViewField[] {
+ const inView = new Set(ctx.viewMeasures.map((m) => m.fid));
+ return ctx.allFields.filter((f) => f.analyticType === 'measure' && !inView.has(f.fid) && f.fid !== COUNT_FIELD_ID && f.aggName !== 'expr' && !f.computed);
+}
+
+export const contributingMeasureExplainer: IExplainer = {
+ type: 'contributing-measure',
+
+ isApplicable(ctx) {
+ if (Object.keys(ctx.selectedMark).length === 0 || ctx.viewDimensions.length === 0) {
+ return { applicable: false, reason: 'explain.skip.noMark' };
+ }
+ if (!targetMeasure(ctx)) {
+ return { applicable: false, reason: 'explain.skip.noDerivableTarget' };
+ }
+ if (candidateMeasures(ctx).length === 0) {
+ return { applicable: false, reason: 'explain.skip.noCandidates' };
+ }
+ return { applicable: true };
+ },
+
+ plan(ctx) {
+ return [marksWithMeasuresQuery(ctx, candidateMeasures(ctx).map((m) => m.fid))];
+ },
+
+ analyze(ctx, results) {
+ const rows = results[0];
+ if (!rows || rows.length === 0) return [];
+ const target = targetMeasure(ctx)!;
+ const table = buildMarksTable(ctx, rows, target);
+ if (!table) return [];
+ const baseX = baseFeatures(ctx, table);
+ const explanations: IExplanation[] = [];
+
+ for (const candidate of candidateMeasures(ctx)) {
+ const sumKey = getMeaAggKey(candidate.fid, 'sum');
+ // per-mark mean of the candidate measure (marks table holds one row per mark here)
+ const values = table.rowsByMark.map((markRows, i) => {
+ const total = markRows.reduce((acc, r) => acc + (Number(r[sumKey]) || 0), 0);
+ return table.counts[i] > 0 ? total / table.counts[i] : 0;
+ });
+ if (new Set(values).size < 2) continue; // constant → no signal
+ const candX = secondOrderFeatures(values);
+ const scored = scoreCandidate(baseX, candX, table.y, table.selectedIndex, seedFromString(`measure:${candidate.fid}`));
+ if (!scored || scored.score < MIN_SCORE || scored.pValue >= PERMUTATION_P_THRESHOLD) continue;
+ explanations.push({
+ type: 'contributing-measure',
+ score: scored.score,
+ strength: modelStrength(scored.score),
+ field: candidate,
+ measure: target,
+ descriptionKey: 'explain.contributingMeasure.desc',
+ descriptionParams: {
+ candidate: candidate.name ?? candidate.fid,
+ target: target.name ?? target.fid,
+ cvGainPercent: Math.round(Math.max(0, scored.fitGain) * 1000) / 10,
+ },
+ evidence: {
+ chartSpec: scatterSpec(values, table.y, table.selectedIndex, `mean ${candidate.name ?? candidate.fid}`, `${target.aggName ?? 'sum'} ${target.name ?? target.fid}`),
+ },
+ });
+ }
+ return explanations.sort((a, b) => b.score - a.score).slice(0, MAX_RESULTS);
+ },
+};
diff --git a/packages/graphic-walker/src/lib/explain/explainers/modelCommon.ts b/packages/graphic-walker/src/lib/explain/explainers/modelCommon.ts
new file mode 100644
index 00000000..4d6a1d2b
Binary files /dev/null and b/packages/graphic-walker/src/lib/explain/explainers/modelCommon.ts differ
diff --git a/packages/graphic-walker/src/lib/explain/goldenModel.test.ts b/packages/graphic-walker/src/lib/explain/goldenModel.test.ts
new file mode 100644
index 00000000..d0c6fb2e
--- /dev/null
+++ b/packages/graphic-walker/src/lib/explain/goldenModel.test.ts
@@ -0,0 +1,127 @@
+import type { IRow, IViewField } from '../../interfaces';
+import { getTestComputation as getComputation } from './testUtils';
+import { explainMarkAll } from './engine';
+import { contributingDimExplainer } from './explainers/contributingDim';
+import { contributingMeasureExplainer } from './explainers/contributingMeasure';
+import type { IExplainContext } from './types';
+
+/**
+ * Golden tests for the model-based explainers (B/C class), run through real
+ * workflow-DSL execution. 12 marks (months); planted signals:
+ * - `traffic` (hidden measure): row-level 2×sales + jitter → per-mark means
+ * track the target tightly
+ * - `channel` (hidden dimension): online share rises with month, and online
+ * rows sell for +60 → composition predicts the target
+ * Noise controls that must NEVER fire:
+ * - `noise_mea`: cycling values, uncorrelated with sales
+ * - `noise_dim`: identical composition in every mark
+ */
+
+const field = (fid: string, analyticType: 'dimension' | 'measure', semanticType: 'nominal' | 'quantitative', aggName?: string): IViewField =>
+ ({ fid, name: fid, analyticType, semanticType, aggName } as unknown as IViewField);
+
+const MONTH = field('month', 'dimension', 'nominal');
+const CHANNEL = field('channel', 'dimension', 'nominal');
+const NOISE_DIM = field('noise_dim', 'dimension', 'nominal');
+const SALES = field('sales', 'measure', 'quantitative', 'mean');
+const TRAFFIC = field('traffic', 'measure', 'quantitative', 'sum');
+const NOISE_MEA = field('noise_mea', 'measure', 'quantitative', 'sum');
+
+const ALL_FIELDS = [MONTH, CHANNEL, NOISE_DIM, SALES, TRAFFIC, NOISE_MEA];
+const ROWS_PER_MONTH = 30;
+
+function makeDataset(planted: boolean): IRow[] {
+ const rows: IRow[] = [];
+ for (let m = 0; m < 12; m++) {
+ const onlineShare = planted ? 0.2 + 0.05 * m : 0.4;
+ for (let i = 0; i < ROWS_PER_MONTH; i++) {
+ const online = i < ROWS_PER_MONTH * onlineShare;
+ const sales = planted ? 40 + (online ? 60 : 0) + (i % 5) : 50 + (i % 20);
+ rows.push({
+ month: `M${String(m + 1).padStart(2, '0')}`,
+ channel: online ? 'online' : 'offline',
+ noise_dim: `n${i % 5}`,
+ sales,
+ traffic: planted ? 2 * sales + (i % 3) : 17 + ((i * 13 + m * 7) % 23),
+ noise_mea: (i * 11 + m * 3) % 19,
+ });
+ }
+ }
+ return rows;
+}
+
+function makeContext(mark: string): IExplainContext {
+ return {
+ allFields: ALL_FIELDS,
+ viewDimensions: [MONTH],
+ viewMeasures: [SALES],
+ viewFilters: [],
+ selectedMark: { month: mark },
+ };
+}
+
+const EXPLAINERS = [contributingDimExplainer, contributingMeasureExplainer];
+
+describe('golden: model-based explainers find planted structure', () => {
+ const computation = getComputation(makeDataset(true));
+
+ it('contributing measure: hidden `traffic` predicts mean sales across marks', async () => {
+ const results = await explainMarkAll(makeContext('M12'), computation, EXPLAINERS);
+ const cm = results.find((r) => r.explainer === 'contributing-measure')!;
+ expect(cm.status).toBe('ok');
+ const traffic = cm.explanations.find((e) => e.field.fid === 'traffic');
+ expect(traffic).toBeDefined();
+ expect(['strong', 'moderate']).toContain(traffic!.strength);
+ // noise measure must not appear
+ expect(cm.explanations.map((e) => e.field.fid)).not.toContain('noise_mea');
+ });
+
+ it('contributing dimension: hidden `channel` composition predicts mean sales', async () => {
+ const results = await explainMarkAll(makeContext('M12'), computation, EXPLAINERS);
+ const cd = results.find((r) => r.explainer === 'contributing-dimension')!;
+ expect(cd.status).toBe('ok');
+ const channel = cd.explanations.find((e) => e.field.fid === 'channel');
+ expect(channel).toBeDefined();
+ expect(['strong', 'moderate']).toContain(channel!.strength);
+ expect(cd.explanations.map((e) => e.field.fid)).not.toContain('noise_dim');
+ });
+
+ it('results are deterministic across runs (fixed-seed permutation tests)', async () => {
+ const run1 = await explainMarkAll(makeContext('M06'), computation, EXPLAINERS);
+ const run2 = await explainMarkAll(makeContext('M06'), computation, EXPLAINERS);
+ const scores = (rs: typeof run1) => rs.flatMap((r) => r.explanations.map((e) => [e.field.fid, e.score]));
+ expect(scores(run1)).toEqual(scores(run2));
+ });
+});
+
+describe('golden: clean data produces zero model-based explanations', () => {
+ const computation = getComputation(makeDataset(false));
+
+ it.each(['M01', 'M06', 'M12'])('mark %s: nothing fires on structureless data', async (mark) => {
+ const results = await explainMarkAll(makeContext(mark), computation, EXPLAINERS);
+ for (const result of results) {
+ expect(result.status).toBe('ok');
+ expect(result.explanations).toHaveLength(0);
+ }
+ });
+});
+
+describe('golden: guardrails for model-based explainers', () => {
+ it('too few marks (< 8) → no model explanations', async () => {
+ const rows = makeDataset(true).filter((r) => ['M01', 'M02', 'M03', 'M04'].includes(r.month as string));
+ const results = await explainMarkAll(makeContext('M01'), getComputation(rows), EXPLAINERS);
+ for (const result of results) {
+ expect(result.explanations).toHaveLength(0);
+ }
+ });
+
+ it('non-derivable target aggregation (median) → skipped with reason', async () => {
+ const MEDIAN_SALES = { ...SALES, aggName: 'median' } as unknown as IViewField;
+ const ctx = { ...makeContext('M12'), viewMeasures: [MEDIAN_SALES] };
+ const results = await explainMarkAll(ctx, getComputation(makeDataset(true)), EXPLAINERS);
+ for (const result of results) {
+ expect(result.status).toBe('skipped');
+ expect(result.reason).toBe('explain.skip.noDerivableTarget');
+ }
+ });
+});
diff --git a/packages/graphic-walker/src/lib/explain/index.ts b/packages/graphic-walker/src/lib/explain/index.ts
index 120f5d06..37289006 100644
--- a/packages/graphic-walker/src/lib/explain/index.ts
+++ b/packages/graphic-walker/src/lib/explain/index.ts
@@ -2,14 +2,23 @@ export * from './types';
export { explainMark, explainMarkAll } from './engine';
export { extremeValueExplainer } from './explainers/extremeValue';
export { uniqueMarkExplainer } from './explainers/uniqueMark';
+export { contributingDimExplainer } from './explainers/contributingDim';
+export { contributingMeasureExplainer } from './explainers/contributingMeasure';
import type { IExplainer } from './types';
import { extremeValueExplainer } from './explainers/extremeValue';
import { uniqueMarkExplainer } from './explainers/uniqueMark';
+import { contributingDimExplainer } from './explainers/contributingDim';
+import { contributingMeasureExplainer } from './explainers/contributingMeasure';
/**
* Registered explainers in display-priority order:
- * data-quality evidence first, exploratory clues last.
- * (M2 adds contributing-dimension / contributing-measure between them.)
+ * data-quality evidence first, model-based evidence next,
+ * exploratory clues last.
*/
-export const defaultExplainers: IExplainer[] = [extremeValueExplainer, uniqueMarkExplainer];
+export const defaultExplainers: IExplainer[] = [
+ extremeValueExplainer,
+ contributingDimExplainer,
+ contributingMeasureExplainer,
+ uniqueMarkExplainer,
+];
diff --git a/packages/graphic-walker/src/lib/explain/stats/ridge.test.ts b/packages/graphic-walker/src/lib/explain/stats/ridge.test.ts
new file mode 100644
index 00000000..53e24804
--- /dev/null
+++ b/packages/graphic-walker/src/lib/explain/stats/ridge.test.ts
@@ -0,0 +1,138 @@
+import {
+ solveLinearSystem,
+ fitRidge,
+ predictRidge,
+ looCvR2,
+ selectLambda,
+ standardize,
+ mulberry32,
+ shuffled,
+ permutationPValue,
+} from './ridge';
+
+describe('solveLinearSystem', () => {
+ it('solves a known 3x3 system', () => {
+ // x=1, y=2, z=3
+ const A = [
+ [2, 1, -1],
+ [-3, -1, 2],
+ [-2, 1, 2],
+ ];
+ const b = [1, 1, 6];
+ const x = solveLinearSystem(A, b);
+ expect(x[0]).toBeCloseTo(1, 8);
+ expect(x[1]).toBeCloseTo(2, 8);
+ expect(x[2]).toBeCloseTo(3, 8);
+ });
+ it('throws on singular matrices', () => {
+ expect(() =>
+ solveLinearSystem(
+ [
+ [1, 2],
+ [2, 4],
+ ],
+ [1, 2]
+ )
+ ).toThrow('singular');
+ });
+});
+
+describe('fitRidge', () => {
+ it('recovers exact linear coefficients at λ≈0 (OLS agreement)', () => {
+ // y = 3 + 2·x1 − 1·x2, no noise
+ const X = [
+ [0, 0],
+ [1, 0],
+ [0, 1],
+ [1, 1],
+ [2, 1],
+ [1, 2],
+ [3, 2],
+ ];
+ const y = X.map(([a, b]) => 3 + 2 * a - b);
+ const model = fitRidge(X, y, 1e-9);
+ expect(model.beta[0]).toBeCloseTo(2, 6);
+ expect(model.beta[1]).toBeCloseTo(-1, 6);
+ expect(model.intercept).toBeCloseTo(3, 6);
+ const preds = predictRidge(model, X);
+ preds.forEach((p, i) => expect(p).toBeCloseTo(y[i], 6));
+ });
+ it('shrinks coefficients as λ grows', () => {
+ const X = Array.from({ length: 20 }, (_, i) => [i, (i * 7) % 5]);
+ const y = X.map(([a, b]) => 1 + 0.5 * a + 2 * b);
+ const small = fitRidge(X, y, 0.01);
+ const large = fitRidge(X, y, 1000);
+ const norm = (m: { beta: number[] }) => Math.hypot(...m.beta);
+ expect(norm(large)).toBeLessThan(norm(small));
+ });
+ it('handles the intercept-only case (no features)', () => {
+ const model = fitRidge([[], [], []] as number[][], [1, 2, 3], 1);
+ expect(model.beta).toEqual([]);
+ expect(model.intercept).toBeCloseTo(2, 10);
+ });
+});
+
+describe('looCvR2', () => {
+ it('is high for genuinely predictive features', () => {
+ const rand = mulberry32(42);
+ const X = Array.from({ length: 30 }, () => [rand() * 10]);
+ const y = X.map(([x]) => 2 * x + 1 + (rand() - 0.5) * 0.1);
+ expect(looCvR2(X, y, 0.1)).toBeGreaterThan(0.95);
+ });
+ it('is ≤ 0 for pure-noise features (the overfitting detector)', () => {
+ const rand = mulberry32(7);
+ const X = Array.from({ length: 25 }, () => [rand(), rand(), rand()]);
+ const y = Array.from({ length: 25 }, () => rand() * 100);
+ expect(looCvR2(X, y, 0.1)).toBeLessThanOrEqual(0.1);
+ });
+});
+
+describe('selectLambda', () => {
+ it('is deterministic and returns a grid member', () => {
+ const rand = mulberry32(1);
+ const X = Array.from({ length: 20 }, () => [rand() * 5, rand() * 3]);
+ const y = X.map(([a, b]) => a - b + (rand() - 0.5) * 0.2);
+ const first = selectLambda(X, y);
+ const second = selectLambda(X, y);
+ expect(first).toEqual(second);
+ expect([0.01, 0.1, 1, 10]).toContain(first.lambda);
+ });
+});
+
+describe('standardize', () => {
+ it('produces zero mean and unit variance', () => {
+ const z = standardize([2, 4, 6, 8]);
+ expect(z.reduce((a, b) => a + b, 0)).toBeCloseTo(0, 10);
+ const varz = z.reduce((acc, v) => acc + v * v, 0) / z.length;
+ expect(varz).toBeCloseTo(1, 10);
+ });
+ it('maps constant columns to zeros instead of dividing by zero', () => {
+ expect(standardize([5, 5, 5])).toEqual([0, 0, 0]);
+ });
+});
+
+describe('determinism and permutation testing', () => {
+ it('mulberry32 yields a reproducible sequence in [0,1)', () => {
+ const a = mulberry32(123);
+ const b = mulberry32(123);
+ const seqA = Array.from({ length: 5 }, a);
+ const seqB = Array.from({ length: 5 }, b);
+ expect(seqA).toEqual(seqB);
+ seqA.forEach((v) => {
+ expect(v).toBeGreaterThanOrEqual(0);
+ expect(v).toBeLessThan(1);
+ });
+ });
+ it('shuffled is deterministic under a fixed seed and preserves elements', () => {
+ const items = [1, 2, 3, 4, 5, 6];
+ const s1 = shuffled(items, mulberry32(9));
+ const s2 = shuffled(items, mulberry32(9));
+ expect(s1).toEqual(s2);
+ expect([...s1].sort()).toEqual(items);
+ });
+ it('permutationPValue implements add-one smoothing', () => {
+ expect(permutationPValue(10, [1, 2, 3, 4])).toBeCloseTo(1 / 5, 10);
+ expect(permutationPValue(0, [1, 2, 3, 4])).toBeCloseTo(5 / 5, 10);
+ expect(permutationPValue(2.5, [1, 2, 3, 4])).toBeCloseTo(3 / 5, 10);
+ });
+});
diff --git a/packages/graphic-walker/src/lib/explain/stats/ridge.ts b/packages/graphic-walker/src/lib/explain/stats/ridge.ts
new file mode 100644
index 00000000..ec6d0553
--- /dev/null
+++ b/packages/graphic-walker/src/lib/explain/stats/ridge.ts
@@ -0,0 +1,163 @@
+/**
+ * Ridge regression kernel for the model-based explainers (B/C class).
+ *
+ * Operates on mark-level aggregates (tens to hundreds of rows, ≤ ~20
+ * features), so closed-form solutions and brute-force leave-one-out are
+ * cheap. No external dependencies.
+ *
+ * FROZEN for the executor agent: do not modify scoring logic here.
+ * See docs/explain-data-worklog.md §1.
+ */
+
+export interface IRidgeModel {
+ beta: number[];
+ intercept: number;
+}
+
+/** Gaussian elimination with partial pivoting; A is modified-safe (copied). */
+export function solveLinearSystem(A: number[][], b: number[]): number[] {
+ 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) {
+ throw new Error('solveLinearSystem: singular matrix');
+ }
+ [m[col], m[pivot]] = [m[pivot], m[col]];
+ for (let r = col + 1; r < n; r++) {
+ const factor = m[r][col] / m[col][col];
+ for (let c = col; c <= n; c++) m[r][c] -= factor * m[col][c];
+ }
+ }
+ const x = new Array<number>(n).fill(0);
+ for (let r = n - 1; r >= 0; r--) {
+ let acc = m[r][n];
+ for (let c = r + 1; c < n; c++) acc -= m[r][c] * x[c];
+ x[r] = acc / m[r][r];
+ }
+ return x;
+}
+
+/**
+ * Closed-form ridge fit with centered features and target (the intercept is
+ * not penalized). λ = 0 reduces to OLS.
+ */
+export function fitRidge(X: number[][], y: number[], lambda: number): IRidgeModel {
+ const n = X.length;
+ if (n === 0 || n !== y.length) throw new Error('fitRidge: bad shapes');
+ const p = X[0]?.length ?? 0;
+ const yMean = y.reduce((a, b) => a + b, 0) / n;
+ if (p === 0) {
+ return { beta: [], intercept: yMean };
+ }
+ const colMeans = Array.from({ length: p }, (_, j) => X.reduce((acc, row) => acc + row[j], 0) / n);
+ const Xc = X.map((row) => row.map((v, j) => v - colMeans[j]));
+ const yc = y.map((v) => v - yMean);
+ // gram = Xc'Xc + λI ; rhs = Xc'yc
+ const gram = Array.from({ length: p }, (_, i) =>
+ Array.from({ length: p }, (_, j) => {
+ let acc = 0;
+ for (let r = 0; r < n; r++) acc += Xc[r][i] * Xc[r][j];
+ return i === j ? acc + lambda : acc;
+ })
+ );
+ const rhs = Array.from({ length: p }, (_, j) => {
+ let acc = 0;
+ for (let r = 0; r < n; r++) acc += Xc[r][j] * yc[r];
+ return acc;
+ });
+ const beta = solveLinearSystem(gram, rhs);
+ const intercept = yMean - beta.reduce((acc, b, j) => acc + b * colMeans[j], 0);
+ return { beta, intercept };
+}
+
+export function predictRidge(model: IRidgeModel, X: number[][]): number[] {
+ return X.map((row) => model.intercept + model.beta.reduce((acc, b, j) => acc + b * row[j], 0));
+}
+
+/**
+ * Leave-one-out cross-validated R². Negative values mean the model predicts
+ * held-out marks worse than the mean — an honest overfitting signal that a
+ * training-set R² would hide (per-mark dummies fit perfectly in-sample).
+ */
+export function looCvR2(X: number[][], y: number[], lambda: number): number {
+ const n = y.length;
+ if (n < 3) return Number.NEGATIVE_INFINITY;
+ const yMean = y.reduce((a, b) => a + b, 0) / n;
+ let sse = 0;
+ let sst = 0;
+ for (let i = 0; i < n; i++) {
+ const Xtrain = X.filter((_, r) => r !== i);
+ const ytrain = y.filter((_, r) => r !== i);
+ let pred: number;
+ try {
+ const model = fitRidge(Xtrain, ytrain, lambda);
+ pred = predictRidge(model, [X[i]])[0];
+ } catch {
+ pred = ytrain.reduce((a, b) => a + b, 0) / ytrain.length;
+ }
+ sse += (y[i] - pred) ** 2;
+ sst += (y[i] - yMean) ** 2;
+ }
+ if (sst < 1e-12) return 0;
+ return 1 - sse / sst;
+}
+
+export const DEFAULT_LAMBDA_GRID = [0.01, 0.1, 1, 10];
+
+/** pick λ maximizing LOO-CV R² over a fixed grid — deterministic */
+export function selectLambda(X: number[][], y: number[], grid: number[] = DEFAULT_LAMBDA_GRID): { lambda: number; cvR2: number } {
+ let best = { lambda: grid[0], cvR2: Number.NEGATIVE_INFINITY };
+ for (const lambda of grid) {
+ const cvR2 = looCvR2(X, y, lambda);
+ if (cvR2 > best.cvR2) best = { lambda, cvR2 };
+ }
+ return best;
+}
+
+/** standardize a column to zero mean / unit variance; constant columns → all zeros */
+export function standardize(values: number[]): number[] {
+ const n = values.length;
+ if (n === 0) return [];
+ const mean = values.reduce((a, b) => a + b, 0) / n;
+ const sd = Math.sqrt(values.reduce((acc, v) => acc + (v - mean) ** 2, 0) / n);
+ if (sd < 1e-12) return values.map(() => 0);
+ return values.map((v) => (v - mean) / sd);
+}
+
+/**
+ * Deterministic PRNG (mulberry32). `Math.random` is forbidden in the explain
+ * module: the same view state must always produce the same explanations.
+ */
+export function mulberry32(seed: number): () => number {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** Fisher–Yates shuffle with an injected PRNG */
+export function shuffled<T>(items: T[], rand: () => number): T[] {
+ const arr = [...items];
+ for (let i = arr.length - 1; i > 0; i--) {
+ const j = Math.floor(rand() * (i + 1));
+ [arr[i], arr[j]] = [arr[j], arr[i]];
+ }
+ return arr;
+}
+
+/**
+ * One-sided permutation p-value with add-one smoothing:
+ * P(score ≥ real | null). Guards the "lucky prediction" failure mode.
+ */
+export function permutationPValue(realScore: number, permutedScores: number[]): number {
+ const asExtreme = permutedScores.filter((s) => s >= realScore).length;
+ return (1 + asExtreme) / (1 + permutedScores.length);
+}