epidsl 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- epidsl/__init__.py +18 -0
- epidsl/backends/__init__.py +167 -0
- epidsl/backends/_stochastic.py +232 -0
- epidsl/backends/gillespie.py +125 -0
- epidsl/backends/ode.py +77 -0
- epidsl/backends/tau_leap.py +203 -0
- epidsl/calibration.py +429 -0
- epidsl/checks.py +205 -0
- epidsl/cli.py +367 -0
- epidsl/compose.py +694 -0
- epidsl/ensemble.py +77 -0
- epidsl/errors.py +23 -0
- epidsl/expr.py +141 -0
- epidsl/grammar.lark +72 -0
- epidsl/ir.py +318 -0
- epidsl/lsp.py +205 -0
- epidsl/parallel.py +86 -0
- epidsl/parser.py +321 -0
- epidsl/py.typed +0 -0
- epidsl/studio/__init__.py +1 -0
- epidsl/studio/api.py +320 -0
- epidsl/studio/server.py +145 -0
- epidsl/studio/static/app.js +740 -0
- epidsl/studio/static/index.html +84 -0
- epidsl/studio/static/style.css +363 -0
- epidsl-0.1.0.dist-info/METADATA +665 -0
- epidsl-0.1.0.dist-info/RECORD +30 -0
- epidsl-0.1.0.dist-info/WHEEL +4 -0
- epidsl-0.1.0.dist-info/entry_points.txt +3 -0
- epidsl-0.1.0.dist-info/licenses/LICENSE +21 -0
epidsl/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""EpiDSL: a domain-specific language for compositional epidemiological modelling."""
|
|
2
|
+
|
|
3
|
+
from epidsl.checks import Diagnostic, Severity, check
|
|
4
|
+
from epidsl.errors import CompositionError, EpiError, EpiSyntaxError
|
|
5
|
+
from epidsl.ir import EpiModel, SimulationConfig
|
|
6
|
+
from epidsl.parser import parse
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"CompositionError",
|
|
10
|
+
"Diagnostic",
|
|
11
|
+
"EpiError",
|
|
12
|
+
"EpiModel",
|
|
13
|
+
"EpiSyntaxError",
|
|
14
|
+
"Severity",
|
|
15
|
+
"SimulationConfig",
|
|
16
|
+
"check",
|
|
17
|
+
"parse",
|
|
18
|
+
]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Simulation backends. Each turns an EpiModel into trajectories."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import NDArray
|
|
10
|
+
|
|
11
|
+
from epidsl.checks import errors
|
|
12
|
+
from epidsl.expr import Evaluator, compile_expr, walk
|
|
13
|
+
from epidsl.ir import EpiModel, Incidence, NoiseDistribution, Semantics, SimulationConfig
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class BackendResult:
|
|
18
|
+
"""Trajectories on a common time grid.
|
|
19
|
+
|
|
20
|
+
``y`` holds the compartments and ``observed`` the model's observables, both
|
|
21
|
+
keyed by name.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
t: NDArray[np.float64]
|
|
25
|
+
y: dict[str, NDArray[np.float64]]
|
|
26
|
+
metadata: dict[str, object] = field(default_factory=dict)
|
|
27
|
+
observed: dict[str, NDArray[np.float64]] = field(default_factory=dict)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Backend(Protocol):
|
|
31
|
+
"""Anything that can simulate a model."""
|
|
32
|
+
|
|
33
|
+
def run(self, model: EpiModel, config: SimulationConfig) -> BackendResult: ...
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class CompiledFlow:
|
|
38
|
+
"""A flow with compartment positions resolved and its rate ready to evaluate."""
|
|
39
|
+
|
|
40
|
+
source: int | None
|
|
41
|
+
target: int | None
|
|
42
|
+
rate: Evaluator
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, slots=True)
|
|
46
|
+
class CompiledModel:
|
|
47
|
+
names: list[str]
|
|
48
|
+
initial: NDArray[np.float64]
|
|
49
|
+
flows: list[CompiledFlow]
|
|
50
|
+
#: Indices of the flows whose cumulative count the observables need.
|
|
51
|
+
tracked: list[int]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def compile_model(model: EpiModel, semantics: Semantics) -> CompiledModel:
|
|
55
|
+
"""Validate ``model`` for a backend and resolve it against a state vector.
|
|
56
|
+
|
|
57
|
+
Raises ValueError if the model has static errors or does not declare ``semantics``.
|
|
58
|
+
"""
|
|
59
|
+
problems = errors(model)
|
|
60
|
+
if problems:
|
|
61
|
+
details = "; ".join(str(p) for p in problems)
|
|
62
|
+
raise ValueError(f"model {model.name} has errors: {details}")
|
|
63
|
+
if semantics not in model.semantics:
|
|
64
|
+
declared = ", ".join(s.value for s in model.semantics)
|
|
65
|
+
raise ValueError(
|
|
66
|
+
f"model {model.name} does not declare {semantics.value} semantics "
|
|
67
|
+
f"(declared: {declared})"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
names = [c.name for c in model.compartments]
|
|
71
|
+
index = {name: i for i, name in enumerate(names)}
|
|
72
|
+
constants = {k.name: k.value for k in model.constants}
|
|
73
|
+
counted = {pair for node in _incidences(model) for pair in node.pairs}
|
|
74
|
+
return CompiledModel(
|
|
75
|
+
names=names,
|
|
76
|
+
initial=np.array([c.initial for c in model.compartments], dtype=np.float64),
|
|
77
|
+
flows=[
|
|
78
|
+
CompiledFlow(
|
|
79
|
+
None if f.source is None else index[f.source],
|
|
80
|
+
None if f.target is None else index[f.target],
|
|
81
|
+
compile_expr(f.expr, index, constants),
|
|
82
|
+
)
|
|
83
|
+
for f in model.flows
|
|
84
|
+
],
|
|
85
|
+
tracked=[j for j, f in enumerate(model.flows) if (f.source, f.target) in counted],
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _incidences(model: EpiModel) -> list[Incidence]:
|
|
90
|
+
return [
|
|
91
|
+
node
|
|
92
|
+
for observable in model.observables
|
|
93
|
+
for node in walk(observable.expr)
|
|
94
|
+
if isinstance(node, Incidence)
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def observe(
|
|
99
|
+
model: EpiModel,
|
|
100
|
+
compiled: CompiledModel,
|
|
101
|
+
t: NDArray[np.float64],
|
|
102
|
+
states: NDArray[np.float64],
|
|
103
|
+
cumulative: NDArray[np.float64],
|
|
104
|
+
rng: np.random.Generator | None = None,
|
|
105
|
+
) -> dict[str, NDArray[np.float64]]:
|
|
106
|
+
"""Evaluate the model's observables at every output time.
|
|
107
|
+
|
|
108
|
+
``states[k]`` is the state at ``t[k]`` and ``cumulative[k, i]`` the number of
|
|
109
|
+
individuals moved so far by flow ``compiled.tracked[i]``. An incidence term is
|
|
110
|
+
the count over the interval that ends at the output time, and zero at the first.
|
|
111
|
+
|
|
112
|
+
When ``rng`` is provided and an observable declares a noise distribution, the
|
|
113
|
+
returned values are drawn from that distribution (mean = deterministic value).
|
|
114
|
+
Without ``rng`` the deterministic mean is always returned.
|
|
115
|
+
"""
|
|
116
|
+
if not model.observables:
|
|
117
|
+
return {}
|
|
118
|
+
moved = np.diff(cumulative, axis=0, prepend=cumulative[:1])
|
|
119
|
+
column = {flow: i for i, flow in enumerate(compiled.tracked)}
|
|
120
|
+
series: dict[Incidence, NDArray[np.float64]] = {}
|
|
121
|
+
for node in _incidences(model):
|
|
122
|
+
columns = [
|
|
123
|
+
column[j] for j, f in enumerate(model.flows) if (f.source, f.target) in node.pairs
|
|
124
|
+
]
|
|
125
|
+
series[node] = moved[:, columns].sum(axis=1)
|
|
126
|
+
|
|
127
|
+
index = {name: i for i, name in enumerate(compiled.names)}
|
|
128
|
+
constants = {k.name: k.value for k in model.constants}
|
|
129
|
+
current: dict[Incidence, float] = {}
|
|
130
|
+
observed: dict[str, NDArray[np.float64]] = {}
|
|
131
|
+
for observable in model.observables:
|
|
132
|
+
evaluate = compile_expr(observable.expr, index, constants, current.__getitem__)
|
|
133
|
+
values = np.empty(len(t), dtype=np.float64)
|
|
134
|
+
for k in range(len(t)):
|
|
135
|
+
for node, counts in series.items():
|
|
136
|
+
current[node] = float(counts[k])
|
|
137
|
+
try:
|
|
138
|
+
values[k] = evaluate(states[k], float(t[k]))
|
|
139
|
+
except (ArithmeticError, ValueError) as error:
|
|
140
|
+
raise RuntimeError(
|
|
141
|
+
f"observable '{observable.name}' could not be evaluated "
|
|
142
|
+
f"at t = {t[k]:g} ({error})"
|
|
143
|
+
) from error
|
|
144
|
+
if rng is not None and observable.noise is not None:
|
|
145
|
+
values = _apply_noise(observable.noise, values, rng)
|
|
146
|
+
observed[observable.name] = values
|
|
147
|
+
return observed
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _apply_noise(
|
|
151
|
+
noise: NoiseDistribution,
|
|
152
|
+
values: NDArray[np.float64],
|
|
153
|
+
rng: np.random.Generator,
|
|
154
|
+
) -> NDArray[np.float64]:
|
|
155
|
+
"""Draw one sample per time point from ``noise`` centred on ``values``."""
|
|
156
|
+
mu = np.maximum(values, 0.0)
|
|
157
|
+
if noise.dist == "poisson":
|
|
158
|
+
return rng.poisson(mu).astype(np.float64)
|
|
159
|
+
elif noise.dist == "normal":
|
|
160
|
+
sd = noise.params[0]
|
|
161
|
+
return rng.normal(mu, sd)
|
|
162
|
+
else: # negbinomial
|
|
163
|
+
phi = noise.params[0]
|
|
164
|
+
# Parametrisation: mean = mu, variance = mu + mu^2 / phi
|
|
165
|
+
# scipy / numpy NB uses (n=phi, p=phi/(phi+mu))
|
|
166
|
+
p = np.where(mu > 0, phi / (phi + mu), 1.0)
|
|
167
|
+
return rng.negative_binomial(phi, p).astype(np.float64)
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Pieces shared by the jump-process backends (Gillespie, tau-leap)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import warnings
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import NDArray
|
|
10
|
+
from scipy.integrate import IntegrationWarning, quad
|
|
11
|
+
from scipy.optimize import brentq
|
|
12
|
+
|
|
13
|
+
from epidsl.backends import CompiledModel
|
|
14
|
+
from epidsl.expr import walk
|
|
15
|
+
from epidsl.ir import EpiModel, Sym
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def require_whole_initial_values(model: EpiModel, label: str) -> None:
|
|
19
|
+
"""Jump processes count individuals; refuse a fractional initial value."""
|
|
20
|
+
for compartment in model.compartments:
|
|
21
|
+
if compartment.initial != math.floor(compartment.initial):
|
|
22
|
+
raise ValueError(
|
|
23
|
+
f"model {model.name}: initial value of '{compartment.name}' "
|
|
24
|
+
f"({compartment.initial:g}) must be a whole number for {label} semantics"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def uses_time(model: EpiModel) -> bool:
|
|
29
|
+
"""Whether any flow's rate names ``t``."""
|
|
30
|
+
return any(
|
|
31
|
+
isinstance(node, Sym) and node.name == "t"
|
|
32
|
+
for flow in model.flows
|
|
33
|
+
for node in walk(flow.expr)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def evaluate_propensities(
|
|
38
|
+
compiled: CompiledModel,
|
|
39
|
+
state: NDArray[np.float64],
|
|
40
|
+
t: float,
|
|
41
|
+
out: NDArray[np.float64],
|
|
42
|
+
model_name: str,
|
|
43
|
+
label: str,
|
|
44
|
+
) -> None:
|
|
45
|
+
"""Fill ``out`` with the rate of every flow in ``state`` at time ``t``.
|
|
46
|
+
|
|
47
|
+
A flow whose source is empty has rate zero, whatever its expression. Raises
|
|
48
|
+
RuntimeError on a rate that cannot be evaluated or is negative or undefined.
|
|
49
|
+
"""
|
|
50
|
+
for i, flow in enumerate(compiled.flows):
|
|
51
|
+
if flow.source is not None and state[flow.source] <= 0:
|
|
52
|
+
out[i] = 0.0
|
|
53
|
+
continue
|
|
54
|
+
try:
|
|
55
|
+
value = flow.rate(state, t)
|
|
56
|
+
except (ArithmeticError, ValueError) as error:
|
|
57
|
+
raise RuntimeError(
|
|
58
|
+
f"{label} simulation failed for model {model_name}: "
|
|
59
|
+
f"a flow rate could not be evaluated ({error})"
|
|
60
|
+
) from error
|
|
61
|
+
if not value >= 0:
|
|
62
|
+
raise RuntimeError(
|
|
63
|
+
f"{label} simulation failed for model {model_name}: "
|
|
64
|
+
f"a flow rate is negative or undefined ({value:g}) at t = {t:g}"
|
|
65
|
+
)
|
|
66
|
+
out[i] = value
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def choose_flow(propensities: NDArray[np.float64], total: float, rng: np.random.Generator) -> int:
|
|
70
|
+
"""Pick a flow index with probability proportional to its propensity."""
|
|
71
|
+
threshold = rng.random() * total
|
|
72
|
+
chosen = int(np.searchsorted(np.cumsum(propensities), threshold, side="right"))
|
|
73
|
+
chosen = min(chosen, len(propensities) - 1)
|
|
74
|
+
while propensities[chosen] == 0.0: # guard against rounding at the upper end
|
|
75
|
+
chosen -= 1
|
|
76
|
+
return chosen
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class TimedJumps:
|
|
80
|
+
"""Exact jump times when rates depend on time.
|
|
81
|
+
|
|
82
|
+
Between two jumps the state does not change, so the total rate is a known function
|
|
83
|
+
of time alone. The next jump falls where its integral reaches a draw from the unit
|
|
84
|
+
exponential law; this class computes that integral and inverts it.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
def __init__(self, compiled: CompiledModel, model_name: str, label: str) -> None:
|
|
88
|
+
self._compiled = compiled
|
|
89
|
+
self._model_name = model_name
|
|
90
|
+
self._label = label
|
|
91
|
+
self._rates = np.zeros(len(compiled.flows), dtype=np.float64)
|
|
92
|
+
|
|
93
|
+
def mass(self, state: NDArray[np.float64], start: float, stop: float) -> float:
|
|
94
|
+
"""The integral of the total rate from ``start`` to ``stop``, in ``state``."""
|
|
95
|
+
failure: list[RuntimeError] = []
|
|
96
|
+
|
|
97
|
+
def total(s: float) -> float:
|
|
98
|
+
# An error must not be raised through the integrator; keep it for after.
|
|
99
|
+
try:
|
|
100
|
+
evaluate_propensities(
|
|
101
|
+
self._compiled, state, s, self._rates, self._model_name, self._label
|
|
102
|
+
)
|
|
103
|
+
except RuntimeError as error:
|
|
104
|
+
failure.append(error)
|
|
105
|
+
return 0.0
|
|
106
|
+
return float(self._rates.sum())
|
|
107
|
+
|
|
108
|
+
with warnings.catch_warnings():
|
|
109
|
+
warnings.simplefilter("ignore", IntegrationWarning)
|
|
110
|
+
value, error = quad(total, start, stop, epsabs=1e-10, epsrel=1e-10, limit=200)
|
|
111
|
+
if failure:
|
|
112
|
+
raise failure[0]
|
|
113
|
+
if error > 1e-6 * max(1.0, abs(value)):
|
|
114
|
+
raise RuntimeError(
|
|
115
|
+
f"{self._label} simulation failed for model {self._model_name}: the rates "
|
|
116
|
+
f"could not be integrated between t = {start:g} and t = {stop:g}"
|
|
117
|
+
)
|
|
118
|
+
return float(value)
|
|
119
|
+
|
|
120
|
+
def reach(self, state: NDArray[np.float64], start: float, stop: float, target: float) -> float:
|
|
121
|
+
"""The time at which the integral from ``start`` equals ``target``.
|
|
122
|
+
|
|
123
|
+
``target`` must not exceed the mass up to ``stop``.
|
|
124
|
+
"""
|
|
125
|
+
return float(
|
|
126
|
+
brentq(
|
|
127
|
+
lambda s: self.mass(state, start, s) - target,
|
|
128
|
+
start,
|
|
129
|
+
stop,
|
|
130
|
+
xtol=1e-12 * max(1.0, abs(stop)),
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def advance(
|
|
135
|
+
self, state: NDArray[np.float64], start: float, stop: float, owed: float
|
|
136
|
+
) -> tuple[float | None, float]:
|
|
137
|
+
"""Integrate the total rate from ``start`` to ``stop``, firing when it hits ``owed``.
|
|
138
|
+
|
|
139
|
+
Fast path: estimate the jump time from the current rate (exponential
|
|
140
|
+
approximation), then refine with Newton-Raphson using a trapezoid
|
|
141
|
+
integral. Typically 3–8 rate evaluations per call vs. ~160 with the
|
|
142
|
+
``quad`` + ``brentq`` combination in :meth:`mass` / :meth:`reach`.
|
|
143
|
+
|
|
144
|
+
Slow fallback: when Newton does not converge (non-monotone rates,
|
|
145
|
+
taux near zero), falls back to :meth:`mass` + :meth:`reach`.
|
|
146
|
+
|
|
147
|
+
Returns ``(t_jump, residual)``:
|
|
148
|
+
- Jump in ``[start, stop]``: ``t_jump`` is the crossing time (the
|
|
149
|
+
caller must draw a fresh exponential); ``residual`` is 0.
|
|
150
|
+
- No jump: ``t_jump`` is ``None``; ``residual = owed - integral``
|
|
151
|
+
must be carried forward.
|
|
152
|
+
"""
|
|
153
|
+
failure: list[RuntimeError] = []
|
|
154
|
+
rates = np.zeros(len(self._compiled.flows), dtype=np.float64)
|
|
155
|
+
|
|
156
|
+
def rate_at(t: float) -> float:
|
|
157
|
+
try:
|
|
158
|
+
evaluate_propensities(
|
|
159
|
+
self._compiled, state, t, rates, self._model_name, self._label
|
|
160
|
+
)
|
|
161
|
+
except RuntimeError as error:
|
|
162
|
+
failure.append(error)
|
|
163
|
+
return 0.0
|
|
164
|
+
return float(rates.sum())
|
|
165
|
+
|
|
166
|
+
def trap(a: float, b: float, ra: float, rb: float) -> float:
|
|
167
|
+
return 0.5 * (ra + rb) * (b - a)
|
|
168
|
+
|
|
169
|
+
r0 = rate_at(start)
|
|
170
|
+
if failure:
|
|
171
|
+
raise failure[0]
|
|
172
|
+
|
|
173
|
+
# Fast estimate: how far would the integral carry us at current rate?
|
|
174
|
+
h = stop - start
|
|
175
|
+
if r0 > 0:
|
|
176
|
+
t_est = start + owed / r0
|
|
177
|
+
else:
|
|
178
|
+
t_est = stop + 1.0 # above stop → check the endpoint
|
|
179
|
+
|
|
180
|
+
# ------------------------------------------------------------------ #
|
|
181
|
+
# Case A: estimate says no jump before stop #
|
|
182
|
+
# ------------------------------------------------------------------ #
|
|
183
|
+
if t_est > stop:
|
|
184
|
+
# Use Simpson's rule (r0 already evaluated, two more points) for
|
|
185
|
+
# higher precision so the residual is accurate to ~1e-5 relative.
|
|
186
|
+
r_mid = rate_at(start + 0.5 * h)
|
|
187
|
+
r1 = rate_at(stop)
|
|
188
|
+
if failure:
|
|
189
|
+
raise failure[0]
|
|
190
|
+
integral = h / 6.0 * (r0 + 4.0 * r_mid + r1)
|
|
191
|
+
if integral < owed:
|
|
192
|
+
return None, max(0.0, owed - integral)
|
|
193
|
+
# The rate rose enough: there IS a jump — fall through with t=stop.
|
|
194
|
+
t_est = stop
|
|
195
|
+
|
|
196
|
+
# ------------------------------------------------------------------ #
|
|
197
|
+
# Case B: Newton-Raphson to pinpoint the crossing #
|
|
198
|
+
# F(t) = ∫[start, t] λ - owed = 0, F'(t) = λ(t) #
|
|
199
|
+
# Simpson rule for the integral gives O(h^5) precision vs O(h^3) #
|
|
200
|
+
# for the trapezoid, so Newton converges to ~1e-6 relative in 3-4 #
|
|
201
|
+
# steps even when the rate varies strongly over the interval. #
|
|
202
|
+
# ------------------------------------------------------------------ #
|
|
203
|
+
t = min(t_est, stop)
|
|
204
|
+
for _ in range(8):
|
|
205
|
+
r_t = rate_at(t)
|
|
206
|
+
r_mid = rate_at(0.5 * (start + t))
|
|
207
|
+
if failure:
|
|
208
|
+
raise failure[0]
|
|
209
|
+
dt_half = t - start
|
|
210
|
+
integral_t = dt_half / 6.0 * (r0 + 4.0 * r_mid + r_t)
|
|
211
|
+
f = integral_t - owed
|
|
212
|
+
if abs(f) <= 1e-9 * max(1.0, abs(owed)):
|
|
213
|
+
return float(np.clip(t, start, stop)), 0.0
|
|
214
|
+
if r_t <= 0.0:
|
|
215
|
+
break # Cannot step — fall back to the slow path.
|
|
216
|
+
t_new = t - f / r_t
|
|
217
|
+
t_new = float(np.clip(t_new, start, stop))
|
|
218
|
+
if abs(t_new - t) <= 1e-12 * max(1.0, abs(t)):
|
|
219
|
+
return float(t_new), 0.0
|
|
220
|
+
t = t_new
|
|
221
|
+
|
|
222
|
+
if failure:
|
|
223
|
+
raise failure[0]
|
|
224
|
+
|
|
225
|
+
# ------------------------------------------------------------------ #
|
|
226
|
+
# Slow fallback (rare): non-monotone or near-zero rates #
|
|
227
|
+
# ------------------------------------------------------------------ #
|
|
228
|
+
mass_total = self.mass(state, start, stop)
|
|
229
|
+
if mass_total < owed:
|
|
230
|
+
return None, max(0.0, owed - mass_total)
|
|
231
|
+
t_jump = self.reach(state, start, stop, owed)
|
|
232
|
+
return float(t_jump), 0.0
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Exact stochastic backend: Gillespie's direct method.
|
|
2
|
+
|
|
3
|
+
Compartments hold whole numbers of individuals. Each flow is a jump that moves one
|
|
4
|
+
individual, firing at a rate (propensity) equal to the flow's expression.
|
|
5
|
+
|
|
6
|
+
When a rate names ``t``, the waiting time to the next jump is found by integrating
|
|
7
|
+
the total rate — exact up to the precision of the quadrature — instead of drawing it
|
|
8
|
+
from an exponential law with a fixed rate. Models without ``t`` take the usual path.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from epidsl.backends import BackendResult, compile_model, observe
|
|
18
|
+
from epidsl.backends._stochastic import (
|
|
19
|
+
TimedJumps,
|
|
20
|
+
choose_flow,
|
|
21
|
+
evaluate_propensities,
|
|
22
|
+
require_whole_initial_values,
|
|
23
|
+
uses_time,
|
|
24
|
+
)
|
|
25
|
+
from epidsl.ir import EpiModel, Semantics, SimulationConfig
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class GillespieBackend:
|
|
29
|
+
"""Simulates one trajectory per run; ``config.seed`` makes it reproducible.
|
|
30
|
+
|
|
31
|
+
``max_events`` bounds the number of jumps, so that a model whose rates grow
|
|
32
|
+
without limit fails instead of running forever.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(self, max_events: int = 10_000_000) -> None:
|
|
36
|
+
self.max_events = max_events
|
|
37
|
+
|
|
38
|
+
def run(self, model: EpiModel, config: SimulationConfig) -> BackendResult:
|
|
39
|
+
compiled = compile_model(model, Semantics.GILLESPIE)
|
|
40
|
+
require_whole_initial_values(model, "Gillespie")
|
|
41
|
+
|
|
42
|
+
rng = np.random.default_rng(config.seed)
|
|
43
|
+
grid = config.grid()
|
|
44
|
+
output = np.empty((len(grid), len(compiled.names)), dtype=np.float64)
|
|
45
|
+
counter = {flow: i for i, flow in enumerate(compiled.tracked)}
|
|
46
|
+
moved = np.zeros(len(compiled.tracked), dtype=np.float64)
|
|
47
|
+
moved_output = np.empty((len(grid), len(compiled.tracked)), dtype=np.float64)
|
|
48
|
+
state = compiled.initial.copy()
|
|
49
|
+
propensities = np.zeros(len(compiled.flows), dtype=np.float64)
|
|
50
|
+
t = float(grid[0])
|
|
51
|
+
recorded = 0
|
|
52
|
+
events = 0
|
|
53
|
+
|
|
54
|
+
jumps = TimedJumps(compiled, model.name, "Gillespie") if uses_time(model) else None
|
|
55
|
+
# With rates that depend on time, the next jump falls where the integral of the
|
|
56
|
+
# total rate reaches a unit-exponential draw; `owed` is what is left of it.
|
|
57
|
+
owed = rng.exponential(1.0) if jumps is not None else 0.0
|
|
58
|
+
while jumps is not None and recorded < len(grid):
|
|
59
|
+
ahead = float(grid[recorded])
|
|
60
|
+
if t >= ahead:
|
|
61
|
+
output[recorded] = state
|
|
62
|
+
moved_output[recorded] = moved
|
|
63
|
+
recorded += 1
|
|
64
|
+
continue
|
|
65
|
+
t_jump, owed = jumps.advance(state, t, ahead, owed)
|
|
66
|
+
if t_jump is None:
|
|
67
|
+
# No jump before the next output time; residual already in `owed`.
|
|
68
|
+
t = ahead
|
|
69
|
+
continue
|
|
70
|
+
if events == self.max_events:
|
|
71
|
+
raise RuntimeError(
|
|
72
|
+
f"Gillespie simulation of model {model.name} needs more than "
|
|
73
|
+
f"{self.max_events} events (reached t = {t:g})"
|
|
74
|
+
)
|
|
75
|
+
t = t_jump
|
|
76
|
+
owed = rng.exponential(1.0)
|
|
77
|
+
evaluate_propensities(compiled, state, t, propensities, model.name, "Gillespie")
|
|
78
|
+
total = float(propensities.sum())
|
|
79
|
+
if total <= 0:
|
|
80
|
+
continue # the rate vanishes exactly here: nothing to choose from
|
|
81
|
+
chosen = choose_flow(propensities, total, rng)
|
|
82
|
+
fired = compiled.flows[chosen]
|
|
83
|
+
if chosen in counter:
|
|
84
|
+
moved[counter[chosen]] += 1
|
|
85
|
+
if fired.source is not None:
|
|
86
|
+
state[fired.source] -= 1
|
|
87
|
+
if fired.target is not None:
|
|
88
|
+
state[fired.target] += 1
|
|
89
|
+
events += 1
|
|
90
|
+
|
|
91
|
+
while jumps is None:
|
|
92
|
+
evaluate_propensities(compiled, state, t, propensities, model.name, "Gillespie")
|
|
93
|
+
total = float(propensities.sum())
|
|
94
|
+
t_next = t + rng.exponential(1.0 / total) if total > 0 else math.inf
|
|
95
|
+
|
|
96
|
+
# The state is constant until the next jump: fill the grid points before it.
|
|
97
|
+
while recorded < len(grid) and grid[recorded] < t_next:
|
|
98
|
+
output[recorded] = state
|
|
99
|
+
moved_output[recorded] = moved
|
|
100
|
+
recorded += 1
|
|
101
|
+
if recorded == len(grid):
|
|
102
|
+
break
|
|
103
|
+
|
|
104
|
+
if events == self.max_events:
|
|
105
|
+
raise RuntimeError(
|
|
106
|
+
f"Gillespie simulation of model {model.name} needs more than "
|
|
107
|
+
f"{self.max_events} events (reached t = {t:g})"
|
|
108
|
+
)
|
|
109
|
+
chosen = choose_flow(propensities, total, rng)
|
|
110
|
+
fired = compiled.flows[chosen]
|
|
111
|
+
if chosen in counter:
|
|
112
|
+
moved[counter[chosen]] += 1
|
|
113
|
+
if fired.source is not None:
|
|
114
|
+
state[fired.source] -= 1
|
|
115
|
+
if fired.target is not None:
|
|
116
|
+
state[fired.target] += 1
|
|
117
|
+
t = t_next
|
|
118
|
+
events += 1
|
|
119
|
+
|
|
120
|
+
return BackendResult(
|
|
121
|
+
t=grid,
|
|
122
|
+
y={name: output[:, i].copy() for i, name in enumerate(compiled.names)},
|
|
123
|
+
metadata={"backend": "Gillespie", "events": events, "seed": config.seed},
|
|
124
|
+
observed=observe(model, compiled, grid, output, moved_output, rng=rng),
|
|
125
|
+
)
|
epidsl/backends/ode.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Deterministic backend: integrate the model's mean-field ODE system."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from numpy.typing import NDArray
|
|
7
|
+
from scipy.integrate import solve_ivp
|
|
8
|
+
|
|
9
|
+
from epidsl.backends import BackendResult, compile_model, observe
|
|
10
|
+
from epidsl.ir import EpiModel, Semantics, SimulationConfig
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ODEBackend:
|
|
14
|
+
"""Integrates with LSODA, which switches between stiff and non-stiff methods."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, rtol: float = 1e-9, atol: float = 1e-9) -> None:
|
|
17
|
+
self.rtol = rtol
|
|
18
|
+
self.atol = atol
|
|
19
|
+
|
|
20
|
+
def run(self, model: EpiModel, config: SimulationConfig) -> BackendResult:
|
|
21
|
+
compiled = compile_model(model, Semantics.ODE)
|
|
22
|
+
n = len(compiled.names)
|
|
23
|
+
# One extra variable per tracked flow accumulates what it has moved.
|
|
24
|
+
counter = {flow: n + i for i, flow in enumerate(compiled.tracked)}
|
|
25
|
+
|
|
26
|
+
failure: list[Exception] = []
|
|
27
|
+
|
|
28
|
+
def rhs(t: float, y: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
29
|
+
state = y[:n]
|
|
30
|
+
dy = np.zeros_like(y)
|
|
31
|
+
for j, flow in enumerate(compiled.flows):
|
|
32
|
+
try:
|
|
33
|
+
value = flow.rate(state, t)
|
|
34
|
+
except (ArithmeticError, ValueError) as error:
|
|
35
|
+
# A rate left the representable range (overflow, division by zero,
|
|
36
|
+
# log of a negative number). Do not raise through the solver: some
|
|
37
|
+
# SciPy versions abort the interpreter. Remember the error and hand
|
|
38
|
+
# back NaN, which makes the solver stop.
|
|
39
|
+
failure.append(error)
|
|
40
|
+
return np.full_like(y, np.nan)
|
|
41
|
+
if flow.source is not None:
|
|
42
|
+
dy[flow.source] -= value
|
|
43
|
+
if flow.target is not None:
|
|
44
|
+
dy[flow.target] += value
|
|
45
|
+
if j in counter:
|
|
46
|
+
dy[counter[j]] = value
|
|
47
|
+
return dy
|
|
48
|
+
|
|
49
|
+
grid = config.grid()
|
|
50
|
+
y0 = np.concatenate([compiled.initial, np.zeros(len(compiled.tracked))])
|
|
51
|
+
solution = solve_ivp(
|
|
52
|
+
rhs,
|
|
53
|
+
(float(grid[0]), float(grid[-1])),
|
|
54
|
+
y0,
|
|
55
|
+
method="LSODA",
|
|
56
|
+
t_eval=grid,
|
|
57
|
+
rtol=self.rtol,
|
|
58
|
+
atol=self.atol,
|
|
59
|
+
)
|
|
60
|
+
if failure:
|
|
61
|
+
raise RuntimeError(
|
|
62
|
+
f"ODE solver failed for model {model.name}: "
|
|
63
|
+
f"a flow rate could not be evaluated ({failure[0]})"
|
|
64
|
+
) from failure[0]
|
|
65
|
+
if not solution.success:
|
|
66
|
+
raise RuntimeError(f"ODE solver failed for model {model.name}: {solution.message}")
|
|
67
|
+
|
|
68
|
+
# The solver interpolates output points; report the initial state exactly.
|
|
69
|
+
solution.y[:, 0] = y0
|
|
70
|
+
states, cumulative = solution.y[:n].T, solution.y[n:].T
|
|
71
|
+
|
|
72
|
+
return BackendResult(
|
|
73
|
+
t=solution.t,
|
|
74
|
+
y={name: solution.y[i] for i, name in enumerate(compiled.names)},
|
|
75
|
+
metadata={"backend": "ODE", "method": "LSODA", "nfev": int(solution.nfev)},
|
|
76
|
+
observed=observe(model, compiled, solution.t, states, cumulative),
|
|
77
|
+
)
|