Sbmlsim Core Python
The python package sbmlsim-core is the compiler and the engine in one extension. It simulates on the native engine: the integrator compiled for the machine of the wheel, with CVODE and SuiteSparse KLU built from their sources, and the model itself as the model.wasm and mathlib.wasm wasmtime compiles. A model compiled from python is the model.wasm and model.json the command line writes, so it runs unchanged in a browser with the JavaScript host .
A Runtime and a model are shared between threads, an instance is one simulation at a time, and model.simulate_many(requests) runs a batch on rayon threads. The same compiled.wasm and compiled.description run unchanged in a browser, see JavaScript , and the same request is the one the Rust host takes.
PyPI has one abi3 wheel for python 3.14 or newer per platform: linux x86_64 and aarch64 (manylinux_2_28), macOS arm64 and x86_64, windows x86_64. Every wheel carries the same model.wasm compiler and the same mathlib.wasm as the npm package of the release, so the math of a model is the same everywhere. There is no source distribution; a build from a checkout needs the toolchain of Installation .
The engine of the wheel ¶
A wheel simulates on the native engine and not on engine.wasm , which is 1.9 to 2.3 times as fast: on the five models of the benchmark of sbmlsim one simulation takes 0.0097 to 37 ms natively against 0.020 to 69 ms with engine.wasm in wasmtime ( Benchmarks , one performance core). The model is model.wasm in both, so only the integrator changes.
What this costs is the last bits. CVODE calls the pow and sqrt of the C library of the platform where the step size is chosen ( SUNRpowerR ), engine.wasm calls those of wasi-libc, so:
a result of a wheel is not bitwise a result of engine.wasm , i.e. not bitwise a result of the same model in the browser or under node ;
a result of a wheel is not guaranteed bitwise across platforms either, since the C library is the platform's.
How large those differences are, measured: on the five models of the benchmark of sbmlsim the integrator took the identical path in the native engine, in wasmtime and under Node, all eighteen configurations of a model, a solver and a Jacobian agreeing on every counter (steps, right hand side evaluations, Jacobian evaluations, nonlinear iterations, error test failures), so nothing of those results moved. On the golden model of crates/host/tests/native.rs , which has events, root functions and a steady state in its request, 3 of 30 values differ and the largest relative difference is 1.0e-14, against an integration at a relative tolerance of 1e-6. So the two engines can differ, and where they do it is near the last bits of a double and far below the error of the integration.
Within one platform and one wheel a result is reproducible as before: the C sources are compiled with -O3 -DNDEBUG -ffp-contract=off -fno-fast-math , so no fused multiply-add and no fast math enter a result, every instance of a model integrates the same way, and a batch gives the results of a serial run bitwise whatever its threads. The differences are those of an integration at the given tolerances, which is what Simulating compares engines at; sbmlsim-core bench --host wasmtime and the JavaScript host are the way to a result of engine.wasm .
Compile and simulate ¶
For ordinary simulations, compile_sbml(sbml_text, parameter_jacobian=False) omits analytic parameter derivatives and the constants used only by them. This reduces compilation and initialization work without changing simulation results. The default is True (0.26.0). Forward sensitivities remain available with False , using numerical parameter derivatives. compile_sbml(sbml_text, driven=["S_ext", "P_ext"]) (0.44.0) drives the species of the ids, as sbmlsim-core compile --driven does ( Compiling a model ): each follows the path X__value + X__slope * (time - driven__t_ref) of three parameters, and the state X__exchange accumulates the amount the model gave to it.
The compiler reads SBML core of any level and version, flat and without a required package but distrib (the uncertainties of its fitted parameters, which are ignored), as the command line does ( Compiling a model ). The request is the one of Simulating . Its nested enums are serde's externally tagged ones: an output is {"uniform": {"steps": 100}} , {"times": [0.0, 1.0]} or, a unit variant and so a bare string, "integrator_steps" (the steps of the integrator, whose number of rows differs by point, which is why simulate_many gives one table per point), and the absolute tolerance of the settings is {"scalar": 1e-12} or {"per_state": [1e-12, 1e-10]} with one value per state in the order of the state vector (a vector of another length is a PointError of that point in a batch):
A request which asks for forward sensitivities answers with them on the output, None without: out.sensitivities.parameters are the ids in the order they were asked for and out.sensitivities.values is a float64 array of the shape (rows, columns, parameters) in C order, the derivative of the column c of the row r in the parameter j at [r, c, j] . They come from the native engine, so a request which asks for them goes through simulate or simulate_many of a model of this package and not through engine.wasm , whose output format has no room for them.
description and initial_values() of a model, description of a compiled model and columns of an output are computed anew by every access, so read them once. The parallelism of simulate_many is min(threads, len(requests)) , and its pool and its per-thread instances live only for the duration of the call (an instance costs 0.3 s to make for a model of 700 kB of description), so give it as many points as you can rather than many small batches: 320 points in one call on 20 threads took 2.09 s against 22.0 s serially.
The allocator of the extension is mimalloc on every target but macOS, where the wheel links none and the system allocator does the work, because mimalloc keeps the heap of a thread in two slots of the pthread TLS block which it claims by compiled in number there, so two extension modules which each link a copy of it corrupt each other's heaps ( sbmlsim_core.__allocator__ is "mimalloc" or "system" , so which of the two a build is comes from the artifact). Where it is linked it is in the wheel and needs nothing of the machine that installs it. A simulation allocates inside the linear memory of the engine and is unchanged by it; the compiler of a model and Cranelift do allocate, so compile_sbml of a model of 919 states takes 21 % less time (124.6 to 98.4 ms), a PBPK model 17 % less, load of the large model 7 % less and an uncached Runtime() 5 % less, and the peak resident set size of such a process falls by 23 %, measured on linux against glibc malloc; what the macOS build gives up is not measured, since it allocates through libmalloc, which is another design. A cold start of a PBPK model spends 560 ms in Runtime() , 3 ms in compile_sbml , 10 ms in load and 0.74 ms in a simulation of 201 points, and a scan of 512 of them takes 445 ms on one thread and 67 ms on eight ( bench/RESULTS.md has the numbers).
model.stepper(settings, changes) (since 0.49.0) is an instance of a model which is advanced from a given state, one interval at a time, for a caller which couples the model to something else and changes its state between two intervals (operator splitting: the transport of species between many instances of a cell model of a tissue). It is initialized as a simulation initializes the model: settings are the settings of the integrator of simulation/1 (a dict, every field left out at its default, the defaults without it) and changes the pre-initialization values of a request (a dict or pairs, in their order: S the amount of a species, [S] its concentration, any other id its value).
advance(t1, state=None, t0=None) integrates from state at t0 (the state and the time of the stepper when they are none) to t1 with the events and the discontinuities of the interval, as a simulation does, and answers an AdvanceResult : the state at t1 , which the stepper holds afterwards, t1 and the steps and rejected steps of the integrator. The integrator starts again for every advance, so a chain of advances is one simulation within the tolerances of the integrator and not to the bit; the triggers of the events, the executions pending and the parameters the events assign carry from one advance to the ( Rust has the semantics). set_state(state, time=None) sets the state without integrating, and an advance from it is the advance from that state to the bit. values(selections) reads the selections of a simulation ( S the amount of a species, [S] its concentration, a reaction its rate, a parameter, a compartment, time ) at the time and the state of the stepper, resolved once and kept for the reads of the same selections, and with the names of libroadrunner the rate of change of a state X' (the right hand side: the amount per time of a species, the rate of a state of a rate rule, 0 for an entity which is no state; a species which stores its concentration is refused) and the unscaled elasticity uec(R, S) , d R / d [S] of a selection (a reaction rate) in the concentration of a species which is a state, with the size of its compartment held: a central difference with the step 6.06e-6 (the cube root of the machine epsilon) times the concentration or, where it is larger, atol / rtol of the state in concentration (the magnitude below which the integrator controls its error absolutely, so the step near 0 does not depend on the unit of the concentration), and below that step (a concentration of 0 included) the one-sided difference of second order. A model of algebraic rules refuses both ( UnsupportedError ). set_values(values) sets values by selection one after the other, as libroadrunner's setValue does: S an amount, [S] a concentration converted with the size its compartment has at that point, any other id the value of its entity, and a compartment which is set keeps the amounts of the species which store their amount, a species which stores its concentration keeps it (unlike the changes of stepper() , which are the simultaneous pre-initialization of PEtab v2 and keep the concentrations). state_ids names the value of every state: [S] of a species which stores its concentration and the id of every other state, the amount of a species among them; parameters and parameter_ids are the parameters of the model in their order, and set_parameters sets some of them by id for the advances after it (the targets of the assignment rules and the constants are computed again, the initial assignments are not). copy() is a new instance with the state, time, parameters and state of the events of its source, which advances from there with the bits of its source (a model of algebraic rules included); memory_bytes estimates the memory of a stepper: the stepper with its integrator and the linear memories of the store of its model, not the description and the code of the model, which the steppers of a model .
A stepper has a store of wasmtime of its own, whose linear memories (the one of the model and the one of mathlib) reserve their size and no more: 1.2 MB of address space per stepper, of which 20 to 45 kB are resident for a cell model, and no memory map of its own, so tens of thousands of steppers fit into a process (40000 of the droplet ischemia-reperfusion model, 20000 in crates/host/tests/stepper.rs ); the address space and the memory of the machine are the limit. (The default of wasmtime reserves 4 GiB and a guard per linear memory, so that compiled code needs no bounds checks: 8.5 GB per stepper, which ran out of address space at 16000 steppers.) The code of a stepper therefore checks the bounds of its accesses, which costs 5 % of an advance (the droplet model 88 to 92 µs per advance of 6 min, the cell model of testdata/models 9.6 to 10.0 µs per advance of 1 min); a simulation of instance() keeps the reserved memories.
A stepper advances without the GIL, so the steppers of one model advance on several threads, each with the bits of one thread; a stepper is locked while it runs, so a second thread which calls it waits. A refused call (a state of the wrong length or with a value which is not finite, an interval which ends before it starts, an id which is no parameter or selection) is a RequestError and changes nothing; an advance which fails is the error of a simulation, after which the stepper raises InternalError .
The steppers run on the native engine of the wheel: their chain of the droplet ischemia-reperfusion model of the liver of the tissue models of pkdb_models agrees with a chain of oneStep of roadrunner over the same 100 steps of 6 min within 200 times the tolerances of the integrator relative to the peak of a selection (68 times at the worst) and within 15000 times row by row for the selections of states, with the absolute tolerance roadrunner applies to the state (5086 times at the worst, the necrosis where it sets in), its rates of change X' within 2e5 times relative to their peak (54441 times at the worst: the rates amplify the difference of the states by the exchange between the fluid and the cell) and its elasticities within 200 times of a central difference of roadrunner, plus the rounding of the difference quotient of the engine (51 times at the worst; roadrunner's own uec is a difference quotient whose step is large near a concentration of 0, 0.8 % off at the hypoxia of the chain), testdata/stepper , recorded by scripts/stepper_oracle.py , and with the steppers of engine.wasm of the JavaScript host within the tolerances, not to the bit ( The engine of the wheel ). The one selection of the record outside of the rule is the concentration of a boundary species of a compartment the changes resize: roadrunner's setValue of a compartment keeps the amounts of its species, the changes of the engine keep their concentrations (the pre-initialization of PEtab v2).
Runtime() enables Wasmtime's persistent compilation cache for engine.wasm , mathlib.wasm and every model passed to load . Later runtimes, including those in another process, reuse the compiled machine code. The SBML-to-Wasm compiler ( compile_sbml ) still runs when called. Keep sharing a runtime and loaded models within a process to avoid repeated setup.
The default directory is Wasmtime's platform cache location, for example $XDG_CACHE_HOME/wasmtime or ~/.cache/wasmtime on Linux. cache_dir accepts a string or a path; relative paths are resolved against the current directory. Passing it with cache=False raises ValueError . The constructor releases the GIL during cache initialization and compilation.
Wasmtime keys entries by the Wasm bytes, its compiler version, CPU features and compilation settings. A changed module or incompatible configuration is compiled again. Missing, unreadable or corrupt entries are treated as misses; an unavailable cache directory also falls back to compilation. Cache files can be deleted to reclaim disk space, and Wasmtime applies its default size and age cleanup policy. The cache contains executable machine code, so choose a local directory writable only by trusted users. It does not contain simulation results or mutable model state. Memory limits and execution deadlines apply to each instance as before, and the wheels remain portable.
sbmlsim_core.chaos is the polynomial chaos expansion of sbmlsim ( sbmlsim.sensitivity.chaos ) in the coordinates of the unit cube of its design: the products of the shifted Legendre polynomials normalized to one, and (since 0.46.0) the fit with the choice of its degree and the Sobol indices of its coefficients, see Sensitivity analysis . The functions are also the names chaos_expansion , chaos_design_matrix and chaos_predict of sbmlsim_core .
The multi-indices are those of sbmlsim.sensitivity.chaos.expansion in its order, and the design matrix is bitwise the one of its design_matrix . A term skips the inputs it does not read, so a basis of many inputs costs per term what its own inputs cost. predict is the product of the design matrix and the coefficients without the design matrix, so a scan of a surrogate of a million points holds no more than its values; coefficients of one value per term give one value per point. supported(n, terms) tells whether n points support a basis of terms terms, POINTS_PER_TERM points per term and a degree of freedom for the correction of the leave-one-out error, the rule by which fit chooses its candidate degrees. fit gives the dictionary of the parameters , the multi_indices , the counts of the terms of every candidate degree, the coefficients , the loo and the degree of every element, the candidate_loo , the indices first_order , total_order and second_order , the mean and the variance . Every function releases the GIL and spreads its work over threads threads (every CPU of the process by default); a value does not depend on them.
sbmlsim_core.petab.Problem (since 0.38.0) is a problem of PEtab v2 read, compiled, simulated and evaluated in Rust (the crate sbmlsim-petab ): Problem.from_yaml("problem.yaml") or Problem.from_files(files, "problem.yaml") of the contents of its files, evaluate() its log-likelihood, chi2 , log priors and simulations at the nominal values of its parameter table or at a point, fit() a fit of its parameters with an optimizer of the engine and fit_problem() the FitProblem of an optimizer of python. Every call holds no GIL. See PEtab .
sbmlsim_core.scan (since 0.45.0) runs a scan of sbmlsim, the request scan/1 , with the planner of the crate sbmlsim-scan : scan.run(request, model, threads=, observe=, on_batch=) on a batch executor of the model, or scan.Scan(request, model) asked for its rounds and told their answers. The result scanresult/1 is a dict whose arrays are arrays of numpy of float64. See Scans .
sbmlsim_core.fitproblem (since 0.48.0) plans the requests fit/1 of a fit of sbmlsim from its document fitproblem/1 with the crate sbmlsim-fitproblem : fitproblem.build(document, models) gives the request of the cost and of the evaluation with the layout of their residuals and the models of the fit, fitproblem.problem(planned) the FitProblem of a request. See Fit problems .
The package carries what a page needs to simulate the models compiled here without a server: sbmlsim_core.runtime_wasm() gives the bytes of engine.wasm , mathlib.wasm and compiler.wasm the extension embeds ( {"engine": ..., "mathlib": ..., "compiler": ...} , the last one the compiler of a page, see the compiler ), sbmlsim_core.plot_wasm() the bytes of plot.wasm , the renderer of the figures in a page (the SVG of render_svg byte for byte, through the C ABI of crates/plot-wasm ), sbmlsim_core.web.script() the inline build of the JavaScript host, one classic script with the global sbmlsimCore , sbmlsim_core.web.figure_script() the script of a static report (the inline build and plot.wasm as base64, which hydrates every with the spec in its child script, see Interactive figures ), and sbmlsim_core.THIRD_PARTY the notices of the libraries of the engine, which a page that distributes it carries. sbmlsimCore.createInlineEndpoint({ bundle, files, engine, mathlib }) is the panel endpoint ( JavaScript ) of a bundle held in memory: bundle the content of bundle.json , files its compiled models by their path in the bundle ( models/ /model.wasm and model.json ), and the workers of its pool start from a blob: URL of the worker the script embeds. So a page which embeds the script, the runtime, a bundle and its models as base64 opens from file:// as well; sbmlsim writes the app of a model so.
sbmlsim_core.chart is the chart builder of the figures, python on numpy but for the thinning of its lines to the points which can be seen, which runs in the extension ( thin_kept_points , the crate sbmlsim-thin ): Chart , ChartPlot and ChartAxis build a figure/1 spec from numbers, quantities of pint and data arrays of xarray (both optional, read by duck typing) and draw it with render_svg and render_png , see Charts . The figures of that page are drawn by scripts/chart_docs.py with an installed wheel of the checkout ( --check compares them), after a change of the page, of the chart builder or of the renderer.
Errors derive from SbmlsimCoreError : CompileError , LoadError (a runtime which cannot start, a model which does not match its description, an instance or a pool which cannot be made) and SimulationError with RequestError , IntegrationError ( flag , time ), UnsupportedError and InternalError . A point of a batch which failed is a PointError ( kind , message , flag , time ) in its position of the result, so one failing request does not fail the batch.
A tag vX.Y.Z publishes the wheels to PyPI together with the npm package ( .github/workflows/publish.yml , trusted publishing): the runtime is built once, every wheel is built with it ( SBMLSIM_CORE_WASM_DIR , .github/workflows/wheels.yml , the linux wheels linked with zig against glibc 2.28), installed in a fresh environment and tested on python 3.14 and 3.15 (windows on python 3.14 alone), and nothing is published unless every wheel and the JavaScript host passed. The wheels are built and tested by every push to develop, and the tag publishes the wheels of the run of its commit; a pull request builds and tests every wheel but the one of macOS x86_64 (see Continuous integration ). A wheel of a checkout is built so:
The full story
This article is one source in a clustered incident — the cluster page carries the summary, timeline and every other outlet covering it.
