@nirs4all/methods 1.2.1 → 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.
@@ -0,0 +1,637 @@
1
+ // SPDX-License-Identifier: CECILL-2.1
2
+ // Thin, owning WASM facade for the native n4m optimizer. Sampling, pruning,
3
+ // trace and checkpoint semantics stay exclusively in libn4m.
4
+ import { Context } from "./context.js";
5
+ import { checkStatus, getModule } from "./ffi.js";
6
+ import { MethodResult } from "./methodResult.js";
7
+ const SAMPLERS = ["random", "sobol", "lhs", "ternary", "ga", "pso", "cmaes", "tpe", "gp_ei"];
8
+ const PRUNERS = ["none", "median", "asha", "hyperband", "racing"];
9
+ const DIRECTIONS = ["auto", "minimize", "maximize"];
10
+ const EVAL_MODES = ["best", "mean", "robust_best"];
11
+ const LIARS = ["none", "min", "mean", "max"];
12
+ const STATUSES = ["running", "completed", "pruned", "failed", "cancelled"];
13
+ const CONSTRAINTS = ["mutex_group", "requires", "exclude", "condition_in", "condition_not_in"];
14
+ const METRICS = {
15
+ rmse: 0, mse: 1, mae: 2, r2: 3, accuracy: 16, balanced_accuracy: 17,
16
+ f1: 18, logloss: 19,
17
+ };
18
+ const MAX_EXACT_INT = 1n << 53n;
19
+ const MAX_BATCH = 10000;
20
+ function integer(value, name) {
21
+ if (typeof value === "number") {
22
+ if (!Number.isInteger(value) || Math.abs(value) > Number(MAX_EXACT_INT)) {
23
+ throw new RangeError(`${name} must be an exactly representable integer`);
24
+ }
25
+ return BigInt(value);
26
+ }
27
+ if (typeof value !== "bigint")
28
+ throw new TypeError(`${name} must be an integer`);
29
+ return value;
30
+ }
31
+ function exactAxisInteger(value, name) {
32
+ const result = integer(value, name);
33
+ if (result < -MAX_EXACT_INT || result > MAX_EXACT_INT) {
34
+ throw new RangeError(`${name} is outside the native exact-integer domain`);
35
+ }
36
+ return result;
37
+ }
38
+ function i32(value, name) {
39
+ if (!Number.isInteger(value) || value < -2147483648 || value > 2147483647) {
40
+ throw new RangeError(`${name} must fit int32`);
41
+ }
42
+ return value;
43
+ }
44
+ function finite(value, name) {
45
+ if (typeof value !== "number" || !Number.isFinite(value)) {
46
+ throw new RangeError(`${name} must be finite`);
47
+ }
48
+ return value;
49
+ }
50
+ function enumValue(value, names, fallback) {
51
+ const index = names.indexOf(value ?? fallback);
52
+ if (index < 0)
53
+ throw new RangeError(`Unknown native optimizer choice: ${value}`);
54
+ return index;
55
+ }
56
+ class NativeArgs {
57
+ module;
58
+ pointers = [];
59
+ constructor(module) {
60
+ this.module = module;
61
+ }
62
+ alloc(bytes) {
63
+ const pointer = this.module._malloc(Math.max(1, bytes));
64
+ if (pointer === 0)
65
+ throw new Error("WASM allocation failed");
66
+ this.pointers.push(pointer);
67
+ return pointer;
68
+ }
69
+ string(value) {
70
+ const bytes = this.module.lengthBytesUTF8(value) + 1;
71
+ const pointer = this.alloc(bytes);
72
+ this.module.stringToUTF8(value, pointer, bytes);
73
+ return pointer;
74
+ }
75
+ pointersArray(values) {
76
+ const pointer = this.alloc(values.length * 4);
77
+ const view = new DataView(this.module.HEAPU8.buffer);
78
+ values.forEach((value, index) => view.setUint32(pointer + index * 4, value, true));
79
+ return pointer;
80
+ }
81
+ doubles(values) {
82
+ const pointer = this.alloc(values.length * 8);
83
+ const view = new DataView(this.module.HEAPU8.buffer);
84
+ values.forEach((value, index) => view.setFloat64(pointer + index * 8, value, true));
85
+ return pointer;
86
+ }
87
+ int64(values) {
88
+ const pointer = this.alloc(values.length * 8);
89
+ const view = new DataView(this.module.HEAPU8.buffer);
90
+ values.forEach((value, index) => view.setBigInt64(pointer + index * 8, value, true));
91
+ return pointer;
92
+ }
93
+ int32(values) {
94
+ const pointer = this.alloc(values.length * 4);
95
+ const view = new DataView(this.module.HEAPU8.buffer);
96
+ values.forEach((value, index) => view.setInt32(pointer + index * 4, value, true));
97
+ return pointer;
98
+ }
99
+ free() {
100
+ for (const pointer of this.pointers.reverse())
101
+ this.module._free(pointer);
102
+ }
103
+ }
104
+ function addAxis(m, args, ptr, name, axis, context) {
105
+ const namePtr = args.string(name);
106
+ let status;
107
+ switch (axis.kind) {
108
+ case "int":
109
+ case "log_int":
110
+ status = m.ccall("n4m_search_space_add_int", "number", ["number", "number", "i64", "i64", "i64", "number"], [ptr, namePtr, exactAxisInteger(axis.low, `${name}.low`),
111
+ exactAxisInteger(axis.high, `${name}.high`),
112
+ exactAxisInteger(axis.step ?? 1, `${name}.step`), Number(axis.kind === "log_int")]);
113
+ break;
114
+ case "float":
115
+ case "log_float":
116
+ status = m.ccall("n4m_search_space_add_float", "number", ["number", "number", "number", "number", "number", "number"], [ptr, namePtr, finite(axis.low, `${name}.low`), finite(axis.high, `${name}.high`),
117
+ finite(axis.step ?? 0, `${name}.step`), Number(axis.kind === "log_float")]);
118
+ break;
119
+ case "categorical": {
120
+ if (axis.choices.length === 0)
121
+ throw new RangeError(`${name} has no choices`);
122
+ i32(axis.choices.length, `${name}.choices.length`);
123
+ const type = ["string", "integer", "float", "boolean"].indexOf(axis.type);
124
+ if (type < 0)
125
+ throw new RangeError(`Unknown category type: ${axis.type}`);
126
+ let valuesPtr;
127
+ if (axis.type === "string") {
128
+ valuesPtr = args.pointersArray(axis.choices.map(value => {
129
+ if (typeof value !== "string")
130
+ throw new TypeError(`${name} choices must be strings`);
131
+ return args.string(value);
132
+ }));
133
+ }
134
+ else if (axis.type === "integer") {
135
+ valuesPtr = args.int64(axis.choices.map(value => exactAxisInteger(value, `${name}.choice`)));
136
+ }
137
+ else if (axis.type === "float") {
138
+ valuesPtr = args.doubles(axis.choices.map(value => finite(value, `${name}.choice`)));
139
+ }
140
+ else {
141
+ valuesPtr = args.int32(axis.choices.map(value => {
142
+ if (typeof value !== "boolean")
143
+ throw new TypeError(`${name} choices must be booleans`);
144
+ return Number(value);
145
+ }));
146
+ }
147
+ status = m.ccall("n4m_search_space_add_categorical", "number", ["number", "number", "number", "number", "number"], [ptr, namePtr, type, valuesPtr, axis.choices.length]);
148
+ break;
149
+ }
150
+ case "ordinal": {
151
+ if (axis.choices.length === 0)
152
+ throw new RangeError(`${name} has no choices`);
153
+ i32(axis.choices.length, `${name}.choices.length`);
154
+ const values = args.doubles(axis.choices.map(value => finite(value, `${name}.choice`)));
155
+ status = m.ccall("n4m_search_space_add_ordinal", "number", ["number", "number", "number", "number"], [ptr, namePtr, values, axis.choices.length]);
156
+ break;
157
+ }
158
+ case "sorted_tuple":
159
+ status = m.ccall("n4m_search_space_add_sorted_tuple", "number", ["number", "number", "number", "number", "number", "number"], [ptr, namePtr, i32(axis.length, `${name}.length`), finite(axis.low, `${name}.low`),
160
+ finite(axis.high, `${name}.high`), Number(axis.integer ?? false)]);
161
+ break;
162
+ }
163
+ checkStatus(status, context);
164
+ }
165
+ function addConstraint(m, args, ptr, constraint, context) {
166
+ const kind = enumValue(constraint.kind, CONSTRAINTS, "mutex_group");
167
+ if (constraint.refs.length === 0 ||
168
+ (constraint.labels !== undefined && constraint.labels.length !== constraint.refs.length)) {
169
+ throw new RangeError("Constraint refs and labels must have equal nonzero length");
170
+ }
171
+ const refs = args.pointersArray(constraint.refs.map(ref => args.string(ref)));
172
+ const labels = args.pointersArray(constraint.refs.map((_, index) => {
173
+ const value = constraint.labels?.[index];
174
+ return value === null || value === undefined ? 0 : args.string(value);
175
+ }));
176
+ const status = m.ccall("n4m_search_space_add_constraint", "number", ["number", "number", "number", "number", "number"], [ptr, kind, refs, labels, constraint.refs.length]);
177
+ checkStatus(status, context);
178
+ }
179
+ function makeOptions(m, args, options) {
180
+ const ptr = args.alloc(120); // sizeof(n4m_optimizer_options_t) on wasm32, ABI 2.15
181
+ m.ccall("n4m_optimizer_options_init", null, ["number"], [ptr]);
182
+ const view = new DataView(m.HEAPU8.buffer);
183
+ if (view.getBigUint64(ptr, true) !== 120n)
184
+ throw new Error("Optimizer options ABI mismatch");
185
+ view.setInt32(ptr + 8, enumValue(options.sampler, SAMPLERS, "random"), true);
186
+ view.setInt32(ptr + 12, enumValue(options.pruner, PRUNERS, "none"), true);
187
+ view.setInt32(ptr + 16, enumValue(options.direction, DIRECTIONS, "auto"), true);
188
+ view.setInt32(ptr + 20, enumValue(options.evalMode, EVAL_MODES, "mean"), true);
189
+ const metric = options.metric ?? "rmse";
190
+ if (!Object.hasOwn(METRICS, metric))
191
+ throw new RangeError(`Unknown native metric: ${metric}`);
192
+ view.setInt32(ptr + 24, METRICS[metric], true);
193
+ view.setInt32(ptr + 28, enumValue(options.liar, LIARS, "none"), true);
194
+ view.setInt32(ptr + 32, i32(options.startupTrials ?? 10, "startupTrials"), true);
195
+ const seed = integer(options.seed ?? 0, "seed");
196
+ if (seed < 0n || seed > (1n << 64n) - 1n)
197
+ throw new RangeError("seed must fit uint64");
198
+ view.setBigUint64(ptr + 40, seed, true);
199
+ view.setFloat64(ptr + 48, finite(options.timeoutSeconds ?? 0, "timeoutSeconds"), true);
200
+ view.setInt32(ptr + 56, i32(options.maxResource ?? 0, "maxResource"), true);
201
+ view.setInt32(ptr + 60, i32(options.reductionFactor ?? 0, "reductionFactor"), true);
202
+ return ptr;
203
+ }
204
+ function copySpace(space) {
205
+ const entries = Object.entries(space);
206
+ if (entries.length === 0)
207
+ throw new RangeError("Search space must have at least one axis");
208
+ return Object.fromEntries(entries.map(([name, axis]) => {
209
+ if (!name || name.includes("#") || name === "__proto__") {
210
+ throw new RangeError(`Invalid search axis name: ${name}`);
211
+ }
212
+ if (!axis || typeof axis !== "object")
213
+ throw new TypeError(`Invalid search axis: ${name}`);
214
+ const owned = ("choices" in axis
215
+ ? { ...axis, choices: Object.freeze([...axis.choices]) }
216
+ : { ...axis });
217
+ return [name, Object.freeze(owned)];
218
+ }));
219
+ }
220
+ function poolStrings(result, prefix, count) {
221
+ const bytes = result.vectorInt(`${prefix}_utf8`);
222
+ const offsets = result.vectorInt64(`${prefix}_offsets`);
223
+ if (offsets.length !== count + 1)
224
+ throw new Error(`Invalid native trace offsets: ${prefix}`);
225
+ const decoder = new TextDecoder("utf-8", { fatal: true });
226
+ const out = [];
227
+ for (let index = 0; index < count; index += 1) {
228
+ const start = Number(offsets[index]);
229
+ const end = Number(offsets[index + 1]);
230
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) ||
231
+ start < 0 || end < start || end > bytes.length) {
232
+ throw new Error(`Invalid native trace string span: ${prefix}`);
233
+ }
234
+ out.push(decoder.decode(Uint8Array.from(bytes.subarray(start, end))));
235
+ }
236
+ return out;
237
+ }
238
+ function decodeRecords(result) {
239
+ if (result.scalar("trace_format_version") !== 1) {
240
+ throw new Error("Unsupported native optimizer trace version");
241
+ }
242
+ const ids = result.vectorInt64("trial_ids_i64");
243
+ const count = ids.length;
244
+ const names = poolStrings(result, "trial_param_name", result.scalar("n_params"));
245
+ const width = names.length;
246
+ const values = result.matrix("trial_param_values");
247
+ const kinds = result.vectorInt("trial_param_kind");
248
+ const categoryTypes = result.vectorInt("trial_param_category_type");
249
+ const integers = result.vectorInt("trial_param_integer");
250
+ const categoryIndices = result.vectorInt("trial_param_category_index");
251
+ const activeBits = result.vectorInt("trial_param_active");
252
+ const labels = poolStrings(result, "trial_param_label", count * width);
253
+ const scores = result.matrix("trial_scores").data;
254
+ const statuses = result.matrix("trial_status").data;
255
+ const rungs = result.matrix("trial_rung").data;
256
+ const asks = result.vectorInt64("trial_ask_sequence");
257
+ const terminals = result.vectorInt64("trial_terminal_sequence");
258
+ const interOffsets = result.vectorInt64("trial_intermediate_offsets");
259
+ const interSequences = result.vectorInt64("trial_intermediate_sequence");
260
+ const interSteps = result.vectorInt("trial_intermediate_steps");
261
+ const interScores = result.matrix("trial_intermediate_scores").data;
262
+ const interPruned = result.vectorInt("trial_intermediate_should_prune");
263
+ const errorCodes = poolStrings(result, "trial_error_code", count);
264
+ const errorMessages = poolStrings(result, "trial_error_message", count);
265
+ const retryable = result.vectorInt("trial_error_retryable");
266
+ if (values.rows !== count || values.cols !== width || kinds.length !== width ||
267
+ categoryTypes.length !== width || integers.length !== width ||
268
+ categoryIndices.length !== count * width || activeBits.length !== count * width ||
269
+ scores.length !== count || statuses.length !== count || rungs.length !== count ||
270
+ asks.length !== count || terminals.length !== count || interOffsets.length !== count + 1 ||
271
+ interSequences.length !== interSteps.length || interSteps.length !== interScores.length ||
272
+ interScores.length !== interPruned.length || retryable.length !== count) {
273
+ throw new Error("Invalid native optimizer trace shape");
274
+ }
275
+ const records = [];
276
+ for (let row = 0; row < count; row += 1) {
277
+ const parameters = Object.create(null);
278
+ const active = Object.create(null);
279
+ for (let col = 0; col < width; col += 1) {
280
+ const offset = row * width + col;
281
+ const name = names[col];
282
+ const isActive = activeBits[offset] !== 0;
283
+ active[name] = isActive;
284
+ if (!isActive)
285
+ continue;
286
+ let value;
287
+ if (kinds[col] === 4) {
288
+ if (categoryIndices[offset] < 0)
289
+ throw new Error("Missing native category index");
290
+ const label = labels[offset];
291
+ const categoryType = categoryTypes[col];
292
+ if (categoryType === 0)
293
+ value = label;
294
+ else if (categoryType === 1)
295
+ value = BigInt(label);
296
+ else if (categoryType === 2)
297
+ value = Number(label);
298
+ else if (categoryType === 3)
299
+ value = label === "true";
300
+ else
301
+ throw new Error("Unknown native category type");
302
+ }
303
+ else if (integers[col] !== 0) {
304
+ value = BigInt(values.data[offset]);
305
+ }
306
+ else {
307
+ value = values.data[offset];
308
+ }
309
+ parameters[name] = value;
310
+ }
311
+ const begin = Number(interOffsets[row]);
312
+ const end = Number(interOffsets[row + 1]);
313
+ if (!Number.isSafeInteger(begin) || !Number.isSafeInteger(end) ||
314
+ begin < 0 || end < begin || end > interSteps.length) {
315
+ throw new Error("Invalid native intermediate trace offsets");
316
+ }
317
+ const intermediates = Array.from({ length: end - begin }, (_, local) => {
318
+ const index = begin + local;
319
+ return { sequence: interSequences[index], step: interSteps[index],
320
+ score: interScores[index], shouldPrune: interPruned[index] !== 0 };
321
+ });
322
+ const status = STATUSES[statuses[row]];
323
+ if (!status)
324
+ throw new Error("Unknown native trace status");
325
+ records.push({
326
+ id: ids[row], parameters, active, status, rung: rungs[row],
327
+ score: Number.isNaN(scores[row]) ? null : scores[row],
328
+ askSequence: asks[row],
329
+ terminalSequence: terminals[row] === -1n ? null : terminals[row],
330
+ intermediates,
331
+ error: errorCodes[row] || errorMessages[row]
332
+ ? { code: errorCodes[row], message: errorMessages[row], retryable: retryable[row] !== 0 }
333
+ : null,
334
+ });
335
+ }
336
+ return records;
337
+ }
338
+ /** Owns a native optimizer and its context. Dispose it after use. */
339
+ export class Optimizer {
340
+ _ptr;
341
+ context;
342
+ space;
343
+ constructor(context, ptr, space) {
344
+ this.context = context;
345
+ this._ptr = ptr;
346
+ this.space = space;
347
+ }
348
+ static create(space, options = {}, constraints = []) {
349
+ const m = getModule();
350
+ const ownedSpace = copySpace(space);
351
+ const context = Context.create();
352
+ const args = new NativeArgs(m);
353
+ let spacePtr = 0;
354
+ try {
355
+ const spaceOut = args.alloc(4);
356
+ checkStatus(m.ccall("n4m_search_space_create", "number", ["number"], [spaceOut]), context.handle);
357
+ spacePtr = m.getValue(spaceOut, "i32");
358
+ for (const [name, axis] of Object.entries(ownedSpace)) {
359
+ addAxis(m, args, spacePtr, name, axis, context.handle);
360
+ }
361
+ for (const constraint of constraints)
362
+ addConstraint(m, args, spacePtr, constraint, context.handle);
363
+ const optionsPtr = makeOptions(m, args, options);
364
+ const optOut = args.alloc(4);
365
+ const status = m.ccall("n4m_optimizer_create", "number", ["number", "number", "number", "number"], [context.handle, spacePtr, optionsPtr, optOut]);
366
+ checkStatus(status, context.handle);
367
+ const pointer = m.getValue(optOut, "i32");
368
+ if (!pointer)
369
+ throw new Error("Native optimizer returned a null handle");
370
+ return new Optimizer(context, pointer, ownedSpace);
371
+ }
372
+ catch (error) {
373
+ context.destroy();
374
+ throw error;
375
+ }
376
+ finally {
377
+ if (spacePtr)
378
+ m.ccall("n4m_search_space_destroy", null, ["number"], [spacePtr]);
379
+ args.free();
380
+ }
381
+ }
382
+ static load(blob, space) {
383
+ if (!(blob instanceof Uint8Array) || blob.length === 0)
384
+ throw new TypeError("Expected N4MOPT bytes");
385
+ const m = getModule();
386
+ const ownedSpace = copySpace(space);
387
+ const context = Context.create();
388
+ const args = new NativeArgs(m);
389
+ try {
390
+ const bytes = args.alloc(blob.length);
391
+ m.HEAPU8.set(blob, bytes);
392
+ const optOut = args.alloc(4);
393
+ checkStatus(m.ccall("n4m_optimizer_load", "number", ["number", "number", "i64", "number"], [context.handle, bytes, BigInt(blob.length), optOut]), context.handle);
394
+ const pointer = m.getValue(optOut, "i32");
395
+ if (!pointer)
396
+ throw new Error("Native optimizer returned a null handle");
397
+ return new Optimizer(context, pointer, ownedSpace);
398
+ }
399
+ catch (error) {
400
+ context.destroy();
401
+ throw error;
402
+ }
403
+ finally {
404
+ args.free();
405
+ }
406
+ }
407
+ get handle() {
408
+ if (!this._ptr)
409
+ throw new Error("Optimizer has been disposed");
410
+ return this._ptr;
411
+ }
412
+ decodeTrial(ptr) {
413
+ const m = getModule();
414
+ const args = new NativeArgs(m);
415
+ try {
416
+ const out8 = args.alloc(8);
417
+ const out4 = args.alloc(4);
418
+ checkStatus(m.ccall("n4m_trial_get_id", "number", ["number", "number"], [ptr, out8]), this.context.handle);
419
+ const id = BigInt(m.getValue(out8, "i64"));
420
+ const parameters = Object.create(null);
421
+ for (const [name, axis] of Object.entries(this.space)) {
422
+ const nativeName = axis.kind === "sorted_tuple" ? `${name}#0` : name;
423
+ const nativeNamePtr = args.string(nativeName);
424
+ checkStatus(m.ccall("n4m_trial_is_active", "number", ["number", "number", "number"], [ptr, nativeNamePtr, out4]), this.context.handle);
425
+ if (!m.getValue(out4, "i32"))
426
+ continue;
427
+ const namePtr = axis.kind === "sorted_tuple" ? args.string(name) : nativeNamePtr;
428
+ if (axis.kind === "int" || axis.kind === "log_int") {
429
+ checkStatus(m.ccall("n4m_trial_get_int", "number", ["number", "number", "number"], [ptr, namePtr, out8]), this.context.handle);
430
+ parameters[name] = BigInt(m.getValue(out8, "i64"));
431
+ }
432
+ else if (axis.kind === "float" || axis.kind === "log_float" || axis.kind === "ordinal") {
433
+ checkStatus(m.ccall("n4m_trial_get_float", "number", ["number", "number", "number"], [ptr, namePtr, out8]), this.context.handle);
434
+ parameters[name] = m.getValue(out8, "double");
435
+ }
436
+ else if (axis.kind === "categorical") {
437
+ const labelOut = args.alloc(4);
438
+ checkStatus(m.ccall("n4m_trial_get_category", "number", ["number", "number", "number", "number"], [ptr, namePtr, out4, labelOut]), this.context.handle);
439
+ const index = m.getValue(out4, "i32");
440
+ if (index < 0 || index >= axis.choices.length)
441
+ throw new Error("Native category index out of range");
442
+ parameters[name] = axis.choices[index];
443
+ }
444
+ else if (axis.kind === "sorted_tuple") {
445
+ const values = [];
446
+ for (let index = 0; index < axis.length; index += 1) {
447
+ const component = args.string(`${name}#${index}`);
448
+ const symbol = axis.integer ? "n4m_trial_get_int" : "n4m_trial_get_float";
449
+ checkStatus(m.ccall(symbol, "number", ["number", "number", "number"], [ptr, component, out8]), this.context.handle);
450
+ values.push(axis.integer ? BigInt(m.getValue(out8, "i64")) : m.getValue(out8, "double"));
451
+ }
452
+ parameters[name] = values;
453
+ }
454
+ else {
455
+ throw new Error(`Unsupported search axis kind: ${JSON.stringify(axis)}`);
456
+ }
457
+ }
458
+ checkStatus(m.ccall("n4m_trial_get_rung", "number", ["number", "number"], [ptr, out4]), this.context.handle);
459
+ const rung = m.getValue(out4, "i32");
460
+ checkStatus(m.ccall("n4m_trial_get_status", "number", ["number", "number"], [ptr, out4]), this.context.handle);
461
+ const status = STATUSES[m.getValue(out4, "i32")];
462
+ if (!status)
463
+ throw new Error("Unknown native trial status");
464
+ return { id, parameters, rung, status };
465
+ }
466
+ finally {
467
+ args.free();
468
+ }
469
+ }
470
+ ask() {
471
+ const m = getModule();
472
+ const args = new NativeArgs(m);
473
+ try {
474
+ const out = args.alloc(4);
475
+ checkStatus(m.ccall("n4m_optimizer_ask", "number", ["number", "number"], [this.handle, out]), this.context.handle);
476
+ return this.decodeTrial(m.getValue(out, "i32"));
477
+ }
478
+ finally {
479
+ args.free();
480
+ }
481
+ }
482
+ askBatch(n) {
483
+ i32(n, "batch size");
484
+ if (n < 0 || n > MAX_BATCH)
485
+ throw new RangeError(`batch size must be 0..${MAX_BATCH}`);
486
+ const m = getModule();
487
+ const args = new NativeArgs(m);
488
+ try {
489
+ const slots = args.alloc(n * 4);
490
+ const count = args.alloc(4);
491
+ const nativeStatus = m.ccall("n4m_optimizer_ask_batch", "number", ["number", "number", "number", "number"], [this.handle, n, slots, count]);
492
+ const committed = m.getValue(count, "i32");
493
+ if (committed < 0 || committed > n)
494
+ throw new Error("Native batch count out of range");
495
+ const trials = [];
496
+ for (let index = 0; index < committed; index += 1) {
497
+ trials.push(this.decodeTrial(m.getValue(slots + index * 4, "i32")));
498
+ }
499
+ if (nativeStatus !== 0 && committed === 0)
500
+ checkStatus(nativeStatus, this.context.handle);
501
+ return { trials, nativeStatus };
502
+ }
503
+ finally {
504
+ args.free();
505
+ }
506
+ }
507
+ /** Queue numeric values; categorical axes use zero-based choice indices. */
508
+ enqueue(parameters) {
509
+ const entries = Object.entries(parameters);
510
+ if (entries.length === 0)
511
+ throw new RangeError("Warm-start candidate is empty");
512
+ const m = getModule();
513
+ const args = new NativeArgs(m);
514
+ try {
515
+ const names = args.pointersArray(entries.map(([name]) => args.string(name)));
516
+ const values = args.doubles(entries.map(([name, value]) => typeof value === "bigint" ? Number(exactAxisInteger(value, name)) : finite(value, name)));
517
+ checkStatus(m.ccall("n4m_optimizer_enqueue", "number", ["number", "number", "number", "number"], [this.handle, names, values, entries.length]), this.context.handle);
518
+ }
519
+ finally {
520
+ args.free();
521
+ }
522
+ }
523
+ tell(trial, status, score, error) {
524
+ const id = typeof trial === "object" ? trial.id : integer(trial, "trial id");
525
+ const code = STATUSES.indexOf(status);
526
+ if (code < 1)
527
+ throw new RangeError("Invalid terminal trial status");
528
+ if (status === "completed")
529
+ finite(score, "completed score");
530
+ else if (score !== undefined)
531
+ throw new RangeError("Only completed trials accept a score");
532
+ if (error !== undefined && (status !== "failed" && status !== "cancelled")) {
533
+ throw new RangeError("Only failed/cancelled trials accept an error");
534
+ }
535
+ const m = getModule();
536
+ const args = new NativeArgs(m);
537
+ try {
538
+ const errorPtr = error === undefined ? 0 : args.string(error);
539
+ checkStatus(m.ccall("n4m_optimizer_tell_result", "number", ["number", "i64", "number", "number", "number"], [this.handle, id, code, score ?? 0, errorPtr]), this.context.handle);
540
+ }
541
+ finally {
542
+ args.free();
543
+ }
544
+ }
545
+ intermediate(trial, step, score) {
546
+ const id = typeof trial === "object" ? trial.id : integer(trial, "trial id");
547
+ i32(step, "step");
548
+ finite(score, "intermediate score");
549
+ const m = getModule();
550
+ const args = new NativeArgs(m);
551
+ try {
552
+ const out = args.alloc(4);
553
+ checkStatus(m.ccall("n4m_optimizer_tell_intermediate", "number", ["number", "i64", "number", "number", "number"], [this.handle, id, step, score, out]), this.context.handle);
554
+ return m.getValue(out, "i32") !== 0;
555
+ }
556
+ finally {
557
+ args.free();
558
+ }
559
+ }
560
+ best() {
561
+ const m = getModule();
562
+ const args = new NativeArgs(m);
563
+ try {
564
+ const out = args.alloc(4);
565
+ const scoreOut = args.alloc(8);
566
+ checkStatus(m.ccall("n4m_optimizer_best", "number", ["number", "number", "number"], [this.handle, out, scoreOut]), this.context.handle);
567
+ return { trial: this.decodeTrial(m.getValue(out, "i32")), score: m.getValue(scoreOut, "double") };
568
+ }
569
+ finally {
570
+ args.free();
571
+ }
572
+ }
573
+ /** Owning native rich trace v1 snapshot. Caller must destroy the result. */
574
+ trials(sinceId = 0) {
575
+ const id = integer(sinceId, "sinceId");
576
+ if (id < 0n)
577
+ throw new RangeError("sinceId must be nonnegative");
578
+ const m = getModule();
579
+ const args = new NativeArgs(m);
580
+ try {
581
+ const out = args.alloc(4);
582
+ checkStatus(m.ccall("n4m_optimizer_get_trials", "number", ["number", "i64", "number"], [this.handle, id, out]), this.context.handle);
583
+ return new MethodResult(m.getValue(out, "i32"));
584
+ }
585
+ finally {
586
+ args.free();
587
+ }
588
+ }
589
+ /** Decode an owning rich-trace snapshot to typed JS values. */
590
+ trialRecords(sinceId = 0) {
591
+ const result = this.trials(sinceId);
592
+ try {
593
+ return decodeRecords(result);
594
+ }
595
+ finally {
596
+ result.destroy();
597
+ }
598
+ }
599
+ /** Portable N4MOPT bytes, directly readable by Python/R/native bindings. */
600
+ save() {
601
+ const m = getModule();
602
+ const args = new NativeArgs(m);
603
+ let arrayPtr = 0;
604
+ try {
605
+ const out = args.alloc(4);
606
+ checkStatus(m.ccall("n4m_optimizer_save", "number", ["number", "number"], [this.handle, out]), this.context.handle);
607
+ arrayPtr = m.getValue(out, "i32");
608
+ const viewPtr = args.alloc(48);
609
+ checkStatus(m.ccall("n4m_array_view", "number", ["number", "number"], [arrayPtr, viewPtr]), this.context.handle);
610
+ const dataPtr = m.getValue(viewPtr, "i32") >>> 0;
611
+ const rows = BigInt(m.getValue(viewPtr + 8, "i64"));
612
+ const cols = BigInt(m.getValue(viewPtr + 16, "i64"));
613
+ const dtype = m.getValue(viewPtr + 40, "i32");
614
+ if (dtype !== 4 || rows !== 1n || cols <= 0n || dataPtr === 0) {
615
+ throw new Error("Invalid native optimizer checkpoint array");
616
+ }
617
+ const byteLength = rows * cols * 8n;
618
+ if (dataPtr > m.HEAPU8.byteLength ||
619
+ byteLength > BigInt(m.HEAPU8.byteLength - dataPtr)) {
620
+ throw new RangeError("Native optimizer checkpoint exceeds WASM memory");
621
+ }
622
+ return m.HEAPU8.slice(dataPtr, dataPtr + Number(byteLength));
623
+ }
624
+ finally {
625
+ if (arrayPtr)
626
+ m.ccall("n4m_array_free", null, ["number"], [arrayPtr]);
627
+ args.free();
628
+ }
629
+ }
630
+ dispose() {
631
+ if (!this._ptr)
632
+ return;
633
+ getModule().ccall("n4m_optimizer_destroy", null, ["number"], [this._ptr]);
634
+ this._ptr = 0;
635
+ this.context.destroy();
636
+ }
637
+ }
@@ -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
+ }