Install and check the environment that will run your code
Use the platform-specific installation guide to download the Runtime wheel, create the supported Python environment, install the wheel and activate your licence. The guide gives the current commands for macOS, Windows and Ubuntu. In a terminal belonging to that environment, verify which Python is running and where it imports the package.
python -c "import sys, onesim; print(sys.executable); print(onesim.__file__)"
The first line should identify the Python executable in your selected environment. The second should identify the installed OneSimulation package. If either path belongs to another environment, select the intended interpreter before continuing. For Jupyter, follow the kernel setup and run the same imports inside a notebook cell.
Remember · A notebook kernel is a Python process
Installing a package from one terminal does not automatically change the process executing an open notebook. Inspect sys.executable in the notebook. After installation or an update, restart that kernel and run the cells from the beginning. This avoids combining variables created by different versions of the model.
The example below uses NumPy and Matplotlib alongside OneSimulation. Save the supplied Python file in a writable working folder so the resulting figure has a predictable location. The downloadable notebook performs the same calculation in your local environment.
Run a study from Codex or Claude Code
The Runtime download includes a local Model Context Protocol (MCP) server. It gives your assistant tools to create, save and run supported studies with OneSimulation. You can build stationary heat-conduction models in rectangular plates and boxes, and linear-elasticity models in 3D boxes. Each study uses the physics modules covered by your licence.
- Follow the
README.mdin your platform ZIP. Install the wheel in a Python 3.13 environment with theagentextra, then activate it withonesimulation-license activate-gumroad. Enter the key at the terminal prompt. - Run the Codex or Claude Code registration command in that README. It starts
onesimulation-mcpfrom the installed environment overstdio. SetONESIMULATION_WORKSPACEto the absolute path of the folder where you want to save your projects. See the setup commands. - Open a new session in your assistant, ask it to list your OneSimulation projects, then try the following study with heat conduction enabled.
Create and save a steady heat study for a 2 × 1 × 1 m block with two cells per axis. Use conductivity 4 W/(m·K), density 1,000 kg/m³ and heat capacity 500 J/(kg·K). Hold the left end at 350 K and the right end at 300 K. Insulate the other faces. Run the study and return its run ID, the temperature at the centre and the path to the HDF5 result.
A uniform block with insulated sides has a linear temperature profile. The centre should be 325 K. In the Apple Silicon package test, the saved field contained nine nodes at each of 350, 325 and 300 K. To check your result later, give a new session the same workspace and ask it to retrieve the temperature field using your run ID. Download the 27 nodal temperatures (CSV).
Start with a physical quantity you can predict
A sealed, well-mixed batch contains species A, which converts irreversibly into B. There is no inflow or outflow. A first-order rate coefficient k means each unit of A has the same conversion probability per unit time. With concentrations measured in mol/m³, the model is
Adding the equations gives d(CA+CB)/dt=0. Dividing the first by CA and integrating gives ln(CA/CA0)=−kt. For an initial concentration CA0 and initially absent B, the reference solution is
Choose k=0.8 s⁻¹ and CA0=1 mol/m³. The characteristic time is 1/k=1.25 s. After five characteristic times, CA is about 0.006738 mol/m³. The sum of concentrations should stay one throughout. These are two independent questions for the calculation, time-history accuracy and conservation.
Background · Why this first model has no spatial mesh
Well mixed means the model assumes one concentration for the entire reactor at each time. A lumped mesh represents that state. If diffusion is slow compared with reaction, the same physical vessel can develop concentration gradients and require a spatial model. A successful lumped calculation verifies the computation under its mixing assumption. It does not establish that every real vessel is well mixed.
Connect each part of the physical description to the model
| Object in the example | Physical or numerical role |
|---|---|
ReactionNetworkIR | Names the two species and declares A → B with its rate. Equal composition and particle mass make the reaction balance check meaningful. |
LumpedDomain and ReactionKinetics | Define the spatially uniform reactor and its concentration variables. |
Problem and InitialValue | Collect the physics and the state at time zero. The initial concentration belongs to the physical problem. |
Numerics | Selects lumped spatial representation and fourth-order Runge–Kutta time integration. The time step belongs to the numerical approximation. |
Simulation | Combines the model and method, validates their compatibility and advances the state. |
result.field(...).time_series() | Retrieves times and concentration values for an explicit reference comparison. |
Keeping the initial condition and the time step in their respective roles makes subsequent experiments easier to interpret. Changing k asks another physical question. Reducing the time step asks whether the same physical question has been computed more accurately.
Run the complete OneSimulation example
Download Python script · Download Jupyter notebook
Run python get-started-reaction.py in the environment you checked above. The script builds the model, performs the calculation, prints the comparison and saves get-started-reaction.png in the current working directory. The assertions at the end test the supplied baseline parameters.
OneSimulation · Complete code, measured output and plot
"""First complete OneSimulation model, verified against an exponential solution."""
import numpy as np
from onesim.cad.geometry import LumpedDomain
from onesim.meshing import LumpedMesh
from onesim.numerics import Numerics
from onesim.numerics.discretization import LumpedParameters
from onesim.numerics.time import ClassicalRungeKutta4
from onesim.physics.chemistry import (
ReactionIR,
ReactionKinetics,
ReactionNetworkIR,
SpeciesIR,
)
from onesim.simulation import Problem, Simulation
from onesim.simulation.initial_conditions import InitialValue
import matplotlib.pyplot as plt
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--rate", type=float, default=0.8, help="Rate in 1/s")
parser.add_argument("--initial", type=float, default=1.0, help="Initial A in mol/m³")
parser.add_argument("--step", type=float, help="Time step in seconds (default: 0.05/rate)")
parser.add_argument("--end", type=float, help="Duration in seconds (default: 5/rate)")
args = parser.parse_args()
for value in (args.rate, args.initial, args.step, args.end):
if value is not None and (not np.isfinite(value) or value <= 0):
parser.error("Rate, initial concentration, step and duration must be finite and positive")
k = args.rate
C_A0 = args.initial
C_B0 = 0.0
tau = 1.0 / k
end_time = args.end if args.end is not None else 5.0 * tau
time_step = args.step if args.step is not None else 0.05 * tau
print(
f"k = {k:.3f} 1/s, characteristic time 1/k = {tau:.2f} s, end time = {end_time:.2f} s"
)
network = ReactionNetworkIR(
"first_order_decay",
"1",
species=(
SpeciesIR("A", 0, 1e-27, composition={"H": 1}),
SpeciesIR("B", 0, 1e-27, composition={"H": 1}),
),
reactions=(
ReactionIR("decay", {"A": 1}, {"B": 1}, {"kind": "constant", "value": k}),
),
strict_balance=True,
)
domain = LumpedDomain()
model = ReactionKinetics(domain=domain.system, temperature=300.0, network=network)
C_A = model.concentration("A")
C_B = model.concentration("B")
problem = Problem(
name="First-order reaction decay",
geometry=domain,
physics=(model,),
initial_conditions=(
InitialValue(C_A, C_A0),
InitialValue(C_B, C_B0),
),
)
simulation = Simulation(
problem=problem,
mesh=LumpedMesh(domain),
numerics=Numerics(
spatial=LumpedParameters(),
time_integrator=ClassicalRungeKutta4(),
),
)
simulation.validate().require_valid()
try:
result = simulation.run(start_time=0.0, end_time=end_time, time_step=time_step)
except ValueError as error:
if "negative concentrations" not in str(error):
raise
raise SystemExit("OneSimulation rejected a negative concentration. Reduce --step; "
"the browser's raw RK4 preview shows why this large step fails.") from None
times, num_A = result.field(C_A).time_series()
_, num_B = result.field(C_B).time_series()
exact_A = C_A0 * np.exp(-k * times)
exact_B = C_A0 * (1.0 - np.exp(-k * times))
err_A = float(np.max(np.abs(num_A - exact_A)))
err_B = float(np.max(np.abs(num_B - exact_B)))
rel_error = max(err_A, err_B) / C_A0
print(
f"Maximum absolute error against the exponential: {max(err_A, err_B):.3e} mol/m^3"
f" ({100 * rel_error:.4f} % of C_A0)"
)
mass_error = float(np.max(np.abs(num_A + num_B - C_A0)))
print(f"Maximum mass-balance error C_A+C_B-C_A0: {mass_error:.3e} mol/m^3")
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
ax.plot(times, num_A, "o", markevery=5, label="A computed")
ax.plot(times, num_B, "s", markevery=5, label="B computed")
ax.plot(times, exact_A, "--", label="A exact")
ax.plot(times, exact_B, "--", label="B exact")
ax.set(xlabel="Time (s)", ylabel="Concentration (mol/m³)")
ax.grid(alpha=0.2)
ax.legend()
fig.savefig("get-started-reaction.png", dpi=170)
if k == 0.8 and C_A0 == 1.0 and end_time == 6.25 and time_step == 0.0625:
assert max(err_A, err_B) < 3e-8
assert mass_error < 1e-12
Output from the supplied model
k = 0.800 1/s, characteristic time 1/k = 1.25 s, end time = 6.25 s
Maximum absolute error against the exponential: 1.998e-08 mol/m^3 (0.0000 % of C_A0)
Maximum mass-balance error C_A+C_B-C_A0: 4.441e-16 mol/m^3

For this run the maximum error against the exact concentration is approximately 2.0×10⁻⁸ mol/m³. The concentration-sum error is approximately 4.4×10⁻¹⁶ mol/m³. Final digits can depend on platform and numerical backend.
Try it · Change the reaction and the numerical time step
The browser evaluates the same two concentration equations with classical fourth-order Runge–Kutta. Change the physical rate and initial concentration, then change the numerical step independently. The final time stays at 6.25 s so the curves are directly comparable. The linked OneSimulation script accepts exactly these inputs.
First double k and predict the half-life. Next halve the step and compare the maximum error. Finally choose k=3 s⁻¹ and a 1.25 s step: check whether conservation alone detects the failed decay. The exact curves remain the reference throughout. This browser preview displays raw RK4 values even when they become unphysical. The full OneSimulation reaction model checks concentration admissibility and rejects such a step; reduce the time step before continuing the local simulation.
Open the same model in a Jupyter notebook. Edit the parameters in its first code cell; the stored output shows the default run.
Make three changes and predict their effects first
Change the rate. Double k to 1.6 s⁻¹. The half-life should halve from ln2/0.8≈0.8664 s to about 0.4332 s. The script defines duration and step as multiples of 1/k, so the dimensionless conversion curve against kt stays the same. To compare the two reactions over the same elapsed seconds, prescribe a fixed end time.
Refine the time step. Keep k and the end time fixed and halve the time step. In the resolved regime a fourth-order method should reduce its leading global error by approximately 16. Repeat once more. Compare error at the same physical times, or compare the maximum error against the exact solution sampled on each grid. Near floating-point roundoff the reduction will eventually level off.
Change the initial amount. Double CA0. Both concentration curves should double while their normalised shapes stay fixed. The numerical error in absolute concentration should scale similarly. If you add an initial B concentration, update the exact B solution and the expected conserved sum together.
Remember · A useful numerical check can fail
Deliberately take a very large time step and inspect concentrations. The Runge–Kutta stability polynomial approximates exp(−kh). Outside its useful regime it can produce an incorrect decay despite a preserved sum. Negative concentrations or growth in an irreversible closed decay are physical diagnostics. The baseline assertions may fail after you change parameters. Recalculate the reference and set an accuracy requirement appropriate to the modified experiment.
Write down the parameter set, predicted change, measured change and error for each run. The results guide extends this workflow to field probes, integrals, plots and exported data.
Move from one state to a field
A spatial simulation adds position-dependent unknowns and boundary data. Begin with a one-dimensional diffusion or conduction example from the spatial modelling guide. Identify the governing balance, the material coefficients, the source, and the prescribed value or flux on each boundary before choosing a mesh.
For a slab of thickness L with uniform conductivity k and fixed endpoint temperatures T0 and TL, the steady source-free balance gives d(k dT/dx)/dx=0. Constant k gives T(x)=T0+(TL−T0)x/L and heat flux q=−k(TL−T0)/L. This reference predicts a line and a constant flux. If a computed curve bends, inspect sources, geometry, coefficients and boundary assignments before interpreting it as a new physical effect.
Background · A boundary value and a boundary flux need different checks
A prescribed temperature fixes a field value. A prescribed outward heat flux fixes energy crossing the boundary. For a pure flux problem, the global source and outward flux must balance, and an additive temperature constant may remain undetermined. Adding a physical temperature reference resolves that freedom. Assigning both a value and a flux to the same independent boundary can overconstrain the model.
Record a physical observable such as total heat flow or displacement at a named point. Refine the mesh and compare that same quantity. Then tighten the linear solver tolerance separately. The five-method Poisson example provides a reference for a more systematic discretisation comparison. For CAD geometry, the STEP sleeve tutorial walks through a tensile problem and its analytical displacement scale.
Diagnose an unexpected calculation in order
- Read the first validation or runtime error and identify the object it names. Confirm imports and the active interpreter.
- Check units and physical scales. A millimetre interpreted as a metre changes gradients, areas and volumes differently.
- Inspect the selected regions and boundaries. Confirm that each load and constraint acts on the intended geometry.
- Check balance and limiting behaviour. Zero source, zero load or identical boundary values can provide a simpler reference.
- Change one numerical setting at a time. Compare mesh size, solver tolerance and time step against a fixed observable.
- Save the smallest model that reproduces the discrepancy, together with parameters and the measured error.
The diagnostic guide develops these checks. The solver guide explains linear, nonlinear, transient and coupled calculations after the physical problem has been specified.
Continue with the question you want to answer
- Use the Application Library for an existing model with geometry, inputs, plots, reference checks and a downloadable notebook.
- Use Fundamentals for derivations, prerequisites and exercises in physics, mechanical engineering and numerical mathematics.
- Use the discretisation guide and custom-equation guide when your governing equation or numerical method needs a different formulation.
- Work through the numerical methods lab and its computational exercises to practise comparing methods on controlled problems.