@nirs4all/methods 1.1.1 → 1.2.1

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 CHANGED
@@ -49,8 +49,8 @@ isolated band (achieved ~1e-16).
49
49
  import * as n4m from "@nirs4all/methods";
50
50
 
51
51
  await n4m.loadModule();
52
- console.log(n4m.version()); // "1.0.21+abi.2.13.0"
53
- console.log(n4m.abiVersion()); // [2, 13, 0]
52
+ console.log(n4m.version()); // "1.0.21+abi.2.14.0"
53
+ console.log(n4m.abiVersion()); // [2, 14, 0]
54
54
 
55
55
  const rows = 40, cols = 6;
56
56
  const X = new Float64Array(rows * cols); // row-major
@@ -52,6 +52,23 @@ export interface FitInputs {
52
52
  XTarget?: Matrix;
53
53
  foldIds?: number[];
54
54
  }
55
+ /** Runs `fn` with a fresh native context, destroyed afterwards. */
56
+ export declare function withContext<T>(fn: (ctx: number) => T): T;
57
+ export declare function readI64(ptr: number): number;
58
+ export type Alloc = {
59
+ ptr: number;
60
+ free: () => void;
61
+ };
62
+ export declare function cString(s: string): Alloc;
63
+ /** Validated native parameters of a method; the caller destroys them. */
64
+ export declare function nativeParams(ctx: number, method: NativeMethod): number;
65
+ /**
66
+ * Runs `fn` over an n4m_fit_inputs_v1_t built from the given data. Per-row
67
+ * inputs (y, labels, sampleWeight, groups, foldIds) must have one entry per
68
+ * row of X and per-column inputs (featureGroups, axis) one per column; the
69
+ * lengths are checked here with the argument named, and again natively.
70
+ */
71
+ export declare function withFitInputs<T>(X: Matrix, y: Matrix | Float64Array | ArrayLike<number> | undefined, labels: boolean, inputs: FitInputs, fn: (struct: number, hold: (a: Alloc) => number) => T): T;
55
72
  /** Parameters of one catalog method (estimator or procedure). */
56
73
  export declare abstract class NativeMethod {
57
74
  /** Catalog method id, for example "models.pls.pls_regression". */
@@ -78,11 +95,21 @@ export declare abstract class NativeEstimator extends NativeMethod {
78
95
  get fitted(): boolean;
79
96
  /**
80
97
  * Fit on row-major X and the target: responses for a regressor (a vector
81
- * or a row-major matrix), integer class ids for a classifier. Returns this.
98
+ * or a row-major matrix, one row per row of X), integer class ids for a
99
+ * classifier (one per row). Returns this. The fitted state is replaced
100
+ * only when the fit succeeds: a failed refit leaves the previous one.
82
101
  */
83
102
  fit(X: Matrix, y?: Matrix | Float64Array | ArrayLike<number>, inputs?: FitInputs): this;
84
- /** Portable fitted state (N4ME bytes), readable by every n4m binding. */
85
- toN4me(): Uint8Array;
103
+ /** True when the fitted state embeds training rows (kernel PLS, GPR-PLS, LW-PLS, ...). */
104
+ containsTrainingRows(): boolean;
105
+ /**
106
+ * Portable fitted state (N4ME bytes), readable by every n4m binding. A
107
+ * state that embeds training rows (containsTrainingRows()) is refused
108
+ * unless `allowTrainingRows` is set: sharing the export shares them.
109
+ */
110
+ toN4me(options?: {
111
+ allowTrainingRows?: boolean;
112
+ }): Uint8Array;
86
113
  /** Rebuilds a fitted estimator of the class registered for its method. */
87
114
  static fromN4me(payload: Uint8Array): NativeEstimator;
88
115
  /** Releases the native estimator. */
@@ -1,6 +1,10 @@
1
1
  // SPDX-License-Identifier: CECILL-2.1
2
2
  // Generic native estimator roles (ABI 2.13).
3
3
  //
4
+ // The helpers exported below (contexts, allocations, typed parameters, fit
5
+ // inputs) are shared with rolePipeline.ts; the package index does not
6
+ // re-export them.
7
+ //
4
8
  // Every class in estimatorRolesGenerated.ts extends NativeEstimator and
5
9
  // implements exactly the role interfaces its native method declares
6
10
  // (Regressor, Transformer, ...). Parameters, defaults, required inputs,
@@ -15,7 +19,7 @@ const OFF = {
15
19
  nAxis: 96, XTarget: 104, foldIds: 108, nFoldIds: 112,
16
20
  };
17
21
  /** Runs `fn` with a fresh native context, destroyed afterwards. */
18
- function withContext(fn) {
22
+ export function withContext(fn) {
19
23
  const m = getModule();
20
24
  const out = m._malloc(4);
21
25
  try {
@@ -33,7 +37,7 @@ function withContext(fn) {
33
37
  m._free(out);
34
38
  }
35
39
  }
36
- function readI64(ptr) {
40
+ export function readI64(ptr) {
37
41
  const m = getModule();
38
42
  return Number(m.getValue(ptr, "i64"));
39
43
  }
@@ -50,7 +54,7 @@ function allocI64(values) {
50
54
  return { ptr, free: () => m._free(ptr) };
51
55
  }
52
56
  const registry = new Map();
53
- function cString(s) {
57
+ export function cString(s) {
54
58
  const m = getModule();
55
59
  const n = m.lengthBytesUTF8(s) + 1;
56
60
  const ptr = m._malloc(n);
@@ -58,7 +62,7 @@ function cString(s) {
58
62
  return { ptr, free: () => m._free(ptr) };
59
63
  }
60
64
  /** Validated native parameters of a method; the caller destroys them. */
61
- function nativeParams(ctx, method) {
65
+ export function nativeParams(ctx, method) {
62
66
  const m = getModule();
63
67
  const indexPtr = m._malloc(4);
64
68
  const out = m._malloc(4);
@@ -121,8 +125,45 @@ function nativeParams(ctx, method) {
121
125
  m._free(out);
122
126
  }
123
127
  }
124
- /** Runs `fn` over an n4m_fit_inputs_v1_t built from the given data. */
125
- function withFitInputs(X, y, labels, inputs, fn) {
128
+ function checkMatrix(name, M) {
129
+ if (!Number.isInteger(M.rows) || !Number.isInteger(M.cols) || M.rows < 1 || M.cols < 1 ||
130
+ M.data.length !== M.rows * M.cols) {
131
+ throw new Error(`${name} must be a non-empty rows x cols matrix with rows*cols values; ` +
132
+ `got ${M.rows} x ${M.cols} with ${M.data.length} values`);
133
+ }
134
+ }
135
+ function checkLength(name, values, length, what) {
136
+ if (values.length !== length) {
137
+ throw new Error(`${name} must have length ${length} (${what}); got ${values.length}`);
138
+ }
139
+ }
140
+ function checkIntegers(name, values) {
141
+ for (let i = 0; i < values.length; ++i) {
142
+ if (!Number.isSafeInteger(values[i]))
143
+ throw new Error(`${name} must contain integers`);
144
+ }
145
+ }
146
+ /** The target as a matrix with one row per row of X (a vector is one column). */
147
+ function targetMatrix(y, rows) {
148
+ if ("data" in y && "rows" in y) {
149
+ const ym = y;
150
+ checkMatrix("y", ym);
151
+ if (ym.rows !== rows) {
152
+ throw new Error(`y must have ${rows} rows (one per row of X); got ${ym.rows} x ${ym.cols}`);
153
+ }
154
+ return ym;
155
+ }
156
+ const values = y;
157
+ checkLength("y", values, rows, "one per row of X");
158
+ return { data: Float64Array.from(values), rows, cols: 1 };
159
+ }
160
+ /**
161
+ * Runs `fn` over an n4m_fit_inputs_v1_t built from the given data. Per-row
162
+ * inputs (y, labels, sampleWeight, groups, foldIds) must have one entry per
163
+ * row of X and per-column inputs (featureGroups, axis) one per column; the
164
+ * lengths are checked here with the argument named, and again natively.
165
+ */
166
+ export function withFitInputs(X, y, labels, inputs, fn) {
126
167
  const m = getModule();
127
168
  const allocs = [];
128
169
  const hold = (a) => (allocs.push(a), a.ptr);
@@ -130,6 +171,27 @@ function withFitInputs(X, y, labels, inputs, fn) {
130
171
  try {
131
172
  m.HEAPU8.fill(0, struct, struct + FIT_INPUTS_SIZE);
132
173
  m.setValue(struct, FIT_INPUTS_SIZE, "i32");
174
+ checkMatrix("X", X);
175
+ const rows = "one per row of X";
176
+ const cols = "one per column of X";
177
+ if (inputs.sampleWeight)
178
+ checkLength("sampleWeight", inputs.sampleWeight, X.rows, rows);
179
+ for (const [name, values] of [["groups", inputs.groups], ["foldIds", inputs.foldIds]]) {
180
+ if (values) {
181
+ checkLength(name, values, X.rows, rows);
182
+ checkIntegers(name, values);
183
+ }
184
+ }
185
+ if (inputs.featureGroups) {
186
+ checkLength("featureGroups", inputs.featureGroups, X.cols, cols);
187
+ checkIntegers("featureGroups", inputs.featureGroups);
188
+ }
189
+ if (inputs.blocks)
190
+ checkIntegers("blocks", inputs.blocks);
191
+ if (inputs.axis)
192
+ checkLength("axis", inputs.axis, X.cols, cols);
193
+ if (inputs.XTarget)
194
+ checkMatrix("XTarget", inputs.XTarget);
133
195
  const xv = makeMatrixView(X.data, X.rows, X.cols);
134
196
  allocs.push({ ptr: xv.viewPtr, free: xv.free });
135
197
  m.setValue(struct + OFF.X, xv.viewPtr, "i32");
@@ -139,11 +201,12 @@ function withFitInputs(X, y, labels, inputs, fn) {
139
201
  };
140
202
  if (y !== undefined && labels) {
141
203
  const ids = Array.from(y);
204
+ checkLength("labels", ids, X.rows, rows);
205
+ checkIntegers("labels", ids);
142
206
  setArray(OFF.labels, OFF.nLabels, allocI64(ids), ids.length);
143
207
  }
144
208
  else if (y !== undefined) {
145
- const ym = "data" in y ? y
146
- : { data: Float64Array.from(y), rows: y.length, cols: 1 };
209
+ const ym = targetMatrix(y, X.rows);
147
210
  const yv = makeMatrixView(ym.data, ym.rows, ym.cols);
148
211
  allocs.push({ ptr: yv.viewPtr, free: yv.free });
149
212
  m.setValue(struct + OFF.Y, yv.viewPtr, "i32");
@@ -218,7 +281,9 @@ export class NativeEstimator extends NativeMethod {
218
281
  }
219
282
  /**
220
283
  * Fit on row-major X and the target: responses for a regressor (a vector
221
- * or a row-major matrix), integer class ids for a classifier. Returns this.
284
+ * or a row-major matrix, one row per row of X), integer class ids for a
285
+ * classifier (one per row). Returns this. The fitted state is replaced
286
+ * only when the fit succeeds: a failed refit leaves the previous one.
222
287
  */
223
288
  fit(X, y, inputs = {}) {
224
289
  const m = getModule();
@@ -246,18 +311,35 @@ export class NativeEstimator extends NativeMethod {
246
311
  this.ptr = est;
247
312
  return this;
248
313
  }
249
- /** Portable fitted state (N4ME bytes), readable by every n4m binding. */
250
- toN4me() {
314
+ /** True when the fitted state embeds training rows (kernel PLS, GPR-PLS, LW-PLS, ...). */
315
+ containsTrainingRows() {
316
+ const m = getModule();
317
+ const out = m._malloc(4);
318
+ try {
319
+ checkStatus(m.ccall("n4m_estimator_contains_training_rows", "number", ["number", "number"], [this.handle(), out]));
320
+ return m.getValue(out, "i32") !== 0;
321
+ }
322
+ finally {
323
+ m._free(out);
324
+ }
325
+ }
326
+ /**
327
+ * Portable fitted state (N4ME bytes), readable by every n4m binding. A
328
+ * state that embeds training rows (containsTrainingRows()) is refused
329
+ * unless `allowTrainingRows` is set: sharing the export shares them.
330
+ */
331
+ toN4me(options = {}) {
251
332
  const m = getModule();
252
333
  const handle = this.handle();
334
+ const flags = options.allowTrainingRows === true ? 1 : 0;
253
335
  return withContext((ctx) => {
254
336
  const sizePtr = m._malloc(4);
255
337
  try {
256
- checkStatus(m.ccall("n4m_estimator_export_size", "number", ["number", "number", "number", "number"], [ctx, handle, 1, sizePtr]), ctx);
338
+ checkStatus(m.ccall("n4m_estimator_export_size", "number", ["number", "number", "number", "number"], [ctx, handle, flags, sizePtr]), ctx);
257
339
  const size = m.getValue(sizePtr, "i32");
258
340
  const buf = m._malloc(Math.max(1, size));
259
341
  try {
260
- checkStatus(m.ccall("n4m_estimator_export_to_buffer", "number", ["number", "number", "number", "number", "number", "number"], [ctx, handle, 1, buf, size, sizePtr]), ctx);
342
+ checkStatus(m.ccall("n4m_estimator_export_to_buffer", "number", ["number", "number", "number", "number", "number", "number"], [ctx, handle, flags, buf, size, sizePtr]), ctx);
261
343
  return m.HEAPU8.slice(buf, buf + m.getValue(sizePtr, "i32"));
262
344
  }
263
345
  finally {
@@ -331,6 +413,9 @@ export class NativeEstimator extends NativeMethod {
331
413
  maskArray(X, y) {
332
414
  const m = getModule();
333
415
  const handle = this.handle();
416
+ checkMatrix("X", X);
417
+ if (y !== undefined)
418
+ checkLength("y", y, X.rows, "one per row of X");
334
419
  const xv = makeMatrixView(X.data, X.rows, X.cols);
335
420
  const yv = y === undefined ? undefined
336
421
  : makeMatrixView(Float64Array.from(y), X.rows, 1);