Project · Adding a system
Adding a system¶
Adding a system to the catalogue is a one-class contribution. You write the dynamics in the appropriate family method. The registry registers the class at import, shared tests include it, and the documentation build generates a page. Add model-specific tests for numerical identities, reference values or behavior the shared checks cannot establish.
This page is the contributor's recipe. For a gentler, worked introduction to the family contracts, read Defining systems first; this page is the checklist you follow to land a catalogue system.
To distribute models in your own package, use the complete Plugins & extensions example instead.
The three steps¶
- Write the class in the right module under
src/tsdynamics/systems/continuous/or.../discrete/, following the family contract below. Add the class name to the module's__all__. - Add it to the category
__all__—src/tsdynamics/systems/continuous/__init__.pyor.../discrete/__init__.py. (systems/__init__.pyflat-re-exports it automatically asts.systems.MyAttractor.) A registry consistency test fails if you forget this step. - Build the documentation. The same template generates the new page and catalogue entry: equations, parameter descriptions, a runnable example, static and animated views, numerical diagnostics and the literature reference. There is no page to copy or navigation entry to maintain.
What the generated page includes¶
The generator reads the class itself. Ordinary flows get an orbit or time trace; maps reveal successive iterates as points. Declared spatial fields get a movie of the evolving profile or heatmap. Higher-dimensional orbits identify the coordinates in the displayed projection. The same page layout applies to every system.
For meaningful parameter descriptions, put a NumPy-style Parameters section
in the class docstring:
# skip-doctest — class docstring example
class MyAttractor(ts.ContinuousSystem):
"""Three-variable nonlinear oscillator.
Parameters
----------
a : float
Coupling strength between the first two coordinates.
"""
Lyapunov spectra, Kaplan–Yorke estimates and equilibrium searches are computed under recorded conditions, then cached with their numerical source fingerprint. An importable new model is measured automatically in a bounded worker. A timeout, unsupported family or insufficient spectrum produces an explicit explanation; the page never substitutes a literature value or an unrelated built-in model. These are finite-time numerical results, with the method and scope shown beside them. Curated illustration settings can improve a difficult model's view, but are optional.
Use uv run mkdocs serve to inspect the page. For a fast layout preview,
TSD_DOCS_FIGURES=0 TSD_DOCS_PROPS=0 uv run mkdocs build --strict skips new
illustrations and measurements while retaining matching cached results. To
refresh the versioned diagnostic dataset explicitly, run:
That command is a maintainer refresh tool; adding a system does not require hand-wiring a diagnostic record or a documentation page.
The family contracts¶
Every system subclasses one of the four family bases and supplies its dynamics
through the method below. For ODEs, DDEs and SDE coefficients, use symbolic
operations such as symengine.sin, cos, exp, Abs, sign, Min, Max
and ordinary arithmetic. Numeric numpy / math calls and Python control flow
over the symbolic state cannot be lowered. Maps receive a state vector instead
and can use supported NumPy operations through the map tracer.
from symengine import sin, cos
import tsdynamics as ts
class MyAttractor(ts.ContinuousSystem):
"""Short one-liner describing the system."""
params = {"a": 1.0, "b": 2.0, "c": 3.0}
dim = 3
@staticmethod
def _equations(y, t, *, a, b, c): # params are KEYWORD-only, matching keys
x, yv, z = y(0), y(1), y(2)
return (
a * (yv - x),
x * (b - z) - yv,
x * yv - c * z,
)
y(i) reads component i of the state; return exactly dim expressions.
t is the time symbol (autonomous systems ignore it). The Jacobian is
generated automatically by symbolic differentiation — you never write one
(a hand-written _jacobian is only cross-checked in tests, never used at
runtime).
import tsdynamics as ts
class MyDDE(ts.DelaySystem):
params = {"beta": 2.0, "gamma": 1.0, "n": 9.65, "tau": 2.0}
dim = 1
_delay_params = ("tau",) # default; override for non-"tau" names
@staticmethod
def _equations(y, t, *, beta, gamma, n, tau):
yd = y(0, t - tau) # the delayed accessor
return [beta * yd / (1 + yd**n) - gamma * y(0)]
y(i, t - tau) reads the delayed state. A delay value is a structural
quantity and is baked into the engine tape, so sweeping it re-lowers. List
every delay parameter's name in _delay_params if it is not called tau.
Parameters are passed by name, as for an ODE.
import tsdynamics as ts
class MyMap(ts.DiscreteMap):
params = {"a": 1.4, "b": 0.3}
dim = 2
@staticmethod
def _step(X, a, b): # ⚠ params arrive POSITIONALLY, in params order
x, y = X
return (1 - a * x**2 + y, b * x)
@staticmethod
def _jacobian(X, a, b):
x, y = X
return ((-2 * a * x, 1.0), (b, 0.0))
Maps take the whole state vector X and their parameters positionally,
in params-dict insertion order — the engine feeds them positionally when it
lowers _step. __init_subclass__ validates the signature order against
params at import, raising TypeError on a mismatch. A hand-written
_jacobian is optional: the default is generated from _step by symbolic
differentiation. The explicit version above can be useful as an independent
check; the engine still requires a traceable _step to run the map.
import tsdynamics as ts
class MyOU(ts.StochasticSystem):
"""Ornstein–Uhlenbeck: dX = θ(μ − X) dt + σ dW."""
params = {"theta": 1.0, "mu": 0.0, "sigma": 0.3}
dim = 1
@staticmethod
def _drift(y, t, *, theta, mu, sigma): # like _equations
return (theta * (mu - y(0)),)
@staticmethod
def _diffusion(y, t, *, theta, mu, sigma): # one coefficient per component
return (sigma,)
A StochasticSystem is a diagonal-Itô SDE \(dX_k = f_k\,dt + g_k\,dW_k\)
with independent Wiener increments. Both _drift and _diffusion are
symbolic and keyword-only; _diffusion returns one coefficient per
component. _drift is the marker that makes the class a concrete sde in
the registry.
Euler–Maruyama accepts cross-dependent diagonal coefficients. The simplified
Milstein solver requires each g_k to depend only on its own state component
and time, g_k(X_k, t); independent Wiener increments alone are not enough.
Run a custom model¶
A class defined outside the package supports the same public simulation API. Pin an initial condition
(and a seed for the SDE) so the numbers are reproducible:
import numpy as np
import tsdynamics as ts
class MyAttractor(ts.ContinuousSystem):
params = {"a": 0.2, "b": 0.2, "c": 5.7}
dim = 3
variables = ("x", "y", "z")
@staticmethod
def _equations(y, t, *, a, b, c):
x, yv, z = y(0), y(1), y(2)
return (-yv - z, x + a * yv, b + z * (x - c))
traj = MyAttractor(ic=[1.0, 0.0, 0.0]).run(final_time=5.0, dt=0.05)
np.round(traj.y[-1], 3) # → [ 0.647, -1.605, 0.037]
exps = ts.analysis.lyapunov_spectrum(MyAttractor(ic=[1.0, 0.0, 0.0])) # composes for free
A user-defined class registers as non-builtin
(registry.get("MyAttractor").is_builtin is False), so it stays out of the
built-in-only sweeps. Analyses and derived wrappers
accept it according to the same family and capability requirements as a
catalogue system; ts.analysis.find(model) lists the available analyses.
Plotting uses the same trajectory interface.
Publishing a system plugin¶
A separate Python package can add its systems to ts.systems without changing
TSDynamics. The complete package example
includes its directory layout, installation and use. Define the class using the
same family contract, then declare an
entry point in that package's pyproject.toml:
After installing the package, start a fresh Python session. The first import of
tsdynamics.systems discovers installed entries, making the class available as
ts.systems.MyAttractor, through ts.systems.get("MyAttractor"), and in
ts.systems.names() and ts.systems.find(). The entry-point name must match the
concrete class's name and be a public Python identifier. An ordinary user class
without an entry point stays in registry and keeps its own import address.
Plugins remain non-builtin registry entries, so the built-in test sweeps and generated catalogue documentation do not silently expand to installed packages. A broken or invalid entry warns and is skipped. Names already used by a built-in, a namespace member or a different registered system are protected. If multiple distributions publish the same entry-point name, all entries with that name are skipped before their targets are imported; installation order never chooses a model for you.
Optional metadata¶
Use these attributes to describe the model and configure its defaults:
class MyAttractor(ts.ContinuousSystem):
params = {"a": 0.2, "b": 0.2, "c": 5.7}
dim = 3
variables = ("x", "y", "z") # named traj["x"] + labelled figures
_reference = "Rössler (1976), Phys. Lett. A 57, 397-398" # shown in the docs
_doi = "10.1016/0375-9601(76)90101-8" # bare DOI for the reference
_default_ic = (1.0, 0.0, 0.0) # only if random ICs miss the basin
_known_lyapunov = { # opt in to the known-value tests
"spectrum": (0.0714, 0.0, -5.39),
"atol": (0.06, 0.06, 1.5),
"kwargs": {"dt": 0.1, "transient": 100.0, "final_time": 500.0},
"source": "Sprott (2003), Chaos and Time-Series Analysis",
}
| ClassVar | What it does |
|---|---|
variables |
Named component access (traj["x"]) and labelled axes on the auto-figure |
_reference |
Literature citation, surfaced on the docs page and via registry.get(...).reference |
_doi |
Bare DOI for the primary reference (used by the bibliography) |
_default_ic |
Fallback IC when a random U[0,1)^dim start escapes the basin |
_known_lyapunov |
Enrolls the system in test_known_values.py — literature spectra checked continuously |
_structural_params |
For variable-dimension systems (see below) |
_default_method |
"bdf" for a system known to be stiff, so run defaults to the implicit kernel |
_field_shape / _field_labels |
For a spatially-extended (PDE) system whose state is a flattened field |
Variable-dimension systems¶
Anything whose _equations has a loop length or comprehension driven by a
parameter (Lorenz-96, Kuramoto–Sivashinsky, a coupled-oscillator chain) must
declare that parameter as structural, so it is baked into the engine tape:
class Lorenz96(ts.ContinuousSystem):
params = {"f": 8.0, "N": 20}
_structural_params = frozenset({"N"})
Control parameters are read live from the system on every run, so they can
change at runtime with no re-lowering. A structural parameter changes the shape
of the tape, so changing it re-lowers (there is no on-disk cache — it just
re-lowers in-process). If the change also resizes the state or spatial grid, use
system = system.with_params(N=40) so the constructor rebuilds the dimension,
geometry and a matching default initial condition. Assigning system.params.N
directly cannot resize an existing object.
The extra line for DDEs and SDEs¶
The registry sweep is automatic, with two guard-enforced exceptions:
- A new DDE needs a non-equilibrium history in
tests/_sampling.py::DDE_HISTORIES(a history at an equilibrium can fail to exercise the intended non-equilibrium dynamics). A guard test fails until you add one. - A new built-in SDE needs a
{"seed": ..., "ic": ...}entry intests/_sampling.py::SDE_SAMPLES. Asde-family guard test enforces completeness.
Common pitfalls¶
| Situation | What happens |
|---|---|
_equations uses numpy or math |
The tape can't lower it — use symengine.sin / cos / … |
Variable-dim system without _structural_params |
Lowering-time range(N) fails — declare the dimension parameter structural |
Map param order ≠ _step signature order |
TypeError at import |
Forgot the category __all__ |
A registry consistency test fails |
| New DDE with an equilibrium history | The test may only exercise equilibrium dynamics; provide a non-equilibrium history |
PR checklist
- Class follows the family contract (symbolic ops only for flows; positional param order for maps).
- Added to the module
__all__and the category__init__.py__all__. -
variablesandreference(anddoiif known) declared. -
make testgreen locally (a new DDE / SDE also has its test-sampling entry). - PR title is a conventional commit (
feat: add …).
See also¶
- Defining systems — the worked, tutorial-paced introduction to the family contracts.
- Contributing — the quality gates and PR flow this recipe lands into.
- Adding a solver — the other extension path: a new integration kernel for the engine.