@nirs4all/methods 1.2.0 → 1.3.0

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.
@@ -3,7 +3,8 @@
3
3
  // estimators (sample filters, transformers / selectors, one regressor or
4
4
  // classifier). Recipe validation, fit-input routing, the feature-name check
5
5
  // and the per-step N4ME states are native (n4m_role_pipeline_*); this file
6
- // marshals only. Class label names stay here, as the other bindings do.
6
+ // marshals only. Class label tables stay here, as the other bindings do, and
7
+ // follow the shared label contract (docs/abi/estimator_roles_design.md).
7
8
  import { checkStatus, getModule, makeMatrixView } from "./ffi.js";
8
9
  import { cString, methodClass, nativeParams, readI64, withContext, withFitInputs, } from "./estimatorRoles.js";
9
10
  const ROLES = {
@@ -33,18 +34,88 @@ function cStrings(values, allocs) {
33
34
  });
34
35
  return head;
35
36
  }
37
+ /** Column names become C strings: a NUL would silently truncate one, so it is refused. */
38
+ function checkNames(names) {
39
+ names.forEach((name, i) => {
40
+ if (name.includes("\0")) {
41
+ throw new Error(`feature name ${i} must not contain NUL: ${JSON.stringify(name)}`);
42
+ }
43
+ });
44
+ }
45
+ /**
46
+ * Class ids for the core and the label table (shared label contract).
47
+ * Integer labels are the ids and must be safe integers (so they fit int64
48
+ * exactly); strings and non-integer numbers become the table of sorted unique
49
+ * labels, the ids their positions. Missing (null / undefined), non-finite and
50
+ * boolean labels, and a mix of strings and numbers, are refused.
51
+ */
36
52
  function encodeLabels(y) {
37
53
  const labels = Array.from(y);
38
- if (labels.every((v) => typeof v === "number" && Number.isInteger(v))) {
54
+ for (const v of labels) {
55
+ if (v === null || v === undefined) {
56
+ throw new TypeError("class labels must not be missing (null or undefined)");
57
+ }
58
+ if (typeof v === "number" && !Number.isFinite(v)) {
59
+ throw new RangeError("class labels must be finite (no NaN or infinity)");
60
+ }
61
+ if (typeof v !== "number" && typeof v !== "string") {
62
+ throw new TypeError(`class labels must be integers, finite numbers or strings; got ${String(v)}`);
63
+ }
64
+ }
65
+ const numbers = labels.every((v) => typeof v === "number");
66
+ if (numbers && labels.every((v) => Number.isInteger(v))) {
67
+ const unsafe = labels.find((v) => !Number.isSafeInteger(v));
68
+ if (unsafe !== undefined) {
69
+ throw new RangeError(`class labels must fit int64 exactly (safe integers); got ${unsafe}`);
70
+ }
39
71
  return { ids: labels };
40
72
  }
41
- if (!labels.every((v) => typeof v === "string")) {
42
- throw new TypeError("class labels must be all integers or all strings");
73
+ if (!numbers && !labels.every((v) => typeof v === "string")) {
74
+ throw new TypeError("class labels must be all numbers or all strings");
43
75
  }
44
- const names = [...new Set(labels)].sort();
76
+ const names = [...new Set(labels)];
77
+ names.sort(numbers ? (a, b) => a - b : undefined);
45
78
  const index = new Map(names.map((name, i) => [name, i]));
46
79
  return { ids: labels.map((v) => index.get(v)), names };
47
80
  }
81
+ /**
82
+ * An imported label table (class_names) checked against the shared label
83
+ * contract: a non-empty list of unique strings or finite numbers (not both,
84
+ * no boolean) with an entry for every class id of the fitted state.
85
+ */
86
+ function labelTable(table, ids) {
87
+ if (!Array.isArray(table))
88
+ throw new TypeError("class_names must be a list");
89
+ if (table.length === 0)
90
+ throw new RangeError("class_names must not be empty");
91
+ table.forEach((v, i) => {
92
+ if (v === null || v === undefined)
93
+ throw new TypeError(`class_names has a missing entry at ${i}`);
94
+ if (typeof v !== "string" && typeof v !== "number") {
95
+ throw new TypeError(`class_names entries must be strings or numbers; entry ${i} is ${String(v)}`);
96
+ }
97
+ if (typeof v === "number" && !Number.isFinite(v)) {
98
+ throw new RangeError(`class_names has a non-finite entry at ${i}: ${v}`);
99
+ }
100
+ });
101
+ if (new Set(table.map((v) => typeof v)).size > 1)
102
+ throw new TypeError("class_names mixes strings and numbers");
103
+ const inexact = table.find((v) => typeof v === "number" && Number.isInteger(v) && Math.abs(v) > 2 ** 53);
104
+ if (inexact !== undefined) {
105
+ throw new RangeError(`numeric class_names must be exactly representable as float64; ${inexact} is beyond ±2^53`);
106
+ }
107
+ const seen = new Set();
108
+ for (const v of table) {
109
+ if (seen.has(v))
110
+ throw new RangeError(`class_names has duplicate label ${JSON.stringify(v)}`);
111
+ seen.add(v);
112
+ }
113
+ const outside = ids.find((id) => id < 0 || id >= table.length);
114
+ if (outside !== undefined) {
115
+ throw new RangeError(`class id ${outside} has no entry in class_names (${table.length} entries)`);
116
+ }
117
+ return [...table];
118
+ }
48
119
  /** Native trained recipe of role steps, portable as N4ME states. */
49
120
  export class RolePipeline {
50
121
  steps;
@@ -63,7 +134,10 @@ export class RolePipeline {
63
134
  /**
64
135
  * A fitted pipeline rebuilt from one N4ME state per stateful step. The
65
136
  * native import refuses states that contradict the recipe (count, method,
66
- * parameters, role, widths). classNames restores string class labels.
137
+ * parameters, role, widths). classNames restores the label table of a
138
+ * classifier trained on strings or non-integer numbers; it is refused
139
+ * unless it is a non-empty list of unique strings or finite numbers with
140
+ * an entry for every class id of the fitted state.
67
141
  */
68
142
  static fromStates(steps, states, options = {}) {
69
143
  const m = getModule();
@@ -71,6 +145,7 @@ export class RolePipeline {
71
145
  const handle = pipeline.create();
72
146
  const payloads = states.map((s) => (s instanceof Uint8Array ? s : s.n4me));
73
147
  const allocs = [];
148
+ let classNames;
74
149
  try {
75
150
  const buffers = m._malloc(Math.max(1, payloads.length) * 4);
76
151
  allocs.push({ ptr: buffers, free: () => m._free(buffers) });
@@ -87,6 +162,12 @@ export class RolePipeline {
87
162
  RolePipeline.setFeatureNames(ctx, handle, options.featureNames);
88
163
  checkStatus(m.ccall("n4m_role_pipeline_import_states", "number", ["number", "number", "number", "number", "number"], [ctx, handle, payloads.length, buffers, sizes]), ctx);
89
164
  });
165
+ if (options.classNames !== undefined) {
166
+ if (RolePipeline.stepInfo(handle, steps.length - 1).role !== "classifier") {
167
+ throw new TypeError("class_names are given but the final step is not a classifier");
168
+ }
169
+ classNames = labelTable(options.classNames, RolePipeline.classIds(handle));
170
+ }
90
171
  }
91
172
  catch (error) {
92
173
  m.ccall("n4m_role_pipeline_destroy", null, ["number"], [handle]);
@@ -95,7 +176,7 @@ export class RolePipeline {
95
176
  finally {
96
177
  allocs.forEach((a) => a.free());
97
178
  }
98
- pipeline.publish(handle, options.featureNames, options.classNames);
179
+ pipeline.publish(handle, options.featureNames, classNames);
99
180
  return pipeline;
100
181
  }
101
182
  get fitted() {
@@ -184,8 +265,11 @@ export class RolePipeline {
184
265
  }
185
266
  /** Fitted classes, ascending ids (names when trained on names). */
186
267
  classes() {
268
+ return RolePipeline.classIds(this.handle()).map((id) => this.label(id));
269
+ }
270
+ /** Native class ids of the final classifier (n4m_role_pipeline_classes). */
271
+ static classIds(handle) {
187
272
  const m = getModule();
188
- const handle = this.handle();
189
273
  const countPtr = m._malloc(8);
190
274
  try {
191
275
  checkStatus(m.ccall("n4m_role_pipeline_classes", "number", ["number", "number", "i64", "number"], [handle, 0, BigInt(0), countPtr]));
@@ -193,7 +277,7 @@ export class RolePipeline {
193
277
  const buf = m._malloc(Math.max(1, count) * 8);
194
278
  try {
195
279
  checkStatus(m.ccall("n4m_role_pipeline_classes", "number", ["number", "number", "i64", "number"], [handle, buf, BigInt(count), countPtr]));
196
- return Array.from({ length: count }, (_, i) => this.label(readI64(buf + 8 * i)));
280
+ return Array.from({ length: count }, (_, i) => readI64(buf + 8 * i));
197
281
  }
198
282
  finally {
199
283
  m._free(buf);
@@ -291,6 +375,7 @@ export class RolePipeline {
291
375
  static setFeatureNames(ctx, handle, names) {
292
376
  if (names === undefined)
293
377
  return;
378
+ checkNames(names);
294
379
  const allocs = [];
295
380
  try {
296
381
  checkStatus(getModule().ccall("n4m_role_pipeline_set_feature_names", "number", ["number", "number", "number", "i64"], [ctx, handle, cStrings(names, allocs), BigInt(names.length)]), ctx);
@@ -304,6 +389,8 @@ export class RolePipeline {
304
389
  if (names !== undefined && names.length !== X.cols) {
305
390
  throw new RangeError(`${names.length} feature names for ${X.cols} columns`);
306
391
  }
392
+ if (names !== undefined)
393
+ checkNames(names);
307
394
  const namesPtr = names === undefined ? 0 : cStrings(names, allocs);
308
395
  checkStatus(getModule().ccall("n4m_role_pipeline_check_features", "number", ["number", "number", "i64", "number"], [ctx, this.handle(), BigInt(X.cols), namesPtr]), ctx);
309
396
  }
@@ -0,0 +1,27 @@
1
+ import type { Matrix } from "./types.js";
2
+ export interface SpectralEncodingOptions {
3
+ kind: "lvse" | "gcu";
4
+ width?: number;
5
+ rank?: number;
6
+ overlap?: number;
7
+ standardize?: boolean;
8
+ snv?: boolean;
9
+ maxIter?: number;
10
+ tolerance?: number;
11
+ }
12
+ /** Fitted native LVSE/GCU. Call dispose() to release its WASM handle. */
13
+ export declare class SpectralEncoder {
14
+ private ptr;
15
+ private features;
16
+ private outputs;
17
+ constructor(options: SpectralEncodingOptions);
18
+ private check;
19
+ fit(X: Matrix): this;
20
+ transform(X: Matrix): Matrix;
21
+ /** LVSE without SNV: transform(X) = X @ operator.T + offset. */
22
+ exportAffine(): {
23
+ operator: Matrix;
24
+ offset: Float64Array;
25
+ };
26
+ dispose(): void;
27
+ }
@@ -0,0 +1,92 @@
1
+ // SPDX-License-Identifier: CECILL-2.1
2
+ import { checkStatus, getModule } from "./ffi.js";
3
+ /** Fitted native LVSE/GCU. Call dispose() to release its WASM handle. */
4
+ export class SpectralEncoder {
5
+ ptr = 0;
6
+ features = 0;
7
+ outputs = 0;
8
+ constructor(options) {
9
+ if (options.kind !== "lvse" && options.kind !== "gcu")
10
+ throw new Error("Unknown encoder kind");
11
+ const width = options.width ?? 64;
12
+ const rank = options.rank ?? (options.kind === "lvse" ? 4 : 16);
13
+ const iterations = options.maxIter ?? 60;
14
+ for (const v of [width, rank, iterations]) {
15
+ if (!Number.isInteger(v) || v < 1 || v > 2147483647)
16
+ throw new Error("Invalid encoder integer parameter");
17
+ }
18
+ const m = getModule(), out = m._malloc(4);
19
+ try {
20
+ checkStatus(m.ccall("n4m_decomposition_spectral_create", "number", Array(9).fill("number"), [options.kind === "lvse" ? 0 : 1, width, rank,
21
+ options.overlap ?? 0, Number(options.standardize ?? true),
22
+ Number(options.snv ?? false), iterations, options.tolerance ?? 1e-3, out]));
23
+ this.ptr = m.HEAP32[out / 4];
24
+ }
25
+ finally {
26
+ m._free(out);
27
+ }
28
+ }
29
+ check(X) {
30
+ if (!this.ptr)
31
+ throw new Error("Encoder is disposed");
32
+ if (!Number.isInteger(X.rows) || !Number.isInteger(X.cols) || X.rows < 1 || X.cols < 1
33
+ || X.rows > 2147483647 || X.cols > 2147483647 || X.data.length !== X.rows * X.cols)
34
+ throw new Error("Invalid spectral matrix dimensions");
35
+ }
36
+ fit(X) {
37
+ this.check(X);
38
+ const m = getModule(), xp = m._malloc(X.data.length * 8), count = m._malloc(8);
39
+ try {
40
+ m.HEAPF64.set(X.data, xp / 8);
41
+ checkStatus(m.ccall("n4m_wasm_spectral_fit", "number", Array(4).fill("number"), [this.ptr, xp, X.rows, X.cols]));
42
+ checkStatus(m.ccall("n4m_decomposition_spectral_output_cols", "number", ["number", "number"], [this.ptr, count]));
43
+ const view = new DataView(m.HEAPU8.buffer);
44
+ this.outputs = Number(view.getBigInt64(count, true));
45
+ this.features = X.cols;
46
+ return this;
47
+ }
48
+ finally {
49
+ m._free(xp);
50
+ m._free(count);
51
+ }
52
+ }
53
+ transform(X) {
54
+ this.check(X);
55
+ if (!this.outputs || X.cols !== this.features)
56
+ throw new Error("Unfitted encoder or feature mismatch");
57
+ const m = getModule(), xp = m._malloc(X.data.length * 8), out = m._malloc(X.rows * this.outputs * 8);
58
+ try {
59
+ m.HEAPF64.set(X.data, xp / 8);
60
+ checkStatus(m.ccall("n4m_wasm_spectral_transform", "number", Array(6).fill("number"), [this.ptr, xp, X.rows, X.cols, out, this.outputs]));
61
+ return { data: Float64Array.from(m.HEAPF64.subarray(out / 8, out / 8 + X.rows * this.outputs)),
62
+ rows: X.rows, cols: this.outputs };
63
+ }
64
+ finally {
65
+ m._free(xp);
66
+ m._free(out);
67
+ }
68
+ }
69
+ /** LVSE without SNV: transform(X) = X @ operator.T + offset. */
70
+ exportAffine() {
71
+ if (!this.ptr || !this.outputs)
72
+ throw new Error("Encoder is not fitted");
73
+ const m = getModule(), size = this.outputs * this.features;
74
+ const op = m._malloc(size * 8), offset = m._malloc(this.outputs * 8);
75
+ try {
76
+ checkStatus(m.ccall("n4m_wasm_spectral_affine", "number", Array(5).fill("number"), [this.ptr, op, offset, this.features, this.outputs]));
77
+ return { operator: { data: Float64Array.from(m.HEAPF64.subarray(op / 8, op / 8 + size)),
78
+ rows: this.outputs, cols: this.features },
79
+ offset: Float64Array.from(m.HEAPF64.subarray(offset / 8, offset / 8 + this.outputs)) };
80
+ }
81
+ finally {
82
+ m._free(op);
83
+ m._free(offset);
84
+ }
85
+ }
86
+ dispose() {
87
+ if (this.ptr) {
88
+ getModule().ccall("n4m_decomposition_spectral_destroy", null, ["number"], [this.ptr]);
89
+ this.ptr = 0;
90
+ }
91
+ }
92
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nirs4all/methods",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
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"
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"
24
24
  },
25
25
  "license": "CECILL-2.1",
26
26
  "publishConfig": {