sbmlsim-core 0.21.0 → 0.23.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/README.md CHANGED
@@ -5,11 +5,12 @@ Simulate SBML models in browsers and in Node. [sbmlsim-core](https://matthiaskoe
5
5
  | module | import | what it is |
6
6
  |---|---|---|
7
7
  | `loader.mjs` | `sbmlsim-core` | runs `engine.wasm`, `mathlib.wasm` and a compiled `model.wasm` |
8
+ | `compile.mjs` | `sbmlsim-core/compile` | compiles SBML text into `model.wasm` and its description with `compiler.wasm` |
8
9
  | `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
10
  | `panels.mjs` | `sbmlsim-core/panels` | the routes of the panel service of sbmlsim, answered inside a page from an exported bundle |
10
11
  | `simulate.mjs` | the command `sbmlsim-core-simulate` | the CSV of a simulation in Node |
11
12
 
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
+ A model is compiled in the host with `compile.mjs`, or ahead of time with the command line of the repository (`sbmlsim-core compile model.xml -o DIR`). Both run the same compiler, so a model compiled in a page gives the `model.wasm` the command line writes, byte for byte.
13
14
 
14
15
  ## Install
15
16
 
@@ -20,7 +21,7 @@ npm install sbmlsim-core
20
21
  or import the modules from a CDN, which serves them with the headers every origin may read:
21
22
 
22
23
  ```js
23
- import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.21.0/panels.mjs";
24
+ import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.23.0/panels.mjs";
24
25
  ```
25
26
 
26
27
  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.
@@ -78,6 +79,22 @@ const result = await pool.simulate("model", request, { signal });
78
79
  pool.close();
79
80
  ```
80
81
 
82
+ ## Compile a model in the host
83
+
84
+ ```js
85
+ import { createCompiler } from "sbmlsim-core/compile";
86
+
87
+ const compiler = await createCompiler({
88
+ compiler: await file("sbmlsim-core/runtime/compiler.wasm"),
89
+ });
90
+ const { wasm, description } = compiler.compile(await readFile("model.xml", "utf8"));
91
+ const instance = await runtime.instantiate(wasm, description);
92
+ ```
93
+
94
+ `compiler.wasm` is the compiler of the command line built for `wasm32-unknown-unknown`: the same reader of SBML, the same model representation and the same code generation, so the module and the description are the ones of `sbmlsim-core compile`. It reads no file and imports nothing of the host, so a page compiles a model a visitor drops into it without a server.
95
+
96
+ `compile` is synchronous and takes a few milliseconds for a model of the size of the repressilator; a model which the compiler refuses raises a `CompileError` with its message. `optimize: false` leaves the optimizer of the compiler out (the results are the same) and `jacobian` is `"auto"`, `"difference-quotient"` or `"analytic"`, as the command line takes them. One compiler compiles any number of models, one after the other.
97
+
81
98
  ## A static app of interactive panels
82
99
 
83
100
  `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:
@@ -86,7 +103,7 @@ pool.close();
86
103
  <!-- the IIFE build of sbmlsim-web, a release with registerEndpoint -->
87
104
  <script src="sbmlsim-web.iife.js"></script>
88
105
  <script type="module">
89
- import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.21.0/panels.mjs";
106
+ import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.23.0/panels.mjs";
90
107
 
91
108
  sbmlsimWeb.registerEndpoint(
92
109
  "local:glimepiride",
package/compile.mjs ADDED
@@ -0,0 +1,156 @@
1
+ // The compiler of sbmlsim-core in a JavaScript host: compiles SBML text into `model.wasm` and
2
+ // its description, which `loader.mjs` instantiates and simulates.
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 { createCompiler } from "sbmlsim-core/compile";
8
+ // import { createRuntime } from "sbmlsim-core";
9
+ // const compiler = await createCompiler({ compiler: compilerWasm }); // a Module or bytes
10
+ // const { wasm, description } = compiler.compile(sbmlText);
11
+ // const runtime = await createRuntime({ engine, mathlib });
12
+ // const instance = await runtime.instantiate(wasm, description);
13
+ //
14
+ // `compiler.wasm` is the module of `crates/wasm`, built for `wasm32-unknown-unknown`: it is the
15
+ // compiler of the command line and of the python package (`sbmlsim-core compile`), the same
16
+ // reader, the same model representation and the same code generation, so a model compiled in a
17
+ // page and the same model compiled by the command line give the same `model.wasm`. The module
18
+ // reads no file and imports nothing of the host, so a page compiles without a server.
19
+ //
20
+ // The interface of the module is the C ABI of `allocate`, `compile` and `deallocate`
21
+ // (`crates/wasm/src/lib.rs`): the document goes into the memory of the module as the bytes of
22
+ // its UTF-8, the result comes back as the description (the JSON of `model.json`) and the bytes
23
+ // of `model.wasm`, and every buffer is freed again. `compile` is synchronous and takes a few
24
+ // milliseconds for a model of the size of the repressilator.
25
+
26
+ /** The exports of `compiler.wasm` this host calls. */
27
+ const COMPILER_EXPORTS = ["allocate", "compile", "deallocate", "memory"];
28
+
29
+ /** The source of the Jacobian of a model, the numbers of the interface. */
30
+ const JACOBIAN = { auto: 0, "difference-quotient": 1, analytic: 2 };
31
+
32
+ /** A model which the compiler refuses, with the message of the compiler. */
33
+ export class CompileError extends Error {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = "CompileError";
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Compiles `compiler.wasm` when it is given as bytes, and checks its exports.
42
+ *
43
+ * @param {WebAssembly.Module|BufferSource} source the module or its bytes
44
+ * @returns {Promise<WebAssembly.Module>} the compiled module
45
+ */
46
+ async function moduleOf(source) {
47
+ const module =
48
+ source instanceof WebAssembly.Module ? source : await WebAssembly.compile(source);
49
+ const exports = new Set(WebAssembly.Module.exports(module).map((entry) => entry.name));
50
+ const missing = COMPILER_EXPORTS.filter((name) => !exports.has(name));
51
+ if (missing.length > 0) {
52
+ throw new Error(`compiler.wasm does not export ${missing.join(", ")}`);
53
+ }
54
+ if (WebAssembly.Module.imports(module).length > 0) {
55
+ throw new Error("compiler.wasm imports from its host, which this host does not provide");
56
+ }
57
+ return module;
58
+ }
59
+
60
+ /** The compiler of a host: one instance of `compiler.wasm`, which compiles one model at a time. */
61
+ class Compiler {
62
+ /**
63
+ * @param {WebAssembly.Module} module the compiled `compiler.wasm`
64
+ * @param {WebAssembly.Instance} instance its instance
65
+ */
66
+ constructor(module, instance) {
67
+ /** The compiled module, which a worker gets to create a compiler of its own. */
68
+ this.module = module;
69
+ this.exports = instance.exports;
70
+ }
71
+
72
+ /** The memory of the module, read again after every call: it grows while a model compiles. */
73
+ bytes() {
74
+ return new Uint8Array(this.exports.memory.buffer);
75
+ }
76
+
77
+ /**
78
+ * Compiles an SBML Level 3 Version 2 document.
79
+ *
80
+ * @param {string} sbml the text of the document
81
+ * @param {{optimize?: boolean, jacobian?: "auto"|"difference-quotient"|"analytic"}} options
82
+ * `optimize` runs the optimizer of the compiler (the default, the results are the same
83
+ * without it) and `jacobian` is the source of the Jacobian of the model
84
+ * @returns {{wasm: Uint8Array, description: object}} `model.wasm` and `model.json`
85
+ * @throws {CompileError} for a document the compiler refuses
86
+ */
87
+ compile(sbml, { optimize = true, jacobian = "auto" } = {}) {
88
+ if (typeof sbml !== "string") {
89
+ throw new TypeError("the document of a compilation is text");
90
+ }
91
+ const choice = JACOBIAN[jacobian];
92
+ if (choice === undefined) {
93
+ throw new TypeError(`the Jacobian ${jacobian} is none of ${Object.keys(JACOBIAN)}`);
94
+ }
95
+ const { allocate, compile, deallocate } = this.exports;
96
+ const document_ = new TextEncoder().encode(sbml);
97
+ const input = allocate(document_.length);
98
+ const words = allocate(4 * 4);
99
+ try {
100
+ if (document_.length > 0) {
101
+ this.bytes().set(document_, input);
102
+ }
103
+ const status = compile(input, document_.length, optimize ? 1 : 0, choice, words);
104
+ const header = new Uint32Array(this.exports.memory.buffer, words, 4);
105
+ const [textPointer, textLength, wasmPointer, wasmLength] = header;
106
+ try {
107
+ const text = this.read(textPointer, textLength);
108
+ if (status !== 1) {
109
+ throw new CompileError(
110
+ new TextDecoder().decode(text) || "the compiler refused the document",
111
+ );
112
+ }
113
+ return {
114
+ wasm: this.read(wasmPointer, wasmLength).slice(),
115
+ description: JSON.parse(new TextDecoder().decode(text)),
116
+ };
117
+ } finally {
118
+ deallocate(textPointer, textLength);
119
+ deallocate(wasmPointer, wasmLength);
120
+ }
121
+ } finally {
122
+ deallocate(words, 4 * 4);
123
+ deallocate(input, document_.length);
124
+ }
125
+ }
126
+
127
+ /**
128
+ * The bytes of a buffer of the module, as a view on its memory.
129
+ *
130
+ * @param {number} pointer the address of the buffer
131
+ * @param {number} length its length in bytes
132
+ * @returns {Uint8Array} the view, empty when the buffer is
133
+ */
134
+ read(pointer, length) {
135
+ if (pointer === 0 || length === 0) {
136
+ return new Uint8Array(0);
137
+ }
138
+ return new Uint8Array(this.exports.memory.buffer, pointer, length);
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Creates the compiler of a host.
144
+ *
145
+ * @param {{compiler: WebAssembly.Module|BufferSource}} options `compiler.wasm` of this version
146
+ * of sbmlsim-core, as a compiled module or as its bytes
147
+ * @returns {Promise<Compiler>} the compiler, whose `compile` is synchronous
148
+ */
149
+ export async function createCompiler({ compiler }) {
150
+ if (!compiler) {
151
+ throw new TypeError("createCompiler needs compiler.wasm");
152
+ }
153
+ const module = await moduleOf(compiler);
154
+ const instance = await WebAssembly.instantiate(module, {});
155
+ return new Compiler(module, instance);
156
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sbmlsim-core",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Simulate SBML models compiled to WebAssembly in browsers and Node: the JavaScript host of sbmlsim-core with its engine (CVODE, KLU), a pool of workers and the panel endpoint of sbmlsim",
5
5
  "keywords": [
6
6
  "sbml",
@@ -27,11 +27,13 @@
27
27
  "type": "module",
28
28
  "exports": {
29
29
  ".": "./loader.mjs",
30
+ "./compile": "./compile.mjs",
30
31
  "./pool": "./pool.mjs",
31
32
  "./panels": "./panels.mjs",
32
33
  "./worker": "./worker.mjs",
33
34
  "./runtime/engine.wasm": "./runtime/engine.wasm",
34
35
  "./runtime/mathlib.wasm": "./runtime/mathlib.wasm",
36
+ "./runtime/compiler.wasm": "./runtime/compiler.wasm",
35
37
  "./package.json": "./package.json"
36
38
  },
37
39
  "bin": {
@@ -39,12 +41,14 @@
39
41
  },
40
42
  "files": [
41
43
  "loader.mjs",
44
+ "compile.mjs",
42
45
  "pool.mjs",
43
46
  "worker.mjs",
44
47
  "panels.mjs",
45
48
  "simulate.mjs",
46
49
  "runtime/engine.wasm",
47
50
  "runtime/mathlib.wasm",
51
+ "runtime/compiler.wasm",
48
52
  "runtime/THIRD_PARTY.md",
49
53
  "LICENSE"
50
54
  ],
package/panels.mjs CHANGED
@@ -70,7 +70,7 @@ import { EngineError } from "./loader.mjs";
70
70
  import { createPool, defaultWorkers } from "./pool.mjs";
71
71
 
72
72
  /** The version of sbmlsim-core (`js/package.json`), which the provenance of a run names. */
73
- export const CORE_VERSION = "0.21.0";
73
+ export const CORE_VERSION = "0.23.0";
74
74
 
75
75
  /** The engine a provenance names. */
76
76
  export const ENGINE = `sbmlsim-core ${CORE_VERSION}`;
Binary file
Binary file
Binary file