sbmlsim-core 0.11.0 → 0.13.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
@@ -20,7 +20,7 @@ npm install sbmlsim-core
20
20
  or import the modules from a CDN, which serves them with the headers every origin may read:
21
21
 
22
22
  ```js
23
- import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.11.0/panels.mjs";
23
+ import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.13.0/panels.mjs";
24
24
  ```
25
25
 
26
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.
@@ -86,7 +86,7 @@ pool.close();
86
86
  <!-- the IIFE build of sbmlsim-web, a release with registerEndpoint -->
87
87
  <script src="sbmlsim-web.iife.js"></script>
88
88
  <script type="module">
89
- import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.11.0/panels.mjs";
89
+ import { createPanelEndpoint } from "https://cdn.jsdelivr.net/npm/sbmlsim-core@0.13.0/panels.mjs";
90
90
 
91
91
  sbmlsimWeb.registerEndpoint(
92
92
  "local:glimepiride",
package/loader.mjs CHANGED
@@ -86,6 +86,9 @@ export const STATS_NAMES = [
86
86
  "jacobian_vector_evals",
87
87
  "preconditioner_evals",
88
88
  "preconditioner_solves",
89
+ "sensitivity_rhs_evals",
90
+ "sensitivity_model_rhs_evals",
91
+ "sensitivity_jac_p_evals",
89
92
  ];
90
93
 
91
94
  const LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sbmlsim-core",
3
- "version": "0.11.0",
3
+ "version": "0.13.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",
package/panels.mjs CHANGED
@@ -22,7 +22,7 @@
22
22
  // GET /api/models/{model}/app[?variant=V] answers[V].app, a 404 for none
23
23
  // GET /api/models/{model}/panels/{panel}[?variant=V] answers[V].panels[panel].declaration
24
24
  // GET /api/models/{model}/panels/{panel}/data[?variant=V] .data
25
- // POST /api/models/{model}/panels/{panel}/simulate body { values?, grid?, variant? }
25
+ // POST /api/models/{model}/panels/{panel}/simulate body { values?, grid?, variant?, draws? }
26
26
  //
27
27
  // A simulation is checked against the declaration as the service checks it (a knob the panel
28
28
  // does not declare, a value outside the bounds of a range knob or none of the choices of a
@@ -36,6 +36,18 @@
36
36
  // its settings with an absolute tolerance per state. A point which does not integrate is a row
37
37
  // of `null` in every curve and its flat index is in `status.failed`, as the service answers it.
38
38
  //
39
+ // A panel whose recipe carries an uncertainty (the sample of the fit of its model, which the
40
+ // bundle holds) answers a band next to its curves for the `draws` a request asks for: every
41
+ // point of the grid is run once per draw, with the parameters of that draw set before the
42
+ // initialization, and `uncertainty.band[curve][point]` is the percentiles of that sample, time
43
+ // by time, of the level the recipe states (`low`, `high`; the linear interpolation of the order
44
+ // statistics, as numpy and the service compute it). A draw which does not integrate is left out
45
+ // of the percentiles and its index is in `uncertainty.failed`. A run of one point alone carries
46
+ // the curves of the draws themselves as `uncertainty.curves[curve]`, where their size is
47
+ // bounded; over a grid only the band travels. The draws are the first ones of the sample, which
48
+ // is why the sample of a recipe is written in the order of a latin hypercube: a prefix of it is
49
+ // a sample of its own, so the band settles as a page asks for more draws instead of jumping.
50
+ //
39
51
  // The runs are shared: the points of one model, end and pre-initialization are one run, so the
40
52
  // panels of a page which show one state (each its own curves, all selections of the model are
41
53
  // simulated) cost one scan. A run in flight is joined, a finished one is kept in a cache bounded
@@ -51,14 +63,14 @@
51
63
  // `spec_hash` is the sha256 of the canonical JSON (sorted keys, no whitespace, every character
52
64
  // which is not ASCII escaped) of the resolved request: the model, the panel, the query `variant`,
53
65
  // the declaration, the sha256 of the SBML, the value of every knob (its default for one the
54
- // request leaves out), the grid, the engine and the settings. It identifies what was simulated
66
+ // request leaves out), the grid, the draws, the engine and the settings. It identifies what was simulated
55
67
  // by this endpoint; it is not the hash of the service, whose engine and settings differ.
56
68
 
57
69
  import { EngineError } from "./loader.mjs";
58
70
  import { createPool, defaultWorkers } from "./pool.mjs";
59
71
 
60
72
  /** The version of sbmlsim-core (`js/package.json`), which the provenance of a run names. */
61
- export const CORE_VERSION = "0.11.0";
73
+ export const CORE_VERSION = "0.13.0";
62
74
 
63
75
  /** The engine a provenance names. */
64
76
  export const ENGINE = `sbmlsim-core ${CORE_VERSION}`;
@@ -79,7 +91,7 @@ export const MAX_ID = 128;
79
91
  const DEFAULT_LIMITS = { knobs: 8, grid: 64 };
80
92
 
81
93
  /** The fields of the body of a simulation. */
82
- const REQUEST_FIELDS = new Set(["values", "grid", "variant"]);
94
+ const REQUEST_FIELDS = new Set(["values", "grid", "variant", "draws"]);
83
95
 
84
96
  /** A request which is answered with an error status. */
85
97
  class HttpError extends Error {
@@ -260,7 +272,7 @@ function readBody(text) {
260
272
  }
261
273
  const unknown = Object.keys(body).filter((key) => !REQUEST_FIELDS.has(key));
262
274
  if (unknown.length > 0) {
263
- throw new HttpError(422, `The body of a simulation has the unknown fields ${pyList(unknown.sort())}; its fields are ['grid', 'values', 'variant'].`);
275
+ throw new HttpError(422, `The body of a simulation has the unknown fields ${pyList(unknown.sort())}; its fields are ['draws', 'grid', 'values', 'variant'].`);
264
276
  }
265
277
  const mapping = (name) => {
266
278
  const value = body[name] ?? {};
@@ -284,7 +296,11 @@ function readBody(text) {
284
296
  if (typeof variant !== "string" || variant.length > MAX_ID) {
285
297
  throw new HttpError(422, `The variant is no text of at most ${MAX_ID} characters.`);
286
298
  }
287
- return { values, grid, variant };
299
+ const draws = body.draws ?? 0;
300
+ if (!Number.isInteger(draws) || draws < 0) {
301
+ throw new HttpError(422, `The draws of the uncertainty are no whole number of at least 0.`);
302
+ }
303
+ return { values, grid, variant, draws };
288
304
  }
289
305
 
290
306
  /**
@@ -514,6 +530,42 @@ function outputRows(result) {
514
530
  return rows;
515
531
  }
516
532
 
533
+ /**
534
+ * The draws of the uncertainty a request gets, 0 for a run without a band.
535
+ *
536
+ * A request which names no number gets no draw: the draws are the work of the band and a
537
+ * request which did not ask for them never pays for them, while the number a client asks for
538
+ * when its host names none is the `draws` of the declaration, which is where a client reads
539
+ * it. A request for more draws than the sample of the recipe holds is refused rather than cut,
540
+ * as a knob outside its bounds is refused: a page which asks for 64 draws and silently gets 32
541
+ * would state a band it did not get. A panel whose recipe carries no uncertainty gets none,
542
+ * whatever it asked for, so a declaration is what decides whether a band exists at all.
543
+ */
544
+ function resolveDraws(panel, uncertainty, asked) {
545
+ if (!uncertainty || asked === 0) return 0;
546
+ const max = uncertainty.max_draws ?? (uncertainty.draws ?? []).length;
547
+ if (asked > max) {
548
+ throw new HttpError(422, `The panel '${panel}' carries ${max} draws of its uncertainty, ${asked} were asked for.`);
549
+ }
550
+ return asked;
551
+ }
552
+
553
+ /**
554
+ * The percentile of a sample, the linear interpolation of its order statistics.
555
+ *
556
+ * It is the `linear` method of numpy, which is the one the python half of a panel uses, so the
557
+ * two halves answer the same band. A value which is no finite number is no member of the
558
+ * sample (a draw which did not integrate), and a sample without one has no percentile.
559
+ */
560
+ function percentile(sample, share) {
561
+ const sorted = sample.filter((one) => one !== null && one !== undefined && Number.isFinite(one)).sort((a, b) => a - b);
562
+ if (sorted.length === 0) return null;
563
+ const at = share * (sorted.length - 1);
564
+ const low = Math.floor(at);
565
+ const high = Math.ceil(at);
566
+ return sorted[low] + (at - low) * (sorted[high] - sorted[low]);
567
+ }
568
+
517
569
  /**
518
570
  * Creates the endpoint of a bundle: a function `(url, init) => Promise<Response>` with the
519
571
  * signature of `fetch`, see the module comment. Options:
@@ -668,13 +720,14 @@ export function createPanelEndpoint(options) {
668
720
  /** Runs a simulation of a panel. */
669
721
  const simulate = async (bundleData, pool, model, panel, text, signal) => {
670
722
  const started = globalThis.performance?.now() ?? Date.now();
671
- const { values, grid, variant } = readBody(text);
723
+ const { values, grid, variant, draws } = readBody(text);
672
724
  const answer = panelOf(bundleData, model, panel, variant);
673
725
  const declaration = answer.declaration;
674
726
  checkLimits(values, grid, { ...DEFAULT_LIMITS, ...declaration.limits });
675
727
  const knobs = declaration.axes ?? [];
676
728
  checkKnobs(panel, knobs, values, grid);
677
729
  const run = answer.run;
730
+ const asked = resolveDraws(panel, run.uncertainty, draws);
678
731
  const info = await abortable(modelOf(bundleData, pool, run.model), signal);
679
732
 
680
733
  const axes = knobs
@@ -705,63 +758,123 @@ export function createPanelEndpoint(options) {
705
758
  };
706
759
  });
707
760
 
708
- const runKey = JSON.stringify([run.model, run.start, run.end, run.points, points]);
709
- const results = await runs.get(
710
- runKey,
711
- async (runSignal) => {
712
- const requests = points.map(({ preinit, changes }) => ({
713
- contract: "simulation/1",
714
- start: run.start,
715
- end: run.end,
716
- output: { uniform: { steps: run.points } },
717
- preinit,
718
- changes,
719
- steady_state: null,
720
- selections: info.selections,
721
- settings: info.settings,
722
- }));
723
- // an error of the engine is a point which failed, any other error fails the run
724
- return Promise.all(
725
- requests.map((request) =>
726
- pool.simulate(info.poolKey, request, { signal: runSignal }).catch((error) => {
727
- if (error instanceof EngineError) return null;
728
- throw error;
729
- }),
730
- ),
731
- );
732
- },
733
- signal,
734
- );
761
+ const runner = (list) => async (runSignal) => {
762
+ const requests = list.map(({ preinit, changes }) => ({
763
+ contract: "simulation/1",
764
+ start: run.start,
765
+ end: run.end,
766
+ output: { uniform: { steps: run.points } },
767
+ preinit,
768
+ changes,
769
+ steady_state: null,
770
+ selections: info.selections,
771
+ settings: info.settings,
772
+ }));
773
+ // an error of the engine is a point which failed, any other error fails the run
774
+ return Promise.all(
775
+ requests.map((request) =>
776
+ pool.simulate(info.poolKey, request, { signal: runSignal }).catch((error) => {
777
+ if (error instanceof EngineError) return null;
778
+ throw error;
779
+ }),
780
+ ),
781
+ );
782
+ };
783
+
784
+ /**
785
+ * The rows of every curve of a list of results, in the order of the list: the row of a
786
+ * result which is null (a run which did not integrate) is null for every time, and its
787
+ * index is one of the failed ones.
788
+ */
789
+ const rowsOf = (list) => {
790
+ const out = {};
791
+ const failedAt = [];
792
+ for (const curve of declaration.curves ?? []) out[curve.id] = [];
793
+ list.forEach((result, index) => {
794
+ if (result === null) failedAt.push(index);
795
+ // a dose at an output time is two rows of that time, the state before it and after it;
796
+ // the curve is the state after it, as the service interpolates onto its times
797
+ const rows = result === null ? [] : outputRows(result);
798
+ if (result !== null && rows.length !== run.x.length) {
799
+ throw new Error(`the run of the panel ${panel} has ${rows.length} rows, its x ${run.x.length}`);
800
+ }
801
+ for (const curve of declaration.curves ?? []) {
802
+ const spec = run.curves?.[curve.id];
803
+ if (!spec) throw new Error(`the run of the panel ${panel} has no curve ${curve.id}`);
804
+ if (result === null) {
805
+ out[curve.id].push(run.x.map(() => null));
806
+ continue;
807
+ }
808
+ const width = result.columns.length;
809
+ const column = result.columns.indexOf(spec.selection);
810
+ if (column < 0) throw new Error(`the model ${run.model} does not select ${spec.selection}`);
811
+ const row = new Array(rows.length);
812
+ rows.forEach((r, i) => {
813
+ const value = result.values[r * width + column] * spec.factor;
814
+ row[i] = Number.isFinite(value) ? value : null;
815
+ });
816
+ out[curve.id].push(row);
817
+ }
818
+ });
819
+ return { curves: out, failed: failedAt };
820
+ };
735
821
 
736
- const failed = [];
737
- const curves = {};
738
- for (const curve of declaration.curves ?? []) curves[curve.id] = [];
739
- results.forEach((result, index) => {
740
- if (result === null) failed.push(index);
741
- // a dose at an output time is two rows of that time, the state before it and after it;
742
- // the curve is the state after it, as the service interpolates onto its times
743
- const rows = result === null ? [] : outputRows(result);
744
- if (result !== null && rows.length !== run.x.length) {
745
- throw new Error(`the run of the panel ${panel} has ${rows.length} rows, its x ${run.x.length}`);
822
+ const runKey = JSON.stringify([run.model, run.start, run.end, run.points, points]);
823
+ const results = await runs.get(runKey, runner(points), signal);
824
+ const { curves, failed } = rowsOf(results);
825
+
826
+ /**
827
+ * The uncertainty of the answer: the band of every curve for every point of the grid, and
828
+ * the curves of the draws themselves for a run of one point, where their size is bounded.
829
+ *
830
+ * Every draw is the run of its point with the parameters of its vector of the sample set
831
+ * before the initialization, exactly as a knob with a `parameter` is set, and the draws of
832
+ * a point are its own sample: the band is the percentiles of that sample, time by time.
833
+ */
834
+ const uncertaintyOf = async () => {
835
+ if (asked === 0) return null;
836
+ const vectors = (run.uncertainty.draws ?? []).slice(0, asked);
837
+ const parameters = run.uncertainty.parameters ?? [];
838
+ const drawPoints = [];
839
+ for (const point of points) {
840
+ for (const vector of vectors) {
841
+ const preinit = new Map(point.preinit);
842
+ parameters.forEach((id, k) => preinit.set(id, vector[k]));
843
+ drawPoints.push({
844
+ preinit: [...preinit].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
845
+ changes: point.changes,
846
+ });
847
+ }
746
848
  }
849
+ const drawKey = JSON.stringify([run.model, run.start, run.end, run.points, drawPoints]);
850
+ const drawResults = await runs.get(drawKey, runner(drawPoints), signal);
851
+ const drawn = rowsOf(drawResults);
852
+ const level = run.uncertainty.level ?? 0.9;
853
+ const low = (1 - level) / 2;
854
+ const high = (1 + level) / 2;
855
+ const band = {};
747
856
  for (const curve of declaration.curves ?? []) {
748
- const spec = run.curves?.[curve.id];
749
- if (!spec) throw new Error(`the run of the panel ${panel} has no curve ${curve.id}`);
750
- if (result === null) {
751
- curves[curve.id].push(run.x.map(() => null));
752
- continue;
753
- }
754
- const width = result.columns.length;
755
- const column = result.columns.indexOf(spec.selection);
756
- if (column < 0) throw new Error(`the model ${run.model} does not select ${spec.selection}`);
757
- const row = new Array(rows.length);
758
- rows.forEach((r, i) => {
759
- const value = result.values[r * width + column] * spec.factor;
760
- row[i] = Number.isFinite(value) ? value : null;
857
+ band[curve.id] = points.map((_, p) => {
858
+ const sample = vectors.map((__, d) => drawn.curves[curve.id][p * asked + d]);
859
+ const ends = { low: new Array(run.x.length), high: new Array(run.x.length) };
860
+ for (let t = 0; t < run.x.length; t += 1) {
861
+ const column = sample.map((row) => row[t]);
862
+ ends.low[t] = percentile(column, low);
863
+ ends.high[t] = percentile(column, high);
864
+ }
865
+ return ends;
761
866
  });
762
- curves[curve.id].push(row);
763
867
  }
764
- });
868
+ return {
869
+ draws: asked,
870
+ fit: run.uncertainty.fit ?? "",
871
+ level,
872
+ band,
873
+ ...(points.length === 1 ? { curves: drawn.curves } : {}),
874
+ failed: drawn.failed,
875
+ };
876
+ };
877
+ const uncertainty = await uncertaintyOf();
765
878
 
766
879
  const resolvedValues = {};
767
880
  for (const knob of knobs) if (!(knob.id in grid)) resolvedValues[knob.id] = fixed[knob.id];
@@ -778,6 +891,7 @@ export function createPanelEndpoint(options) {
778
891
  model_sha256: run.model_sha256,
779
892
  values: resolvedValues,
780
893
  grid: resolvedGrid,
894
+ draws: asked,
781
895
  engine: ENGINE,
782
896
  settings: { settings: modelEntry.settings, absolute_tolerances: modelEntry.absolute_tolerances ?? {} },
783
897
  }),
@@ -801,6 +915,7 @@ export function createPanelEndpoint(options) {
801
915
  created: new Date().toISOString(),
802
916
  },
803
917
  status: { ok: failed.length === 0, points: results.length, failed },
918
+ ...(uncertainty === null ? {} : { uncertainty }),
804
919
  };
805
920
  };
806
921
 
@@ -4,7 +4,7 @@ The code of sbmlsim-core is MIT licensed (`LICENSE`). `engine.wasm`, which `sbml
4
4
 
5
5
  | Library | Version | Submodule and commit | License |
6
6
  |---|---|---|---|
7
- | SUNDIALS (CVODE, IDA and their vectors, matrices and linear solvers) | 7.9.0 | `third_party/sundials`, tag v7.9.0, commit 312fc0f3684f27209ca9dc9249d194436eb41a7a | BSD-3-Clause |
7
+ | SUNDIALS (CVODES, IDA and their vectors, matrices and linear solvers) | 7.9.0 | `third_party/sundials`, tag v7.9.0, commit 312fc0f3684f27209ca9dc9249d194436eb41a7a | BSD-3-Clause |
8
8
  | KLU (SuiteSparse) | 2.3.6 | `third_party/SuiteSparse`, tag v7.14.1, commit e202a5bcef55f5a780c26830ebd6ff13af193baf | LGPL-2.1-or-later |
9
9
  | BTF (SuiteSparse) | 2.3.3 | the same | LGPL-2.1-or-later |
10
10
  | AMD (SuiteSparse) | 3.3.4 | the same | BSD-3-Clause |
@@ -19,7 +19,7 @@ Also compiled into the modules, under permissive licenses whose texts are in the
19
19
 
20
20
  `mathlib.wasm` and the crate `sbmlsim-mathlib` it is built from (which every native build of the compiler links for constant folding) also contain `exp`, `log` and `pow` of ARM optimized-routines (https://github.com/ARM-software/optimized-routines, commit 20859d3fd9e797dde592c489c8ef7d383f778620: `math/exp.c`, `math/log.c`, `math/pow.c` and their tables), ported to Rust in `crates/mathlib/src/arm`. optimized-routines is under `MIT OR Apache-2.0 WITH LLVM-exception` and is used here under the MIT License, whose text is below.
21
21
 
22
- The extension module of the python package (`sbmlsim_core._core`, the crate `sbmlsim-python`) additionally links mimalloc 3.3.2 statically, the allocator of the extension (`crates/python/src/lib.rs`). Its C sources are vendored in the crate `libmimalloc-sys` 0.1.49, which compiles them with `cc`; mimalloc is under the MIT License (Microsoft Corporation, Daan Leijen) and the crate which wraps it under the MIT License (Octavian Oncescu), both texts below. Nothing else carries mimalloc: it is in no wasm module, in no other crate and in no package of the JavaScript host.
22
+ The extension module of the python package (`sbmlsim_core._core`, the crate `sbmlsim-python`) additionally links mimalloc 3.3.2 statically on every target but macOS, where it allocates through the system allocator and the wheel links none, because two extension modules which each link a copy of mimalloc claim the same two fixed slots of the pthread TLS block there (the allocator of the extension, `crates/python/src/lib.rs`, where the long version is; `sbmlsim_core.__allocator__` reports which of the two a build is). Its C sources are vendored in the crate `libmimalloc-sys` 0.1.49, which compiles them with `cc`; mimalloc is under the MIT License (Microsoft Corporation, Daan Leijen) and the crate which wraps it under the MIT License (Octavian Oncescu), both texts below, which the wheels carry whether or not their platform links it. Nothing else carries mimalloc: it is in no wasm module, in no other crate, in no package of the JavaScript host and in no wheel for macOS.
23
23
 
24
24
  The native Wasmtime hosts (`sbmlsim-host`, the command line and the Python extension) also link Zstandard 1.5.7 for the persistent compilation cache, through `zstd` 0.13.5, `zstd-safe` 7.4.1 and `zstd-sys` 2.1.3. Zstandard and these Rust wrappers are used under BSD-3-Clause; their license texts are below. These cache dependencies are in no Wasm module and in no package of the JavaScript host.
25
25
 
Binary file
Binary file