@nirs4all/methods 1.3.6 → 1.3.8
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/README.md +2 -2
- package/dist/estimatorRolesGenerated.js +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/n4m.js +1 -1
- package/dist/n4m.wasm +0 -0
- package/dist/nativeModel.d.ts +19 -1
- package/dist/nativeModel.js +28 -1
- package/dist/preflightDiagnostics.d.ts +288 -1
- package/dist/preflightDiagnostics.js +623 -8
- package/dist/types.d.ts +19 -0
- package/dist/types.js +20 -0
- package/package.json +2 -2
|
@@ -3,12 +3,33 @@
|
|
|
3
3
|
import { checkStatus, getModule, makeMatrixView } from "./ffi.js";
|
|
4
4
|
import { Context } from "./context.js";
|
|
5
5
|
import { N4mError, Status } from "./types.js";
|
|
6
|
+
function validatePermutation(nPermutations, seed) {
|
|
7
|
+
if (!Number.isInteger(nPermutations) || nPermutations < 0 || nPermutations > 1_000_000) {
|
|
8
|
+
throw new RangeError("permutation count must be an integer in [0, 1000000]");
|
|
9
|
+
}
|
|
10
|
+
if (typeof seed === "number" && !Number.isSafeInteger(seed)) {
|
|
11
|
+
throw new RangeError("seeds supplied as numbers must be safe integers");
|
|
12
|
+
}
|
|
13
|
+
const seed64 = BigInt(seed);
|
|
14
|
+
if (seed64 < 0n || seed64 >= (1n << 64n))
|
|
15
|
+
throw new RangeError("seed is outside uint64 range");
|
|
16
|
+
return seed64;
|
|
17
|
+
}
|
|
6
18
|
function validateMatrix(X) {
|
|
7
19
|
if (!Number.isSafeInteger(X.rows) || !Number.isSafeInteger(X.cols) ||
|
|
8
20
|
X.rows < 1 || X.cols < 1 || X.data.length !== X.rows * X.cols) {
|
|
9
21
|
throw new RangeError("invalid Preflight matrix dimensions");
|
|
10
22
|
}
|
|
11
23
|
}
|
|
24
|
+
/** Integer in [lo, hi] and representable as a C int32_t (Emscripten passes
|
|
25
|
+
* "number" arguments as 32-bit integers and would wrap larger values). */
|
|
26
|
+
function isInt32In(value, lo, hi) {
|
|
27
|
+
return Number.isInteger(value) && value >= -0x80000000 && value <= 0x7fffffff &&
|
|
28
|
+
value >= lo && value <= hi;
|
|
29
|
+
}
|
|
30
|
+
/** Validated Savitzky-Golay domain of the native noise proxy. */
|
|
31
|
+
const NOISE_PROXY_MAX_WINDOW = 1001;
|
|
32
|
+
const NOISE_PROXY_MAX_POLYORDER = 10;
|
|
12
33
|
function validateGroupIds(values) {
|
|
13
34
|
for (const value of values) {
|
|
14
35
|
if (typeof value === "number" && !Number.isSafeInteger(value)) {
|
|
@@ -56,10 +77,10 @@ class NativeScope {
|
|
|
56
77
|
function copyF64(ptr, n) {
|
|
57
78
|
return new Float64Array(getModule().HEAPF64.slice(ptr / 8, ptr / 8 + n));
|
|
58
79
|
}
|
|
59
|
-
/** Centered PCA
|
|
80
|
+
/** Centered PCA (exact Gram eigendecomposition in Methods). Output matrices are row-major. */
|
|
60
81
|
export function preflightPca(X, k) {
|
|
61
82
|
validateMatrix(X);
|
|
62
|
-
if (!
|
|
83
|
+
if (!isInt32In(k, 1, Math.min(X.rows, X.cols))) {
|
|
63
84
|
throw new RangeError("invalid PCA component count");
|
|
64
85
|
}
|
|
65
86
|
const m = getModule();
|
|
@@ -70,13 +91,18 @@ export function preflightPca(X, k) {
|
|
|
70
91
|
const scores = scope.matrix(new Float64Array(X.rows * k), X.rows, k);
|
|
71
92
|
const loadings = scope.matrix(new Float64Array(k * X.cols), k, X.cols);
|
|
72
93
|
const eigen = scope.alloc(k * 8), moments = scope.alloc(16);
|
|
73
|
-
const
|
|
94
|
+
const resolution = scope.alloc(8), unresolved = scope.alloc(k);
|
|
95
|
+
const st = m.ccall("n4m_preflight_pca_compute_resolved", "number", ["number", "number", "number", "number", "number", "number", "number", "number",
|
|
96
|
+
"number"], [ctx.handle, x.viewPtr, k, scores.viewPtr, loadings.viewPtr, eigen, moments,
|
|
97
|
+
resolution, unresolved]);
|
|
74
98
|
checkStatus(st, ctx.handle);
|
|
75
99
|
return {
|
|
76
100
|
scores: { data: copyF64(scores.dataPtr, X.rows * k), rows: X.rows, cols: k },
|
|
77
101
|
loadings: { data: copyF64(loadings.dataPtr, k * X.cols), rows: k, cols: X.cols },
|
|
78
102
|
eigenvalues: copyF64(eigen, k),
|
|
79
103
|
fullMoments: [m.HEAPF64[moments / 8], m.HEAPF64[moments / 8 + 1]],
|
|
104
|
+
resolution: m.HEAPF64[resolution / 8],
|
|
105
|
+
unresolved: m.HEAPU8.slice(unresolved, unresolved + k),
|
|
80
106
|
};
|
|
81
107
|
}
|
|
82
108
|
finally {
|
|
@@ -138,7 +164,7 @@ export function preflightSummary(values, validMask) {
|
|
|
138
164
|
export function preflightNearestNeighbors(query, reference, k, queryGroups, referenceGroups) {
|
|
139
165
|
validateMatrix(query);
|
|
140
166
|
validateMatrix(reference);
|
|
141
|
-
if (query.cols !== reference.cols || !
|
|
167
|
+
if (query.cols !== reference.cols || !isInt32In(k, 1, 0x7fffffff) ||
|
|
142
168
|
(queryGroups === undefined) !== (referenceGroups === undefined) ||
|
|
143
169
|
(queryGroups && queryGroups.length !== query.rows) ||
|
|
144
170
|
(referenceGroups && referenceGroups.length !== reference.rows)) {
|
|
@@ -171,7 +197,7 @@ export function preflightNearestNeighbors(query, reference, k, queryGroups, refe
|
|
|
171
197
|
}
|
|
172
198
|
/** Local Y coherence using an existing row-major n x k neighbor-index table. */
|
|
173
199
|
export function preflightLocalContrast(targets, neighborIndices, k, categorical, groupIds) {
|
|
174
|
-
if (!
|
|
200
|
+
if (!isInt32In(k, 1, 0x7fffffff) || targets.length < 1 ||
|
|
175
201
|
neighborIndices.length !== targets.length * k ||
|
|
176
202
|
(groupIds && groupIds.length !== targets.length)) {
|
|
177
203
|
throw new RangeError("invalid local contrast dimensions or groups");
|
|
@@ -263,12 +289,48 @@ export function preflightAdjustedRandIndex(a, b) {
|
|
|
263
289
|
scope.close();
|
|
264
290
|
}
|
|
265
291
|
}
|
|
292
|
+
/**
|
|
293
|
+
* SNV with rounding bounds (ABI 2.20 n4m_preflight_snv_compute). With
|
|
294
|
+
* `groupIds` (dense codes 0..nGroups-1, every group non-empty), each output
|
|
295
|
+
* row is the equal-weight mean of the SNV rows of one group.
|
|
296
|
+
*/
|
|
297
|
+
export function preflightSnv(X, groupIds, nGroups) {
|
|
298
|
+
validateMatrix(X);
|
|
299
|
+
const groups = groupIds ? nGroups : X.rows;
|
|
300
|
+
if (X.cols < 2 || groups === undefined || !isInt32In(groups, 1, X.rows) ||
|
|
301
|
+
(groupIds && groupIds.length !== X.rows) || (!groupIds && nGroups !== undefined &&
|
|
302
|
+
nGroups !== X.rows)) {
|
|
303
|
+
throw new RangeError("invalid SNV shape or groups");
|
|
304
|
+
}
|
|
305
|
+
if (groupIds)
|
|
306
|
+
validateGroupIds(groupIds);
|
|
307
|
+
const m = getModule(), scope = new NativeScope();
|
|
308
|
+
try {
|
|
309
|
+
const ctx = scope.ctx;
|
|
310
|
+
const x = scope.matrix(X.data, X.rows, X.cols);
|
|
311
|
+
const out = scope.matrix(new Float64Array(groups * X.cols), groups, X.cols);
|
|
312
|
+
const gid = groupIds ? scope.i64(groupIds) : 0;
|
|
313
|
+
const bounds = scope.alloc(groups * 8);
|
|
314
|
+
const st = m.ccall("n4m_preflight_snv_compute", "number", ["number", "number", "number", "i64", "number", "number"], [ctx.handle, x.viewPtr, gid, BigInt(groups), out.viewPtr, bounds]);
|
|
315
|
+
checkStatus(st, ctx.handle);
|
|
316
|
+
return {
|
|
317
|
+
matrix: { data: copyF64(out.dataPtr, groups * X.cols), rows: groups, cols: X.cols },
|
|
318
|
+
errorBounds: copyF64(bounds, groups),
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
finally {
|
|
322
|
+
scope.close();
|
|
323
|
+
}
|
|
324
|
+
}
|
|
266
325
|
/** Savitzky-Golay smoothing-residual noise proxy; interior features only. */
|
|
267
326
|
export function preflightNoiseProxy(X, windowLength, polyorder, validMask) {
|
|
268
327
|
validateMatrix(X);
|
|
269
|
-
if (!
|
|
328
|
+
if (!isInt32In(windowLength, 3, Math.min(NOISE_PROXY_MAX_WINDOW, X.cols)) ||
|
|
329
|
+
windowLength % 2 === 0 ||
|
|
330
|
+
!isInt32In(polyorder, 0, Math.min(NOISE_PROXY_MAX_POLYORDER, windowLength - 2)) ||
|
|
270
331
|
(validMask && validMask.length !== X.data.length)) {
|
|
271
|
-
throw new RangeError("
|
|
332
|
+
throw new RangeError("noise proxy needs an odd window in [3, min(1001, cols)], " +
|
|
333
|
+
"polyorder in [0, min(10, window - 2)] and a matching mask");
|
|
272
334
|
}
|
|
273
335
|
const m = getModule(), scope = new NativeScope();
|
|
274
336
|
try {
|
|
@@ -348,7 +410,7 @@ export function preflightPairsWithinTolerance(query, tolerance, maxPairs, refere
|
|
|
348
410
|
* The seed is an unsigned 64-bit integer; pass a bigint above 2^53. */
|
|
349
411
|
export function preflightFactorAssociation(factorCodes, targets, categorical, nPermutations, seed) {
|
|
350
412
|
if (factorCodes.length !== targets.length || targets.length < 2 ||
|
|
351
|
-
!
|
|
413
|
+
!isInt32In(nPermutations, 0, 1_000_000)) {
|
|
352
414
|
throw new RangeError("invalid association dimensions or permutation count");
|
|
353
415
|
}
|
|
354
416
|
validateGroupIds(factorCodes);
|
|
@@ -399,3 +461,556 @@ export function preflightHolmAdjust(pValues) {
|
|
|
399
461
|
scope.close();
|
|
400
462
|
}
|
|
401
463
|
}
|
|
464
|
+
/** Pearson or Spearman correlation over exchangeable units with a seeded
|
|
465
|
+
* two-sided permutation test of y. The seed is an unsigned 64-bit integer;
|
|
466
|
+
* pass a bigint above 2^53. */
|
|
467
|
+
export function statsCorrelationTest(x, y, method, nPermutations, seed) {
|
|
468
|
+
if (x.length !== y.length || x.length < 2 || (method !== "pearson" && method !== "spearman") ||
|
|
469
|
+
!Number.isInteger(nPermutations) || nPermutations < 0 || nPermutations > 1_000_000) {
|
|
470
|
+
throw new RangeError("invalid correlation dimensions, method or permutation count");
|
|
471
|
+
}
|
|
472
|
+
if (typeof seed === "number" && !Number.isSafeInteger(seed)) {
|
|
473
|
+
throw new RangeError("seeds supplied as numbers must be safe integers");
|
|
474
|
+
}
|
|
475
|
+
const seed64 = BigInt(seed);
|
|
476
|
+
if (seed64 < 0n || seed64 >= (1n << 64n))
|
|
477
|
+
throw new RangeError("seed is outside uint64 range");
|
|
478
|
+
const m = getModule(), scope = new NativeScope();
|
|
479
|
+
try {
|
|
480
|
+
const ctx = scope.ctx;
|
|
481
|
+
const xs = scope.alloc(x.length * 8), ys = scope.alloc(y.length * 8);
|
|
482
|
+
const out = scope.alloc(40), counts = scope.alloc(16);
|
|
483
|
+
m.HEAPF64.set(x, xs / 8);
|
|
484
|
+
m.HEAPF64.set(y, ys / 8);
|
|
485
|
+
const st = m.ccall("n4m_stats_correlation_test", "number", ["number", "number", "number", "i64", "number", "number", "i64", "number", "number"], [ctx.handle, xs, ys, BigInt(x.length), method === "spearman" ? 1 : 0,
|
|
486
|
+
nPermutations, seed64, out, counts]);
|
|
487
|
+
checkStatus(st, ctx.handle);
|
|
488
|
+
const r = copyF64(out, 5);
|
|
489
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
490
|
+
return {
|
|
491
|
+
coefficient: r[0], nDistinctX: r[1], nDistinctY: r[2],
|
|
492
|
+
log10DistinctPermutations: r[3], pValue: r[4],
|
|
493
|
+
nAtLeastObserved: Number(dv.getBigInt64(counts, true)),
|
|
494
|
+
nPermutationsExecuted: Number(dv.getBigInt64(counts + 8, true)),
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
finally {
|
|
498
|
+
scope.close();
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/** Benjamini-Hochberg step-up adjusted p-values for one hypothesis family. */
|
|
502
|
+
export function statsBhAdjust(pValues) {
|
|
503
|
+
if (pValues.length < 1)
|
|
504
|
+
throw new RangeError("Benjamini-Hochberg family must not be empty");
|
|
505
|
+
const m = getModule(), scope = new NativeScope();
|
|
506
|
+
try {
|
|
507
|
+
const ctx = scope.ctx;
|
|
508
|
+
const input = scope.alloc(pValues.length * 8), out = scope.alloc(pValues.length * 8);
|
|
509
|
+
m.HEAPF64.set(pValues, input / 8);
|
|
510
|
+
const st = m.ccall("n4m_stats_bh_adjust", "number", ["number", "number", "i64", "number"], [ctx.handle, input, BigInt(pValues.length), out]);
|
|
511
|
+
checkStatus(st, ctx.handle);
|
|
512
|
+
return copyF64(out, pValues.length);
|
|
513
|
+
}
|
|
514
|
+
finally {
|
|
515
|
+
scope.close();
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
function exactResult(out) {
|
|
519
|
+
const r = copyF64(out, 4);
|
|
520
|
+
return { nArrangements: r[0], pValue: r[1], minimumPValue: r[2], maximumStatistic: r[3] };
|
|
521
|
+
}
|
|
522
|
+
/** Exact permutation distribution of the factor-target association statistic
|
|
523
|
+
* (eta^2 or Cramer's V^2) by enumerating distinct arrangements. */
|
|
524
|
+
export function statsFactorAssociationExact(factorCodes, targets, categorical, maxArrangements) {
|
|
525
|
+
if (factorCodes.length !== targets.length || targets.length < 2 ||
|
|
526
|
+
!Number.isSafeInteger(maxArrangements) || maxArrangements < 1 || maxArrangements > 10_000_000) {
|
|
527
|
+
throw new RangeError("invalid exact association dimensions or arrangement budget");
|
|
528
|
+
}
|
|
529
|
+
validateGroupIds(factorCodes);
|
|
530
|
+
const m = getModule(), scope = new NativeScope();
|
|
531
|
+
try {
|
|
532
|
+
const ctx = scope.ctx;
|
|
533
|
+
const codes = scope.i64(factorCodes);
|
|
534
|
+
const y = scope.alloc(targets.length * 8), out = scope.alloc(32);
|
|
535
|
+
m.HEAPF64.set(targets, y / 8);
|
|
536
|
+
const st = m.ccall("n4m_stats_factor_association_exact", "number", ["number", "number", "number", "i64", "number", "i64", "number"], [ctx.handle, codes, y, BigInt(targets.length), categorical ? 1 : 0,
|
|
537
|
+
BigInt(maxArrangements), out]);
|
|
538
|
+
checkStatus(st, ctx.handle);
|
|
539
|
+
return exactResult(out);
|
|
540
|
+
}
|
|
541
|
+
finally {
|
|
542
|
+
scope.close();
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/** Exact permutation distribution of |r| (Pearson or Spearman). */
|
|
546
|
+
export function statsCorrelationExact(x, y, method, maxArrangements) {
|
|
547
|
+
if (x.length !== y.length || x.length < 2 || (method !== "pearson" && method !== "spearman") ||
|
|
548
|
+
!Number.isSafeInteger(maxArrangements) || maxArrangements < 1 || maxArrangements > 10_000_000) {
|
|
549
|
+
throw new RangeError("invalid exact correlation dimensions, method or arrangement budget");
|
|
550
|
+
}
|
|
551
|
+
const m = getModule(), scope = new NativeScope();
|
|
552
|
+
try {
|
|
553
|
+
const ctx = scope.ctx;
|
|
554
|
+
const xs = scope.alloc(x.length * 8), ys = scope.alloc(y.length * 8), out = scope.alloc(32);
|
|
555
|
+
m.HEAPF64.set(x, xs / 8);
|
|
556
|
+
m.HEAPF64.set(y, ys / 8);
|
|
557
|
+
const st = m.ccall("n4m_stats_correlation_exact", "number", ["number", "number", "number", "i64", "number", "i64", "number"], [ctx.handle, xs, ys, BigInt(x.length), method === "spearman" ? 1 : 0,
|
|
558
|
+
BigInt(maxArrangements), out]);
|
|
559
|
+
checkStatus(st, ctx.handle);
|
|
560
|
+
return exactResult(out);
|
|
561
|
+
}
|
|
562
|
+
finally {
|
|
563
|
+
scope.close();
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
/** PERMANOVA of one categorical term on Euclidean distances between rows,
|
|
567
|
+
* optionally given strata (permutations stay inside each stratum). */
|
|
568
|
+
export function statsPermanova(X, termCodes, strataCodes, nPermutations, seed) {
|
|
569
|
+
validateMatrix(X);
|
|
570
|
+
if (X.rows < 2 || termCodes.length !== X.rows ||
|
|
571
|
+
(strataCodes !== undefined && strataCodes.length !== X.rows)) {
|
|
572
|
+
throw new RangeError("invalid PERMANOVA dimensions");
|
|
573
|
+
}
|
|
574
|
+
validateGroupIds(termCodes);
|
|
575
|
+
if (strataCodes)
|
|
576
|
+
validateGroupIds(strataCodes);
|
|
577
|
+
const seed64 = validatePermutation(nPermutations, seed);
|
|
578
|
+
const m = getModule(), scope = new NativeScope();
|
|
579
|
+
try {
|
|
580
|
+
const ctx = scope.ctx;
|
|
581
|
+
const x = scope.matrix(X.data, X.rows, X.cols);
|
|
582
|
+
const term = scope.i64(termCodes);
|
|
583
|
+
const strata = strataCodes ? scope.i64(strataCodes) : 0;
|
|
584
|
+
const out = scope.alloc(15 * 8), counts = scope.alloc(16), exponent = scope.alloc(4);
|
|
585
|
+
const st = m.ccall("n4m_stats_permanova", "number", ["number", "number", "number", "number", "number", "i64", "number", "number", "number"], [ctx.handle, x.viewPtr, term, strata, nPermutations, seed64, out, counts,
|
|
586
|
+
exponent]);
|
|
587
|
+
checkStatus(st, ctx.handle);
|
|
588
|
+
const r = copyF64(out, 15);
|
|
589
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
590
|
+
return {
|
|
591
|
+
ssExponent: dv.getInt32(exponent, true),
|
|
592
|
+
ssTotal: r[0], ssStrata: r[1], ssTerm: r[2], ssResidual: r[3],
|
|
593
|
+
r2: r[4], partialR2: r[5], pseudoF: r[6], dfTerm: r[7], dfResidual: r[8],
|
|
594
|
+
nLevels: r[9], nStrata: r[10], log10DistinctPermutations: r[11], pValue: r[12],
|
|
595
|
+
residualResolution: r[13], fNumericallyUnresolved: r[14] === 1,
|
|
596
|
+
nAtLeastObserved: Number(dv.getBigInt64(counts, true)),
|
|
597
|
+
nPermutationsExecuted: Number(dv.getBigInt64(counts + 8, true)),
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
finally {
|
|
601
|
+
scope.close();
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
/** PERMDISP (betadisper type "centroid"): distances to group centroids, their
|
|
605
|
+
* one-way ANOVA F and a residual-permutation test. Not an exchangeability check. */
|
|
606
|
+
export function statsPermdisp(X, groupCodes, nPermutations, seed) {
|
|
607
|
+
validateMatrix(X);
|
|
608
|
+
if (X.rows < 2 || groupCodes.length !== X.rows) {
|
|
609
|
+
throw new RangeError("invalid PERMDISP dimensions");
|
|
610
|
+
}
|
|
611
|
+
validateGroupIds(groupCodes);
|
|
612
|
+
const seed64 = validatePermutation(nPermutations, seed);
|
|
613
|
+
const m = getModule(), scope = new NativeScope();
|
|
614
|
+
try {
|
|
615
|
+
const ctx = scope.ctx;
|
|
616
|
+
const x = scope.matrix(X.data, X.rows, X.cols);
|
|
617
|
+
const groups = scope.i64(groupCodes);
|
|
618
|
+
const distances = scope.alloc(X.rows * 8), means = scope.alloc(X.rows * 8);
|
|
619
|
+
const out = scope.alloc(8 * 8), counts = scope.alloc(16), exponent = scope.alloc(4);
|
|
620
|
+
const st = m.ccall("n4m_stats_permdisp", "number", ["number", "number", "number", "number", "i64", "number", "number", "number", "number",
|
|
621
|
+
"number"], [ctx.handle, x.viewPtr, groups, nPermutations, seed64, distances, means, out,
|
|
622
|
+
counts, exponent]);
|
|
623
|
+
checkStatus(st, ctx.handle);
|
|
624
|
+
const r = copyF64(out, 8);
|
|
625
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
626
|
+
return {
|
|
627
|
+
distanceExponent: dv.getInt32(exponent, true),
|
|
628
|
+
distances: copyF64(distances, X.rows),
|
|
629
|
+
groupMeanDistances: copyF64(means, r[3]),
|
|
630
|
+
f: r[0], df1: r[1], df2: r[2], nGroups: r[3], log10DistinctPermutations: r[4],
|
|
631
|
+
pValue: r[5], residualResolution: r[6], fNumericallyUnresolved: r[7] === 1,
|
|
632
|
+
nAtLeastObserved: Number(dv.getBigInt64(counts, true)),
|
|
633
|
+
nPermutationsExecuted: Number(dv.getBigInt64(counts + 8, true)),
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
finally {
|
|
637
|
+
scope.close();
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
/** Partial PERMANOVA of a term given the additive main effects of condition
|
|
641
|
+
* factors (one code array per factor), tested by Freedman-Lane permutation of
|
|
642
|
+
* the reduced-model residuals. */
|
|
643
|
+
export function statsPermanovaFreedmanLane(X, termCodes, conditionCodes, nPermutations, seed) {
|
|
644
|
+
validateMatrix(X);
|
|
645
|
+
if (X.rows < 2 || termCodes.length !== X.rows || conditionCodes.length > 64 ||
|
|
646
|
+
conditionCodes.some((c) => c.length !== X.rows)) {
|
|
647
|
+
throw new RangeError("invalid Freedman-Lane PERMANOVA dimensions");
|
|
648
|
+
}
|
|
649
|
+
validateGroupIds(termCodes);
|
|
650
|
+
conditionCodes.forEach(validateGroupIds);
|
|
651
|
+
const seed64 = validatePermutation(nPermutations, seed);
|
|
652
|
+
const m = getModule(), scope = new NativeScope();
|
|
653
|
+
try {
|
|
654
|
+
const ctx = scope.ctx;
|
|
655
|
+
const x = scope.matrix(X.data, X.rows, X.cols);
|
|
656
|
+
const term = scope.i64(termCodes);
|
|
657
|
+
const rowMajor = [];
|
|
658
|
+
for (let i = 0; i < X.rows; i++)
|
|
659
|
+
for (const c of conditionCodes)
|
|
660
|
+
rowMajor.push(c[i]);
|
|
661
|
+
const conditions = conditionCodes.length ? scope.i64(rowMajor) : 0;
|
|
662
|
+
const out = scope.alloc(14 * 8), counts = scope.alloc(16), exponent = scope.alloc(4);
|
|
663
|
+
const st = m.ccall("n4m_stats_permanova_freedman_lane", "number", ["number", "number", "number", "number", "number", "number", "i64", "number", "number",
|
|
664
|
+
"number"], [ctx.handle, x.viewPtr, term, conditions, conditionCodes.length, nPermutations, seed64,
|
|
665
|
+
out, counts, exponent]);
|
|
666
|
+
checkStatus(st, ctx.handle);
|
|
667
|
+
const r = copyF64(out, 14);
|
|
668
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
669
|
+
return {
|
|
670
|
+
ssExponent: dv.getInt32(exponent, true),
|
|
671
|
+
ssTotal: r[0], ssReduced: r[1], ssTerm: r[2], ssResidual: r[3], r2: r[4],
|
|
672
|
+
partialR2: r[5], pseudoF: r[6], dfTerm: r[7], dfResidual: r[8], rankReduced: r[9],
|
|
673
|
+
log10DistinctPermutations: r[10], pValue: r[11],
|
|
674
|
+
residualResolution: r[12], fNumericallyUnresolved: r[13] === 1,
|
|
675
|
+
nAtLeastObserved: Number(dv.getBigInt64(counts, true)),
|
|
676
|
+
nPermutationsExecuted: Number(dv.getBigInt64(counts + 8, true)),
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
finally {
|
|
680
|
+
scope.close();
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
/** Energy distance between groups of rows with a K-sample permutation test.
|
|
684
|
+
* groupCodes are integers in [0, nGroups); the seed is an unsigned 64-bit
|
|
685
|
+
* integer (pass a bigint above 2^53). The native size limits are checked
|
|
686
|
+
* before any WASM allocation and raise N4mError(ERR_UNSUPPORTED); inputs
|
|
687
|
+
* outside the supported numerical domain raise the same status. */
|
|
688
|
+
export function statsEnergyDistance(X, groupCodes, nGroups, nPermutations, seed) {
|
|
689
|
+
validateMatrix(X);
|
|
690
|
+
if (groupCodes.length !== X.rows || !Number.isSafeInteger(nGroups) || nGroups < 2 ||
|
|
691
|
+
nGroups > X.rows || groupCodes.some((c) => !Number.isInteger(c) || c < 0 || c >= nGroups)) {
|
|
692
|
+
throw new RangeError("invalid energy distance groups");
|
|
693
|
+
}
|
|
694
|
+
const seed64 = validatePermutation(nPermutations, seed);
|
|
695
|
+
const pairs = X.rows * (X.rows - 1) / 2;
|
|
696
|
+
if (pairs > 20_000_000 || X.rows * X.cols > 50_000_000 || nGroups * nGroups > 10_000_000 ||
|
|
697
|
+
pairs * (X.cols + nPermutations + 1) > 2.5e9) {
|
|
698
|
+
throw new N4mError(Status.ERR_UNSUPPORTED, "energy distance exceeds its pair, cell, group or operation budget");
|
|
699
|
+
}
|
|
700
|
+
const m = getModule(), scope = new NativeScope();
|
|
701
|
+
try {
|
|
702
|
+
const ctx = scope.ctx;
|
|
703
|
+
const x = scope.matrix(X.data, X.rows, X.cols);
|
|
704
|
+
const codes = scope.i64(groupCodes);
|
|
705
|
+
const g2 = nGroups * nGroups;
|
|
706
|
+
const energy = scope.alloc(g2 * 8), bounds = scope.alloc(g2 * 8), mean = scope.alloc(g2 * 8);
|
|
707
|
+
const out = scope.alloc(40), counts = scope.alloc(24);
|
|
708
|
+
const st = m.ccall("n4m_stats_energy_distance", "number", ["number", "number", "number", "number", "number", "i64", "number", "number", "number",
|
|
709
|
+
"number", "number"], [ctx.handle, x.viewPtr, codes, nGroups, nPermutations, seed64, energy, bounds, mean, out,
|
|
710
|
+
counts]);
|
|
711
|
+
checkStatus(st, ctx.handle);
|
|
712
|
+
const r = copyF64(out, 5);
|
|
713
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
714
|
+
return {
|
|
715
|
+
energy: copyF64(energy, g2), energyBounds: copyF64(bounds, g2),
|
|
716
|
+
meanDistances: copyF64(mean, g2),
|
|
717
|
+
statistic: r[0], statisticBound: r[1], log10DistinctPermutations: r[2], pValue: r[3],
|
|
718
|
+
pValueConservative: r[4],
|
|
719
|
+
nAtLeastObserved: Number(dv.getBigInt64(counts, true)),
|
|
720
|
+
nPermutationsExecuted: Number(dv.getBigInt64(counts + 8, true)),
|
|
721
|
+
nUndecidable: Number(dv.getBigInt64(counts + 16, true)),
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
finally {
|
|
725
|
+
scope.close();
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
/** PCA monitoring of rows against a reference PCA with out-of-fold limits.
|
|
729
|
+
* The native size limits are checked before any WASM allocation. */
|
|
730
|
+
export function statsPcaMonitor(reference, monitored, maxComponents, nFolds, alpha) {
|
|
731
|
+
validateMatrix(reference);
|
|
732
|
+
validateMatrix(monitored);
|
|
733
|
+
if (monitored.cols !== reference.cols || !Number.isSafeInteger(maxComponents) ||
|
|
734
|
+
maxComponents < 1 || !Number.isSafeInteger(nFolds) || nFolds < 2 ||
|
|
735
|
+
nFolds > reference.rows || !(alpha > 0 && alpha < 1)) {
|
|
736
|
+
throw new RangeError("invalid PCA monitor dimensions");
|
|
737
|
+
}
|
|
738
|
+
const nr = reference.rows, nm = monitored.rows, p = reference.cols;
|
|
739
|
+
const small = Math.min(nr, p);
|
|
740
|
+
if ((nr + nm) * p > 50_000_000 ||
|
|
741
|
+
(nFolds + 1) * small * small * Math.max(nr, p) + 4 * (nr + nm) * maxComponents * p > 1e10) {
|
|
742
|
+
throw new N4mError(Status.ERR_UNSUPPORTED, "PCA monitor exceeds its cell or operation budget");
|
|
743
|
+
}
|
|
744
|
+
const m = getModule(), scope = new NativeScope();
|
|
745
|
+
try {
|
|
746
|
+
const ctx = scope.ctx;
|
|
747
|
+
const r = scope.matrix(reference.data, nr, p);
|
|
748
|
+
const mo = scope.matrix(monitored.data, nm, p);
|
|
749
|
+
const eigen = scope.alloc(maxComponents * 8);
|
|
750
|
+
const rt = scope.alloc(nr * 8), rq = scope.alloc(nr * 8);
|
|
751
|
+
const mt = scope.alloc(nm * 8), mq = scope.alloc(nm * 8);
|
|
752
|
+
const k = scope.alloc(4), counts = scope.alloc(48), out = scope.alloc(13 * 8);
|
|
753
|
+
const st = m.ccall("n4m_stats_pca_monitor", "number", ["number", "number", "number", "number", "number", "number", "number", "number",
|
|
754
|
+
"number", "number", "number", "number", "number", "number"], [ctx.handle, r.viewPtr, mo.viewPtr, maxComponents, nFolds, alpha, eigen, rt, rq, mt,
|
|
755
|
+
mq, k, counts, out]);
|
|
756
|
+
checkStatus(st, ctx.handle);
|
|
757
|
+
const o = copyF64(out, 13);
|
|
758
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
759
|
+
const count = (i) => Number(dv.getBigInt64(counts + 8 * i, true));
|
|
760
|
+
return {
|
|
761
|
+
eigenvalues: copyF64(eigen, maxComponents),
|
|
762
|
+
effectiveComponents: dv.getInt32(k, true),
|
|
763
|
+
referenceT2: copyF64(rt, nr), referenceQ: copyF64(rq, nr),
|
|
764
|
+
monitoredT2: copyF64(mt, nm), monitoredQ: copyF64(mq, nm),
|
|
765
|
+
nBeyondT2: count(0), nBeyondQ: count(1), nBeyondEither: count(2),
|
|
766
|
+
nNearT2: count(3), nNearQ: count(4), nNearEither: count(5),
|
|
767
|
+
t2Limit: o[0], qLimit: o[1], tolerance: o[9], condition: o[10],
|
|
768
|
+
qToleranceScale: o[11], eigenvalueResolution: o[12], referenceTotalVariance: o[2],
|
|
769
|
+
monitoredTotalVariance: o[3], centroidDistance: o[4],
|
|
770
|
+
centroidSubspaceDistance: o[5], centroidResidualDistance: o[6], centroidT2: o[7],
|
|
771
|
+
retainedFraction: o[8],
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
finally {
|
|
775
|
+
scope.close();
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
function pairs(r, cols, offset) {
|
|
779
|
+
const out = new Float64Array(2 * cols);
|
|
780
|
+
for (let j = 0; j < cols; ++j) {
|
|
781
|
+
out[2 * j] = r[8 * j + offset];
|
|
782
|
+
out[2 * j + 1] = r[8 * j + offset + 1];
|
|
783
|
+
}
|
|
784
|
+
return out;
|
|
785
|
+
}
|
|
786
|
+
/** One-way random-effects variance components by REML, per feature. */
|
|
787
|
+
export function statsVarianceComponentsReml(X, groupIds, validMask) {
|
|
788
|
+
validateMatrix(X);
|
|
789
|
+
if (groupIds.length !== X.rows || (validMask && validMask.length !== X.data.length)) {
|
|
790
|
+
throw new RangeError("variance-components group or mask length mismatch");
|
|
791
|
+
}
|
|
792
|
+
validateGroupIds(groupIds);
|
|
793
|
+
const m = getModule(), scope = new NativeScope();
|
|
794
|
+
try {
|
|
795
|
+
const ctx = scope.ctx;
|
|
796
|
+
const x = scope.matrix(X.data, X.rows, X.cols);
|
|
797
|
+
const groups = scope.i64(groupIds);
|
|
798
|
+
const mask = validMask ? scope.alloc(validMask.length) : 0;
|
|
799
|
+
const out = scope.alloc(X.cols * 64), status = scope.alloc(X.cols * 4);
|
|
800
|
+
if (validMask)
|
|
801
|
+
m.HEAPU8.set(validMask, mask);
|
|
802
|
+
const st = m.ccall("n4m_stats_variance_components_reml", "number", Array(6).fill("number"), [ctx.handle, x.viewPtr, groups, mask, out, status]);
|
|
803
|
+
checkStatus(st, ctx.handle);
|
|
804
|
+
const r = copyF64(out, X.cols * 8);
|
|
805
|
+
const field = (k) => Float64Array.from({ length: X.cols }, (_, j) => r[8 * j + k]);
|
|
806
|
+
const count = (k) => Array.from({ length: X.cols }, (_, j) => r[8 * j + k]);
|
|
807
|
+
return {
|
|
808
|
+
sigma2Between: field(0), sigma2Within: field(1), icc: field(2), logLikelihood: field(3),
|
|
809
|
+
nGroups: count(4), nObservations: count(5), remlCandidates: count(6),
|
|
810
|
+
bisectionIterations: count(7),
|
|
811
|
+
status: new Int32Array(m.HEAP32.slice(status / 4, status / 4 + X.cols)),
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
finally {
|
|
815
|
+
scope.close();
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
/** Exact and cluster-bootstrap confidence intervals of the same model.
|
|
819
|
+
* clusterIds (optional) names the resampling unit; the seed is a uint64. */
|
|
820
|
+
export function statsVarianceComponentsIntervals(X, groupIds, options) {
|
|
821
|
+
validateMatrix(X);
|
|
822
|
+
const { confidence, nBootstrap, seed, clusterIds, validMask } = options;
|
|
823
|
+
if (groupIds.length !== X.rows || (clusterIds && clusterIds.length !== X.rows) ||
|
|
824
|
+
(validMask && validMask.length !== X.data.length)) {
|
|
825
|
+
throw new RangeError("variance-components group, cluster or mask length mismatch");
|
|
826
|
+
}
|
|
827
|
+
if (!(confidence > 0 && confidence < 1) || !Number.isInteger(nBootstrap) ||
|
|
828
|
+
nBootstrap < 0 || nBootstrap > 100_000) {
|
|
829
|
+
throw new RangeError("invalid confidence or bootstrap count");
|
|
830
|
+
}
|
|
831
|
+
validateGroupIds(groupIds);
|
|
832
|
+
if (clusterIds)
|
|
833
|
+
validateGroupIds(clusterIds);
|
|
834
|
+
if (typeof seed === "number" && !Number.isSafeInteger(seed)) {
|
|
835
|
+
throw new RangeError("seeds supplied as numbers must be safe integers");
|
|
836
|
+
}
|
|
837
|
+
const seed64 = BigInt(seed);
|
|
838
|
+
if (seed64 < 0n || seed64 >= (1n << 64n))
|
|
839
|
+
throw new RangeError("seed is outside uint64 range");
|
|
840
|
+
const m = getModule(), scope = new NativeScope();
|
|
841
|
+
try {
|
|
842
|
+
const ctx = scope.ctx;
|
|
843
|
+
const x = scope.matrix(X.data, X.rows, X.cols);
|
|
844
|
+
const groups = scope.i64(groupIds);
|
|
845
|
+
const clusters = clusterIds ? scope.i64(clusterIds) : 0;
|
|
846
|
+
const mask = validMask ? scope.alloc(validMask.length) : 0;
|
|
847
|
+
const out = scope.alloc(X.cols * 64), valid = scope.alloc(X.cols * 8);
|
|
848
|
+
if (validMask)
|
|
849
|
+
m.HEAPU8.set(validMask, mask);
|
|
850
|
+
const st = m.ccall("n4m_stats_variance_components_intervals", "number", ["number", "number", "number", "number", "number", "number", "number", "i64",
|
|
851
|
+
"number", "number"], [ctx.handle, x.viewPtr, groups, clusters, mask, confidence, nBootstrap, seed64,
|
|
852
|
+
out, valid]);
|
|
853
|
+
checkStatus(st, ctx.handle);
|
|
854
|
+
const r = copyF64(out, X.cols * 8);
|
|
855
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
856
|
+
return {
|
|
857
|
+
sdChiSquare: pairs(r, X.cols, 0), iccExactF: pairs(r, X.cols, 2),
|
|
858
|
+
sdBootstrap: pairs(r, X.cols, 4), iccBootstrap: pairs(r, X.cols, 6),
|
|
859
|
+
nValidReplicates: Array.from({ length: X.cols }, (_, j) => Number(dv.getBigInt64(valid + j * 8, true))),
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
finally {
|
|
863
|
+
scope.close();
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
/** Equal-weight per-group column means (double-double sums): codes in
|
|
867
|
+
* [0, nGroups), every group nonempty, values in the declared numerical domain
|
|
868
|
+
* (nonzero |x| in [2^-256, 2^256]; a summary, so no spread limit), else N4mError. */
|
|
869
|
+
export function statsGroupMeans(X, groupCodes, nGroups) {
|
|
870
|
+
validateMatrix(X);
|
|
871
|
+
if (groupCodes.length !== X.rows || !Number.isSafeInteger(nGroups) || nGroups < 1 ||
|
|
872
|
+
nGroups > X.rows || groupCodes.some((c) => !Number.isSafeInteger(c))) {
|
|
873
|
+
throw new RangeError("invalid group-means dimensions");
|
|
874
|
+
}
|
|
875
|
+
const m = getModule(), scope = new NativeScope();
|
|
876
|
+
try {
|
|
877
|
+
const ctx = scope.ctx;
|
|
878
|
+
const x = scope.matrix(X.data, X.rows, X.cols);
|
|
879
|
+
const codes = scope.i64(groupCodes);
|
|
880
|
+
const means = scope.alloc(nGroups * X.cols * 8), counts = scope.alloc(nGroups * 8);
|
|
881
|
+
const st = m.ccall("n4m_stats_group_means", "number", ["number", "number", "number", "i64", "number", "number"], [ctx.handle, x.viewPtr, codes, BigInt(nGroups), means, counts]);
|
|
882
|
+
checkStatus(st, ctx.handle);
|
|
883
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
884
|
+
return {
|
|
885
|
+
means: { data: copyF64(means, nGroups * X.cols), rows: nGroups, cols: X.cols },
|
|
886
|
+
counts: Array.from({ length: nGroups }, (_, i) => Number(dv.getBigInt64(counts + i * 8, true))),
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
finally {
|
|
890
|
+
scope.close();
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
/** RMSE, MAE and R² through n4m_stats_regression_scores (explicit residuals,
|
|
894
|
+
* double-double sums). Inputs outside the declared numerical domain
|
|
895
|
+
* (nonzero |x| in [2^-256, 2^256], spread <= 2^32) throw N4mError
|
|
896
|
+
* ERR_UNSUPPORTED. */
|
|
897
|
+
export function statsRegressionScores(yTrue, yPred) {
|
|
898
|
+
if (yTrue.length < 1 || yTrue.length !== yPred.length) {
|
|
899
|
+
throw new RangeError("regression scores need paired nonempty vectors");
|
|
900
|
+
}
|
|
901
|
+
const m = getModule(), scope = new NativeScope();
|
|
902
|
+
try {
|
|
903
|
+
const t = scope.alloc(yTrue.length * 8), p = scope.alloc(yPred.length * 8);
|
|
904
|
+
m.HEAPF64.set(yTrue, t / 8);
|
|
905
|
+
m.HEAPF64.set(yPred, p / 8);
|
|
906
|
+
const out = scope.alloc(4 * 8);
|
|
907
|
+
const st = m.ccall("n4m_stats_regression_scores", "number", ["number", "number", "number", "i64", "number"], [scope.ctx.handle, t, p, BigInt(yTrue.length), out]);
|
|
908
|
+
checkStatus(st, scope.ctx.handle);
|
|
909
|
+
const r = copyF64(out, 4);
|
|
910
|
+
return { rmse: r[0], mae: r[1], r2: r[2], r2Exponent: r[3] };
|
|
911
|
+
}
|
|
912
|
+
finally {
|
|
913
|
+
scope.close();
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
/** Cluster overlap between two partitions; negative labels are unassigned. */
|
|
917
|
+
export function clusterJaccardMatrix(labelsA, labelsB, nClustersA, nClustersB) {
|
|
918
|
+
if (labelsA.length !== labelsB.length || !Number.isSafeInteger(nClustersA) || nClustersA < 0 ||
|
|
919
|
+
!Number.isSafeInteger(nClustersB) || nClustersB < 0) {
|
|
920
|
+
throw new RangeError("invalid Jaccard labels or cluster counts");
|
|
921
|
+
}
|
|
922
|
+
validateGroupIds(labelsA);
|
|
923
|
+
validateGroupIds(labelsB);
|
|
924
|
+
const cells = nClustersA * nClustersB;
|
|
925
|
+
const m = getModule(), scope = new NativeScope();
|
|
926
|
+
try {
|
|
927
|
+
const ctx = scope.ctx;
|
|
928
|
+
const pa = scope.i64(labelsA), pb = scope.i64(labelsB);
|
|
929
|
+
const jac = scope.alloc(cells * 8), inter = scope.alloc(cells * 8);
|
|
930
|
+
const sa = scope.alloc(nClustersA * 8), sb = scope.alloc(nClustersB * 8);
|
|
931
|
+
const st = m.ccall("n4m_cluster_jaccard_matrix", "number", ["number", "number", "number", "i64", "i64", "i64", "number", "number", "number", "number"], [ctx.handle, pa, pb, BigInt(labelsA.length), BigInt(nClustersA), BigInt(nClustersB),
|
|
932
|
+
jac, inter, sa, sb]);
|
|
933
|
+
checkStatus(st, ctx.handle);
|
|
934
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
935
|
+
const i64 = (ptr, n) => Array.from({ length: n }, (_, j) => Number(dv.getBigInt64(ptr + j * 8, true)));
|
|
936
|
+
return {
|
|
937
|
+
jaccard: { data: copyF64(jac, cells), rows: nClustersA, cols: nClustersB },
|
|
938
|
+
intersections: i64(inter, cells), sizesA: i64(sa, nClustersA), sizesB: i64(sb, nClustersB),
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
finally {
|
|
942
|
+
scope.close();
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
/** scipy.optimize.linear_sum_assignment (SciPy 1.18.1 tie order); +Infinity forbids a pair. */
|
|
946
|
+
export function linearSumAssignment(cost, maximize = false) {
|
|
947
|
+
validateMatrix(cost);
|
|
948
|
+
const k = Math.min(cost.rows, cost.cols);
|
|
949
|
+
const m = getModule(), scope = new NativeScope();
|
|
950
|
+
try {
|
|
951
|
+
const ctx = scope.ctx;
|
|
952
|
+
const c = scope.matrix(cost.data, cost.rows, cost.cols);
|
|
953
|
+
const rows = scope.alloc(k * 8), cols = scope.alloc(k * 8), count = scope.alloc(8);
|
|
954
|
+
const st = m.ccall("n4m_linear_sum_assignment", "number", ["number", "number", "number", "number", "number", "number"], [ctx.handle, c.viewPtr, maximize ? 1 : 0, rows, cols, count]);
|
|
955
|
+
checkStatus(st, ctx.handle);
|
|
956
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
957
|
+
const i64 = (ptr) => Array.from({ length: k }, (_, j) => Number(dv.getBigInt64(ptr + j * 8, true)));
|
|
958
|
+
return { rowInd: i64(rows), colInd: i64(cols) };
|
|
959
|
+
}
|
|
960
|
+
finally {
|
|
961
|
+
scope.close();
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
/** numpy.random.default_rng(seed).multivariate_normal(mean, cov, size=n, method="cholesky").
|
|
965
|
+
* The seed is an unsigned 64-bit integer; pass a bigint above 2^53. Returns a row-major n x d matrix. */
|
|
966
|
+
export function randomMultivariateNormal(mean, cov, n, seed) {
|
|
967
|
+
validateMatrix(cov);
|
|
968
|
+
if (cov.rows !== cov.cols || mean.length !== cov.rows || !Number.isSafeInteger(n) || n < 0) {
|
|
969
|
+
throw new RangeError("invalid multivariate normal dimensions");
|
|
970
|
+
}
|
|
971
|
+
if (typeof seed === "number" && !Number.isSafeInteger(seed)) {
|
|
972
|
+
throw new RangeError("seeds supplied as numbers must be safe integers");
|
|
973
|
+
}
|
|
974
|
+
const seed64 = BigInt(seed);
|
|
975
|
+
if (seed64 < 0n || seed64 >= (1n << 64n))
|
|
976
|
+
throw new RangeError("seed is outside uint64 range");
|
|
977
|
+
const d = cov.rows;
|
|
978
|
+
const m = getModule(), scope = new NativeScope();
|
|
979
|
+
try {
|
|
980
|
+
const ctx = scope.ctx;
|
|
981
|
+
const c = scope.matrix(cov.data, d, d);
|
|
982
|
+
const mu = scope.alloc(d * 8), out = scope.alloc(n * d * 8);
|
|
983
|
+
m.HEAPF64.set(mean, mu / 8);
|
|
984
|
+
const st = m.ccall("n4m_random_multivariate_normal", "number", ["number", "i64", "number", "number", "i64", "number"], [ctx.handle, seed64, mu, c.viewPtr, BigInt(n), out]);
|
|
985
|
+
checkStatus(st, ctx.handle);
|
|
986
|
+
return { data: copyF64(out, n * d), rows: n, cols: d };
|
|
987
|
+
}
|
|
988
|
+
finally {
|
|
989
|
+
scope.close();
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
/** Successive numpy.random.default_rng(seed).permutation(n) draws from one generator.
|
|
993
|
+
* The seed is an unsigned 64-bit integer; pass a bigint above 2^53. */
|
|
994
|
+
export function randomPermutations(seed, n, nPermutations) {
|
|
995
|
+
if (!Number.isSafeInteger(n) || n < 0 || !Number.isSafeInteger(nPermutations) || nPermutations < 0) {
|
|
996
|
+
throw new RangeError("invalid permutation dimensions");
|
|
997
|
+
}
|
|
998
|
+
if (typeof seed === "number" && !Number.isSafeInteger(seed)) {
|
|
999
|
+
throw new RangeError("seeds supplied as numbers must be safe integers");
|
|
1000
|
+
}
|
|
1001
|
+
const seed64 = BigInt(seed);
|
|
1002
|
+
if (seed64 < 0n || seed64 >= (1n << 64n))
|
|
1003
|
+
throw new RangeError("seed is outside uint64 range");
|
|
1004
|
+
const m = getModule(), scope = new NativeScope();
|
|
1005
|
+
try {
|
|
1006
|
+
const ctx = scope.ctx;
|
|
1007
|
+
const out = scope.alloc(n * nPermutations * 8);
|
|
1008
|
+
const st = m.ccall("n4m_random_permutations", "number", ["number", "i64", "i64", "i64", "number"], [ctx.handle, seed64, BigInt(n), BigInt(nPermutations), out]);
|
|
1009
|
+
checkStatus(st, ctx.handle);
|
|
1010
|
+
const dv = new DataView(m.HEAPU8.buffer);
|
|
1011
|
+
return Array.from({ length: nPermutations }, (_, b) => Array.from({ length: n }, (_, j) => Number(dv.getBigInt64(out + (b * n + j) * 8, true))));
|
|
1012
|
+
}
|
|
1013
|
+
finally {
|
|
1014
|
+
scope.close();
|
|
1015
|
+
}
|
|
1016
|
+
}
|