sbmlsim-core 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthias König
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,103 @@
1
- # Temporary Holding Version
1
+ # sbmlsim-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Simulate SBML models in browsers and in Node. [sbmlsim-core](https://matthiaskoenig.github.io/sbmlsim-core/) compiles an SBML model into a WebAssembly module (`model.wasm` with its description `model.json`) and simulates it with its engine (`engine.wasm`: CVODE of SUNDIALS with the sparse solver KLU), with the semantics of [sbmlsim](https://matthiaskoenig.github.io/sbmlsim/) and bitwise the same results on every host. This package is its JavaScript host: plain ES modules without dependencies, the engine and its math library included.
4
+
5
+ | module | import | what it is |
6
+ |---|---|---|
7
+ | `loader.mjs` | `sbmlsim-core` | runs `engine.wasm`, `mathlib.wasm` and a compiled `model.wasm` |
8
+ | `pool.mjs` (with `worker.mjs`) | `sbmlsim-core/pool` | a pool of Web Workers (worker threads in Node) which run the loader off the main thread |
9
+ | `panels.mjs` | `sbmlsim-core/panels` | the routes of the panel service of sbmlsim, answered inside a page from an exported bundle |
10
+ | `simulate.mjs` | the command `sbmlsim-core-simulate` | the CSV of a simulation in Node |
11
+
12
+ A model is compiled ahead of time with the command line of the repository (`sbmlsim-core compile model.xml -o DIR`); compiling SBML in the browser is not part of this package yet.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm install sbmlsim-core
18
+ ```
19
+
20
+ or import the modules from a CDN, which serves them with the headers every origin may read:
21
+
22
+ ```js
23
+ import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.1.0/panels.mjs";
24
+ ```
25
+
26
+ A pool started from a module of another origin starts its workers through a module of the page's own origin, so the CDN works for the workers as well. The engine needs fixed-width SIMD of WebAssembly: Chrome 91, Firefox 89, Safari 16.4 or newer, Node 20 or newer.
27
+
28
+ ## Simulate a model
29
+
30
+ ```js
31
+ import { readFile } from "node:fs/promises";
32
+ import { fileURLToPath } from "node:url";
33
+ import { createRuntime } from "sbmlsim-core";
34
+
35
+ // the engine and its math library are files of the package; a page fetches them from where it
36
+ // serves them
37
+ const file = (specifier) => readFile(fileURLToPath(import.meta.resolve(specifier)));
38
+ const runtime = await createRuntime({
39
+ engine: await file("sbmlsim-core/runtime/engine.wasm"),
40
+ mathlib: await file("sbmlsim-core/runtime/mathlib.wasm"),
41
+ });
42
+ // model.wasm and model.json of `sbmlsim-core compile model.xml -o model`
43
+ const instance = await runtime.instantiate(
44
+ await readFile("model/model.wasm"),
45
+ await readFile("model/model.json", "utf8"),
46
+ );
47
+ const { columns, nRows, values } = instance.simulate({
48
+ contract: "simulation/1",
49
+ start: 0,
50
+ end: 100,
51
+ output: { uniform: { steps: 100 } },
52
+ preinit: [["k1", 0.5]],
53
+ changes: [],
54
+ steady_state: null,
55
+ selections: ["time", "[S1]"],
56
+ settings: {
57
+ relative_tolerance: 1e-8,
58
+ absolute_tolerance: { scalar: 1e-12 },
59
+ maximum_num_steps: 20000,
60
+ maximum_time_step: 0,
61
+ initial_time_step: 0,
62
+ stiff: true,
63
+ linear_solver: "auto",
64
+ jacobian: "auto",
65
+ },
66
+ });
67
+ // values: a Float64Array of nRows rows of columns.length values, row major
68
+ ```
69
+
70
+ A simulation is one synchronous call; in a page it belongs into a worker:
71
+
72
+ ```js
73
+ import { createPool } from "sbmlsim-core/pool";
74
+
75
+ const pool = await createPool({ engine, mathlib }); // WebAssembly.Modules or their bytes
76
+ await pool.addModel("model", modelWasm, modelJson);
77
+ const result = await pool.simulate("model", request, { signal });
78
+ pool.close();
79
+ ```
80
+
81
+ ## A static app of interactive panels
82
+
83
+ `python -m sbmlsim.serve --model id=module:attribute --export DIR` of sbmlsim writes the panels and the app of a model as a bundle; `createPanelEndpoint` answers the routes of the service from it, with the simulations on a pool of workers, and the components of [sbmlsim-web](https://matthiaskoenig.github.io/sbmlsim-web/) draw them:
84
+
85
+ ```html
86
+ <!-- the IIFE build of sbmlsim-web, a release with registerEndpoint -->
87
+ <script src="sbmlsim-web.iife.js"></script>
88
+ <script type="module">
89
+ import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.1.0/panels.mjs";
90
+
91
+ sbmlsimWeb.registerEndpoint(
92
+ "local:glimepiride",
93
+ createPanelEndpoint({ bundle: new URL("./bundle/bundle.json", location.href) }),
94
+ );
95
+ </script>
96
+ <sbmlsim-app endpoint="local:glimepiride" model="glimepiride"></sbmlsim-app>
97
+ ```
98
+
99
+ The [glimepiride app](https://matthiaskoenig.github.io/sbmlsim-web/examples/glimepiride/) is built this way. The [JavaScript page](https://matthiaskoenig.github.io/sbmlsim-core/javascript/) of the documentation describes every module, option and route.
100
+
101
+ ## License
102
+
103
+ The JavaScript is MIT licensed. `runtime/engine.wasm` contains SUNDIALS (BSD-3-Clause) and KLU with AMD, COLAMD and BTF of SuiteSparse (LGPL-2.1-or-later), whose notices and sources are named in `runtime/THIRD_PARTY.md`; the package as a whole is `MIT AND BSD-3-Clause AND LGPL-2.1-or-later`.
package/loader.mjs ADDED
@@ -0,0 +1,532 @@
1
+ // The JavaScript loader of sbmlsim-core: runs `engine.wasm`, `mathlib.wasm` and a compiled
2
+ // `model.wasm` in a JavaScript host (Node, browsers), with the bits of the wasmtime host.
3
+ //
4
+ // Plain ECMAScript without dependencies and without APIs of Node (no `fs`, no `process`), so it
5
+ // runs in browsers as well:
6
+ //
7
+ // import { createRuntime } from "./loader.mjs";
8
+ // const runtime = await createRuntime({ engine, mathlib }); // WebAssembly.Modules or bytes
9
+ // const instance = await runtime.instantiate(modelWasm, modelJson); // a Promise; a Module or bytes, the
10
+ // // text of model.json or
11
+ // // its object
12
+ // const { columns, nRows, values } = instance.simulate(request); // values: a Float64Array
13
+ //
14
+ // The linking is the one of the wasmtime host (`crates/host/src/lib.rs`): a memory of the type
15
+ // the engine imports (its minimum is the custom section `sbmlsim.engine` of `engine.wasm`, with a
16
+ // maximum of `MAX_MEMORY_PAGES`, the `MAX_MEMORY_BYTES` of the wasmtime host), then mathlib, then
17
+ // the model (which imports the memory as `env.memory` and the functions of mathlib as
18
+ // `math.*`), then the engine (which imports the memory, the functions of the model as
19
+ // `model.*` and WASI preview1), so every call between them is a call from wasm to wasm.
20
+ //
21
+ // WASI preview1: `fd_write` writes to the console (stdout with `console.log`, stderr with
22
+ // `console.error`, line by line), `proc_exit` throws, `environ_get` and `environ_sizes_get` give
23
+ // an empty environment, `clock_time_get` and `random_get` throw, and so does every other
24
+ // function of WASI the engine imports: the engine calls none of them while it loads or simulates
25
+ // (`instance.wasiCalls()` counts the calls), so a call is a visible failure.
26
+ //
27
+ // The exports of `engine.wasm` and its output are documented in `crates/engine/src/exports.rs`:
28
+ // a `u32` (little endian) with the length of a JSON header, the header (`{"columns", "n_rows"}`,
29
+ // or `{"error": {...}}`), zero bytes up to a multiple of 8, then the values as `f64` (little
30
+ // endian), row major. The output starts at an address aligned to 8, so the values are read
31
+ // through a `Float64Array` over the memory (copied once, into the result, since the memory is
32
+ // reused by the next call and detached when it grows); the bits are kept, NaN payloads too.
33
+ //
34
+ // The description is passed to the engine as JSON: the text of `model.json` as it is, or an
35
+ // object as `JSON.stringify` writes it. `model.json` writes an initial value which is not
36
+ // finite as the string "NaN", "inf" or "-inf" (JSON has no such numbers), which `JSON.parse`
37
+ // keeps as a string and `JSON.stringify` writes back, and the engine reads.
38
+
39
+ /** The contract of a model description this loader loads. */
40
+ export const MODEL_CONTRACT = "model/1";
41
+
42
+ /** The most pages of 64 KiB the memory of an instance grows to: 2 GiB, as the wasmtime host. */
43
+ export const MAX_MEMORY_PAGES = 32768;
44
+
45
+ /**
46
+ * The custom section of `engine.wasm` with the minimum of the memory it imports and the version
47
+ * of its output (`ENGINE_SECTION` of `crates/abi`).
48
+ */
49
+ export const ENGINE_SECTION = "sbmlsim.engine";
50
+
51
+ /** The version of the output of `engine.wasm` this loader reads (`ENGINE_OUTPUT_FORMAT`). */
52
+ export const ENGINE_OUTPUT_FORMAT = 1;
53
+
54
+ const WASI = "wasi_snapshot_preview1";
55
+
56
+ const ENGINE_EXPORTS = [
57
+ "engine_alloc",
58
+ "engine_free",
59
+ "engine_load",
60
+ "engine_simulate",
61
+ "engine_output_ptr",
62
+ "engine_output_len",
63
+ "engine_stats_ptr",
64
+ ];
65
+
66
+ /**
67
+ * The counters of the last simulation in the order of `engine_stats_ptr` (`SimulationStats`
68
+ * of `crates/abi`).
69
+ */
70
+ export const STATS_NAMES = [
71
+ "steps",
72
+ "rhs_evals",
73
+ "jacobian_evals",
74
+ "jacobian_rhs_evals",
75
+ "jacobian_fallbacks",
76
+ "linear_setups",
77
+ "error_test_failures",
78
+ "nonlinear_iterations",
79
+ "nonlinear_convergence_failures",
80
+ "root_evals",
81
+ "integrations",
82
+ "probe_rhs_evals",
83
+ "steady_state_rhs_evals",
84
+ ];
85
+
86
+ const LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
87
+
88
+ /**
89
+ * An error of the engine: `kind` is `load`, `request`, `unsupported`, `integration` (with
90
+ * `flag` and `time`, `NaN` for a time which is not finite) or `internal` (a trap of the engine
91
+ * or of the model, a panic of the engine, a failure of the loader).
92
+ */
93
+ export class EngineError extends Error {
94
+ constructor(kind, message, { flag, time } = {}) {
95
+ super(`${kind}: ${message}`);
96
+ this.name = "EngineError";
97
+ this.kind = kind;
98
+ this.detail = message;
99
+ if (flag !== undefined) this.flag = flag;
100
+ if (time !== undefined) this.time = time === null ? NaN : time;
101
+ }
102
+ }
103
+
104
+ /** The exit of the engine through `proc_exit`. */
105
+ export class WasiExit extends Error {
106
+ constructor(code) {
107
+ super(`engine.wasm called proc_exit(${code})`);
108
+ this.name = "WasiExit";
109
+ this.code = code;
110
+ }
111
+ }
112
+
113
+ /** A `WebAssembly.Module` of a module or of its bytes. */
114
+ async function toModule(source, what) {
115
+ if (source instanceof WebAssembly.Module) return source;
116
+ try {
117
+ return await WebAssembly.compile(source);
118
+ } catch (error) {
119
+ throw new Error(`${what} does not compile: ${error.message}`);
120
+ }
121
+ }
122
+
123
+ /**
124
+ * The minimum of the memory `engine.wasm` imports, from its section `sbmlsim.engine`, whose
125
+ * output format must be `ENGINE_OUTPUT_FORMAT`.
126
+ */
127
+ function memoryMinimum(engineModule) {
128
+ const sections = WebAssembly.Module.customSections(engineModule, ENGINE_SECTION);
129
+ if (sections.length !== 1) {
130
+ throw new Error(
131
+ `engine.wasm has no custom section ${ENGINE_SECTION} with the minimum of its memory and ` +
132
+ "the version of its output (the build script of sbmlsim-host adds it)",
133
+ );
134
+ }
135
+ const { memory_minimum_pages: pages, output_format: format } = JSON.parse(
136
+ new TextDecoder().decode(sections[0]),
137
+ );
138
+ if (format === undefined) {
139
+ throw new Error(
140
+ `engine.wasm declares no output format in its section ${ENGINE_SECTION}, this loader ` +
141
+ `reads ${ENGINE_OUTPUT_FORMAT}`,
142
+ );
143
+ }
144
+ if (format !== ENGINE_OUTPUT_FORMAT) {
145
+ throw new Error(
146
+ `engine.wasm writes the output format ${format}, this loader reads ${ENGINE_OUTPUT_FORMAT}`,
147
+ );
148
+ }
149
+ if (!Number.isInteger(pages) || pages < 0 || pages > MAX_MEMORY_PAGES) {
150
+ throw new Error(`engine.wasm declares a memory of ${pages} pages`);
151
+ }
152
+ return pages;
153
+ }
154
+
155
+ /**
156
+ * The functions of WASI preview1 of an instance: the stubs of the module comment, one per
157
+ * function `engine.wasm` imports (`{ imports, calls() }`, `calls()` the number of their calls);
158
+ * `getMemory()` gives the memory of the instance, `out` has `log` and `error` (the console).
159
+ */
160
+ export function wasiImports(engineModule, getMemory, out) {
161
+ let calls = 0;
162
+ const decoders = new Map();
163
+ const lines = new Map();
164
+ const view = () => new DataView(getMemory().buffer);
165
+ const write = (fd, bytes) => {
166
+ if (!decoders.has(fd)) decoders.set(fd, new TextDecoder());
167
+ let text = (lines.get(fd) ?? "") + decoders.get(fd).decode(bytes, { stream: true });
168
+ let newline;
169
+ while ((newline = text.indexOf("\n")) >= 0) {
170
+ (fd === 2 ? out.error : out.log)(text.slice(0, newline));
171
+ text = text.slice(newline + 1);
172
+ }
173
+ lines.set(fd, text);
174
+ };
175
+ const provided = {
176
+ fd_write(fd, iovs, iovsLen, nwritten) {
177
+ calls += 1;
178
+ if (fd !== 1 && fd !== 2) return 8; // EBADF
179
+ const memory = view();
180
+ let total = 0;
181
+ for (let i = 0; i < iovsLen; i += 1) {
182
+ const ptr = memory.getUint32(iovs + 8 * i, true);
183
+ const len = memory.getUint32(iovs + 8 * i + 4, true);
184
+ write(fd, new Uint8Array(getMemory().buffer, ptr, len));
185
+ total += len;
186
+ }
187
+ memory.setUint32(nwritten, total, true);
188
+ return 0;
189
+ },
190
+ proc_exit(code) {
191
+ calls += 1;
192
+ throw new WasiExit(code);
193
+ },
194
+ environ_get() {
195
+ calls += 1;
196
+ return 0;
197
+ },
198
+ environ_sizes_get(count, size) {
199
+ calls += 1;
200
+ const memory = view();
201
+ memory.setUint32(count, 0, true);
202
+ memory.setUint32(size, 0, true);
203
+ return 0;
204
+ },
205
+ clock_time_get() {
206
+ calls += 1;
207
+ throw new Error("engine.wasm called WASI clock_time_get: the engine reads no clock");
208
+ },
209
+ random_get() {
210
+ calls += 1;
211
+ throw new Error("engine.wasm called WASI random_get: the engine draws no random bytes");
212
+ },
213
+ };
214
+ const imports = {};
215
+ for (const { module, name, kind } of WebAssembly.Module.imports(engineModule)) {
216
+ if (module !== WASI || kind !== "function") continue;
217
+ imports[name] =
218
+ provided[name] ??
219
+ (() => {
220
+ calls += 1;
221
+ throw new Error(`engine.wasm called WASI ${name}, which the loader does not provide`);
222
+ });
223
+ }
224
+ return { imports, calls: () => calls };
225
+ }
226
+
227
+ /** Checks the imports and exports of `engine.wasm` and `mathlib.wasm`. */
228
+ function checkRuntime(engineModule, mathlibModule) {
229
+ let memory = false;
230
+ for (const { module, name, kind } of WebAssembly.Module.imports(engineModule)) {
231
+ if (module === "env" && name === "memory" && kind === "memory") memory = true;
232
+ else if ((module === "model" || module === WASI) && kind === "function") continue;
233
+ else throw new Error(`engine.wasm imports ${module}.${name}`);
234
+ }
235
+ if (!memory) throw new Error("engine.wasm imports no memory");
236
+ const exports = new Set(WebAssembly.Module.exports(engineModule).map((e) => e.name));
237
+ for (const name of ENGINE_EXPORTS) {
238
+ if (!exports.has(name)) throw new Error(`engine.wasm does not export ${name}`);
239
+ }
240
+ const [mathImport] = WebAssembly.Module.imports(mathlibModule);
241
+ if (mathImport) {
242
+ throw new Error(
243
+ `mathlib.wasm imports ${mathImport.module}.${mathImport.name}, it imports nothing`,
244
+ );
245
+ }
246
+ }
247
+
248
+ /** Checks that a model imports `env.memory` and otherwise only functions of mathlib. */
249
+ function checkModel(modelModule, mathlibModule) {
250
+ const math = new Set(
251
+ WebAssembly.Module.exports(mathlibModule)
252
+ .filter((e) => e.kind === "function")
253
+ .map((e) => e.name),
254
+ );
255
+ let memory = false;
256
+ for (const { module, name, kind } of WebAssembly.Module.imports(modelModule)) {
257
+ if (module === "env" && name === "memory" && kind === "memory") memory = true;
258
+ else if (module === "math" && kind === "function" && math.has(name)) continue;
259
+ else {
260
+ throw new Error(
261
+ `model.wasm imports ${module}.${name}, which is neither env.memory nor a function of mathlib`,
262
+ );
263
+ }
264
+ }
265
+ if (!memory) throw new Error("model.wasm does not import env.memory");
266
+ }
267
+
268
+ /** The JSON text of a description, request or other value. */
269
+ function jsonText(value) {
270
+ return typeof value === "string" ? value : JSON.stringify(value);
271
+ }
272
+
273
+ /**
274
+ * Compiles (or takes) `engine.wasm` and `mathlib.wasm` and checks their imports and exports;
275
+ * the runtime instantiates models with them. `engine` and `mathlib` are `WebAssembly.Module`s
276
+ * (e.g. posted to a worker) or their bytes; `console` gets the output of `fd_write` (`log`,
277
+ * `error`), `maxMemoryPages` lowers the maximum of the memory (tests).
278
+ */
279
+ export async function createRuntime({
280
+ engine,
281
+ mathlib,
282
+ console: out = globalThis.console,
283
+ maxMemoryPages = MAX_MEMORY_PAGES,
284
+ }) {
285
+ const engineModule = await toModule(engine, "engine.wasm");
286
+ const mathlibModule = await toModule(mathlib, "mathlib.wasm");
287
+ checkRuntime(engineModule, mathlibModule);
288
+ const minimum = memoryMinimum(engineModule);
289
+ return {
290
+ /** The compiled modules, which a worker gets to create a runtime of its own. */
291
+ modules: { engine: engineModule, mathlib: mathlibModule },
292
+
293
+ /**
294
+ * Instantiates a model (a `WebAssembly.Module` or the bytes of `model.wasm`) with its
295
+ * description (the text of `model.json` or its object) and loads it into a new engine.
296
+ * Asynchronous (a Promise of the instance): bytes compile with `WebAssembly.compile`, which
297
+ * browsers require for modules above a few KB on the main thread.
298
+ */
299
+ async instantiate(modelWasm, description) {
300
+ const descText = jsonText(description);
301
+ const desc = typeof description === "string" ? JSON.parse(description) : description;
302
+ if (desc.contract !== MODEL_CONTRACT) {
303
+ throw new Error(`the description is of the contract ${desc.contract}, not ${MODEL_CONTRACT}`);
304
+ }
305
+ const modelModule = await toModule(modelWasm, "model.wasm");
306
+ checkModel(modelModule, mathlibModule);
307
+ const memory = new WebAssembly.Memory({ initial: minimum, maximum: maxMemoryPages });
308
+ const wasi = wasiImports(engineModule, () => memory, out);
309
+ const math = await WebAssembly.instantiate(mathlibModule, {});
310
+ const model = await WebAssembly.instantiate(modelModule, {
311
+ env: { memory },
312
+ math: math.exports,
313
+ });
314
+ let engineInstance;
315
+ try {
316
+ engineInstance = await WebAssembly.instantiate(engineModule, {
317
+ env: { memory },
318
+ model: model.exports,
319
+ [WASI]: wasi.imports,
320
+ });
321
+ } catch (error) {
322
+ // a model which lacks a function of the contract: the error of the wasmtime host
323
+ if (error instanceof WebAssembly.LinkError) {
324
+ throw new Error(`engine.wasm does not instantiate with the model: ${error.message}`);
325
+ }
326
+ throw error;
327
+ }
328
+ const instance = new Instance(engineInstance.exports, memory, wasi.calls);
329
+ if (engineInstance.exports._initialize) {
330
+ instance.guard(() => engineInstance.exports._initialize());
331
+ }
332
+ instance.initializeCalls = wasi.calls();
333
+ instance.load(descText, desc.id);
334
+ return instance;
335
+ },
336
+ };
337
+ }
338
+
339
+ /** A model loaded into an engine; one per model and thread. */
340
+ class Instance {
341
+ constructor(exports, memory, calls) {
342
+ this.exports = exports;
343
+ this.memory = memory;
344
+ this.calls = calls;
345
+ this.trapped = false;
346
+ this.encoder = new TextEncoder();
347
+ this.decoder = new TextDecoder();
348
+ }
349
+
350
+ /** The number of calls of the engine into WASI since the instance was created. */
351
+ wasiCalls() {
352
+ return this.calls();
353
+ }
354
+
355
+ /** The size of the memory of the instance in bytes. */
356
+ memoryBytes() {
357
+ return this.memory.buffer.byteLength;
358
+ }
359
+
360
+ /**
361
+ * The counters of the integrator of the last simulation: an object of the names of
362
+ * `STATS_NAMES` to numbers (`engine_stats_ptr`).
363
+ */
364
+ stats() {
365
+ if (this.trapped) {
366
+ throw new EngineError("internal", "the instance trapped before and is not used again");
367
+ }
368
+ const ptr = this.guard(() => this.exports.engine_stats_ptr()) >>> 0;
369
+ const view = new DataView(this.memory.buffer, ptr, 8 * STATS_NAMES.length);
370
+ return Object.fromEntries(STATS_NAMES.map((name, i) => [name, Number(view.getBigUint64(8 * i, true))]));
371
+ }
372
+
373
+ /** The address of the output of the last call in the memory (aligned to 8). */
374
+ outputAddress() {
375
+ return this.exports.engine_output_ptr() >>> 0;
376
+ }
377
+
378
+ /**
379
+ * Simulates a request (an object of the contract `simulation/1` or its JSON text); gives
380
+ * `{ columns, nRows, values }`, the values a `Float64Array` of the rows, row major. The result
381
+ * does not depend on the simulations before. An error of the engine is an `EngineError`.
382
+ */
383
+ simulate(request) {
384
+ const code = this.call(this.exports.engine_simulate, jsonText(request));
385
+ const output = this.output();
386
+ if (code === 0 && output.table) return output.table;
387
+ if (code === 1 && output.error) throw output.error;
388
+ throw new EngineError("internal", `engine_simulate returned ${code} with the output ${JSON.stringify(output.header)}`);
389
+ }
390
+
391
+ /** Loads the description (`engine_load`). */
392
+ load(descText, id) {
393
+ const before = this.calls();
394
+ const code = this.call(this.exports.engine_load, descText);
395
+ this.loadCalls = this.calls() - before;
396
+ if (code !== 0) {
397
+ const { error } = this.output();
398
+ const message = error?.kind === "load" ? error.detail : `engine_load failed: ${error?.message}`;
399
+ throw new Error(`the engine refuses the description of model ${id}: ${message}`);
400
+ }
401
+ }
402
+
403
+ /** Calls `engine_load` or `engine_simulate` with `text` in a buffer of the engine. */
404
+ call(fn, text) {
405
+ if (this.trapped) {
406
+ throw new EngineError("internal", "the instance trapped before and is not used again");
407
+ }
408
+ const bytes = this.encoder.encode(text);
409
+ const ptr = this.guard(() => this.exports.engine_alloc(bytes.length)) >>> 0;
410
+ if (ptr === 0 && bytes.length > 0) {
411
+ throw new EngineError("internal", "engine_alloc found no memory for the input");
412
+ }
413
+ new Uint8Array(this.memory.buffer, ptr, bytes.length).set(bytes);
414
+ const code = this.guard(() => fn(ptr, bytes.length));
415
+ this.guard(() => this.exports.engine_free(ptr, bytes.length));
416
+ return code;
417
+ }
418
+
419
+ /**
420
+ * Runs a call of the engine; whatever it throws marks the instance and is an `EngineError`
421
+ * `internal` ([`trapError`]), as a trap of the wasmtime host, but `WasiExit`.
422
+ */
423
+ guard(call) {
424
+ try {
425
+ return call();
426
+ } catch (error) {
427
+ this.trapped = true;
428
+ if (error instanceof WasiExit) throw error;
429
+ let panic = null;
430
+ try {
431
+ const { error: e } = this.output();
432
+ if (e?.engineKind === "panic") panic = e.detail;
433
+ } catch {
434
+ // no output to read
435
+ }
436
+ throw trapError(error, panic);
437
+ }
438
+ }
439
+
440
+ /** The output of the last call: `{ header, table }` or `{ header, error }`. */
441
+ output() {
442
+ const ptr = this.exports.engine_output_ptr() >>> 0;
443
+ const len = this.exports.engine_output_len() >>> 0;
444
+ const buffer = this.memory.buffer;
445
+ if (len < 4 || ptr + len > buffer.byteLength) {
446
+ throw new EngineError("internal", "the output of the engine is outside of the memory");
447
+ }
448
+ const view = new DataView(buffer, ptr, len);
449
+ const headerLength = view.getUint32(0, true);
450
+ if (4 + headerLength > len) {
451
+ throw new EngineError("internal", "the header of the output of the engine is cut off");
452
+ }
453
+ const header = JSON.parse(this.decoder.decode(new Uint8Array(buffer, ptr + 4, headerLength)));
454
+ if (header.error) {
455
+ const { kind, message, flag, time } = header.error;
456
+ const known = ["load", "request", "unsupported", "integration"];
457
+ const error = known.includes(kind)
458
+ ? new EngineError(kind, message, { flag, time })
459
+ : new EngineError("internal", kind === "panic" ? `engine.wasm panicked: ${message}` : `an error of the unknown kind ${kind}: ${message}`);
460
+ error.detail = message;
461
+ error.engineKind = kind;
462
+ return { header, error };
463
+ }
464
+ const { columns, n_rows: nRows } = header;
465
+ const start = (4 + headerLength + 7) & ~7;
466
+ const n = nRows * columns.length;
467
+ if (start + 8 * n !== len) {
468
+ throw new EngineError(
469
+ "internal",
470
+ `the output of the engine does not hold ${nRows} rows of ${columns.length} columns`,
471
+ );
472
+ }
473
+ let values;
474
+ if (LITTLE_ENDIAN) {
475
+ // the output is aligned to 8, so the values are a Float64Array over the memory
476
+ values = new Float64Array(buffer, ptr + start, n).slice();
477
+ } else {
478
+ values = new Float64Array(n);
479
+ for (let i = 0; i < n; i += 1) values[i] = view.getFloat64(start + 8 * i, true);
480
+ }
481
+ return { header, table: { columns, nRows, values } };
482
+ }
483
+ }
484
+
485
+ /**
486
+ * The `EngineError` of what a call of the engine threw, as the wasmtime host maps a trap: a
487
+ * trap of the engine or the model (`WebAssembly.RuntimeError`), the exhaustion of the stack of
488
+ * the host (V8 throws a `RangeError`, wasmtime traps) and an error a WASI stub threw are all of
489
+ * the kind `internal`, with the message of a panic of the engine when it wrote one; the error is
490
+ * the `cause`. (`WasiExit`, the engine calling `proc_exit`, stays an error of its own, which
491
+ * `guard` throws as it is.)
492
+ */
493
+ export function trapError(error, panic = null) {
494
+ const what = error instanceof WebAssembly.RuntimeError ? "trapped" : `failed (${error?.name ?? "Error"})`;
495
+ const message = `engine.wasm ${what}: ${error?.message ?? String(error)}${panic ? ` (${panic})` : ""}`;
496
+ const mapped = new EngineError("internal", message);
497
+ mapped.cause = error;
498
+ return mapped;
499
+ }
500
+
501
+ /**
502
+ * A number as the CSV of the command line writes it (Rust's `{}` of `f64`): the shortest
503
+ * decimal which reads back as the same double, without an exponent, `-0` for the negative
504
+ * zero, and `NaN`, `inf`, `-inf`.
505
+ */
506
+ export function formatNumber(x) {
507
+ if (Number.isNaN(x)) return "NaN";
508
+ if (x === Infinity) return "inf";
509
+ if (x === -Infinity) return "-inf";
510
+ const sign = x < 0 || Object.is(x, -0) ? "-" : "";
511
+ // the shortest digits which read back as x, with the exponent of the first one
512
+ const [mantissa, exponent] = Math.abs(x).toExponential().split("e");
513
+ const digits = mantissa.replace(".", "");
514
+ const e = Number(exponent);
515
+ let text;
516
+ if (e < 0) text = `0.${"0".repeat(-e - 1)}${digits}`;
517
+ else if (digits.length <= e + 1) text = digits + "0".repeat(e + 1 - digits.length);
518
+ else text = `${digits.slice(0, e + 1)}.${digits.slice(e + 1)}`;
519
+ return sign + text;
520
+ }
521
+
522
+ /** The CSV of a result as the command line writes it (`sbmlsim_cli::csv`). */
523
+ export function toCsv({ columns, values }) {
524
+ const k = Math.max(columns.length, 1);
525
+ const lines = [columns.join(",")];
526
+ for (let i = 0; i < values.length; i += k) {
527
+ const row = [];
528
+ for (let j = i; j < Math.min(i + k, values.length); j += 1) row.push(formatNumber(values[j]));
529
+ lines.push(row.join(","));
530
+ }
531
+ return `${lines.join("\n")}\n`;
532
+ }