@nirs4all/methods 1.3.4 → 1.3.6

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.
package/dist/n4m.wasm CHANGED
Binary file
@@ -0,0 +1,116 @@
1
+ import { type Matrix } from "./types.js";
2
+ export interface PreflightPcaResult {
3
+ scores: Matrix;
4
+ loadings: Matrix;
5
+ eigenvalues: Float64Array;
6
+ /** [trace(C), trace(C*C)] over the full centered covariance spectrum. */
7
+ fullMoments: readonly [number, number];
8
+ }
9
+ export interface PreflightRepeatabilityResult {
10
+ pooledSd: Float64Array;
11
+ icc: Float64Array;
12
+ nCompleteGroups: number[];
13
+ /** 0=computed, 1=insufficient, 2=unbalanced, 3=zero total variance. */
14
+ bandStatus: Int32Array;
15
+ }
16
+ export interface PreflightNeighborResult {
17
+ indices: number[];
18
+ distances: Float64Array;
19
+ rows: number;
20
+ k: number;
21
+ }
22
+ export interface PreflightLocalContrastResult {
23
+ contrast: number;
24
+ fractionRowsWithNeighbors: number;
25
+ observedSameClassFraction: number;
26
+ expectedSameClassFraction: number;
27
+ }
28
+ export interface HdbscanOptions {
29
+ minClusterSize: number;
30
+ /** Neighbors defining the core distance, the row itself included (scikit-learn). */
31
+ minSamples: number;
32
+ selection?: "eom" | "leaf";
33
+ allowSingleCluster?: boolean;
34
+ }
35
+ export interface HdbscanTreeNode {
36
+ /** Parent node index, -1 for the root (node 0). */
37
+ parent: number;
38
+ size: number;
39
+ /** Selected cluster label or -1. */
40
+ label: number;
41
+ lambdaBirth: number;
42
+ lambdaDeath: number;
43
+ stability: number;
44
+ }
45
+ export interface HdbscanResult {
46
+ /** -1 = noise; clusters 0..nClusters-1. */
47
+ labels: number[];
48
+ /** scikit-learn probabilities_: a membership strength, not a probability. */
49
+ membership: Float64Array;
50
+ /** GLOSH outlier scores in [0, 1]. */
51
+ outlierScores: Float64Array;
52
+ nClusters: number;
53
+ /** scikit-learn-contrib/hdbscan cluster_persistence_, one value per label. */
54
+ persistence: Float64Array;
55
+ tree: HdbscanTreeNode[];
56
+ }
57
+ export interface PreflightFactorAssociationResult {
58
+ /** eta^2 (continuous) or Cramer's V (categorical); NaN when undefined. */
59
+ effectSize: number;
60
+ /** One-way ANOVA F or Pearson chi-square; NaN when undefined. */
61
+ statistic: number;
62
+ df1: number;
63
+ df2: number;
64
+ nLevels: number;
65
+ nTargetValues: number;
66
+ /** log10 upper bound on distinct permutation outcomes. */
67
+ log10DistinctPermutations: number;
68
+ /** Monte Carlo (1+b)/(1+B); NaN without permutations. */
69
+ pValue: number;
70
+ nAtLeastObserved: number;
71
+ nPermutationsExecuted: number;
72
+ }
73
+ /** Centered PCA using the native Methods SVD. Output matrices are row-major. */
74
+ export declare function preflightPca(X: Matrix, k: number): PreflightPcaResult;
75
+ /** Per-feature pooled repeatability and balanced ICC(1,1). */
76
+ export declare function preflightRepeatability(X: Matrix, groupIds: readonly (number | bigint)[], validMask?: Uint8Array): PreflightRepeatabilityResult;
77
+ /** Finite-value summary: count, min, max, mean, sample SD, Q1, median, Q3. */
78
+ export declare function preflightSummary(values: Float64Array, validMask?: Uint8Array): Float64Array;
79
+ /** Euclidean reference neighbors, optionally excluding equal group IDs. */
80
+ export declare function preflightNearestNeighbors(query: Matrix, reference: Matrix, k: number, queryGroups?: readonly (number | bigint)[], referenceGroups?: readonly (number | bigint)[]): PreflightNeighborResult;
81
+ /** Local Y coherence using an existing row-major n x k neighbor-index table. */
82
+ export declare function preflightLocalContrast(targets: Float64Array, neighborIndices: readonly (number | bigint)[], k: number, categorical: boolean, groupIds?: readonly (number | bigint)[]): PreflightLocalContrastResult;
83
+ /** Euclidean HDBSCAN* (scikit-learn 1.9.1 semantics, stable MST tie order). */
84
+ export declare function clusterHdbscan(X: Matrix, options: HdbscanOptions): HdbscanResult;
85
+ /** Adjusted Rand index; NaN for n<2 or identical trivial partitions. Noise is an ordinary label. */
86
+ export declare function preflightAdjustedRandIndex(a: readonly (number | bigint)[], b: readonly (number | bigint)[]): number;
87
+ export interface PreflightNoiseProxyResult {
88
+ /** sqrt(mean residual^2)/gain per feature; NaN at edges or without rows. */
89
+ bandNoise: Float64Array;
90
+ bandCounts: number[];
91
+ /** Root mean square over every evaluable residual cell, divided by gain. */
92
+ pooled: number;
93
+ /** Residual gain sqrt(sum((delta - weights)^2)) for unit white noise. */
94
+ gain: number;
95
+ }
96
+ export interface PreflightPairsResult {
97
+ /** Row-major listed pairs: [query, reference] for each listed pair. */
98
+ pairs: number[];
99
+ distances: Float64Array;
100
+ queryFlags: Uint8Array;
101
+ referenceFlags: Uint8Array;
102
+ totalPairs: number;
103
+ candidatePairs: number;
104
+ }
105
+ /** Savitzky-Golay smoothing-residual noise proxy; interior features only. */
106
+ export declare function preflightNoiseProxy(X: Matrix, windowLength: number, polyorder: number, validMask?: Uint8Array): PreflightNoiseProxyResult;
107
+ /**
108
+ * Row pairs with root-mean-square feature difference <= tolerance. Without a
109
+ * reference, query rows are compared with each other (i < h).
110
+ */
111
+ export declare function preflightPairsWithinTolerance(query: Matrix, tolerance: number, maxPairs: number, reference?: Matrix, queryGroups?: readonly (number | bigint)[], referenceGroups?: readonly (number | bigint)[]): PreflightPairsResult;
112
+ /** Factor-target association over exchangeable units with seeded permutations.
113
+ * The seed is an unsigned 64-bit integer; pass a bigint above 2^53. */
114
+ export declare function preflightFactorAssociation(factorCodes: readonly (number | bigint)[], targets: Float64Array, categorical: boolean, nPermutations: number, seed: number | bigint): PreflightFactorAssociationResult;
115
+ /** Holm step-down adjusted p-values for one hypothesis family. */
116
+ export declare function preflightHolmAdjust(pValues: Float64Array): Float64Array;
@@ -0,0 +1,401 @@
1
+ // SPDX-License-Identifier: CECILL-2.1
2
+ // Thin, caller-buffer wrappers for the public Methods Preflight diagnostics.
3
+ import { checkStatus, getModule, makeMatrixView } from "./ffi.js";
4
+ import { Context } from "./context.js";
5
+ import { N4mError, Status } from "./types.js";
6
+ function validateMatrix(X) {
7
+ if (!Number.isSafeInteger(X.rows) || !Number.isSafeInteger(X.cols) ||
8
+ X.rows < 1 || X.cols < 1 || X.data.length !== X.rows * X.cols) {
9
+ throw new RangeError("invalid Preflight matrix dimensions");
10
+ }
11
+ }
12
+ function validateGroupIds(values) {
13
+ for (const value of values) {
14
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
15
+ throw new RangeError("group IDs supplied as numbers must be safe integers");
16
+ }
17
+ const id = BigInt(value);
18
+ if (id < -(1n << 63n) || id >= (1n << 63n)) {
19
+ throw new RangeError("group ID is outside signed int64 range");
20
+ }
21
+ }
22
+ }
23
+ class NativeScope {
24
+ ctx = Context.create();
25
+ releases = [];
26
+ alloc(bytes) {
27
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > 0x7fffffff) {
28
+ throw new RangeError("Preflight buffer exceeds WASM allocation limit");
29
+ }
30
+ const m = getModule();
31
+ const ptr = m._malloc(Math.max(1, bytes));
32
+ if (ptr === 0)
33
+ throw new N4mError(Status.ERR_OUT_OF_MEMORY, "WASM allocation failed");
34
+ this.releases.push(() => m._free(ptr));
35
+ return ptr;
36
+ }
37
+ matrix(data, rows, cols) {
38
+ const v = makeMatrixView(data, rows, cols);
39
+ this.releases.push(v.free);
40
+ return v;
41
+ }
42
+ i64(values) {
43
+ const ptr = this.alloc(values.length * 8);
44
+ const dv = new DataView(getModule().HEAPU8.buffer);
45
+ for (let i = 0; i < values.length; i++) {
46
+ dv.setBigInt64(ptr + i * 8, BigInt(values[i]), true);
47
+ }
48
+ return ptr;
49
+ }
50
+ close() {
51
+ for (let i = this.releases.length - 1; i >= 0; --i)
52
+ this.releases[i]();
53
+ this.ctx.destroy();
54
+ }
55
+ }
56
+ function copyF64(ptr, n) {
57
+ return new Float64Array(getModule().HEAPF64.slice(ptr / 8, ptr / 8 + n));
58
+ }
59
+ /** Centered PCA using the native Methods SVD. Output matrices are row-major. */
60
+ export function preflightPca(X, k) {
61
+ validateMatrix(X);
62
+ if (!Number.isInteger(k) || k < 1 || k > Math.min(X.rows, X.cols)) {
63
+ throw new RangeError("invalid PCA component count");
64
+ }
65
+ const m = getModule();
66
+ const scope = new NativeScope();
67
+ try {
68
+ const ctx = scope.ctx;
69
+ const x = scope.matrix(X.data, X.rows, X.cols);
70
+ const scores = scope.matrix(new Float64Array(X.rows * k), X.rows, k);
71
+ const loadings = scope.matrix(new Float64Array(k * X.cols), k, X.cols);
72
+ const eigen = scope.alloc(k * 8), moments = scope.alloc(16);
73
+ const st = m.ccall("n4m_preflight_pca_compute", "number", ["number", "number", "number", "number", "number", "number", "number"], [ctx.handle, x.viewPtr, k, scores.viewPtr, loadings.viewPtr, eigen, moments]);
74
+ checkStatus(st, ctx.handle);
75
+ return {
76
+ scores: { data: copyF64(scores.dataPtr, X.rows * k), rows: X.rows, cols: k },
77
+ loadings: { data: copyF64(loadings.dataPtr, k * X.cols), rows: k, cols: X.cols },
78
+ eigenvalues: copyF64(eigen, k),
79
+ fullMoments: [m.HEAPF64[moments / 8], m.HEAPF64[moments / 8 + 1]],
80
+ };
81
+ }
82
+ finally {
83
+ scope.close();
84
+ }
85
+ }
86
+ /** Per-feature pooled repeatability and balanced ICC(1,1). */
87
+ export function preflightRepeatability(X, groupIds, validMask) {
88
+ validateMatrix(X);
89
+ if (groupIds.length !== X.rows || (validMask && validMask.length !== X.data.length)) {
90
+ throw new RangeError("repeatability group or mask length mismatch");
91
+ }
92
+ validateGroupIds(groupIds);
93
+ const m = getModule(), scope = new NativeScope();
94
+ try {
95
+ const ctx = scope.ctx;
96
+ const x = scope.matrix(X.data, X.rows, X.cols);
97
+ const groups = scope.i64(groupIds);
98
+ const mask = validMask ? scope.alloc(validMask.length) : 0;
99
+ const sd = scope.alloc(X.cols * 8), icc = scope.alloc(X.cols * 8);
100
+ const counts = scope.alloc(X.cols * 8), status = scope.alloc(X.cols * 4);
101
+ if (validMask)
102
+ m.HEAPU8.set(validMask, mask);
103
+ const st = m.ccall("n4m_preflight_repeatability_compute", "number", Array(8).fill("number"), [ctx.handle, x.viewPtr, groups, mask, sd, icc, counts, status]);
104
+ checkStatus(st, ctx.handle);
105
+ const dv = new DataView(m.HEAPU8.buffer);
106
+ return {
107
+ pooledSd: copyF64(sd, X.cols), icc: copyF64(icc, X.cols),
108
+ nCompleteGroups: Array.from({ length: X.cols }, (_, j) => Number(dv.getBigInt64(counts + j * 8, true))),
109
+ bandStatus: new Int32Array(m.HEAP32.slice(status / 4, status / 4 + X.cols)),
110
+ };
111
+ }
112
+ finally {
113
+ scope.close();
114
+ }
115
+ }
116
+ /** Finite-value summary: count, min, max, mean, sample SD, Q1, median, Q3. */
117
+ export function preflightSummary(values, validMask) {
118
+ if (validMask && validMask.length !== values.length)
119
+ throw new RangeError("summary mask length mismatch");
120
+ const m = getModule(), scope = new NativeScope();
121
+ try {
122
+ const ctx = scope.ctx;
123
+ const input = scope.alloc(values.length * 8);
124
+ const mask = validMask ? scope.alloc(validMask.length) : 0;
125
+ const out = scope.alloc(64);
126
+ m.HEAPF64.set(values, input / 8);
127
+ if (validMask)
128
+ m.HEAPU8.set(validMask, mask);
129
+ const st = m.ccall("n4m_preflight_summary_compute", "number", ["number", "number", "number", "i64", "number"], [ctx.handle, input, mask, BigInt(values.length), out]);
130
+ checkStatus(st, ctx.handle);
131
+ return copyF64(out, 8);
132
+ }
133
+ finally {
134
+ scope.close();
135
+ }
136
+ }
137
+ /** Euclidean reference neighbors, optionally excluding equal group IDs. */
138
+ export function preflightNearestNeighbors(query, reference, k, queryGroups, referenceGroups) {
139
+ validateMatrix(query);
140
+ validateMatrix(reference);
141
+ if (query.cols !== reference.cols || !Number.isInteger(k) || k < 1 ||
142
+ (queryGroups === undefined) !== (referenceGroups === undefined) ||
143
+ (queryGroups && queryGroups.length !== query.rows) ||
144
+ (referenceGroups && referenceGroups.length !== reference.rows)) {
145
+ throw new RangeError("invalid neighbor shapes, groups or k");
146
+ }
147
+ if (queryGroups)
148
+ validateGroupIds(queryGroups);
149
+ if (referenceGroups)
150
+ validateGroupIds(referenceGroups);
151
+ const m = getModule(), scope = new NativeScope();
152
+ try {
153
+ const ctx = scope.ctx;
154
+ const q = scope.matrix(query.data, query.rows, query.cols);
155
+ const r = scope.matrix(reference.data, reference.rows, reference.cols);
156
+ const qg = queryGroups ? scope.i64(queryGroups) : 0;
157
+ const rg = referenceGroups ? scope.i64(referenceGroups) : 0;
158
+ const len = query.rows * k;
159
+ const idx = scope.alloc(len * 8), dist = scope.alloc(len * 8);
160
+ const st = m.ccall("n4m_preflight_nearest_neighbors", "number", Array(8).fill("number"), [ctx.handle, q.viewPtr, r.viewPtr, qg, rg, k, idx, dist]);
161
+ checkStatus(st, ctx.handle);
162
+ const dv = new DataView(m.HEAPU8.buffer);
163
+ return {
164
+ indices: Array.from({ length: len }, (_, j) => Number(dv.getBigInt64(idx + j * 8, true))),
165
+ distances: copyF64(dist, len), rows: query.rows, k,
166
+ };
167
+ }
168
+ finally {
169
+ scope.close();
170
+ }
171
+ }
172
+ /** Local Y coherence using an existing row-major n x k neighbor-index table. */
173
+ export function preflightLocalContrast(targets, neighborIndices, k, categorical, groupIds) {
174
+ if (!Number.isSafeInteger(k) || k < 1 || targets.length < 1 ||
175
+ neighborIndices.length !== targets.length * k ||
176
+ (groupIds && groupIds.length !== targets.length)) {
177
+ throw new RangeError("invalid local contrast dimensions or groups");
178
+ }
179
+ validateGroupIds(neighborIndices);
180
+ if (groupIds)
181
+ validateGroupIds(groupIds);
182
+ const m = getModule(), scope = new NativeScope();
183
+ try {
184
+ const ctx = scope.ctx;
185
+ const y = scope.alloc(targets.length * 8);
186
+ const neighbors = scope.i64(neighborIndices);
187
+ const groups = groupIds ? scope.i64(groupIds) : 0;
188
+ const out = scope.alloc(32);
189
+ m.HEAPF64.set(targets, y / 8);
190
+ const st = m.ccall("n4m_preflight_local_contrast", "number", ["number", "number", "number", "number", "i64", "number", "number", "number"], [ctx.handle, y, neighbors, groups, BigInt(targets.length), k,
191
+ categorical ? 1 : 0, out]);
192
+ checkStatus(st, ctx.handle);
193
+ const result = copyF64(out, 4);
194
+ return {
195
+ contrast: result[0], fractionRowsWithNeighbors: result[1],
196
+ observedSameClassFraction: result[2], expectedSameClassFraction: result[3],
197
+ };
198
+ }
199
+ finally {
200
+ scope.close();
201
+ }
202
+ }
203
+ /** Euclidean HDBSCAN* (scikit-learn 1.9.1 semantics, stable MST tie order). */
204
+ export function clusterHdbscan(X, options) {
205
+ validateMatrix(X);
206
+ const { minClusterSize, minSamples } = options;
207
+ if (X.rows < 2 || !Number.isSafeInteger(minClusterSize) || minClusterSize < 2 ||
208
+ !Number.isSafeInteger(minSamples) || minSamples < 1 || minSamples > X.rows) {
209
+ throw new RangeError("invalid HDBSCAN dimensions or parameters");
210
+ }
211
+ const m = getModule(), scope = new NativeScope();
212
+ try {
213
+ const ctx = scope.ctx;
214
+ const x = scope.matrix(X.data, X.rows, X.cols);
215
+ const perRow = () => scope.alloc(X.rows * 8);
216
+ const labels = perRow(), membership = perRow(), outlier = perRow();
217
+ const persistence = perRow(), parent = perRow(), size = perRow(), label = perRow();
218
+ const birth = perRow(), death = perRow(), stability = perRow();
219
+ const nClusters = scope.alloc(8), nNodes = scope.alloc(8);
220
+ const st = m.ccall("n4m_cluster_hdbscan", "number", ["number", "number", "i64", "i64", "number", "number", ...Array(12).fill("number")], [ctx.handle, x.viewPtr, BigInt(minClusterSize), BigInt(minSamples),
221
+ options.selection === "leaf" ? 1 : 0, options.allowSingleCluster ? 1 : 0,
222
+ labels, membership, outlier, nClusters, persistence, nNodes, parent, size, label,
223
+ birth, death, stability]);
224
+ checkStatus(st, ctx.handle);
225
+ const dv = new DataView(m.HEAPU8.buffer);
226
+ const i64 = (ptr, n) => Array.from({ length: n }, (_, j) => Number(dv.getBigInt64(ptr + j * 8, true)));
227
+ const k = Number(dv.getBigInt64(nNodes, true));
228
+ const clusters = Number(dv.getBigInt64(nClusters, true));
229
+ const parents = i64(parent, k), sizes = i64(size, k), treeLabels = i64(label, k);
230
+ const births = copyF64(birth, k), deaths = copyF64(death, k);
231
+ const stabilities = copyF64(stability, k);
232
+ return {
233
+ labels: i64(labels, X.rows),
234
+ membership: copyF64(membership, X.rows),
235
+ outlierScores: copyF64(outlier, X.rows),
236
+ nClusters: clusters,
237
+ persistence: copyF64(persistence, clusters),
238
+ tree: Array.from({ length: k }, (_, j) => ({
239
+ parent: parents[j], size: sizes[j], label: treeLabels[j],
240
+ lambdaBirth: births[j], lambdaDeath: deaths[j], stability: stabilities[j],
241
+ })),
242
+ };
243
+ }
244
+ finally {
245
+ scope.close();
246
+ }
247
+ }
248
+ /** Adjusted Rand index; NaN for n<2 or identical trivial partitions. Noise is an ordinary label. */
249
+ export function preflightAdjustedRandIndex(a, b) {
250
+ if (a.length !== b.length)
251
+ throw new RangeError("ARI label length mismatch");
252
+ validateGroupIds(a);
253
+ validateGroupIds(b);
254
+ const m = getModule(), scope = new NativeScope();
255
+ try {
256
+ const ctx = scope.ctx;
257
+ const pa = scope.i64(a), pb = scope.i64(b), out = scope.alloc(8);
258
+ const st = m.ccall("n4m_preflight_adjusted_rand_index", "number", ["number", "number", "number", "i64", "number"], [ctx.handle, pa, pb, BigInt(a.length), out]);
259
+ checkStatus(st, ctx.handle);
260
+ return m.HEAPF64[out / 8];
261
+ }
262
+ finally {
263
+ scope.close();
264
+ }
265
+ }
266
+ /** Savitzky-Golay smoothing-residual noise proxy; interior features only. */
267
+ export function preflightNoiseProxy(X, windowLength, polyorder, validMask) {
268
+ validateMatrix(X);
269
+ if (!Number.isInteger(windowLength) || !Number.isInteger(polyorder) ||
270
+ (validMask && validMask.length !== X.data.length)) {
271
+ throw new RangeError("invalid noise proxy window, polyorder or mask");
272
+ }
273
+ const m = getModule(), scope = new NativeScope();
274
+ try {
275
+ const ctx = scope.ctx;
276
+ const x = scope.matrix(X.data, X.rows, X.cols);
277
+ const mask = validMask ? scope.alloc(validMask.length) : 0;
278
+ const band = scope.alloc(X.cols * 8), counts = scope.alloc(X.cols * 8);
279
+ const out = scope.alloc(16);
280
+ if (validMask)
281
+ m.HEAPU8.set(validMask, mask);
282
+ const st = m.ccall("n4m_preflight_noise_proxy_compute", "number", Array(8).fill("number"), [ctx.handle, x.viewPtr, mask, windowLength, polyorder, band, counts, out]);
283
+ checkStatus(st, ctx.handle);
284
+ const dv = new DataView(m.HEAPU8.buffer);
285
+ return {
286
+ bandNoise: copyF64(band, X.cols),
287
+ bandCounts: Array.from({ length: X.cols }, (_, j) => Number(dv.getBigInt64(counts + j * 8, true))),
288
+ pooled: m.HEAPF64[out / 8], gain: m.HEAPF64[out / 8 + 1],
289
+ };
290
+ }
291
+ finally {
292
+ scope.close();
293
+ }
294
+ }
295
+ /**
296
+ * Row pairs with root-mean-square feature difference <= tolerance. Without a
297
+ * reference, query rows are compared with each other (i < h).
298
+ */
299
+ export function preflightPairsWithinTolerance(query, tolerance, maxPairs, reference, queryGroups, referenceGroups) {
300
+ validateMatrix(query);
301
+ if (reference)
302
+ validateMatrix(reference);
303
+ if (!Number.isSafeInteger(maxPairs) || maxPairs < 0 ||
304
+ (reference && reference.cols !== query.cols) ||
305
+ (queryGroups && queryGroups.length !== query.rows) ||
306
+ (reference && (queryGroups === undefined) !== (referenceGroups === undefined)) ||
307
+ (referenceGroups && (!reference || referenceGroups.length !== reference.rows))) {
308
+ throw new RangeError("invalid pair shapes, groups or listing budget");
309
+ }
310
+ if (queryGroups)
311
+ validateGroupIds(queryGroups);
312
+ if (referenceGroups)
313
+ validateGroupIds(referenceGroups);
314
+ const m = getModule(), scope = new NativeScope();
315
+ try {
316
+ const ctx = scope.ctx;
317
+ const q = scope.matrix(query.data, query.rows, query.cols);
318
+ const r = reference ? scope.matrix(reference.data, reference.rows, reference.cols) : undefined;
319
+ const qg = queryGroups ? scope.i64(queryGroups) : 0;
320
+ const rg = referenceGroups ? scope.i64(referenceGroups) : 0;
321
+ const idx = maxPairs ? scope.alloc(maxPairs * 16) : 0;
322
+ const dist = maxPairs ? scope.alloc(maxPairs * 8) : 0;
323
+ const qf = scope.alloc(query.rows);
324
+ const rf = reference ? scope.alloc(reference.rows) : 0;
325
+ const counts = scope.alloc(16);
326
+ const st = m.ccall("n4m_preflight_pairs_within_tolerance", "number", ["number", "number", "number", "number", "number", "number", "i64",
327
+ "number", "number", "number", "number", "number"], [ctx.handle, q.viewPtr, r ? r.viewPtr : 0, qg, rg, tolerance, BigInt(maxPairs),
328
+ idx, dist, qf, rf, counts]);
329
+ checkStatus(st, ctx.handle);
330
+ const dv = new DataView(m.HEAPU8.buffer);
331
+ const total = Number(dv.getBigInt64(counts, true));
332
+ const listed = Math.min(total, maxPairs);
333
+ return {
334
+ pairs: Array.from({ length: listed * 2 }, (_, j) => Number(dv.getBigInt64(idx + j * 8, true))),
335
+ distances: copyF64(dist, listed),
336
+ queryFlags: new Uint8Array(m.HEAPU8.slice(qf, qf + query.rows)),
337
+ referenceFlags: reference ? new Uint8Array(m.HEAPU8.slice(rf, rf + reference.rows))
338
+ : new Uint8Array(0),
339
+ totalPairs: total,
340
+ candidatePairs: Number(dv.getBigInt64(counts + 8, true)),
341
+ };
342
+ }
343
+ finally {
344
+ scope.close();
345
+ }
346
+ }
347
+ /** Factor-target association over exchangeable units with seeded permutations.
348
+ * The seed is an unsigned 64-bit integer; pass a bigint above 2^53. */
349
+ export function preflightFactorAssociation(factorCodes, targets, categorical, nPermutations, seed) {
350
+ if (factorCodes.length !== targets.length || targets.length < 2 ||
351
+ !Number.isInteger(nPermutations) || nPermutations < 0 || nPermutations > 1_000_000) {
352
+ throw new RangeError("invalid association dimensions or permutation count");
353
+ }
354
+ validateGroupIds(factorCodes);
355
+ if (typeof seed === "number" && !Number.isSafeInteger(seed)) {
356
+ throw new RangeError("seeds supplied as numbers must be safe integers");
357
+ }
358
+ const seed64 = BigInt(seed);
359
+ if (seed64 < 0n || seed64 >= (1n << 64n))
360
+ throw new RangeError("seed is outside uint64 range");
361
+ const m = getModule(), scope = new NativeScope();
362
+ try {
363
+ const ctx = scope.ctx;
364
+ const codes = scope.i64(factorCodes);
365
+ const y = scope.alloc(targets.length * 8);
366
+ const out = scope.alloc(64), counts = scope.alloc(16);
367
+ m.HEAPF64.set(targets, y / 8);
368
+ const st = m.ccall("n4m_preflight_factor_association", "number", ["number", "number", "number", "i64", "number", "number", "i64", "number", "number"], [ctx.handle, codes, y, BigInt(targets.length), categorical ? 1 : 0,
369
+ nPermutations, seed64, out, counts]);
370
+ checkStatus(st, ctx.handle);
371
+ const r = copyF64(out, 8);
372
+ const dv = new DataView(m.HEAPU8.buffer);
373
+ return {
374
+ effectSize: r[0], statistic: r[1], df1: r[2], df2: r[3],
375
+ nLevels: r[4], nTargetValues: r[5], log10DistinctPermutations: r[6],
376
+ pValue: r[7],
377
+ nAtLeastObserved: Number(dv.getBigInt64(counts, true)),
378
+ nPermutationsExecuted: Number(dv.getBigInt64(counts + 8, true)),
379
+ };
380
+ }
381
+ finally {
382
+ scope.close();
383
+ }
384
+ }
385
+ /** Holm step-down adjusted p-values for one hypothesis family. */
386
+ export function preflightHolmAdjust(pValues) {
387
+ if (pValues.length < 1)
388
+ throw new RangeError("Holm family must not be empty");
389
+ const m = getModule(), scope = new NativeScope();
390
+ try {
391
+ const ctx = scope.ctx;
392
+ const input = scope.alloc(pValues.length * 8), out = scope.alloc(pValues.length * 8);
393
+ m.HEAPF64.set(pValues, input / 8);
394
+ const st = m.ccall("n4m_preflight_holm_adjust", "number", ["number", "number", "i64", "number"], [ctx.handle, input, BigInt(pValues.length), out]);
395
+ checkStatus(st, ctx.handle);
396
+ return copyF64(out, pValues.length);
397
+ }
398
+ finally {
399
+ scope.close();
400
+ }
401
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nirs4all/methods",
3
- "version": "1.3.4",
3
+ "version": "1.3.6",
4
4
  "description": "WebAssembly build of libn4m (nirs4all-methods) — portable PLS/NIRS engine and native method bindings.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -20,7 +20,7 @@
20
20
  "build": "npm run clean && tsc -p .",
21
21
  "stage:wasm": "node -e \"const fs=require('fs'),p='../../build/emscripten/bindings/js/';fs.mkdirSync('dist',{recursive:true});for(const f of ['n4m.js','n4m.wasm']){if(!fs.existsSync(p+f))throw new Error('missing WASM artifact '+p+f+' — run: cmake --preset emscripten && cmake --build --preset emscripten --target n4m_wasm');fs.copyFileSync(p+f,'dist/'+f)}console.log('staged n4m.js + n4m.wasm into dist/')\"",
22
22
  "prepack": "npm run build && npm run stage:wasm",
23
- "test": "node --experimental-vm-modules test/run_smoke.mjs && node --experimental-vm-modules test/run_api.mjs && node --experimental-vm-modules test/run_generic_method.mjs && node --experimental-vm-modules test/run_pop_aom.mjs && node --experimental-vm-modules test/run_new_pack.mjs && node --experimental-vm-modules test/run_serialization_inspect.mjs && node --experimental-vm-modules test/run_method_result_model.mjs && node --experimental-vm-modules test/run_native_preprocessing_pipeline.mjs && node --experimental-vm-modules test/run_native_splitter.mjs && node --experimental-vm-modules test/run_native_augmentation.mjs && node --experimental-vm-modules test/run_estimator_roles.mjs && node --experimental-vm-modules test/run_estimator_roles_negative.mjs && node --experimental-vm-modules test/run_role_pipeline.mjs && node --experimental-vm-modules test/run_spectral_encoding.mjs && node --experimental-vm-modules test/run_optimization.mjs"
23
+ "test": "node --experimental-vm-modules test/run_smoke.mjs && node --experimental-vm-modules test/run_api.mjs && node --experimental-vm-modules test/run_generic_method.mjs && node --experimental-vm-modules test/run_pop_aom.mjs && node --experimental-vm-modules test/run_new_pack.mjs && node --experimental-vm-modules test/run_serialization_inspect.mjs && node --experimental-vm-modules test/run_method_result_model.mjs && node --experimental-vm-modules test/run_native_preprocessing_pipeline.mjs && node --experimental-vm-modules test/run_native_splitter.mjs && node --experimental-vm-modules test/run_native_augmentation.mjs && node --experimental-vm-modules test/run_estimator_roles.mjs && node --experimental-vm-modules test/run_estimator_roles_negative.mjs && node --experimental-vm-modules test/run_role_pipeline.mjs && node --experimental-vm-modules test/run_spectral_encoding.mjs && node --experimental-vm-modules test/run_optimization.mjs && node --experimental-vm-modules test/run_preflight_diagnostics.mjs"
24
24
  },
25
25
  "license": "CECILL-2.1",
26
26
  "publishConfig": {