Skip to content

Backends

Define the backends, which write the numeric functions that solvers call.

They are NumPy, the default, Numba, which compiles the functions to machine code for large groups, and JAX, which also gives their derivatives, such as LogisticGrowthSystem(backend=NumbaBackend()).

BaseBackend

Bases: BaseConfig[None, LoweredKernelsSpec]

An abstract backend, which writes the numeric functions of a compiled problem.

A system compiles its laws into kernels, and a backend turns them into the functions a solver calls, such as the rate function f(t, x, p) of x' = f(t, x, p). It stores its settings in __init__, prepare() takes nothing, and run(kernels) keeps the functions in functions_. A subclass names itself with _get_name and says what it can write with _get_support. One backend runs the growth of a herd, a spin lattice, and an epidemic on a network.

Read more in the user guide, under Backends.

Attributes:

Name Type Description
functions_ LoweredFunctionsSpec

The numeric functions of the form of the kernels of the last run.

See Also

NumpyBackend: Writes the functions with NumPy, the default. NumbaBackend: Compiles the functions to machine code. JaxBackend: Writes functions that JAX differentiates.

Examples:

>>> from skcomplex.core.engine.backends import BaseBackend, NumpyBackend
>>> isinstance(NumpyBackend(), BaseBackend)
True

get_supported_tags() classmethod

Return the capability tags the backend supports.

They come from the classes of time, space, and laws it supports.

Returns:

Name Type Description
tags Tags

The supported times, spaces, and law kinds, where an empty field supports any value.

Examples:

>>> from skcomplex.core.engine.backends import JaxBackend
>>> sorted(JaxBackend.get_supported_tags().space)
['none']
Source code in src/skcomplex/core/engine/backends/_base.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
@classmethod
def get_supported_tags(cls) -> Tags:
    """Return the capability tags the backend supports.

    They come from the classes of time, space, and laws it supports.

    Returns:
        tags:
            The supported times, spaces, and law kinds, where an empty field supports any value.

    Examples:
        >>> from skcomplex.core.engine.backends import JaxBackend
        >>> sorted(JaxBackend.get_supported_tags().space)
        ['none']
    """
    return cls._get_support().get_tags()

JaxBackend

Bases: BaseBackend

A backend that writes discrete maps and differential equations as JAX functions.

It writes the rate function f(t, x, p) of x' = f(t, x, p), or the next state of a map, as a function that returns new arrays, so JAX can compile it, run it on a GPU, and take its gradient, as in System(..., backend=JaxBackend()). The functions in functions_ take and return NumPy arrays in double precision, and traced_ is the pure JAX function. Rule, noise, and jump laws, sums over neighbourhoods, and laws given as Python functions have no JAX form. The rates of an epidemic are fitted by gradients, a neural differential equation is trained, and the parameters of a circuit are tuned.

Read more in the user guide, under Backends.

Attributes:

Name Type Description
functions_ LoweredFunctionsSpec

The forward functions of the form of the kernels of the last run, on NumPy arrays.

traced_ TracedFunction

The pure JAX function f(t, x, p) of the form of the kernels of the last run, the drift of ordinary differential equations or the update of a discrete map.

See Also

NumpyBackend: Writes the functions with NumPy, the default. NumbaBackend: Compiles the functions to machine code.

Examples:

>>> from skcomplex.core.engine.backends import JaxBackend
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> system = LotkaVolterraSystem(backend=JaxBackend()).prepare()
>>> system.simulate(until=1.0).problem.backend
'jax'

advance(function, t, t1, x, p, *, form, throw=True) staticmethod

Return the state after one step of a pure function, traced by JAX.

A discrete map applies its update once, and ordinary differential equations are solved from t to t1 by diffrax.diffeqsolve with Tsit5, a PID step size controller, and recursive checkpointing, so gradients flow through the step.

Parameters:

Name Type Description Default
function TracedFunction

The pure function f(t, x, p), the update of a map or the drift of ordinary differential equations.

required
t TracedArray

The time of the state.

required
t1 TracedArray

The time after the step.

required
x TracedArray

The state.

required
p TracedArray

The parameter vector.

required
form FormKind | str

The form of the function, a discrete map or ordinary differential equations.

required
throw bool

Whether a solve that fails, such as one that reaches its largest number of steps, raises an error, or else returns states that are not finite, as samplers that reject such proposals need.

True

Returns:

Name Type Description
state TracedArray

The state at t1.

Source code in src/skcomplex/core/engine/backends/_jax.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@staticmethod
def advance(
    function: TracedFunction,
    t: TracedArray,
    t1: TracedArray,
    x: TracedArray,
    p: TracedArray,
    *,
    form: FormKind | str,
    throw: bool = True,
) -> TracedArray:
    """Return the state after one step of a pure function, traced by JAX.

    A discrete map applies its update once, and ordinary differential equations are solved from `t` to `t1` by
    `diffrax.diffeqsolve` with `Tsit5`, a PID step size controller, and recursive checkpointing, so gradients flow
    through the step.

    Args:
        function:
            The pure function `f(t, x, p)`, the update of a map or the drift of ordinary differential equations.

        t:
            The time of the state.

        t1:
            The time after the step.

        x:
            The state.

        p:
            The parameter vector.

        form:
            The form of the function, a discrete map or ordinary differential equations.

        throw:
            Whether a solve that fails, such as one that reaches its largest number of steps, raises an error, or
            else returns states that are not finite, as samplers that reject such proposals need.

    Returns:
        state:
            The state at `t1`.
    """
    if form == FormKind.DISCRETE:
        return function(t, x, p)
    solution = diffrax.diffeqsolve(
        diffrax.ODETerm(function),
        diffrax.Tsit5(),
        t0=t,
        t1=t1,
        dt0=None,
        y0=x,
        args=p,
        saveat=diffrax.SaveAt(t1=True),
        stepsize_controller=diffrax.PIDController(rtol=1e-10, atol=1e-10),
        adjoint=diffrax.RecursiveCheckpointAdjoint(),
        max_steps=100000,
        throw=throw,
    )
    if throw:
        return solution.ys[-1]
    return jnp.where(solution.result == diffrax.RESULTS.successful, solution.ys[-1], jnp.nan)

unroll(function, form, times, *, throw=True, draws=None) staticmethod

Return the pure function that maps an initial state and parameters to states.

The states are those at the given times.

A discrete map is unrolled over every whole step up to the last time with jax.lax.scan, and ordinary differential equations over the intervals between the times, each solved by advance. A map that draws takes a JAX key, splits one key per step, and writes the uniform and normal values of the step after the parameters, where the draw kernel writes them in NumPy runs, so the run is a pure function of the key.

Parameters:

Name Type Description Default
function TracedFunction

The pure function f(t, x, p), the update of a map or the drift of ordinary differential equations.

required
form FormKind | str

The form of the function, a discrete map or ordinary differential equations.

required
times Array

The increasing times, at least 0, whole numbers for a map.

required
throw bool

Whether a failed solve raises an error, or else gives states that are not finite.

True
draws DrawKernel | None

The draw kernel of a map that draws, or None.

None

Returns:

Name Type Description
run Callable[..., TracedArray]

The function run(x0, p, key=None) that returns one row of states per time, which needs a key when the map draws.

Raises:

Type Description
BackendError

The draws hold draws from scipy.stats distributions or random orders, which have no JAX form, or ordinary differential equations draw.

Examples:

>>> import jax.numpy as jnp
>>> import numpy as np
>>> from skcomplex.core.engine.backends import JaxBackend
>>> from skcomplex.core.enums import FormKind
>>> run = JaxBackend.unroll(lambda t, x, p: p * x, FormKind.DISCRETE, np.array([0.0, 2.0]))
>>> np.asarray(run(jnp.array([1.0]), 3.0)).ravel().tolist()
[1.0, 9.0]
Source code in src/skcomplex/core/engine/backends/_jax.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
@staticmethod
def unroll(
    function: TracedFunction,
    form: FormKind | str,
    times: Array,
    *,
    throw: bool = True,
    draws: DrawKernel | None = None,
) -> Callable[..., TracedArray]:
    """Return the pure function that maps an initial state and parameters to states.

    The states are those at the given times.

    A discrete map is unrolled over every whole step up to the last time with `jax.lax.scan`, and ordinary
    differential equations over the intervals between the times, each solved by `advance`. A map that draws takes
    a JAX key, splits one key per step, and writes the uniform and normal values of the step after the parameters,
    where the draw kernel writes them in NumPy runs, so the run is a pure function of the key.

    Args:
        function:
            The pure function `f(t, x, p)`, the update of a map or the drift of ordinary differential equations.

        form:
            The form of the function, a discrete map or ordinary differential equations.

        times:
            The increasing times, at least 0, whole numbers for a map.

        throw:
            Whether a failed solve raises an error, or else gives states that are not finite.

        draws:
            The draw kernel of a map that draws, or `None`.

    Returns:
        run:
            The function `run(x0, p, key=None)` that returns one row of states per time, which needs a key when the
            map draws.

    Raises:
        BackendError:
            The draws hold draws from `scipy.stats` distributions or random orders, which have no JAX form, or
            ordinary differential equations draw.

    Examples:
        >>> import jax.numpy as jnp
        >>> import numpy as np
        >>> from skcomplex.core.engine.backends import JaxBackend
        >>> from skcomplex.core.enums import FormKind
        >>> run = JaxBackend.unroll(lambda t, x, p: p * x, FormKind.DISCRETE, np.array([0.0, 2.0]))
        >>> np.asarray(run(jnp.array([1.0]), 3.0)).ravel().tolist()
        [1.0, 9.0]
    """
    times = np.asarray(times, dtype=float)
    if form == FormKind.DISCRETE:
        steps = np.arange(round(float(times.max()))) if times.size else np.arange(0)
        starts, ends, indices = steps.astype(float), steps + 1.0, np.rint(times).astype(int)
    else:
        ends = np.unique(times[times > 0])
        starts = np.concatenate([[0.0], ends[:-1]])
        indices = np.searchsorted(np.concatenate([[0.0], ends]), times)
    drawn = JaxBackend._get_drawn(draws, form)

    def run(x0: TracedArray, p: TracedArray, key: TracedArray | None = None) -> TracedArray:
        if drawn is None:
            keys = jnp.zeros(starts.size)
        elif key is None:
            error_msg = 'The map draws at every step, so its run takes a JAX key, `run(x0, p, key)`.'
            raise ValidationError(error_msg)
        else:
            keys = jax.random.split(key, starts.size)

        def body(x: TracedArray, item: tuple[TracedArray, ...]) -> tuple[TracedArray, TracedArray]:
            t, t1, step_key = item
            q = p if drawn is None else drawn(p, step_key)
            following = JaxBackend.advance(function, t, t1, x, q, form=form, throw=throw)
            return following, following

        scanned = jax.lax.scan(body, x0, (jnp.asarray(starts), jnp.asarray(ends), keys))[1]
        states = jnp.concatenate([x0[None, :], scanned])
        return states[jnp.asarray(indices)]

    return run

LoweredFunctionsSpec(drift=None, diffusion=None, noise_rows=(lambda: np.zeros(0, dtype=np.intp))(), noise_columns=(lambda: np.zeros(0, dtype=np.intp))(), n_processes=0, noise_blocks=(), propensities=None, jumps=(), update=None, boundary=None, accelerated=None, backends=dict()) dataclass

Bases: BaseSpec

A spec of the numeric functions that a backend writes from a problem.

It holds what a solver calls, each a function of the time, the states, and the parameters: the rates f of x' = f(t, x, p), the size of the noise, the rates of random jumps, or the next state of a map. A field that the problem does not need stays None, so LoweredFunctionsSpec() holds no function at all. The rates of a falling ball, the noise of a stock price, and the jumps of a chemical reaction all reach their solver through it.

Read more in the user guide, under Backends.

Parameters:

Name Type Description Default
drift VectorFunction | None

The function f(t, x, p) of the rates of the states, or None.

None
diffusion VectorFunction | None

The function that returns the size of every source of noise, or None.

None
noise_rows Indices

The state index each noise amplitude drives.

(lambda: zeros(0, dtype=intp))()
noise_columns Indices

The Wiener process each noise amplitude draws.

(lambda: zeros(0, dtype=intp))()
n_processes int

The number of Wiener processes.

0
noise_blocks tuple[_WienerBlockSpec, ...]

The blocks of correlated processes with their covariance factors.

()
propensities VectorFunction | None

The function that returns every jump channel rate, or None.

None
jumps tuple[_JumpChannelsSpec, ...]

The channels of every jump law.

()
update VectorFunction | None

The next-state function of a discrete map, or None.

None
boundary VectorFunction | None

The function that applies the boundary laws, or None.

None
accelerated _AcceleratedSpec | None

The compiled stepper loops, or None when the backend has none.

None
backends Mapping[str, str]

The backend that runs the kernels of every law kind, by the kind's name, when it differs by kind.

dict()
See Also

BaseBackend: Writes these functions in functions_.

Examples:

>>> from skcomplex.core.engine.backends import LoweredFunctionsSpec
>>> LoweredFunctionsSpec().drift is None
True

NumbaBackend(cache_dir=None, parallel=True)

Bases: BaseBackend

A backend that compiles the functions of a problem to machine code with Numba.

It writes the laws as Python source, compiles it with Numba, and keeps it on disk, so a second run starts at once, as in System(..., backend=NumbaBackend()). It also compiles the loop that steps the solver, which makes large groups run much faster than NumPy. Laws that hold a plain Python function fall back to NumPy. Long runs of a spin lattice, a sandpile, and an epidemic on a large network all gain from it.

Read more in the user guide, under Backends.

Parameters:

Name Type Description Default
cache_dir str | Path | None

The directory of the generated kernel sources and Numba's cache, or None for ~/.cache/skcomplex.

None
parallel bool

Whether member and pair loops over groups of at least 1000 members run in parallel threads. Kernels that the compiled loops of jump processes and discrete maps call once per event always run serially.

True
See Also

NumpyBackend: Writes the functions with NumPy, the default. JaxBackend: Writes functions that JAX differentiates.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.engine.backends import NumbaBackend
>>> from skcomplex.core.systems import System
>>> system = System(elements=[Element('herd', values={'x': 2.0})], backend=NumbaBackend())
>>> system.prepare().simulate(until=0).problem.backend
'numba'
Source code in src/skcomplex/core/engine/backends/_numba.py
145
146
147
def __init__(self, cache_dir: str | Path | None = None, parallel: bool = True) -> None:
    self.cache_dir = cache_dir
    self.parallel = parallel

NumpyBackend

Bases: BaseBackend

A backend that evaluates every law with NumPy array operations, the default.

It writes the rate function f(t, x, p) of x' = f(t, x, p), or the next state of a map, as NumPy operations on whole arrays, so it needs no compiling and runs any law the system can compile, as in System(..., backend=NumpyBackend()). It suits small systems and checks the results of the other backends. A reaction network, a predator and its prey, and a small market all run on it by default.

Read more in the user guide, under Backends.

See Also

NumbaBackend: Compiles the functions to machine code for large groups. JaxBackend: Writes functions that JAX differentiates.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.engine.backends import NumpyBackend
>>> from skcomplex.core.systems import System
>>> system = System(elements=[Element('herd', values={'x': 2.0})], backend=NumpyBackend())
>>> system.prepare().simulate(until=0).problem.backend
'numpy'

SupportSpec(time=frozenset(), space=frozenset(), laws=frozenset(), noise=frozenset(), orders=frozenset()) dataclass

Bases: BaseSpec

A spec of what a solver or a backend supports.

It lists the kinds of time, space, and law a solver or a backend can run, so a system can refuse a choice that does not fit, such as a backend that writes rate laws alone in SupportSpec(laws={RateLaw}). An empty field supports anything, a subclass of a listed class is supported too, and None among the spaces supports a system with no space. It keeps a stiff chemical network off a solver of maps and a lattice of spins off a backend with no rules.

Read more in the user guide, under Backends.

Parameters:

Name Type Description Default
time Set[type]

The time classes supported.

frozenset()
space Set[type | None]

The space classes supported, with None for no space.

frozenset()
laws Set[type]

The law classes supported.

frozenset()
noise frozenset[NoiseKind]

The structures of Wiener processes supported.

frozenset()
orders frozenset[OrderKind]

The kinds of derivative orders supported.

frozenset()
See Also

BaseBackend: Declares what it supports with this spec.

Examples:

>>> from skcomplex.core.components.laws import NoiseLaw, RateLaw
>>> from skcomplex.core.engine.backends import SupportSpec
>>> SupportSpec(laws={RateLaw}).get_missing('laws', [RateLaw, NoiseLaw])
['NoiseLaw']

get_missing(category, terms)

Return the names of the terms of a category that are not supported, sorted.

Parameters:

Name Type Description Default
category str

The name of the field, such as 'laws'.

required
terms Iterable[object]

The classes or kinds a system needs, with None for a system without a space.

required

Returns:

Name Type Description
missing list[str]

The names of the unsupported terms.

Source code in src/skcomplex/core/engine/backends/_support_spec.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def get_missing(self, category: str, terms: Iterable[object]) -> list[str]:
    """Return the names of the terms of a category that are not supported, sorted.

    Args:
        category:
            The name of the field, such as `'laws'`.

        terms:
            The classes or kinds a system needs, with `None` for a system without a space.

    Returns:
        missing:
            The names of the unsupported terms.
    """
    found = {self._get_name_of(term) for term in terms if not self._supports(category, term)}
    return sorted(found)

get_tags()

Return the capability tags supported.

They are those of the supported classes of time, space, and laws. A supported class supports its subclasses, so the tags of the subclasses count too, and an empty field of the support gives an empty field of the tags, which supports any value.

Returns:

Name Type Description
tags Tags

The supported times, spaces, and law kinds.

Source code in src/skcomplex/core/engine/backends/_support_spec.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def get_tags(self) -> Tags:
    """Return the capability tags supported.

    They are those of the supported classes of time, space, and laws. A supported class supports its subclasses, so
    the tags of the subclasses count too, and an empty field of the support gives an empty field of the tags, which
    supports any value.

    Returns:
        tags:
            The supported times, spaces, and law kinds.
    """
    return Tags(
        time=self._get_class_tags(self.time, 'time_tag'),
        space=self._get_class_tags(self.space, 'space_tags'),
        laws=self._get_class_tags(self.laws, 'law_tag'),
        randomness=None,
    )