@nirs4all/methods 1.3.16 → 1.3.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,554 @@
1
+ // SPDX-License-Identifier: CECILL-2.1 OR AGPL-3.0-or-later
2
+ //
3
+ // Model explanation (attribution) bindings over cpp/include/n4m/explain.h.
4
+ //
5
+ // Every attribution is computed by libn4m. This module only marshals inputs,
6
+ // drives the ask/tell session (the host predicts the requested rows with any
7
+ // backend, synchronously or asynchronously) and reports the native results.
8
+ import { Context } from "./context.js";
9
+ import { checkStatus, getModule, makeMatrixView } from "./ffi.js";
10
+ import { N4mError, Status } from "./types.js";
11
+ // ---- enum codes (explain.h) ------------------------------------------------
12
+ const METHOD_CODES = {
13
+ exact_shap: 0, permutation_shap: 1, kernel_shap: 2, lime: 3, occlusion: 4,
14
+ };
15
+ const BASELINE_CODES = {
16
+ background: 0, mean: 1, interpolate: 2,
17
+ };
18
+ const OPTION_KEYS = new Set(["method", "baseline", "nPermutations", "nCoalitions",
19
+ "limeKernelWidth", "limeRidge", "maxBatchRows", "seed"]);
20
+ // ---- n4m_explain_options_v1_t layout (identical on wasm32 and LP64) ---------
21
+ // uint64 struct_size @0, int32 method @8, int32 baseline @12,
22
+ // int64 n_outputs @16, n_permutations @24, n_coalitions @32,
23
+ // double lime_kernel_width @40, lime_ridge @48, int64 max_batch_rows @56,
24
+ // uint64 seed @64; total 72 bytes.
25
+ const OPTIONS_SIZE = 72;
26
+ const OPT_METHOD = 8, OPT_BASELINE = 12, OPT_N_OUTPUTS = 16, OPT_N_PERMUTATIONS = 24, OPT_N_COALITIONS = 32, OPT_LIME_WIDTH = 40, OPT_LIME_RIDGE = 48, OPT_MAX_BATCH_ROWS = 56, OPT_SEED = 64;
27
+ const DEFAULT_MAX_BATCH_ROWS = 4096;
28
+ const MAX_HEAP_BYTES = 0x7fffffff;
29
+ // ---- marshalling helpers ----------------------------------------------------
30
+ /** Tracks WASM heap allocations of one call; free() releases all of them. */
31
+ class Arena {
32
+ ptrs = [];
33
+ alloc(bytes) {
34
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > MAX_HEAP_BYTES) {
35
+ throw new RangeError("explanation buffer exceeds the WASM allocation limit");
36
+ }
37
+ const ptr = getModule()._malloc(Math.max(8, bytes));
38
+ if (ptr === 0)
39
+ throw new N4mError(Status.ERR_OUT_OF_MEMORY, "explanation allocation failed");
40
+ this.ptrs.push(ptr);
41
+ return ptr;
42
+ }
43
+ /** Copy an integer array into the heap as int64 (BigInt64 under WASM_BIGINT). */
44
+ int64(values) {
45
+ const ptr = this.alloc(values.length * 8);
46
+ const view = new BigInt64Array(getModule().HEAPU8.buffer, ptr, values.length);
47
+ for (let i = 0; i < values.length; i += 1)
48
+ view[i] = BigInt(values[i]);
49
+ return ptr;
50
+ }
51
+ f64(values) {
52
+ const ptr = this.alloc(values.length * 8);
53
+ getModule().HEAPF64.set(values, ptr / 8);
54
+ return ptr;
55
+ }
56
+ free() {
57
+ const m = getModule();
58
+ for (const ptr of this.ptrs)
59
+ m._free(ptr);
60
+ this.ptrs.length = 0;
61
+ }
62
+ }
63
+ function readF64(ptr, n) {
64
+ // slice() copies, so the result never aliases the (growable) heap.
65
+ return getModule().HEAPF64.slice(ptr / 8, ptr / 8 + n);
66
+ }
67
+ function readI64(ptr) {
68
+ return Number(new DataView(getModule().HEAPU8.buffer).getBigInt64(ptr, true));
69
+ }
70
+ function checkMatrix(name, x, allowEmptyRows = false) {
71
+ if (!(x?.data instanceof Float64Array) || !Number.isSafeInteger(x.rows) ||
72
+ !Number.isSafeInteger(x.cols) || x.rows < (allowEmptyRows ? 0 : 1) || x.cols < 1 ||
73
+ x.data.length !== x.rows * x.cols) {
74
+ throw new Error(`${name} must be a Float64Array row-major matrix with rows*cols entries`);
75
+ }
76
+ }
77
+ function checkIntegers(name, values, length) {
78
+ if (values == null || values.length !== length) {
79
+ throw new Error(`${name} must have ${length} entries`);
80
+ }
81
+ for (let i = 0; i < values.length; i += 1) {
82
+ if (!Number.isSafeInteger(values[i]))
83
+ throw new Error(`${name} must contain integers`);
84
+ }
85
+ }
86
+ function checkGrouping(grouping, nFeatures) {
87
+ if (grouping === undefined)
88
+ return nFeatures;
89
+ if (!(grouping.featureGroup instanceof Int32Array) || !Number.isSafeInteger(grouping.nGroups) ||
90
+ grouping.nGroups < 1 || grouping.featureGroup.length !== nFeatures) {
91
+ throw new Error("grouping.featureGroup must be an Int32Array of nFeatures group indices " +
92
+ "and grouping.nGroups a positive integer");
93
+ }
94
+ return grouping.nGroups;
95
+ }
96
+ function engineInfo() {
97
+ const m = getModule();
98
+ const ptr = m.ccall("n4m_get_version_string", "number", [], []);
99
+ const abi = ["major", "minor", "patch"].map(part => m.ccall(`n4m_get_abi_version_${part}`, "number", [], [])).join(".");
100
+ return { name: "nirs4all-methods", version: ptr === 0 ? "" : m.UTF8ToString(ptr), abi };
101
+ }
102
+ function additivityError(attributions, expected, predictions, nRows, nGroups, nOutputs) {
103
+ // Reported diagnostic only: max |prediction - expected - sum_g attribution|.
104
+ let worst = 0;
105
+ for (let r = 0; r < nRows; r += 1) {
106
+ for (let o = 0; o < nOutputs; o += 1) {
107
+ let total = expected[r * nOutputs + o];
108
+ for (let g = 0; g < nGroups; g += 1)
109
+ total += attributions[(r * nGroups + g) * nOutputs + o];
110
+ worst = Math.max(worst, Math.abs(predictions[r * nOutputs + o] - total));
111
+ }
112
+ }
113
+ return worst;
114
+ }
115
+ function abortError() {
116
+ return new DOMException("The explanation was aborted.", "AbortError");
117
+ }
118
+ function toPredictions(raw, rows, nOutputs) {
119
+ if (!(raw instanceof Float64Array) && !Array.isArray(raw)) {
120
+ throw new TypeError("predictBatch must return a Float64Array or number[]");
121
+ }
122
+ if (raw.length !== rows * nOutputs) {
123
+ throw new Error(`predictBatch returned ${raw.length} values, expected ${rows} x ${nOutputs}`);
124
+ }
125
+ const out = raw instanceof Float64Array ? raw : Float64Array.from(raw);
126
+ for (let i = 0; i < out.length; i += 1) {
127
+ if (!Number.isFinite(out[i]))
128
+ throw new Error("predictBatch returned a nonfinite prediction");
129
+ }
130
+ return out;
131
+ }
132
+ /** True when kernel SHAP evaluates every proper nonempty coalition, i.e. the
133
+ * native coalition budget (explain.h: 0 = min(2^G - 2, 2G + 2048)) covers
134
+ * all 2^G - 2 of them; the weighted least squares is then the exact solve. */
135
+ function kernelEnumerates(nCoalitions, nGroups) {
136
+ if (nGroups > 52)
137
+ return false;
138
+ const all = 2 ** nGroups - 2;
139
+ return (nCoalitions > 0 ? nCoalitions : 2 * nGroups + 2048) >= all;
140
+ }
141
+ function sessionExactness(method, nCoalitions, nGroups) {
142
+ switch (method) {
143
+ case "exact_shap": return "exact";
144
+ case "kernel_shap": return kernelEnumerates(nCoalitions, nGroups) ? "exact" : "sampled";
145
+ case "permutation_shap": return "sampled";
146
+ case "lime": return "surrogate";
147
+ case "occlusion": return "perturbation";
148
+ }
149
+ }
150
+ // ---- ask/tell session --------------------------------------------------------
151
+ /** Explain any model through a native ask/tell session. The host predicts
152
+ * the requested perturbed rows with predictBatch (sync or async). */
153
+ export async function explainModel(input) {
154
+ const { X, background, grouping, predictBatch, onProgress, signal } = input;
155
+ const options = input.options ?? {};
156
+ for (const key of Object.keys(options)) {
157
+ if (!OPTION_KEYS.has(key))
158
+ throw new Error(`unknown explain option ${key}`);
159
+ }
160
+ const method = options.method ?? "permutation_shap";
161
+ const baseline = options.baseline ?? "background";
162
+ if (!Object.prototype.hasOwnProperty.call(METHOD_CODES, method)) {
163
+ throw new Error(`unknown explain method ${method}`);
164
+ }
165
+ if (!Object.prototype.hasOwnProperty.call(BASELINE_CODES, baseline)) {
166
+ throw new Error(`unknown explain baseline ${baseline}`);
167
+ }
168
+ const nPermutations = options.nPermutations ?? 10;
169
+ const nCoalitions = options.nCoalitions ?? 0;
170
+ const maxBatchRows = options.maxBatchRows ?? DEFAULT_MAX_BATCH_ROWS;
171
+ const seed = options.seed ?? 0;
172
+ if (!Number.isSafeInteger(nPermutations) || nPermutations < 1) {
173
+ throw new Error("nPermutations must be a positive integer");
174
+ }
175
+ if (!Number.isSafeInteger(nCoalitions) || nCoalitions < 0) {
176
+ throw new Error("nCoalitions must be a nonnegative integer");
177
+ }
178
+ if (!Number.isSafeInteger(maxBatchRows) || maxBatchRows < 1) {
179
+ throw new Error("maxBatchRows must be a positive integer");
180
+ }
181
+ if (!Number.isSafeInteger(seed) || seed < 0) {
182
+ throw new Error("seed must be a nonnegative integer below 2^53");
183
+ }
184
+ for (const key of ["limeKernelWidth", "limeRidge"]) {
185
+ if (options[key] !== undefined && !Number.isFinite(options[key])) {
186
+ throw new Error(`${key} must be finite`);
187
+ }
188
+ }
189
+ if (typeof predictBatch !== "function")
190
+ throw new TypeError("predictBatch must be a function");
191
+ checkMatrix("X", X);
192
+ const nFeatures = X.cols;
193
+ if (background !== undefined) {
194
+ checkMatrix("background", background, true);
195
+ if (background.cols !== nFeatures)
196
+ throw new Error("background must have X.cols columns");
197
+ }
198
+ else if (baseline !== "interpolate") {
199
+ throw new Error(`the ${baseline} baseline requires a background matrix`);
200
+ }
201
+ const nGroupsIn = checkGrouping(grouping, nFeatures);
202
+ if (signal?.aborted)
203
+ throw abortError();
204
+ let evaluations = 0;
205
+ let nOutputs = input.nOutputs;
206
+ if (nOutputs === undefined) {
207
+ const probe = await predictBatch(X.data.slice(0, nFeatures), 1, nFeatures);
208
+ if (signal?.aborted)
209
+ throw abortError();
210
+ if (!(probe instanceof Float64Array) && !Array.isArray(probe)) {
211
+ throw new TypeError("predictBatch must return a Float64Array or number[]");
212
+ }
213
+ nOutputs = probe.length;
214
+ evaluations += 1;
215
+ }
216
+ if (!Number.isSafeInteger(nOutputs) || nOutputs < 1) {
217
+ throw new Error("nOutputs must be a positive integer");
218
+ }
219
+ const m = getModule();
220
+ const arena = new Arena();
221
+ let ctx = null;
222
+ let xView = null;
223
+ let bgView = null;
224
+ let session = 0;
225
+ try {
226
+ ctx = Context.create();
227
+ xView = makeMatrixView(X.data, X.rows, X.cols);
228
+ bgView = background !== undefined
229
+ ? makeMatrixView(background.data, background.rows, background.cols)
230
+ : makeMatrixView(new Float64Array(0), 0, nFeatures);
231
+ const opt = arena.alloc(OPTIONS_SIZE);
232
+ checkStatus(m.ccall("n4m_explain_options_init_v1", "number", ["number"], [opt]));
233
+ {
234
+ const dv = new DataView(m.HEAPU8.buffer);
235
+ dv.setInt32(opt + OPT_METHOD, METHOD_CODES[method], true);
236
+ dv.setInt32(opt + OPT_BASELINE, BASELINE_CODES[baseline], true);
237
+ dv.setBigInt64(opt + OPT_N_OUTPUTS, BigInt(nOutputs), true);
238
+ dv.setBigInt64(opt + OPT_N_PERMUTATIONS, BigInt(nPermutations), true);
239
+ dv.setBigInt64(opt + OPT_N_COALITIONS, BigInt(nCoalitions), true);
240
+ if (options.limeKernelWidth !== undefined) {
241
+ dv.setFloat64(opt + OPT_LIME_WIDTH, options.limeKernelWidth, true);
242
+ }
243
+ if (options.limeRidge !== undefined)
244
+ dv.setFloat64(opt + OPT_LIME_RIDGE, options.limeRidge, true);
245
+ dv.setBigInt64(opt + OPT_MAX_BATCH_ROWS, BigInt(maxBatchRows), true);
246
+ dv.setBigUint64(opt + OPT_SEED, BigInt(seed), true);
247
+ }
248
+ const groupPtr = grouping === undefined ? 0 : arena.int64(grouping.featureGroup);
249
+ const outSession = arena.alloc(4);
250
+ m.setValue(outSession, 0, "i32");
251
+ checkStatus(m.ccall("n4m_explain_session_create_v1", "number", ["number", "number", "number", "number", "i64", "number", "number"], [ctx.handle, xView.viewPtr, bgView.viewPtr, groupPtr,
252
+ BigInt(nGroupsIn), opt, outSession]), ctx.handle);
253
+ session = m.getValue(outSession, "i32");
254
+ const info = arena.alloc(5 * 8);
255
+ checkStatus(m.ccall("n4m_explain_session_info_v1", "number", Array(6).fill("number"), [session, info, info + 8, info + 16, info + 24, info + 32]));
256
+ const nRows = readI64(info), nGroups = readI64(info + 16);
257
+ const total = readI64(info + 32);
258
+ if (readI64(info + 8) !== nFeatures || readI64(info + 24) !== nOutputs) {
259
+ throw new Error("native explanation session reports unexpected dimensions");
260
+ }
261
+ const capacity = Math.max(1, Math.min(maxBatchRows, total));
262
+ const rowsPtr = arena.alloc(capacity * nFeatures * 8);
263
+ const predPtr = arena.alloc(capacity * nOutputs * 8);
264
+ const writtenPtr = arena.alloc(8);
265
+ let done = 0;
266
+ for (;;) {
267
+ if (signal?.aborted)
268
+ throw abortError();
269
+ checkStatus(m.ccall("n4m_explain_session_next_batch_v1", "number", ["number", "number", "number", "i64", "number"], [ctx.handle, session, rowsPtr, BigInt(capacity), writtenPtr]), ctx.handle);
270
+ const written = readI64(writtenPtr);
271
+ if (written === 0)
272
+ break;
273
+ // Fresh copy: the heap may grow (detaching views) while predictBatch awaits.
274
+ const rows = readF64(rowsPtr, written * nFeatures);
275
+ const predicted = toPredictions(await predictBatch(rows, written, nFeatures), written, nOutputs);
276
+ if (signal?.aborted)
277
+ throw abortError();
278
+ m.HEAPF64.set(predicted, predPtr / 8);
279
+ checkStatus(m.ccall("n4m_explain_session_submit_v1", "number", ["number", "number", "number", "i64"], [ctx.handle, session, predPtr, BigInt(written)]), ctx.handle);
280
+ done += written;
281
+ evaluations += written;
282
+ onProgress?.(done, total);
283
+ }
284
+ const attrSize = nRows * nGroups * nOutputs, outSize = nRows * nOutputs;
285
+ const attrPtr = arena.alloc(attrSize * 8);
286
+ const expPtr = arena.alloc(outSize * 8);
287
+ const predOutPtr = arena.alloc(outSize * 8);
288
+ const hasStdError = method === "permutation_shap";
289
+ const stdPtr = hasStdError ? arena.alloc(attrSize * 8) : 0;
290
+ checkStatus(m.ccall("n4m_explain_session_result_v1", "number", ["number", "number", "number", "i64", "number", "i64", "number", "i64", "number", "i64"], [ctx.handle, session, attrPtr, BigInt(attrSize), expPtr, BigInt(outSize),
291
+ predOutPtr, BigInt(outSize), stdPtr, BigInt(hasStdError ? attrSize : 0)]), ctx.handle);
292
+ const attributions = readF64(attrPtr, attrSize);
293
+ const expected = readF64(expPtr, outSize);
294
+ const predictions = readF64(predOutPtr, outSize);
295
+ const additive = method !== "lime" && method !== "occlusion";
296
+ return {
297
+ kind: method,
298
+ baseline,
299
+ exactness: sessionExactness(method, nCoalitions, nGroups),
300
+ additive,
301
+ groupAggregation: "group_game",
302
+ nRows, nGroups, nOutputs, nFeatures,
303
+ attributions, expected, predictions,
304
+ stdError: hasStdError ? readF64(stdPtr, attrSize) : null,
305
+ additivityMaxAbsError: additive
306
+ ? additivityError(attributions, expected, predictions, nRows, nGroups, nOutputs)
307
+ : null,
308
+ evaluations,
309
+ settings: {
310
+ method, baseline,
311
+ // The interpolate baseline ignores background rows.
312
+ n_background: baseline === "interpolate" ? 0 : background?.rows ?? 0,
313
+ n_permutations: method === "permutation_shap" ? nPermutations : null,
314
+ n_coalitions: method === "kernel_shap" || method === "lime" ? nCoalitions : null,
315
+ lime_kernel_width: method === "lime" ? (options.limeKernelWidth ?? 0) : null,
316
+ lime_ridge: method === "lime" ? (options.limeRidge ?? 1) : null,
317
+ max_batch_rows: maxBatchRows,
318
+ seed,
319
+ n_outputs_inferred: input.nOutputs === undefined,
320
+ total_evaluations: total,
321
+ },
322
+ engine: engineInfo(),
323
+ };
324
+ }
325
+ finally {
326
+ if (session !== 0)
327
+ m.ccall("n4m_explain_session_destroy", null, ["number"], [session]);
328
+ bgView?.free();
329
+ xView?.free();
330
+ arena.free();
331
+ ctx?.destroy();
332
+ }
333
+ }
334
+ // ---- model-specific exact explainers ----------------------------------------
335
+ /** Exact interventional SHAP of an affine model X . coefficients + intercept. */
336
+ export function linearShap(input) {
337
+ const { X, coefficients, intercept, reference, grouping } = input;
338
+ checkMatrix("X", X);
339
+ checkMatrix("coefficients", coefficients);
340
+ const nFeatures = X.cols, nOutputs = coefficients.cols;
341
+ if (coefficients.rows !== nFeatures)
342
+ throw new Error("coefficients must be nFeatures x nOutputs");
343
+ if (!(reference instanceof Float64Array) || reference.length !== nFeatures) {
344
+ throw new Error("reference must be a Float64Array of nFeatures values");
345
+ }
346
+ if (intercept !== undefined && (!(intercept instanceof Float64Array) || intercept.length !== nOutputs)) {
347
+ throw new Error("intercept must be a Float64Array of nOutputs values");
348
+ }
349
+ const nGroups = checkGrouping(grouping, nFeatures);
350
+ const m = getModule();
351
+ const arena = new Arena();
352
+ let ctx = null;
353
+ let xView = null;
354
+ let bView = null;
355
+ try {
356
+ ctx = Context.create();
357
+ xView = makeMatrixView(X.data, X.rows, X.cols);
358
+ bView = makeMatrixView(coefficients.data, coefficients.rows, coefficients.cols);
359
+ const nRows = X.rows, attrSize = nRows * nGroups * nOutputs, outSize = nRows * nOutputs;
360
+ const interceptPtr = intercept === undefined ? 0 : arena.f64(intercept);
361
+ const referencePtr = arena.f64(reference);
362
+ const groupPtr = grouping === undefined ? 0 : arena.int64(grouping.featureGroup);
363
+ const attrPtr = arena.alloc(attrSize * 8), expPtr = arena.alloc(outSize * 8);
364
+ const predPtr = arena.alloc(outSize * 8);
365
+ checkStatus(m.ccall("n4m_explain_linear_v1", "number", ["number", "number", "number", "number", "number", "number", "i64",
366
+ "number", "i64", "number", "i64", "number", "i64"], [ctx.handle, xView.viewPtr, bView.viewPtr, interceptPtr, referencePtr, groupPtr,
367
+ BigInt(nGroups), attrPtr, BigInt(attrSize),
368
+ expPtr, BigInt(outSize), predPtr, BigInt(outSize)]), ctx.handle);
369
+ const attributions = readF64(attrPtr, attrSize);
370
+ const expected = readF64(expPtr, outSize);
371
+ const predictions = readF64(predPtr, outSize);
372
+ return {
373
+ kind: "linear_shap", baseline: null, exactness: "exact", additive: true,
374
+ // Linear group sums are exact Shapley values of the group game.
375
+ groupAggregation: grouping === undefined ? "none" : "group_game",
376
+ nRows, nGroups, nOutputs, nFeatures, attributions, expected, predictions,
377
+ stdError: null,
378
+ additivityMaxAbsError: additivityError(attributions, expected, predictions, nRows, nGroups, nOutputs),
379
+ evaluations: 0,
380
+ settings: { method: "linear_shap", has_intercept: intercept !== undefined },
381
+ engine: engineInfo(),
382
+ };
383
+ }
384
+ finally {
385
+ bView?.free();
386
+ xView?.free();
387
+ arena.free();
388
+ ctx?.destroy();
389
+ }
390
+ }
391
+ /** Exact path-dependent TreeSHAP over a generic flat tree ensemble. Grouped
392
+ * values are sums of per-feature Shapley values, not group-game values. */
393
+ export function treeShap(input) {
394
+ const { X, trees, grouping } = input;
395
+ checkMatrix("X", X);
396
+ const nFeatures = X.cols, nOutputs = trees.nOutputs;
397
+ if (!Number.isSafeInteger(nOutputs) || nOutputs < 1)
398
+ throw new Error("trees.nOutputs must be a positive integer");
399
+ const nTrees = trees.treeOffsets.length - 1;
400
+ const nNodes = trees.feature.length;
401
+ if (nTrees < 1)
402
+ throw new Error("trees.treeOffsets must hold nTrees + 1 offsets");
403
+ checkIntegers("trees.treeOffsets", trees.treeOffsets, nTrees + 1);
404
+ for (let t = 0; t < nTrees; t += 1) {
405
+ if (trees.treeOffsets[t] >= trees.treeOffsets[t + 1]) {
406
+ throw new Error("trees.treeOffsets must be strictly increasing");
407
+ }
408
+ }
409
+ if (trees.treeOffsets[0] !== 0 || trees.treeOffsets[nTrees] !== nNodes) {
410
+ throw new Error("trees.treeOffsets must start at 0 and end at the node count");
411
+ }
412
+ checkIntegers("trees.feature", trees.feature, nNodes);
413
+ checkIntegers("trees.left", trees.left, nNodes);
414
+ checkIntegers("trees.right", trees.right, nNodes);
415
+ if (!(trees.threshold instanceof Float64Array) || trees.threshold.length !== nNodes ||
416
+ !(trees.cover instanceof Float64Array) || trees.cover.length !== nNodes ||
417
+ !(trees.value instanceof Float64Array) || trees.value.length !== nNodes * nOutputs) {
418
+ throw new Error("trees.threshold/cover must hold nNodes values and trees.value nNodes * nOutputs");
419
+ }
420
+ if (trees.defaultLeft !== undefined &&
421
+ (!(trees.defaultLeft instanceof Uint8Array) || trees.defaultLeft.length !== nNodes)) {
422
+ throw new Error("trees.defaultLeft must be a Uint8Array of nNodes flags");
423
+ }
424
+ if (trees.baseOffset !== undefined &&
425
+ (!(trees.baseOffset instanceof Float64Array) || trees.baseOffset.length !== nOutputs)) {
426
+ throw new Error("trees.baseOffset must be a Float64Array of nOutputs values");
427
+ }
428
+ const decisionType = trees.decisionType ?? 0;
429
+ if (decisionType !== 0 && decisionType !== 1)
430
+ throw new Error("trees.decisionType must be 0 or 1");
431
+ const treeScale = trees.treeScale ?? 1;
432
+ if (!Number.isFinite(treeScale))
433
+ throw new Error("trees.treeScale must be finite");
434
+ const nGroups = checkGrouping(grouping, nFeatures);
435
+ const m = getModule();
436
+ const arena = new Arena();
437
+ let ctx = null;
438
+ let xView = null;
439
+ try {
440
+ ctx = Context.create();
441
+ xView = makeMatrixView(X.data, X.rows, X.cols);
442
+ const nRows = X.rows, attrSize = nRows * nGroups * nOutputs, outSize = nRows * nOutputs;
443
+ const offsetsPtr = arena.int64(trees.treeOffsets);
444
+ const featurePtr = arena.int64(trees.feature);
445
+ const thresholdPtr = arena.f64(trees.threshold);
446
+ const leftPtr = arena.int64(trees.left);
447
+ const rightPtr = arena.int64(trees.right);
448
+ let defaultLeftPtr = 0;
449
+ if (trees.defaultLeft !== undefined) {
450
+ defaultLeftPtr = arena.alloc(nNodes);
451
+ m.HEAPU8.set(trees.defaultLeft, defaultLeftPtr);
452
+ }
453
+ const coverPtr = arena.f64(trees.cover);
454
+ const valuePtr = arena.f64(trees.value);
455
+ const basePtr = trees.baseOffset === undefined ? 0 : arena.f64(trees.baseOffset);
456
+ const groupPtr = grouping === undefined ? 0 : arena.int64(grouping.featureGroup);
457
+ const attrPtr = arena.alloc(attrSize * 8), expPtr = arena.alloc(outSize * 8);
458
+ const predPtr = arena.alloc(outSize * 8);
459
+ checkStatus(m.ccall("n4m_explain_tree_path_dependent_v1", "number", ["number", "number", "i64", "number", "number", "number", "number", "number", "number",
460
+ "number", "number", "i64", "number", "number", "number", "number", "i64",
461
+ "number", "i64", "number", "i64", "number", "i64"], [ctx.handle, xView.viewPtr, BigInt(nTrees), offsetsPtr, featurePtr, thresholdPtr,
462
+ leftPtr, rightPtr, defaultLeftPtr, coverPtr, valuePtr, BigInt(nOutputs), decisionType,
463
+ basePtr, treeScale, groupPtr, BigInt(nGroups),
464
+ attrPtr, BigInt(attrSize), expPtr, BigInt(outSize), predPtr, BigInt(outSize)]), ctx.handle);
465
+ const attributions = readF64(attrPtr, attrSize);
466
+ const expected = readF64(expPtr, outSize);
467
+ const predictions = readF64(predPtr, outSize);
468
+ return {
469
+ kind: "tree_shap", baseline: null, exactness: "exact", additive: true,
470
+ groupAggregation: grouping === undefined ? "none" : "sum_of_feature_values",
471
+ nRows, nGroups, nOutputs, nFeatures, attributions, expected, predictions,
472
+ stdError: null,
473
+ additivityMaxAbsError: additivityError(attributions, expected, predictions, nRows, nGroups, nOutputs),
474
+ evaluations: 0,
475
+ settings: { method: "tree_shap", feature_perturbation: "tree_path_dependent",
476
+ n_trees: nTrees, decision_type: decisionType, tree_scale: treeScale },
477
+ engine: engineInfo(),
478
+ };
479
+ }
480
+ finally {
481
+ xView?.free();
482
+ arena.free();
483
+ ctx?.destroy();
484
+ }
485
+ }
486
+ // ---- grouping and summary helpers -------------------------------------------
487
+ function toInt32(ptr, n) {
488
+ const view = new BigInt64Array(getModule().HEAPU8.buffer, ptr, n);
489
+ return Int32Array.from(view, v => Number(v));
490
+ }
491
+ /** Contiguous fixed-width partition: feature j -> group floor(j / width). */
492
+ export function groupsFixedWidth(nFeatures, width) {
493
+ if (!Number.isSafeInteger(nFeatures) || nFeatures < 1 || !Number.isSafeInteger(width) || width < 1) {
494
+ throw new Error("nFeatures and width must be positive integers");
495
+ }
496
+ const m = getModule();
497
+ const arena = new Arena();
498
+ try {
499
+ const groups = arena.alloc(nFeatures * 8), count = arena.alloc(8);
500
+ checkStatus(m.ccall("n4m_explain_groups_fixed_width_v1", "number", ["i64", "i64", "number", "i64", "number"], [BigInt(nFeatures), BigInt(width), groups, BigInt(nFeatures), count]));
501
+ return { featureGroup: toInt32(groups, nFeatures), nGroups: readI64(count) };
502
+ }
503
+ finally {
504
+ arena.free();
505
+ }
506
+ }
507
+ /** Partition from half-open [start, end) feature-index ranges. Range r becomes
508
+ * group r; every maximal uncovered run becomes one further group. */
509
+ export function groupsFromRanges(nFeatures, ranges) {
510
+ if (!Number.isSafeInteger(nFeatures) || nFeatures < 1)
511
+ throw new Error("nFeatures must be a positive integer");
512
+ if (!Array.isArray(ranges) || ranges.some(r => !Array.isArray(r) || r.length !== 2)) {
513
+ throw new Error("ranges must be an array of [start, end) pairs");
514
+ }
515
+ const flat = ranges.flatMap(r => [r[0], r[1]]);
516
+ checkIntegers("ranges", flat, flat.length);
517
+ const m = getModule();
518
+ const arena = new Arena();
519
+ try {
520
+ const rangesPtr = arena.int64(flat);
521
+ const capacity = ranges.length + nFeatures;
522
+ const groups = arena.alloc(nFeatures * 8), rangeOf = arena.alloc(capacity * 8);
523
+ const count = arena.alloc(8);
524
+ checkStatus(m.ccall("n4m_explain_groups_from_ranges_v1", "number", ["i64", "number", "i64", "number", "i64", "number", "i64", "number"], [BigInt(nFeatures), rangesPtr, BigInt(ranges.length), groups, BigInt(nFeatures),
525
+ rangeOf, BigInt(capacity), count]));
526
+ const nGroups = readI64(count);
527
+ return { featureGroup: toInt32(groups, nFeatures), nGroups, rangeOfGroup: toInt32(rangeOf, nGroups) };
528
+ }
529
+ finally {
530
+ arena.free();
531
+ }
532
+ }
533
+ /** Per-group mean |attribution| and mean signed attribution over rows. */
534
+ export function summarizeAttributions(result, outputIndex = 0) {
535
+ const { nRows, nGroups, nOutputs, attributions } = result;
536
+ if (!(attributions instanceof Float64Array) || attributions.length !== nRows * nGroups * nOutputs) {
537
+ throw new Error("result.attributions must hold nRows * nGroups * nOutputs values");
538
+ }
539
+ if (!Number.isSafeInteger(outputIndex) || outputIndex < 0 || outputIndex >= nOutputs) {
540
+ throw new Error("outputIndex out of range");
541
+ }
542
+ const m = getModule();
543
+ const arena = new Arena();
544
+ try {
545
+ const attrPtr = arena.f64(attributions);
546
+ const absPtr = arena.alloc(nGroups * 8), signedPtr = arena.alloc(nGroups * 8);
547
+ checkStatus(m.ccall("n4m_explain_summarize_v1", "number", ["number", "i64", "i64", "i64", "i64", "number", "number", "i64"], [attrPtr, BigInt(nRows), BigInt(nGroups), BigInt(nOutputs), BigInt(outputIndex),
548
+ absPtr, signedPtr, BigInt(nGroups)]));
549
+ return { meanAbs: readF64(absPtr, nGroups), meanSigned: readF64(signedPtr, nGroups) };
550
+ }
551
+ finally {
552
+ arena.free();
553
+ }
554
+ }
package/dist/index.d.ts CHANGED
@@ -24,3 +24,4 @@ export declare function version(): string;
24
24
  export declare function abiVersion(): readonly [number, number, number];
25
25
  export { rank, type RankingMethod, type RankingOptions, type RankingCandidate, type RankingResult } from "./ranking.js";
26
26
  export { mixedEffects, fanova, normalizeLoss, type MixedEffectsOptions, type MixedEffectsResult, type FanovaOptions, type FanovaResult } from "./componentAnalysis.js";
27
+ export { explainModel, linearShap, treeShap, groupsFixedWidth, groupsFromRanges, summarizeAttributions, type ExplainMethod, type ExplainBaseline, type AttributionKind, type ExplainOptions, type PredictBatch, type FeatureGrouping, type ExplainModelInput, type AttributionResult, type FlatTreeEnsemble } from "./explain.js";
package/dist/index.js CHANGED
@@ -47,3 +47,4 @@ export function abiVersion() {
47
47
  }
48
48
  export { rank } from "./ranking.js";
49
49
  export { mixedEffects, fanova, normalizeLoss } from "./componentAnalysis.js";
50
+ export { explainModel, linearShap, treeShap, groupsFixedWidth, groupsFromRanges, summarizeAttributions } from "./explain.js";