@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/dist/n4m.wasm CHANGED
Binary file
@@ -1,6 +1,19 @@
1
1
  import type { Context } from "./context.js";
2
2
  import type { MethodResult } from "./methodResult.js";
3
- import type { Matrix } from "./types.js";
3
+ import { ModelArray, type Matrix } from "./types.js";
4
+ /** Component resolution of a PLS regression or PCR model (ABI 2.20). */
5
+ export interface ComponentResolution {
6
+ /** Absolute X-Y cross-covariance resolution, in centred (scaled) X times
7
+ * Y units, shared by every component. */
8
+ resolution: number;
9
+ /** Per component: true when its cross-covariance is not above the
10
+ * resolution, whether mathematically undefined (exact value zero) or
11
+ * merely not resolved numerically (below the bound). PLS publishes such
12
+ * a component, and every later one, as a null component (zero latent
13
+ * columns, no contribution to the coefficients); PCR keeps a resolved
14
+ * X direction (n4m.h, N4M_MODEL_UNRESOLVED_COMPONENTS). */
15
+ unresolved: boolean[];
16
+ }
4
17
  export declare class NativeModel {
5
18
  private _ptr;
6
19
  private readonly _ctx;
@@ -11,6 +24,11 @@ export declare class NativeModel {
11
24
  static fromN4mm(ctx: Context, payload: Uint8Array): NativeModel;
12
25
  /** Predict through libn4m; no coefficients are evaluated in JS. */
13
26
  predict(X: Matrix): Matrix;
27
+ /** Copy one fitted-model array (n4m_model_get_array). */
28
+ getArray(kind: ModelArray): Matrix;
29
+ /** Component resolution and unresolved flags; throws N4mError
30
+ * (unsupported) for models that do not record them. */
31
+ componentResolution(): ComponentResolution;
14
32
  /** Export the complete native model as N4MM bytes. */
15
33
  toN4mm(): Uint8Array;
16
34
  destroy(): void;
@@ -1,6 +1,7 @@
1
1
  // SPDX-License-Identifier: CECILL-2.1
2
2
  // Native predict-only model promoted from an affine MethodResult.
3
- import { checkStatus, getModule, makeMatrixView } from "./ffi.js";
3
+ import { checkStatus, getModule, makeMatrixView, readArrayView } from "./ffi.js";
4
+ import { ModelArray } from "./types.js";
4
5
  export class NativeModel {
5
6
  _ptr;
6
7
  _ctx;
@@ -69,6 +70,32 @@ export class NativeModel {
69
70
  m._free(targetsPtr);
70
71
  }
71
72
  }
73
+ /** Copy one fitted-model array (n4m_model_get_array). */
74
+ getArray(kind) {
75
+ const m = getModule();
76
+ const out = m._malloc(4);
77
+ try {
78
+ m.setValue(out, 0, "i32");
79
+ checkStatus(m.ccall("n4m_model_get_array", "number", ["number", "number", "number", "number"], [this._ctx.handle, this._ptr, kind, out]), this._ctx.handle);
80
+ const arr = m.getValue(out, "i32");
81
+ try {
82
+ return readArrayView(arr);
83
+ }
84
+ finally {
85
+ m.ccall("n4m_array_free", null, ["number"], [arr]);
86
+ }
87
+ }
88
+ finally {
89
+ m._free(out);
90
+ }
91
+ }
92
+ /** Component resolution and unresolved flags; throws N4mError
93
+ * (unsupported) for models that do not record them. */
94
+ componentResolution() {
95
+ const resolution = this.getArray(ModelArray.COMPONENT_RESOLUTION).data[0];
96
+ const flags = this.getArray(ModelArray.UNRESOLVED_COMPONENTS).data;
97
+ return { resolution, unresolved: Array.from(flags, (v) => v !== 0) };
98
+ }
72
99
  /** Export the complete native model as N4MM bytes. */
73
100
  toN4mm() {
74
101
  const m = getModule();
@@ -2,9 +2,14 @@ import { type Matrix } from "./types.js";
2
2
  export interface PreflightPcaResult {
3
3
  scores: Matrix;
4
4
  loadings: Matrix;
5
+ /** Variances; 0 for an unresolved component. */
5
6
  eigenvalues: Float64Array;
6
7
  /** [trace(C), trace(C*C)] over the full centered covariance spectrum. */
7
8
  fullMoments: readonly [number, number];
9
+ /** Conservative absolute accuracy threshold of the eigenvalues (16 max(n,p) eps lambda_max). */
10
+ resolution: number;
11
+ /** 1 when the component's variance is not above `resolution` (not rank). */
12
+ unresolved: Uint8Array;
8
13
  }
9
14
  export interface PreflightRepeatabilityResult {
10
15
  pooledSd: Float64Array;
@@ -70,7 +75,133 @@ export interface PreflightFactorAssociationResult {
70
75
  nAtLeastObserved: number;
71
76
  nPermutationsExecuted: number;
72
77
  }
73
- /** Centered PCA using the native Methods SVD. Output matrices are row-major. */
78
+ export interface StatsCorrelationTestResult {
79
+ /** Pearson r or Spearman rho; NaN when x or y is constant. */
80
+ coefficient: number;
81
+ nDistinctX: number;
82
+ nDistinctY: number;
83
+ /** log10 upper bound on distinct permutation outcomes. */
84
+ log10DistinctPermutations: number;
85
+ /** Two-sided Monte Carlo (1+b)/(1+B); NaN without permutations. */
86
+ pValue: number;
87
+ nAtLeastObserved: number;
88
+ nPermutationsExecuted: number;
89
+ }
90
+ export interface StatsExactPermutationResult {
91
+ /** Number N of distinct arrangements enumerated. */
92
+ nArrangements: number;
93
+ /** Exact p-value #{T >= T_obs}/N; NaN when the statistic is undefined. */
94
+ pValue: number;
95
+ /** Smallest attainable exact p-value #{T >= T_max}/N. */
96
+ minimumPValue: number;
97
+ maximumStatistic: number;
98
+ }
99
+ export interface PermanovaResult {
100
+ /** Sums of squares are ss* x 2^ssExponent; 0 when they are normal doubles. */
101
+ ssExponent: number;
102
+ ssTotal: number;
103
+ /** Between-strata SS (0 without strata). */
104
+ ssStrata: number;
105
+ /** SS of the term given the strata (additive strata + term model). */
106
+ ssTerm: number;
107
+ ssResidual: number;
108
+ r2: number;
109
+ partialR2: number;
110
+ pseudoF: number;
111
+ /** Identifiable term df: levels - connected components; 0 when aliased. */
112
+ dfTerm: number;
113
+ dfResidual: number;
114
+ nLevels: number;
115
+ nStrata: number;
116
+ /** log10 of the distinct within-strata level assignments. */
117
+ log10DistinctPermutations: number;
118
+ /** Monte Carlo (1+b)/(1+B); NaN without an executed test. */
119
+ pValue: number;
120
+ /** Error estimate of the residual SS divided by it (+Infinity when the
121
+ * residual SS is 0; NaN when the pseudo-F has no df). */
122
+ residualResolution: number;
123
+ /** True when the residual SS is not resolved above rounding
124
+ * (residualResolution >= 1): the pseudo-F is published but unresolved. */
125
+ fNumericallyUnresolved: boolean;
126
+ nAtLeastObserved: number;
127
+ nPermutationsExecuted: number;
128
+ }
129
+ export interface FreedmanLaneResult {
130
+ /** Sums of squares are ss* x 2^ssExponent; 0 when they are normal doubles. */
131
+ ssExponent: number;
132
+ ssTotal: number;
133
+ /** Model SS of the reduced design (intercept + condition main effects). */
134
+ ssReduced: number;
135
+ /** SS(full) - SS(reduced). */
136
+ ssTerm: number;
137
+ ssResidual: number;
138
+ r2: number;
139
+ partialR2: number;
140
+ pseudoF: number;
141
+ /** rank(full) - rank(reduced); 0 when aliased with the conditions. */
142
+ dfTerm: number;
143
+ dfResidual: number;
144
+ rankReduced: number;
145
+ log10DistinctPermutations: number;
146
+ pValue: number;
147
+ /** Error estimate of the residual SS divided by it (+Infinity when the
148
+ * residual SS is 0; NaN when the pseudo-F has no df). */
149
+ residualResolution: number;
150
+ /** True when the residual SS is not resolved above rounding
151
+ * (residualResolution >= 1): the pseudo-F is published but unresolved. */
152
+ fNumericallyUnresolved: boolean;
153
+ nAtLeastObserved: number;
154
+ nPermutationsExecuted: number;
155
+ }
156
+ export interface PermdispResult {
157
+ /** Distances are distances x 2^distanceExponent; 0 when normal doubles. */
158
+ distanceExponent: number;
159
+ /** Euclidean distance of each row to its group centroid. */
160
+ distances: Float64Array;
161
+ /** Mean distance per group, in ascending group-code order. */
162
+ groupMeanDistances: Float64Array;
163
+ f: number;
164
+ df1: number;
165
+ df2: number;
166
+ nGroups: number;
167
+ log10DistinctPermutations: number;
168
+ pValue: number;
169
+ /** Error estimate of the within SS of the distances divided by it. */
170
+ residualResolution: number;
171
+ /** True when F is published but not resolved above rounding. */
172
+ fNumericallyUnresolved: boolean;
173
+ nAtLeastObserved: number;
174
+ nPermutationsExecuted: number;
175
+ }
176
+ export interface VarianceComponentsRemlResult {
177
+ /** REML s2_between per feature (NaN when undefined). */
178
+ sigma2Between: Float64Array;
179
+ sigma2Within: Float64Array;
180
+ /** ICC(1) = s2b / (s2b + s2w). */
181
+ icc: Float64Array;
182
+ /** Restricted log-likelihood, statsmodels MixedLM convention. */
183
+ logLikelihood: Float64Array;
184
+ nGroups: number[];
185
+ nObservations: number[];
186
+ /** Local maxima of the restricted likelihood compared. */
187
+ remlCandidates: number[];
188
+ bisectionIterations: number[];
189
+ /** 0 interior, 1 insufficient, 2 s2b=0 boundary, 3 zero total variance,
190
+ * 4 s2w=0 boundary, 5 not converged. */
191
+ status: Int32Array;
192
+ }
193
+ export interface VarianceComponentsIntervalsResult {
194
+ /** Exact chi-square interval of the within-group SD, [lower, upper] per feature. */
195
+ sdChiSquare: Float64Array;
196
+ /** Exact F interval of the balanced ANOVA ICC(1,1); NaN when unbalanced. */
197
+ iccExactF: Float64Array;
198
+ /** Cluster-bootstrap percentile interval of the pooled within-group SD. */
199
+ sdBootstrap: Float64Array;
200
+ /** Cluster-bootstrap percentile interval of the REML ICC(1). */
201
+ iccBootstrap: Float64Array;
202
+ nValidReplicates: number[];
203
+ }
204
+ /** Centered PCA (exact Gram eigendecomposition in Methods). Output matrices are row-major. */
74
205
  export declare function preflightPca(X: Matrix, k: number): PreflightPcaResult;
75
206
  /** Per-feature pooled repeatability and balanced ICC(1,1). */
76
207
  export declare function preflightRepeatability(X: Matrix, groupIds: readonly (number | bigint)[], validMask?: Uint8Array): PreflightRepeatabilityResult;
@@ -102,6 +233,18 @@ export interface PreflightPairsResult {
102
233
  totalPairs: number;
103
234
  candidatePairs: number;
104
235
  }
236
+ export interface PreflightSnvResult {
237
+ /** Row-major SNV rows (population SD), or group means when groups are given. */
238
+ matrix: Matrix;
239
+ /** Per output row, a first-order bound on the absolute rounding error of each entry. */
240
+ errorBounds: Float64Array;
241
+ }
242
+ /**
243
+ * SNV with rounding bounds (ABI 2.20 n4m_preflight_snv_compute). With
244
+ * `groupIds` (dense codes 0..nGroups-1, every group non-empty), each output
245
+ * row is the equal-weight mean of the SNV rows of one group.
246
+ */
247
+ export declare function preflightSnv(X: Matrix, groupIds?: readonly (number | bigint)[], nGroups?: number): PreflightSnvResult;
105
248
  /** Savitzky-Golay smoothing-residual noise proxy; interior features only. */
106
249
  export declare function preflightNoiseProxy(X: Matrix, windowLength: number, polyorder: number, validMask?: Uint8Array): PreflightNoiseProxyResult;
107
250
  /**
@@ -114,3 +257,147 @@ export declare function preflightPairsWithinTolerance(query: Matrix, tolerance:
114
257
  export declare function preflightFactorAssociation(factorCodes: readonly (number | bigint)[], targets: Float64Array, categorical: boolean, nPermutations: number, seed: number | bigint): PreflightFactorAssociationResult;
115
258
  /** Holm step-down adjusted p-values for one hypothesis family. */
116
259
  export declare function preflightHolmAdjust(pValues: Float64Array): Float64Array;
260
+ /** Pearson or Spearman correlation over exchangeable units with a seeded
261
+ * two-sided permutation test of y. The seed is an unsigned 64-bit integer;
262
+ * pass a bigint above 2^53. */
263
+ export declare function statsCorrelationTest(x: Float64Array, y: Float64Array, method: "pearson" | "spearman", nPermutations: number, seed: number | bigint): StatsCorrelationTestResult;
264
+ /** Benjamini-Hochberg step-up adjusted p-values for one hypothesis family. */
265
+ export declare function statsBhAdjust(pValues: Float64Array): Float64Array;
266
+ /** Exact permutation distribution of the factor-target association statistic
267
+ * (eta^2 or Cramer's V^2) by enumerating distinct arrangements. */
268
+ export declare function statsFactorAssociationExact(factorCodes: readonly (number | bigint)[], targets: Float64Array, categorical: boolean, maxArrangements: number): StatsExactPermutationResult;
269
+ /** Exact permutation distribution of |r| (Pearson or Spearman). */
270
+ export declare function statsCorrelationExact(x: Float64Array, y: Float64Array, method: "pearson" | "spearman", maxArrangements: number): StatsExactPermutationResult;
271
+ /** PERMANOVA of one categorical term on Euclidean distances between rows,
272
+ * optionally given strata (permutations stay inside each stratum). */
273
+ export declare function statsPermanova(X: Matrix, termCodes: readonly (number | bigint)[], strataCodes: readonly (number | bigint)[] | undefined, nPermutations: number, seed: number | bigint): PermanovaResult;
274
+ /** PERMDISP (betadisper type "centroid"): distances to group centroids, their
275
+ * one-way ANOVA F and a residual-permutation test. Not an exchangeability check. */
276
+ export declare function statsPermdisp(X: Matrix, groupCodes: readonly (number | bigint)[], nPermutations: number, seed: number | bigint): PermdispResult;
277
+ /** Partial PERMANOVA of a term given the additive main effects of condition
278
+ * factors (one code array per factor), tested by Freedman-Lane permutation of
279
+ * the reduced-model residuals. */
280
+ export declare function statsPermanovaFreedmanLane(X: Matrix, termCodes: readonly (number | bigint)[], conditionCodes: readonly (readonly (number | bigint)[])[], nPermutations: number, seed: number | bigint): FreedmanLaneResult;
281
+ export interface StatsEnergyDistanceResult {
282
+ /** Row-major nGroups x nGroups energies E = 2M_ab - M_aa - M_bb (unit of X), symmetric, >= 0. */
283
+ energy: Float64Array;
284
+ /** Row-major absolute rounding bounds of the energies. */
285
+ energyBounds: Float64Array;
286
+ /** Row-major mean pairwise distances M (V-statistic, self-pairs included). */
287
+ meanDistances: Float64Array;
288
+ /** sum_{a<b} n_a n_b / (n_a + n_b) energy[a][b] and its rounding bound. */
289
+ statistic: number;
290
+ statisticBound: number;
291
+ /** log10(n! / prod n_a!), distinct label assignments. */
292
+ log10DistinctPermutations: number;
293
+ /** Monte Carlo (1+b)/(1+B) under T_perm >= T - sqrt(eps)|T|; NaN without permutations. */
294
+ pValue: number;
295
+ /** (1+b')/(1+B) counting every numerically undecidable draw as a tie. */
296
+ pValueConservative: number;
297
+ nAtLeastObserved: number;
298
+ nPermutationsExecuted: number;
299
+ /** Draws within 2 bound(T) of the tie threshold. */
300
+ nUndecidable: number;
301
+ }
302
+ /** Energy distance between groups of rows with a K-sample permutation test.
303
+ * groupCodes are integers in [0, nGroups); the seed is an unsigned 64-bit
304
+ * integer (pass a bigint above 2^53). The native size limits are checked
305
+ * before any WASM allocation and raise N4mError(ERR_UNSUPPORTED); inputs
306
+ * outside the supported numerical domain raise the same status. */
307
+ export declare function statsEnergyDistance(X: Matrix, groupCodes: readonly number[], nGroups: number, nPermutations: number, seed: number | bigint): StatsEnergyDistanceResult;
308
+ export interface StatsPcaMonitorResult {
309
+ /** First effectiveComponents eigenvalues (ddof 1), then NaN. */
310
+ eigenvalues: Float64Array;
311
+ /** Smallest numerical rank of the fold and full fits, capped at maxComponents. */
312
+ effectiveComponents: number;
313
+ /** Out-of-fold reference statistics (row i in fold i mod nFolds). */
314
+ referenceT2: Float64Array;
315
+ referenceQ: Float64Array;
316
+ /** Monitored rows in the fit on every reference row. */
317
+ monitoredT2: Float64Array;
318
+ monitoredQ: Float64Array;
319
+ /** Monitored rows above the T^2 limit, the Q limit, either, by more than the tolerance. */
320
+ nBeyondT2: number;
321
+ nBeyondQ: number;
322
+ nBeyondEither: number;
323
+ /** Rows within the tolerance of a limit (numerically undetermined). */
324
+ nNearT2: number;
325
+ nNearQ: number;
326
+ nNearEither: number;
327
+ /** Empirical (1 - alpha) type-7 quantiles of the out-of-fold values. */
328
+ t2Limit: number;
329
+ qLimit: number;
330
+ /** Conservative relative tolerance tau = 16 m eps cond (an estimate). */
331
+ tolerance: number;
332
+ condition: number;
333
+ /** Q tolerance scale S (Q tolerance = tau S). */
334
+ qToleranceScale: number;
335
+ /** Eigenvalue resolution 16 m eps lambda_1. */
336
+ eigenvalueResolution: number;
337
+ referenceTotalVariance: number;
338
+ monitoredTotalVariance: number;
339
+ centroidDistance: number;
340
+ centroidSubspaceDistance: number;
341
+ centroidResidualDistance: number;
342
+ centroidT2: number;
343
+ retainedFraction: number;
344
+ }
345
+ /** PCA monitoring of rows against a reference PCA with out-of-fold limits.
346
+ * The native size limits are checked before any WASM allocation. */
347
+ export declare function statsPcaMonitor(reference: Matrix, monitored: Matrix, maxComponents: number, nFolds: number, alpha: number): StatsPcaMonitorResult;
348
+ /** One-way random-effects variance components by REML, per feature. */
349
+ export declare function statsVarianceComponentsReml(X: Matrix, groupIds: readonly (number | bigint)[], validMask?: Uint8Array): VarianceComponentsRemlResult;
350
+ /** Exact and cluster-bootstrap confidence intervals of the same model.
351
+ * clusterIds (optional) names the resampling unit; the seed is a uint64. */
352
+ export declare function statsVarianceComponentsIntervals(X: Matrix, groupIds: readonly (number | bigint)[], options: {
353
+ confidence: number;
354
+ nBootstrap: number;
355
+ seed: number | bigint;
356
+ clusterIds?: readonly (number | bigint)[];
357
+ validMask?: Uint8Array;
358
+ }): VarianceComponentsIntervalsResult;
359
+ export interface GroupMeansResult {
360
+ /** One row per group code, in code order. */
361
+ means: Matrix;
362
+ counts: number[];
363
+ }
364
+ /** Equal-weight per-group column means (double-double sums): codes in
365
+ * [0, nGroups), every group nonempty, values in the declared numerical domain
366
+ * (nonzero |x| in [2^-256, 2^256]; a summary, so no spread limit), else N4mError. */
367
+ export declare function statsGroupMeans(X: Matrix, groupCodes: readonly number[], nGroups: number): GroupMeansResult;
368
+ export interface RegressionScoresResult {
369
+ rmse: number;
370
+ mae: number;
371
+ /** R^2 = r2 * 2^r2Exponent; NaN (undefined) when y is constant. */
372
+ r2: number;
373
+ /** 0 whenever R^2 is a double; otherwise R^2 = -SSE/SST is scaled. */
374
+ r2Exponent: number;
375
+ }
376
+ /** RMSE, MAE and R² through n4m_stats_regression_scores (explicit residuals,
377
+ * double-double sums). Inputs outside the declared numerical domain
378
+ * (nonzero |x| in [2^-256, 2^256], spread <= 2^32) throw N4mError
379
+ * ERR_UNSUPPORTED. */
380
+ export declare function statsRegressionScores(yTrue: Float64Array, yPred: Float64Array): RegressionScoresResult;
381
+ export interface ClusterJaccardResult {
382
+ /** Row-major nClustersA x nClustersB Jaccard indices; NaN when both clusters are empty. */
383
+ jaccard: Matrix;
384
+ /** Row-major |A_i ∩ B_j| counts. */
385
+ intersections: number[];
386
+ sizesA: number[];
387
+ sizesB: number[];
388
+ }
389
+ export interface LinearSumAssignmentResult {
390
+ /** min(rows, cols) pairs in increasing row order. */
391
+ rowInd: number[];
392
+ colInd: number[];
393
+ }
394
+ /** Cluster overlap between two partitions; negative labels are unassigned. */
395
+ export declare function clusterJaccardMatrix(labelsA: readonly (number | bigint)[], labelsB: readonly (number | bigint)[], nClustersA: number, nClustersB: number): ClusterJaccardResult;
396
+ /** scipy.optimize.linear_sum_assignment (SciPy 1.18.1 tie order); +Infinity forbids a pair. */
397
+ export declare function linearSumAssignment(cost: Matrix, maximize?: boolean): LinearSumAssignmentResult;
398
+ /** numpy.random.default_rng(seed).multivariate_normal(mean, cov, size=n, method="cholesky").
399
+ * The seed is an unsigned 64-bit integer; pass a bigint above 2^53. Returns a row-major n x d matrix. */
400
+ export declare function randomMultivariateNormal(mean: Float64Array, cov: Matrix, n: number, seed: number | bigint): Matrix;
401
+ /** Successive numpy.random.default_rng(seed).permutation(n) draws from one generator.
402
+ * The seed is an unsigned 64-bit integer; pass a bigint above 2^53. */
403
+ export declare function randomPermutations(seed: number | bigint, n: number, nPermutations: number): number[][];