Every model in the corpus¶
The corpus is the project's specification: each model in examples/models/ comes with a
.toml saying what it must do, and tests/test_examples.py runs the pair on every commit.
This page shows what those models are, and it is generated from the same files — a model
added to the corpus appears here without anybody editing this notebook, and a model that
stopped simulating fails the docs build rather than showing a stale picture.
Three things per model: what it teaches, its picture, and its trajectory.
import tomllib
from pathlib import Path
# `..` twice: this notebook is executed from `docs/notebooks/`.
ROOT = Path.cwd()
while not (ROOT / "examples").is_dir():
ROOT = ROOT.parent
MODELS = ROOT / "examples" / "models"
LIBRARY = ROOT / "examples" / "library"
SPECS = {
path.stem: tomllib.loads(path.with_suffix(".toml").read_text(encoding="utf-8"))
for path in sorted(MODELS.glob("*.mo"))
}
print(f"{len(SPECS)} models")
61 models
import matplotlib as mpl
import matplotlib.pyplot as plt
# The same figure style the other notebooks use. A picture does not get to change colour
# halfway down the site, so the surface stays light in both themes.
SURFACE, INK, MUTED = "#fcfcfb", "#0b0b0b", "#52514e"
RAMP = ["#2a78d6", "#eb6834", "#3f9e5a", "#9153c9", "#c2405a", "#0f8b8d"]
mpl.rcParams.update(
{
"figure.figsize": (8.4, 2.9),
"figure.facecolor": SURFACE,
"axes.facecolor": SURFACE,
"axes.edgecolor": MUTED,
"axes.labelcolor": INK,
"axes.spines.top": False,
"axes.spines.right": False,
"text.color": INK,
"xtick.color": MUTED,
"ytick.color": MUTED,
"font.size": 9,
"lines.linewidth": 1.6,
"figure.dpi": 130,
}
)
from IPython.display import HTML, display
from modelica import diagram
from modelica.lang import parse
from modelica.sim import causalize, flatten, simulate
def sources(name: str) -> list[Path]:
"""The model and every library its spec names, in load order."""
spec = SPECS[name]
return [LIBRARY / f"{lib}.mo" for lib in spec.get("requires", [])] + [MODELS / f"{name}.mo"]
def show(name: str) -> None:
"""One entry: what it teaches, its picture, and what it does."""
spec = SPECS[name]
teaches = " · ".join(spec.get("teaches", []))
display(
HTML(
f"<h3 style='margin-bottom:.2em'>{name}</h3>"
f"<p style='margin:.2em 0'>{spec['summary']}</p>"
f"<p style='margin:.2em 0;color:#52514e;font-size:.9em'>{teaches}</p>"
)
)
# The picture, when the model has components to draw. A flat pile of equations has no
# schematic to have an opinion about, and drawing an empty frame would say otherwise.
graph = diagram.of(*(str(path) for path in sources(name)), model=name)
if graph.nodes:
display(HTML(graph.to_svg()))
run = spec.get("simulate")
if run is None:
return
system = causalize(flatten([parse(p.read_text(encoding="utf-8")) for p in sources(name)], name))
result = simulate(
system,
stop=run["stop"],
# Floored at 1e-9: a page does not need the spec's tightest sweep, and the build
# pays for every decade. `absolute` is NOT floored — it defaults to `tolerance`
# inside `simulate`, which is fatal for a model whose states are nowhere near
# order one. E5 runs to 1e-30 and its spec says `absolute = 1.7e-24` for exactly
# this reason; dropping it is how this page failed on a CI runner it had survived
# locally.
tolerance=max(run.get("tolerance", 1e-6), 1e-9),
absolute=run.get("absolute"),
method=run.get("method", "Radau"),
)
# The states are what the model integrates, so they are what a reader wants to see.
# Everything else is derived from them and would only crowd the axes.
shown = [n for n in system.states if not n.startswith("der_")][:6]
figure, axes = plt.subplots()
for index, variable in enumerate(shown):
axes.plot(result.time, result[variable], color=RAMP[index % len(RAMP)], label=variable)
for event in result.events[:40]:
axes.axvline(event.time, color=MUTED, linewidth=0.5, alpha=0.35)
axes.set_xlabel("time (s)")
axes.legend(loc="best", frameon=False, ncols=min(len(shown), 3))
plt.show()
The vertical hairlines are events — the moments the integrator stopped, relocated a zero
crossing, and restarted. A model with none is smooth all the way through; BouncingBall and
Thermostat are mostly hairline.
for name in SPECS:
show(name)
AtwoodPendulum
A swinging Atwood machine on an elastic string carrying a double pendulum: five coupled degrees of freedom, a 4x4 linear block, and a conserved energy that is the only proof the algebra is right.
a Lagrangian model written as equations, not as an ODE · an implicit block the flattener has to solve · energy as an invariant · chaos
BouncingBall
A ball bouncing on the floor: the canonical hybrid model, one state event per bounce.
when · reinit · pre · repeated state events · Zeno behaviour
BouncingBallRest
A bouncing ball that comes to rest: the well-posed companion to BouncingBall, with a discrete flag that sticks it to the floor once a rebound would be smaller than v_min, so the whole run is defined instead of falling through the floor past the Zeno point.
a discrete Boolean state that switches the dynamics (an if-expression on it) · resolving Zeno behaviour with a rest mode rather than a terminal time · when/reinit/pre alongside a discrete assignment
Brusselator
The Brusselator at A = 1, B = 3: two chemical concentrations that feed each other into a steady oscillation with a period of 7.16 -- a stable limit cycle, which every start point is drawn onto and no integrator error can push off.
a limit cycle: an orbit that attracts, where Lotka-Volterra's only persists · a stiffness that comes and goes within one period · the phase plane, y against x, closing on the same loop from any start · a mathematical toy as an integrator benchmark
BuckConverter
An averaged buck converter under PI voltage control. The switching is averaged away into a duty cycle D that a PI loop sets, so the model is smooth: from rest the output rings up past 12 V and the inductor current swings negative as the loop reins it in, then both settle -- 12 V across the load, 2 A through the inductor, D at exactly V_ref/V_in = 0.5. Two asserts guard the averaged switch: D must stay in [0, 1], because a buck can neither invert its output nor boost above its input.
power electronics as an averaged model, no switching events · a duty cycle is the control, bounded to [0, 1] · PI control holds the output against the load · asserts guard a model's physical range
BumpStop
A mass on a spring swinging into an elastic stop: the contact law is a user-written function, inlined into the equations.
function · algorithm section · a one-sided contact law · energy across an event
CSTR
An irreversible exothermic reaction A to B in a cooled continuous stirred-tank reactor. The reaction rate follows Arrhenius, so it climbs with temperature, and the heat it releases climbs the temperature: warm feed ignites the tank to 542 K within seconds, burning off almost all the reactant, and then, its fuel spent and the jacket cooling, the tank falls back and settles on the low-conversion steady state at 324 K.
reaction kinetics coupled to a heat balance · Arrhenius feedback: rate and temperature drive each other · thermal runaway then recovery · one stable operating point reached through an ignition transient
Chua
Chua's circuit at alpha = 15.6, beta = 28, m0 = -8/7, m1 = -5/7: two capacitors, an inductor and a resistor with a kinked, negative-slope characteristic -- the double scroll, chaos in a circuit you can build on a bench.
chaos from a piecewise-linear element: three linear regions, glued · the double scroll, two lobes the trajectory switches between at random · a kink the step-size control has to take without an event · a mathematical toy as an integrator benchmark
CoulombOscillator
A mass on a spring, damped not by a viscous dashpot but by dry (Coulomb) friction: a force of constant magnitude that always opposes the motion. Ideal Coulomb friction is fc*sign(v), which has no derivative where the velocity crosses zero -- awkward for a solver that wants a Jacobian -- so the sign is smoothed to tanh(v/v_eps), the same force away from zero and differentiable through it. Released from rest at x = 1.5 m, the mass swings back and forth, and its amplitude falls by 2*fc/k on every half-swing: a straight-line envelope, the signature of Coulomb damping, where a viscous damper would decay exponentially. The oscillation dies within a few periods and the mass comes to rest at the origin, its energy dropping monotonically to zero.
dry (Coulomb) friction, a constant force opposing the motion · tanh as a smooth, differentiable stand-in for sign, so the Jacobian exists at v = 0 · the linear amplitude decay that tells Coulomb damping from viscous · monotone energy dissipation to rest
CoupledOscillators
Two equal masses, each held by a wall spring and coupled to the other by a third spring, written as a linear state-space system der(z) = A*z with z = [x1, x2, v1, v2]. This is the array-product form: the whole right-hand side is one matrix-vector multiply, the companion matrix A carrying the springs. Started with the first mass pulled aside and the second at rest, the motion is a beat: the two normal modes -- the in-phase mode at frequency 1 and the out-of-phase mode at sqrt(2) -- are excited equally, and their interference passes the energy back and forth between the masses, x1 = (cos(t) + cos(sqrt(2) t))/2 and x2 = (cos(t) - cos(sqrt(2) t))/2. Because the model is linear and undamped it has a closed-form solution and a conserved energy, so it is a benchmark with an exact reference like the Hamiltonian ones, and the first corpus model written as a matrix ODE.
a linear system in state-space form der(z) = A*z, the array-product (matrix-vector) equation · two coupled normal modes and the beat their interference makes · a conserved energy for an undamped linear system, checked as the invariant · a matrix parameter and a vector state, scalarised into the contraction sum
DCMotor
A DC motor started from rest on 12 V: the current spikes, the rotor runs up, and both settle against viscous friction.
two domains in one model · a component that holds components · a parameter passed inward
DCMotorThermal
A loaded DC motor warms as it runs: the winding's ohmic loss heats it, and the hotter winding resists more, so the current settles and then creeps as the temperature climbs.
three domains coupled in one model · temperature feeding back into resistance · heat splitting at a thermal node
DoublePendulum
A double pendulum with unit masses and rods, released from horizontal: the textbook chaotic machine, written in angles so it is an ODE, with its total energy as a variable the run must hold at zero.
chaos in a mechanism with two degrees of freedom · the equations of motion written out, not derived from a constraint · a conserved energy, exposed as a variable and asserted flat · a lower arm that winds: an angle with no bound, against a bounded velocity
DrainingTank
A tank draining through an orifice; the level reaches zero at a known time and must stay there.
if in an equation · a state event · sqrt · a solution that must not go negative
<modelica:DrainingTank>:51: RuntimeWarning: invalid value encountered in sqrt <modelica:DrainingTank>:116: RuntimeWarning: invalid value encountered in sqrt <modelica:DrainingTank>:92: RuntimeWarning: invalid value encountered in sqrt <modelica:DrainingTank>:177: RuntimeWarning: invalid value encountered in sqrt
Duffing
The Duffing oscillator at delta = 0.3, alpha = -1, beta = 1, gamma = 0.5, omega = 1.2: a beam between two magnets, shaken at a steady rhythm, that never settles into one -- one degree of freedom, an explicit function of time on the right-hand side, and chaos.
chaos in a single driven degree of freedom · an explicit function of time in an equation: the drive · a phase plot, v against x, of an orbit that visits two wells · a mathematical toy as an integrator benchmark
E5
E5: chemical pyrolysis over thirteen decades of time, and the corpus model that documents a limit instead of hiding one.
a badly scaled problem · why one tolerance is not enough · cancellation, and the rearrangement that avoids it
FigureEight
The figure-eight three-body choreography: three equal masses moving under their mutual Newtonian gravity, chasing one another around a single closed figure-eight curve. Discovered numerically by Moore and proved to exist by Chenciner and Montgomery, it is the most famous of the periodic three-body orbits, and its initial condition (the Chenciner-Montgomery values used here) is a fixed landmark. Where KeplerOrbit is a single body in a fixed central field, this is the real N-body problem: every body pulls on every other, six coupled inverse-square accelerations, and the orbit stays bounded and periodic only because the three interact just so. It is a conservative Hamiltonian system with several constants of motion held here as invariants -- the energy 0.5*sum|v|^2 - gm*sum(1/r_ij), the total linear momentum (the centre of mass, which stays at the origin), and the total angular momentum, which for this configuration is exactly zero. None is a state the solver integrates, so holding them fixed over a full period is the test; over one period at 1e-10 the energy drifts by about 2.5e-12. After half a period the configuration is its own mirror image (bodies 1 and 2 have swapped places), and after a full period T = 6.3259 every body has returned to where it began.
the gravitational N-body problem: every mass pulls on every other, six coupled inverse-square accelerations · a choreography -- several bodies sharing one closed curve -- the figure-eight being the canonical example · conserved quantities as invariants: energy, linear momentum (the centre of mass) and angular momentum, none of them integrated · a periodic orbit that closes: mirror-symmetric at half a period, back to the start after a full one
FisherKPP
The Fisher-KPP equation, u_t = d * u_xx + r * u * (1 - u): diffusion plus logistic growth, the canonical reaction-diffusion model. Fisher wrote it in 1937 for the spread of an advantageous gene, and Kolmogorov, Petrovsky and Piskunov analysed it the same year; it is the textbook model of a biological invasion, a flame front, or any process where local growth saturates and spreads by diffusion. Discretised by the method of lines on sixteen interior points, the left end is held at the invaded state (u = 1) and the right end empty (u = 0), with the interior starting empty. A front forms at the left and travels right at the asymptotic speed 2 * sqrt(r * d) = 2, connecting the invaded state behind it to the empty state ahead. It is the corpus's third PDE and its first reaction-diffusion one: where TorusHeat is pure diffusion (parabolic) and WaveString a pure wave (hyperbolic), this couples diffusion to a nonlinear local reaction, and the nonlinearity is what makes the front. The comparison principle keeps every u[i] in [0, 1] for all time, and the front only ever advances, both held here as invariants. Sixteen states, so it crosses onto the sparse-Jacobian path with the other two grids -- the reaction adds only a diagonal term, so the pattern stays tridiagonal.
reaction-diffusion: a diffusion term coupled to a nonlinear local reaction, the class behind pattern formation and invasion fronts · the Fisher-KPP travelling front, invading the empty state at speed 2*sqrt(r*d) · the method of lines on a reaction-diffusion PDE, with a held (Dirichlet) boundary driving the invasion · the comparison principle as an invariant: the solution stays between its two equilibria, 0 and 1, for all time
Genset
A governed generator set: a PI speed governor runs the shaft up to 100 rad/s, and when a resistive load is switched on at t = 1 s the speed dips to 94 and the governor pulls it back, the classic load-rejection test of a genset.
a speed governor rejecting a load · an event switches a load on · electrical braking couples into the shaft · the integrator holds the speed with no offset
HIRES
HIRES: eight reactants of photomorphogenesis, and the first corpus model checked against a published reference rather than against ourselves.
mild stiffness · a published reference solution · conservation between two species
HeatBar
A rod split into eight cells, hot at one end and insulated at the other: the method of lines, which is arrays and a `for` equation and nothing else.
a declared shape · a `for` equation · subscripts · a structural parameter
HeatExchanger
A heat exchanger as three lumped thermal masses: a hot fluid stream, the wall that separates it from a cold stream, and the cold stream. Each stream carries enthalpy in and out with its flow, and gives up or takes on heat by conduction across the wall. The wall has its own heat capacity, so it lags -- heat the hot stream sheds does not reach the cold stream at once but soaks into the wall first. Starting with everything at the cold inlet temperature, hot fluid flows in and the three temperatures climb toward a steady state where the heat the hot stream loses exactly equals the heat the cold stream gains. Throughout, the temperatures stay ordered hot > wall > cold, which is the direction heat flows through the exchanger.
a flow-through thermal system: enthalpy carried by a stream, q*(T_in - T) · conduction across a wall coupling two streams · wall thermal inertia, which delays the transfer between the streams · a temperature ordering that fixes the direction of heat flow
HenonHeiles
The Henon-Heiles system: a star moving in the plane of an axisymmetric galaxy, the two-degree-of-freedom Hamiltonian introduced to ask whether such an orbit has a third integral of motion. The potential 0.5*(x^2 + y^2) + x^2*y - y^3/3 is a harmonic well with a cubic distortion that couples the two coordinates and opens three escape channels at the energy 1/6. Below that the motion is bounded inside a triangular well: quasi-periodic and regular at low energy, mixing into chaos as the energy rises toward escape. Run here at energy 0.1125, a regular orbit that two good integrators reproduce point for point over fifty time units. Its reason for being in the corpus is the same as Kepler's: the energy is a conserved quantity the integrator must hold, and on a Hamiltonian system it is the invariant, not the trajectory, that measures the scheme.
a two-degree-of-freedom Hamiltonian with a cubic coupling potential · energy conservation as the invariant that grades a conservative integration · bounded motion below the escape energy 1/6, regular at this energy · a second Hamiltonian benchmark beside Kepler, non-integrable rather than closed-form
KeplerOrbit
The Kepler two-body problem: a light body orbiting a fixed mass under inverse-square gravity, the benchmark every book on Hamiltonian simulation opens with. Started at perihelion with the velocity for eccentricity 0.6, it traces an ellipse of semi-major axis 1 and period 2*pi, swinging fast and close past the centre (perihelion r = 0.4) and slow and far at aphelion (r = 1.6). It is a conservative Hamiltonian system with two constants of motion: the energy 0.5*(vx^2 + vy^2) - mu/r and the angular momentum x*vy - y*vx. Neither is a state the solver integrates -- they are quantities that must stay fixed if the integration is faithful -- so holding them constant over three orbits is the real test. A non-symplectic method like Radau conserves them to a tolerance that grows with the horizon; over these three orbits at 1e-11 the drift is below 1e-12.
the Kepler two-body orbit, the canonical Hamiltonian benchmark · conserved quantities as invariants: energy and angular momentum, not integrated but held · an eccentric ellipse: fast perihelion, slow aphelion, closed after one period · why a conservative system stresses an integrator differently -- the invariant, not the trajectory, is what drifts
Kuramoto
The Kuramoto model, the canonical account of how coupled oscillators fall into step: four phase oscillators, each running at its own natural frequency, each pulled toward every other by the sine of their phase difference, der(theta_i) = omega_i + k/n * sum_j sin(theta_j - theta_i). It is the model behind fireflies flashing together, pacemaker cells, power-grid generators staying in phase and a room of metronomes on a shared table syncing up. With the coupling k below a critical value the oscillators drift apart, each keeping its own frequency; above it -- k = 1.5 here, against a frequency spread of 1.2 -- they lock, holding a fixed pattern of phase offsets and rotating together at the mean frequency, which is zero for this symmetric set, so the locked cluster stands still. The order parameter r = |mean(exp(i*theta))|, written here as sqrt(mean(cos)^2 + mean(sin)^2), measures how tight the cluster is: 0 when the phases are spread evenly around the circle, 1 when they coincide. Started spread out (r = 0.05) it climbs to r = 0.95 and holds, the signature of synchronisation. It is the corpus's first model of a coupled-oscillator network and its first with a synchronisation transition, distinct from the chaotic tumblers and the reaction oscillators by pulling many rhythms into one.
the Kuramoto model: N phase oscillators coupled through the sine of their phase differences · synchronisation: above a critical coupling the phases lock into a fixed pattern and rotate together · the order parameter r as the measure of coherence, climbing from incoherent (0) to synchronised (1) · an all-to-all coupled network written as a sum over every other oscillator
Lorenz
The Lorenz system at sigma = 10, rho = 28, beta = 8/3: three smooth equations whose solution never repeats -- the butterfly, and a benchmark for how fast an integrator's error grows.
deterministic chaos from three smooth equations · a phase plot, where the x axis is a state and not time · error growth as the real limit on a long integration · a mathematical toy as an integrator benchmark
LotkaVolterra
Lotka-Volterra prey and predators at alpha = 1.1, beta = 0.4, delta = 0.1, gamma = 0.4: two populations on a closed orbit with a period of 14.3, and a conserved quantity that says exactly how far an integrator has drifted.
a conserved quantity as the sharpest test of a long integration · a closed orbit in the phase plane, x against y · populations that fall to a few hundredths and recover: a range of three decades · a mathematical toy as an integrator benchmark
MagLev
A steel ball levitated under an electromagnet: the magnetic pull rises as the inverse square of the gap, so the open loop is unstable, and PD feedback on the coil voltage holds the ball at a 10 mm gap, catching it from a 2 mm displacement.
an open-loop-unstable plant held by feedback · a nonlinear force law · electrical and mechanical coupled through a coil · the equilibrium current balances gravity
MassSpringDamper
A mass on a spring and damper released from 1 m: the same second-order physics as the RLC circuit, through a different domain's connectors.
translational connectors · three components on one flange · domain analogies
MixingRing
A closed ring of N stirred tanks pumped one way around the loop: each tank is fed from its predecessor and drains to its successor at the same rate, so der(c[i]) = k * (c[i-1] - c[i]) with the predecessor wrapping around periodically. Every row of the transport matrix sums to zero, so the total tracer sum(c) is conserved exactly for all time; the model states that total as an algebraic variable and it stays at its starting value. A tracer injected in one tank (c = {4, 0, 0, 0}) advects around the loop while it disperses -- the transport matrix has a conjugate pair of complex eigenvalues, so the pulse circulates as it decays -- and every tank settles to the common mean, one. It exercises the array reductions on a physical conservation law: sum(c) for the conserved total, and min(c) in an assert that guards the model's positivity (a well-posed mixing model never makes a concentration negative).
a closed conservation law written as an array equation: a directed transport ring der(c[i]) = k * (c[i-1] - c[i]) whose rows sum to zero · sum() over an array as a conserved total, held as an algebraic variable and constant for all time · min() over an array in an assert, guarding the positivity of a well-posed mixing model · advection around a loop with dispersion: complex eigenvalues carry the pulse around while it relaxes to the uniform mean
NewtonCooling
A hot object cooling toward ambient: one state, one equation, closed-form answer.
der · parameter · start/fixed · a scalar ODE
PIControl
A first-order plant under PI control: the setpoint steps to 1, the loop overshoots by 8 percent and settles.
input and output connectors · a signal is directed · a closed loop · block diagrams
Pendulum
A point mass on a rigid rod in Cartesian coordinates: an index-3 DAE that cannot be simulated without index reduction.
a constraint equation · index 3 · Pantelides · dummy derivatives · consistent initialisation
PhaseChange
A steel bar heated, held and quenched: JMAK and Koistinen-Marburger kinetics, with the latent heat of transformation feeding back into the temperature that drives it.
phase-transformation kinetics · fractions that must sum to one · a rate that depends on the derivative it drives · a simultaneous block that came from the physics · a prescribed schedule with state events
ProbeLC
The same Electrical.Probe rig with an inductor redeclared into the slot: one modification turns a first-order charge into a second-order oscillation.
redeclare · a constraining clause · one model text, two circuits
ProbeRC
The Electrical.Probe rig with the element it declares by default -- a resistor, so the capacitor charges on an RC curve.
replaceable · a default element · one model text, two circuits
Projectile
A ball thrown straight up at 30 m/s, with quadratic air drag opposing its motion. Which force law acts is chosen by a structural if-equation on the Boolean parameter `drag`: with drag on, the ball feels gravity plus a resistance proportional to the square of its speed and always pointing against the velocity; with drag off, only gravity, the textbook vacuum parabola. Drag makes the flight asymmetric -- the ball is decelerated harder on the way up than gravity alone would (so it climbs less), and on the way down it is held back toward a terminal speed, so it falls slower than it rose. The apex, 33.5 m, sits well below the 45.9 m a vacuum shot would reach. The if-equation is resolved when the model is flattened, so this is the drag branch; flipping the parameter reflattens to the vacuum one.
a structural if-equation choosing the equations from a parameter, resolved at flatten · quadratic air drag, cd*v*abs(v), a force that always opposes the velocity · the asymmetric rise and fall drag gives a projectile, unlike the symmetric vacuum parabola · approach to a terminal velocity on the way down
PumpTank
A DC motor drives a positive-displacement pump that fills a tank. The empty tank offers no head, so the motor first races to 113 rad/s, then as the water rises the head loads the shaft back down to 50 rad/s and the current climbs to 14 A. Three domains and three separated timescales: the armature settles in hundredths of a second, the tank fills over minutes.
electrical, rotational and hydraulic in one model · well-separated timescales in one run · a rising head is a load that grows with the state it fills · steady state is inflow equal to outflow
PurePursuit
A pursuer under pure-pursuit guidance: it always steers its heading toward a fixed target, turning at a rate proportional to the bearing error. The bearing is atan2 of the relative position, so the steering law depends on where the pursuer is. Starting abeam of the target and heading the wrong way, it swings its heading onto the line of sight within two seconds and then runs straight down it, closing the range steadily -- the geometry a homing missile or a dog chasing a ball traces out.
pure-pursuit guidance, heading toward a moving bearing · atan2 of a state: the bearing depends on where the pursuer is · a heading law that turns proportional to the bearing error · convergence onto the line of sight, then a straight run-in
RCCircuit
A capacitor charging through a resistor: the smallest model built out of connected components.
connect · flow variables · extends · hierarchical names · alias equations
RLCCircuit
A series RLC circuit stepped with 1 V: two coupled states, an underdamped ring-down.
two states from two components · a coupled linear system · connect
RigidBodyFlip
A torque-free rigid body tumbling about its principal axes, governed by Euler's equations: I1*w1' = (I2 - I3)*w2*w3 and its two cyclic permutations. The three principal moments of inertia are distinct (1, 2, 3), and the body is set spinning almost exactly about the intermediate axis (axis 2, whose inertia lies between the other two). That spin is unstable: w2 holds nearly steady for a while, then flips sign in a quick tumble, settles, and flips back, over and over. This is the tennis-racket theorem (flip a racket about its intermediate axis and it rotates half a turn about the handle) and the Dzhanibekov effect, which a cosmonaut famously filmed a wing-nut doing in orbit. Unlike the chaotic tumblers, the torque-free rigid body is integrable -- the motion is exactly periodic, expressible in Jacobi elliptic functions -- so the flips recur on a fixed period (about 15.2 here). It is a conservative system with two constants of the motion: the rotational kinetic energy 0.5*(I1*w1^2 + I2*w2^2 + I3*w3^2) and the squared magnitude of the angular momentum (I1*w1)^2 + (I2*w2)^2 + (I3*w3)^2. Neither is integrated; holding both fixed across several flips is the test.
Euler's equations for a torque-free rigid body: three coupled quadratic rates about the principal axes · the intermediate-axis (tennis-racket) instability: a spin about the middle axis flips, one about the largest or smallest is stable · two constants of the motion as invariants: rotational kinetic energy and the magnitude of the angular momentum · an integrable nonlinear system whose flips recur on a fixed period, distinct from a chaotic tumble
RoastingMachine
A Loring S15 coffee roaster over one batch: gas on a clock, water on a threshold, and a probe that lags both.
time in an equation · time events beside a state event · a parameter computed from other parameters · modelling the sensor, not just the thing measured · checking a model against a real machine · an event the model owns -- the drop -- named by the flag it sets
Robertson
Robertson's autocatalytic reaction: the standard stiff benchmark, spanning ten decades in time.
stiffness · why an explicit solver is not enough · mass conservation
Rossler
The Rössler system at a = 0.2, b = 0.2, c = 5.7: a spiral in the x-y plane that a single nonlinear term folds back on itself -- chaotic like Lorenz, but with an error growth an order of magnitude slower, so a solver stays right for hundreds of time units.
chaos from one nonlinear term · a slow Lyapunov exponent: where pointwise checks still mean something late in a run · a phase plot in x-y, and the fold in z · a mathematical toy as an integrator benchmark
SIR
The Kermack-McKendrick SIR model, the equation every account of an epidemic starts from: a population split into susceptible, infected and recovered fractions, with s' = -beta*s*i, i' = beta*s*i - gamma*i, r' = gamma*i. Susceptibles meet infectives and are infected at rate beta*s*i; infectives recover (or are removed) at rate gamma*i. Nobody is created or destroyed, so s + i + r stays at 1 for all time -- the conservation law that makes this a compartmental model, the first invariant, and exactly the sort of quantity the derive box can now plot and watch hold flat. With the basic reproduction number R0 = beta/gamma = 4, the infected fraction climbs to a peak near 0.41 and falls. The peak is not where the susceptibles run out: it is exactly where the susceptible fraction crosses gamma/beta = 1/R0 = 0.25, the level at which each case stops replacing itself, and it happens with three quarters of the population still susceptible. The epidemic then burns out with a fraction s_inf = 0.0196 never infected at all -- it ends because infectives recover faster than they are replaced, not because there is no one left to infect. It is a plain smooth ODE, three states, and it earns its place as the corpus's first compartmental / epidemiological model, distinct from the predator-prey and reaction-kinetics oscillators by being a strictly monotone burn-through with a single conserved total.
the SIR compartmental model: three coupled rates for susceptible, infected and recovered fractions · conservation as an invariant: s + i + r = 1 for all time, a linear constant of the motion · the epidemic threshold: the infected fraction peaks when s crosses gamma/beta = 1/R0, not when susceptibles run out · the final size: an epidemic ends with a fraction never infected, because recovery outpaces new infection
SaturatingServo
A voice-coil position servo under PD control whose actuator voltage saturates. A step to 1 m asks the PD law for 50 V, four times what the amplifier can deliver, so the command clips to +12 V and the coil drives at its limit: the mass accelerates flat-out, the loop only regains control as it nears the setpoint, and it settles on 1 m with no standing error. The saturation is a max(-Vmax, min(Vmax, u)) in the control law, so the model is nonlinear where a textbook servo is not.
actuator saturation, the nonlinearity every real servo has · min/max in a model and its effect on the response · a step larger than the actuator can serve drives it open-loop first · PD position control settling to its setpoint
SchwarzschildOrbit
A test mass on a timelike geodesic of the Schwarzschild metric: an orbit around a non-rotating black hole, the general-relativistic version of the Kepler two-body problem. In geometrized units (G = c = 1) with the black-hole mass as the length scale, the equatorial radial motion is governed by an effective potential (1 - 2M/r)(1 + L^2/r^2) whose Newtonian pieces (gravity and the centrifugal barrier) are joined by a purely relativistic -3*M*L^2/r^4 term. That extra term is what makes a bound orbit fail to close: instead of a fixed ellipse it precesses, tracing a rosette. Started at r = 20M with angular momentum L = 4M, the orbit swings between perihelion 8.2M and aphelion 20M, advancing about 2.78 radians of precession on every radial cycle -- Mercury's 43 arcseconds a century, but in the strong field where the effect is enormous. The specific energy is conserved for all time, held here as the invariant that grades the integrator, exactly as in the Newtonian benchmarks.
a timelike geodesic of Schwarzschild, the relativistic two-body orbit · orbital precession from the relativistic -3*M*L^2/r^4 term, a rosette not an ellipse · energy conservation as the invariant, extending the Kepler/Henon-Heiles line into GR · geometrized units G = c = 1 with the mass as the length scale
ServoDrive
A DC motor under PI speed control: the loop brings the shaft from rest to a 100 rad/s setpoint, overshoots by 19 percent, and settles with no standing error because the integrator carries the holding voltage.
a control loop closed on a physical plant · three domains in one model · the integrator kills the steady-state error · overshoot from loop gain
Setback
A room following a two-position setpoint chosen by an enumeration: the clock picks day or night, and the room follows with one time constant.
enumeration · an ordinal encoding · a state event on a schedule
SphericalPendulum
A spherical pendulum: a bob on a rigid rod free to swing in all directions, so it traces a path on a sphere rather than in a plane. In the angles (theta from the downward vertical, phi around it) the motion is the Lagrangian one -- theta feels gravity and the centrifugal push of the azimuthal spin, phi is carried by the Coriolis term that conserves the vertical angular momentum sin(theta)^2 * w_phi. Started at theta = 1 rad with a pure azimuthal rate, the bob does not fall through the bottom (the angular-momentum barrier keeps theta away from zero) nor reach the top; it oscillates in theta between about 0.47 and 1.0 rad while phi precesses, so the trace is a rosette wrapped on the sphere. Two quantities are conserved for all time -- the energy and the vertical angular momentum -- and they grade the integrator exactly as in the Kepler, Henon-Heiles and Schwarzschild benchmarks. Because the rod is rigid the radius is constant, so the state reads directly as spherical coordinates (r, theta, phi): it is the corpus's first genuine spherical-coordinate trajectory.
a 2-degree-of-freedom pendulum in three dimensions, the Lagrangian angular equations · conserved energy and vertical angular momentum as the invariants, extending the Hamiltonian line · the Coriolis coupling that keeps the bob off the poles (the sin(theta) in the denominator) · a genuine spherical-coordinate trajectory (constant r) for the 3-D spherical view
SyncGenerator
A synchronous generator tied to an infinite bus, as the swing equation. The rotor angle delta measures how far the machine leads the grid; the electrical power it delivers is Pmax*sin(delta), so the angle both sets the power and is driven by the imbalance between mechanical power in and electrical power out. Started 0.36 rad below its operating angle, the rotor accelerates, overshoots to 0.70 rad, and the damping rings it down to the equilibrium delta = asin(Pm/Pmax) = 0.5625 rad (32 degrees), where the two powers balance.
electromechanical coupling: rotor angle sets electrical power and is driven by it · the swing equation, a driven damped oscillator that is not a constraint pendulum · a stable machine damps to its power-angle equilibrium · an assert guards against losing synchronism
Thermoelectric
A thermoelectric generator warming up: heat from a 500 K source raises the hot junction, the Seebeck effect drives a current into a matched load, and the current carries heat back (the Peltier effect), so the junction settles at 433 K delivering 11 W.
thermal and electrical coupled both ways · the Seebeck effect makes a current from a temperature difference · the Peltier effect makes the current carry heat · a solid-state heat engine
Thermostat
A heater with hysteresis: the regime is remembered between events, not re-decided from the temperature.
a discrete variable that holds its value · pre() · two `when` clauses that disagree · hysteresis
TorusHeat
The heat equation on a flat torus: diffusion over an 8-by-8 grid whose edges wrap around, so every cell has four neighbours and there is no boundary. It is the method of lines in two dimensions -- the space discretised into cells by hand, the time left continuous -- exactly the recipe HeatBar uses in one dimension, now on a periodic domain, the simplest manifold a PDE can live on. The initial temperature is a single grid Fourier mode, cos(2*pi*(i-1)/n)*cos(2*pi*(j-1)/n), which is an exact eigenvector of the discrete periodic Laplacian. So the whole field keeps its shape and decays uniformly at the eigenvalue's rate, and the solution is known in closed form: T(t) = T(0) * exp(lambda*t) at every cell, with lambda = 4*a*(cos(2*pi/n) - 1). That makes it a PDE benchmark with an exact reference, not another integration, and a first concrete rung toward fields on curved manifolds.
the heat equation in two dimensions by the method of lines, arrays and a nested `for` · periodic boundaries by index wrap-around (mod), the torus as a manifold with no edge · an initial condition set by an `initial equation` over the grid indices · a diffusion eigenmode: an exact closed-form decay to check the discretisation against
TwoBodyHeat
Two thermal masses equilibrating through a conductor; total energy is conserved exactly.
connectors in a second domain · a conservation law as an invariant
TwoFalls
Two bodies in free fall from different heights, reaching one shared gravity through inner/outer rather than through a wire.
inner/outer · a shared environment · equal acceleration
TwoInertias
Two inertias bolted to one shaft and braked: the constraint is between two states, so the index is 3 and the two candidate state sets are indistinguishable.
index reduction across a rotational constraint · a symmetric choice of dummy derivatives · candidate state sets
TwoTank
Two tanks in series, filling from a constant inflow and draining by gravity. The first tank drains into the second through a coupling valve whose flow follows Torricelli's law -- proportional to the square root of the level DIFFERENCE between the tanks -- and the second drains to atmosphere through its own valve, proportional to the square root of its own level. Because the coupling flow depends on both levels, the tanks interact: the second tank's level feeds back into how fast the first one drains. Starting nearly empty, both levels climb toward a steady state where the inflow exactly balances each outflow. This is the textbook interacting-tank process, the level-control example every process-dynamics course opens with.
an interacting two-tank level system, the canonical process-control plant · Torricelli outflow: valve flow proportional to the square root of the head · coupling through a level difference, so one tank's state changes another's drain rate · approach to a hydraulic steady state where inflow balances outflow
VanDerPol
The van der Pol oscillator at mu = 1000: a relaxation limit cycle whose step size has to swing over three orders of magnitude.
stiffness from a nonlinearity · step-size control · why a fixed step is hopeless
WaveString
The wave equation on a string of length 1 with both ends held fixed, discretised in space by the method of lines: n interior points, each obeying u'' = c^2 * (the second difference of its neighbours), the same recipe HeatBar and TorusHeat use but for a hyperbolic equation rather than a parabolic one, so the string oscillates instead of decaying. The initial shape is the fundamental mode sin(pi*x), an exact eigenvector of the discrete Laplacian with fixed ends, so the string keeps its shape and swings at a single frequency -- a standing wave. On the grid that frequency is omega = (2c/h) sin(pi/(2(n+1))), a hair below the continuum pi*c, and the solution is known in closed form, u_i(t) = sin(pi*i/(n+1)) cos(omega t), which makes it a PDE benchmark with an exact reference. The energy, kinetic plus the spring energy of the grid, is conserved: the wave counterpart of the Hamiltonian benchmarks, and the second PDE in the corpus after the heat equation.
the wave equation in one dimension by the method of lines, a hyperbolic PDE as a first-order system der(u) = v, der(v) = c^2 * Laplacian(u) · fixed (Dirichlet) ends by dropping the missing neighbour in the boundary rows · a standing wave: a discrete Laplacian eigenmode oscillating at an exact closed-form frequency · a conserved energy for the discretised string, the wave analogue of the Hamiltonian invariant