@nirs4all/methods 1.3.3 → 1.3.5

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,37 @@
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
+ /** Centered PCA using the native Methods SVD. Output matrices are row-major. */
29
+ export declare function preflightPca(X: Matrix, k: number): PreflightPcaResult;
30
+ /** Per-feature pooled repeatability and balanced ICC(1,1). */
31
+ export declare function preflightRepeatability(X: Matrix, groupIds: readonly (number | bigint)[], validMask?: Uint8Array): PreflightRepeatabilityResult;
32
+ /** Finite-value summary: count, min, max, mean, sample SD, Q1, median, Q3. */
33
+ export declare function preflightSummary(values: Float64Array, validMask?: Uint8Array): Float64Array;
34
+ /** Euclidean reference neighbors, optionally excluding equal group IDs. */
35
+ export declare function preflightNearestNeighbors(query: Matrix, reference: Matrix, k: number, queryGroups?: readonly (number | bigint)[], referenceGroups?: readonly (number | bigint)[]): PreflightNeighborResult;
36
+ /** Local Y coherence using an existing row-major n x k neighbor-index table. */
37
+ export declare function preflightLocalContrast(targets: Float64Array, neighborIndices: readonly (number | bigint)[], k: number, categorical: boolean, groupIds?: readonly (number | bigint)[]): PreflightLocalContrastResult;
@@ -0,0 +1,202 @@
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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nirs4all/methods",
3
- "version": "1.3.3",
3
+ "version": "1.3.5",
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": {