@nirs4all/methods 1.3.5 → 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
@@ -25,6 +25,51 @@ export interface PreflightLocalContrastResult {
25
25
  observedSameClassFraction: number;
26
26
  expectedSameClassFraction: number;
27
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
+ }
28
73
  /** Centered PCA using the native Methods SVD. Output matrices are row-major. */
29
74
  export declare function preflightPca(X: Matrix, k: number): PreflightPcaResult;
30
75
  /** Per-feature pooled repeatability and balanced ICC(1,1). */
@@ -35,3 +80,37 @@ export declare function preflightSummary(values: Float64Array, validMask?: Uint8
35
80
  export declare function preflightNearestNeighbors(query: Matrix, reference: Matrix, k: number, queryGroups?: readonly (number | bigint)[], referenceGroups?: readonly (number | bigint)[]): PreflightNeighborResult;
36
81
  /** Local Y coherence using an existing row-major n x k neighbor-index table. */
37
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;
@@ -200,3 +200,202 @@ export function preflightLocalContrast(targets, neighborIndices, k, categorical,
200
200
  scope.close();
201
201
  }
202
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.5",
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",