epymorph 1.0.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.
- epymorph/__init__.py +7 -0
- epymorph/__main__.py +16 -0
- epymorph/adrio/__init__.py +0 -0
- epymorph/adrio/acs5.py +1378 -0
- epymorph/adrio/adrio.py +953 -0
- epymorph/adrio/cdc.py +1826 -0
- epymorph/adrio/commuting_flows.py +283 -0
- epymorph/adrio/csv.py +499 -0
- epymorph/adrio/humidity.py +206 -0
- epymorph/adrio/lodes.py +509 -0
- epymorph/adrio/numpy.py +160 -0
- epymorph/adrio/prism.py +345 -0
- epymorph/adrio/processing.py +1221 -0
- epymorph/adrio/soda.py +602 -0
- epymorph/adrio/us_tiger.py +289 -0
- epymorph/adrio/validation.py +382 -0
- epymorph/attribute.py +614 -0
- epymorph/cache.py +680 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +78 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1873 -0
- epymorph/data/__init__.py +1 -0
- epymorph/data/ipm/__init__.py +22 -0
- epymorph/data/ipm/no.py +14 -0
- epymorph/data/ipm/pei.py +40 -0
- epymorph/data/ipm/seirs.py +50 -0
- epymorph/data/ipm/sirh.py +55 -0
- epymorph/data/ipm/sirs.py +48 -0
- epymorph/data/ipm/sparsemod.py +96 -0
- epymorph/data/mm/__init__.py +22 -0
- epymorph/data/mm/centroids.py +76 -0
- epymorph/data/mm/flat.py +61 -0
- epymorph/data/mm/icecube.py +50 -0
- epymorph/data/mm/no.py +29 -0
- epymorph/data/mm/pei.py +105 -0
- epymorph/data/mm/sparsemod.py +73 -0
- epymorph/data/pei.py +424 -0
- epymorph/data_shape.py +593 -0
- epymorph/data_type.py +185 -0
- epymorph/data_usage.py +258 -0
- epymorph/database.py +1301 -0
- epymorph/error.py +195 -0
- epymorph/event.py +196 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +93 -0
- epymorph/geography/scope.py +457 -0
- epymorph/geography/us_census.py +1056 -0
- epymorph/geography/us_geography.py +502 -0
- epymorph/geography/us_tiger.py +1083 -0
- epymorph/initializer.py +786 -0
- epymorph/kit.py +107 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +128 -0
- epymorph/log/messaging.py +139 -0
- epymorph/log/movement.py +228 -0
- epymorph/movement_model.py +347 -0
- epymorph/parameter_fitting/__init__.py +0 -0
- epymorph/parameter_fitting/distribution.py +68 -0
- epymorph/parameter_fitting/dynamics.py +19 -0
- epymorph/parameter_fitting/filter/__init__.py +0 -0
- epymorph/parameter_fitting/filter/base_filter.py +50 -0
- epymorph/parameter_fitting/filter/particle.py +32 -0
- epymorph/parameter_fitting/filter/particle_filter.py +296 -0
- epymorph/parameter_fitting/likelihood.py +54 -0
- epymorph/parameter_fitting/output.py +73 -0
- epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
- epymorph/parameter_fitting/perturbation.py +19 -0
- epymorph/parameter_fitting/utils/__init__.py +0 -0
- epymorph/parameter_fitting/utils/data_loader.py +97 -0
- epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
- epymorph/parameter_fitting/utils/observations.py +63 -0
- epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
- epymorph/parameter_fitting/utils/params_perturb.py +43 -0
- epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
- epymorph/parameter_fitting/utils/resampler.py +258 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +438 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +871 -0
- epymorph/simulation.py +991 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +171 -0
- epymorph/simulator/basic/ipm_exec.py +437 -0
- epymorph/simulator/basic/mm_exec.py +244 -0
- epymorph/simulator/basic/output.py +213 -0
- epymorph/simulator/world.py +149 -0
- epymorph/simulator/world_list.py +274 -0
- epymorph/strata.py +24 -0
- epymorph/sympy_shim.py +57 -0
- epymorph/time.py +1197 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +297 -0
- epymorph/tools/ipm_diagram.py +208 -0
- epymorph/tools/out_map.py +551 -0
- epymorph/tools/out_plot.py +423 -0
- epymorph/tools/out_table.py +582 -0
- epymorph/util.py +1036 -0
- epymorph-1.0.0.dist-info/METADATA +57 -0
- epymorph-1.0.0.dist-info/RECORD +104 -0
- epymorph-1.0.0.dist-info/WHEEL +5 -0
- epymorph-1.0.0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0.dist-info/top_level.txt +1 -0
|
File without changes
|
epymorph/tools/data.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""General tools for processing epymorph data."""
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
from abc import abstractmethod
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Protocol, TypeVar
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from epymorph.attribute import NamePattern
|
|
12
|
+
from epymorph.compartment_model import (
|
|
13
|
+
CompartmentDef,
|
|
14
|
+
QuantityAggregation,
|
|
15
|
+
QuantitySelection,
|
|
16
|
+
)
|
|
17
|
+
from epymorph.geography.scope import GeoAggregation, GeoSelection
|
|
18
|
+
from epymorph.rume import RUME
|
|
19
|
+
from epymorph.time import Dim, TimeAggregation, TimeSelection
|
|
20
|
+
from epymorph.util import mask
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Output(Protocol):
|
|
24
|
+
"""A generic simulation result."""
|
|
25
|
+
|
|
26
|
+
# NOTE: this decouples us from concrete Output implementations.
|
|
27
|
+
|
|
28
|
+
rume: RUME
|
|
29
|
+
"""The RUME used in the simulation that generated this output."""
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
@abstractmethod
|
|
33
|
+
def dataframe(self) -> pd.DataFrame:
|
|
34
|
+
"""The simulation results as a DataFrame."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _validate(
|
|
38
|
+
output: Output,
|
|
39
|
+
geo: GeoSelection | GeoAggregation,
|
|
40
|
+
time: TimeSelection | TimeAggregation,
|
|
41
|
+
quantity: QuantitySelection | QuantityAggregation,
|
|
42
|
+
) -> None:
|
|
43
|
+
"""
|
|
44
|
+
Check that the given axis strategies use the same objects that produced the output.
|
|
45
|
+
|
|
46
|
+
For example, it's an error to run a RUME with one scope, then try to render a table
|
|
47
|
+
using a selection on a completely different scope.
|
|
48
|
+
"""
|
|
49
|
+
if geo.scope is not output.rume.scope:
|
|
50
|
+
err = (
|
|
51
|
+
"When applying a geo selection to an output, both selection and "
|
|
52
|
+
"output must reference the same GeoScope instance.\n"
|
|
53
|
+
"In this case:\n"
|
|
54
|
+
f" selection references {object.__repr__(geo.scope)}\n"
|
|
55
|
+
f" output references {object.__repr__(output.rume.scope)}\n"
|
|
56
|
+
"You might fix this by selecting from the output's RUME's scope, "
|
|
57
|
+
"e.g.: `out.rume.scope.select.all()`"
|
|
58
|
+
)
|
|
59
|
+
raise ValueError(err)
|
|
60
|
+
if time.time_frame is not output.rume.time_frame:
|
|
61
|
+
err = (
|
|
62
|
+
"When applying a time frame selection to an output, both selection and "
|
|
63
|
+
"output must reference the same TimeFrame instance.\n"
|
|
64
|
+
"In this case:\n"
|
|
65
|
+
f" selection references {object.__repr__(time.time_frame)}\n"
|
|
66
|
+
f" output references {object.__repr__(output.rume.time_frame)}\n"
|
|
67
|
+
"You might fix this by selecting from the output's RUME's time frame, "
|
|
68
|
+
"e.g.: `out.rume.time_frame.select.all()`"
|
|
69
|
+
)
|
|
70
|
+
raise ValueError(err)
|
|
71
|
+
if quantity.ipm is not output.rume.ipm:
|
|
72
|
+
err = (
|
|
73
|
+
"When applying an IPM quantity selection to an output, both selection and "
|
|
74
|
+
"output must reference the same CompartmentModel instance.\n"
|
|
75
|
+
"In this case:\n"
|
|
76
|
+
f" selection references {object.__repr__(quantity.ipm)}\n"
|
|
77
|
+
f" output references {object.__repr__(output.rume.ipm)}\n"
|
|
78
|
+
"You might fix this by selecting from the output's RUME's IPM, "
|
|
79
|
+
"e.g.: `out.rume.ipm.select.events()`"
|
|
80
|
+
)
|
|
81
|
+
raise ValueError(err)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def munge(
|
|
85
|
+
output: Output,
|
|
86
|
+
geo: GeoSelection | GeoAggregation,
|
|
87
|
+
time: TimeSelection | TimeAggregation,
|
|
88
|
+
quantity: QuantitySelection | QuantityAggregation,
|
|
89
|
+
) -> pd.DataFrame:
|
|
90
|
+
"""
|
|
91
|
+
Apply select/group/aggregate operations to an output dataframe.
|
|
92
|
+
|
|
93
|
+
This function powers many of our more-specialized output processing tools, but we
|
|
94
|
+
expose this general utility to enable re-use of this logic in more use-cases.
|
|
95
|
+
|
|
96
|
+
Parameters
|
|
97
|
+
----------
|
|
98
|
+
output :
|
|
99
|
+
The result data to process.
|
|
100
|
+
geo :
|
|
101
|
+
The geo-axis strategy.
|
|
102
|
+
time :
|
|
103
|
+
The time-axis strategy.
|
|
104
|
+
quantity :
|
|
105
|
+
The quantity-axis strategy.
|
|
106
|
+
|
|
107
|
+
Returns
|
|
108
|
+
-------
|
|
109
|
+
:
|
|
110
|
+
The munged result.
|
|
111
|
+
|
|
112
|
+
It is a dataframe with columns "time", "geo", and a column per selected
|
|
113
|
+
quantity. The values in "time" and "geo" come from the chosen aggregation
|
|
114
|
+
for those axes. Without any group or aggregation specified, "time" is the
|
|
115
|
+
simulation ticks and "geo" is node IDs.
|
|
116
|
+
|
|
117
|
+
Raises
|
|
118
|
+
------
|
|
119
|
+
ValueError
|
|
120
|
+
If the axis strategies don't refer to the same `RUME` used to produce the
|
|
121
|
+
`Output`. Generally it's safest to create the axis strategies using the methods
|
|
122
|
+
from an output's `RUME` object.
|
|
123
|
+
"""
|
|
124
|
+
_validate(output, geo, time, quantity)
|
|
125
|
+
|
|
126
|
+
N = output.rume.scope.nodes
|
|
127
|
+
S = output.rume.num_ticks
|
|
128
|
+
taus = output.rume.num_tau_steps
|
|
129
|
+
|
|
130
|
+
# Apply selections first so that aggregations operate on less data.
|
|
131
|
+
time_mask = np.repeat(mask(S, time.selection_ticks(taus)), N)
|
|
132
|
+
geo_mask = np.tile(geo.selection, S)
|
|
133
|
+
|
|
134
|
+
# columns are: ["tick", "date", "node", *quantities]
|
|
135
|
+
columns = np.concatenate(([True, True, True], quantity.selection))
|
|
136
|
+
data_df = output.dataframe.loc[time_mask & geo_mask].loc[:, columns]
|
|
137
|
+
data_df = data_df.set_axis(["tick", "date", "geo", *data_df.columns[3:]], axis=1)
|
|
138
|
+
|
|
139
|
+
# I think it makes the most intuitive sense to apply time aggregation last.
|
|
140
|
+
# For example, if the user simulates at tract and wants the peak infection
|
|
141
|
+
# by county -- they probably want each county's peak to represent a single date,
|
|
142
|
+
# rather than summing tract peaks from different days.
|
|
143
|
+
|
|
144
|
+
if geo.aggregation is None:
|
|
145
|
+
# Without agg: use node IDs as the geo dimension.
|
|
146
|
+
pass
|
|
147
|
+
else:
|
|
148
|
+
# With agg:
|
|
149
|
+
agg_df = data_df
|
|
150
|
+
if geo.grouping is None:
|
|
151
|
+
# With no grouping: the geo dimension collapses.
|
|
152
|
+
geo_groups = "*"
|
|
153
|
+
else:
|
|
154
|
+
# With group: geo dimension comes from group.
|
|
155
|
+
geo_groups = geo.grouping.map(agg_df["geo"].to_numpy())
|
|
156
|
+
|
|
157
|
+
data_df = (
|
|
158
|
+
data_df.assign(geo=geo_groups)
|
|
159
|
+
.groupby(["tick", "date", "geo"], sort=False)
|
|
160
|
+
.agg(geo.aggregation)
|
|
161
|
+
.reset_index()
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
if quantity.aggregation is None:
|
|
165
|
+
# For the sake of aggregating and sorting, we need to ensure column names
|
|
166
|
+
# are not ambiguous. But we don't want to alter the names arbitrarily;
|
|
167
|
+
# so we'll rename the columns, do our munging, then restore the original names.
|
|
168
|
+
q_mapping = quantity.disambiguate()
|
|
169
|
+
data_df = data_df.set_axis([*data_df.columns[0:3], *q_mapping.keys()], axis=1)
|
|
170
|
+
else:
|
|
171
|
+
# currently only supported agg is "sum"
|
|
172
|
+
def agg(qty_indices: tuple[int, ...]) -> pd.Series:
|
|
173
|
+
offset = 3 # we have three leading columns before quantities start
|
|
174
|
+
col_indices = [i + offset for i in qty_indices]
|
|
175
|
+
return data_df.iloc[:, col_indices].sum(axis=1)
|
|
176
|
+
|
|
177
|
+
group_defs, group_indices = quantity.grouping.map(quantity.selected)
|
|
178
|
+
group_names = [g.name.full for g in group_defs]
|
|
179
|
+
data_df = pd.DataFrame(
|
|
180
|
+
{
|
|
181
|
+
"tick": data_df["tick"],
|
|
182
|
+
"date": data_df["date"],
|
|
183
|
+
"geo": data_df["geo"],
|
|
184
|
+
**{g: agg(xs) for g, xs in zip(group_names, group_indices)},
|
|
185
|
+
}
|
|
186
|
+
)
|
|
187
|
+
# When there is any grouping applied, it should not be possible to
|
|
188
|
+
# produce ambiguous quantity names; but to keep things simple we'll
|
|
189
|
+
# just provide a no-op map for this case.
|
|
190
|
+
q_mapping = dict(zip(group_names, group_names))
|
|
191
|
+
|
|
192
|
+
if time.aggregation is None:
|
|
193
|
+
# Without agg: drop date and use ticks as the time dimension.
|
|
194
|
+
data_df = data_df.drop(columns=["date"]).rename(columns={"tick": "time"})
|
|
195
|
+
else:
|
|
196
|
+
# With agg:
|
|
197
|
+
if time.grouping is None:
|
|
198
|
+
# Without group: time dimension collapses.
|
|
199
|
+
time_axis = "*"
|
|
200
|
+
else:
|
|
201
|
+
# With group: time dimension comes from grouping.
|
|
202
|
+
nodes = data_df["geo"].unique().shape[0]
|
|
203
|
+
days = data_df.shape[0] // (nodes * taus)
|
|
204
|
+
time_axis = time.grouping.map(
|
|
205
|
+
Dim(nodes=nodes, days=days, tau_steps=taus),
|
|
206
|
+
data_df["tick"].to_numpy(),
|
|
207
|
+
data_df["date"].to_numpy(),
|
|
208
|
+
)
|
|
209
|
+
if time_axis.shape[0] != data_df.shape[0]:
|
|
210
|
+
err = "Chosen time-axis grouping did not return a group for every row."
|
|
211
|
+
raise ValueError(err)
|
|
212
|
+
data_df = (
|
|
213
|
+
data_df.drop(columns=["tick", "date"])
|
|
214
|
+
.assign(time=time_axis)
|
|
215
|
+
.groupby(["time", "geo"], sort=False)
|
|
216
|
+
.agg(
|
|
217
|
+
{
|
|
218
|
+
col: (
|
|
219
|
+
time.aggregation.compartments
|
|
220
|
+
if isinstance(q, CompartmentDef)
|
|
221
|
+
else time.aggregation.events
|
|
222
|
+
)
|
|
223
|
+
for col, q in zip(q_mapping.keys(), quantity.selected)
|
|
224
|
+
}
|
|
225
|
+
)
|
|
226
|
+
.reset_index()
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
# Reset column names
|
|
230
|
+
return data_df.rename(columns=q_mapping)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
RumeT = TypeVar("RumeT", bound=RUME)
|
|
234
|
+
"""A type of RUME."""
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def memoize_rume(
|
|
238
|
+
path: str | Path,
|
|
239
|
+
rume: RumeT,
|
|
240
|
+
*,
|
|
241
|
+
refresh: bool = False,
|
|
242
|
+
rng: np.random.Generator | None = None,
|
|
243
|
+
) -> RumeT:
|
|
244
|
+
"""
|
|
245
|
+
Cache a RUME's parameter data using a local file.
|
|
246
|
+
|
|
247
|
+
If the file doesn't exist, the RUME's parameters are evaluated and saved.
|
|
248
|
+
If the file does exist (and we're not forcing a refresh), values are loaded from
|
|
249
|
+
the file and the RUME's parameters are overridden to use those values.
|
|
250
|
+
|
|
251
|
+
This is intended as a utility for working with RUMEs that use data from ADRIOs
|
|
252
|
+
that may be expensive to fetch repeatedly.
|
|
253
|
+
|
|
254
|
+
For example, working interactively in a Notebook you may have to reprocess code
|
|
255
|
+
cells many times, which could mean spending a long time re-fetching data and/or
|
|
256
|
+
incurring API usage costs. This function helps you avoid those costs.
|
|
257
|
+
|
|
258
|
+
Parameters
|
|
259
|
+
----------
|
|
260
|
+
path :
|
|
261
|
+
The path to the cache file.
|
|
262
|
+
rume :
|
|
263
|
+
The RUME to use.
|
|
264
|
+
refresh :
|
|
265
|
+
True to force this logic to ignore any existing cache file. Parameters will be
|
|
266
|
+
evaluated and the cache file will be overwritten.
|
|
267
|
+
rng :
|
|
268
|
+
A random number generator instance to use. Otherwise we'll use numpy's default
|
|
269
|
+
RNG.
|
|
270
|
+
|
|
271
|
+
Returns
|
|
272
|
+
-------
|
|
273
|
+
:
|
|
274
|
+
A clone of the `RUME` with all parameters replaced by the fully-evaluated numpy
|
|
275
|
+
data arrays.
|
|
276
|
+
|
|
277
|
+
Warning
|
|
278
|
+
-------
|
|
279
|
+
This is not a full serialization of the RUME, so if you change the RUME config
|
|
280
|
+
you should _not_ re-use the cache file; passing `refresh=True` is an easy way to
|
|
281
|
+
make this function ignore any previously saved file.
|
|
282
|
+
"""
|
|
283
|
+
path = Path(path)
|
|
284
|
+
if not refresh and path.exists():
|
|
285
|
+
# Load from cache
|
|
286
|
+
param_values = dict(np.load(path))
|
|
287
|
+
else:
|
|
288
|
+
# Save to cache
|
|
289
|
+
# Evaluate parameters and store the resulting arrays
|
|
290
|
+
resolver = rume.evaluate_params(rng=rng or np.random.default_rng())
|
|
291
|
+
param_values = resolver.to_dict(simplify_names=True)
|
|
292
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
293
|
+
np.savez(path, **param_values)
|
|
294
|
+
|
|
295
|
+
# In either case: clone RUME and replace all parameters from saved arrays
|
|
296
|
+
params = {NamePattern.parse(key): value for key, value in param_values.items()}
|
|
297
|
+
return dataclasses.replace(rume, params=params)
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Produce graphical diagrams of compartmental disease models (IPMs).
|
|
3
|
+
|
|
4
|
+
Usage of these features requires separate installation of a latex converter and
|
|
5
|
+
graphviz.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from abc import abstractmethod
|
|
9
|
+
from collections.abc import Iterable
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from functools import lru_cache, reduce
|
|
12
|
+
from io import BytesIO
|
|
13
|
+
from itertools import groupby
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from shutil import which
|
|
16
|
+
from tempfile import NamedTemporaryFile, TemporaryDirectory
|
|
17
|
+
from typing import Iterator, Protocol, Sequence
|
|
18
|
+
|
|
19
|
+
import matplotlib.pyplot as plt
|
|
20
|
+
from graphviz import Digraph
|
|
21
|
+
from matplotlib.image import imread
|
|
22
|
+
from sympy import Expr, preview
|
|
23
|
+
|
|
24
|
+
from epymorph.error import ExternalDependencyError
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@lru_cache(maxsize=1)
|
|
28
|
+
def _dependency_issues() -> list[tuple[str, str]]:
|
|
29
|
+
"""
|
|
30
|
+
Return a record of dependency issues for the IPM diagram feature.
|
|
31
|
+
Cached so we only compute this once.
|
|
32
|
+
|
|
33
|
+
If there are no issues, an empty list is returned.
|
|
34
|
+
If there are issues, they are returned as (package name, issue description) tuples.
|
|
35
|
+
"""
|
|
36
|
+
issues = []
|
|
37
|
+
|
|
38
|
+
if which("latex") is None:
|
|
39
|
+
msg = (
|
|
40
|
+
"- Unable to find LaTeX converter 'latex'.\n"
|
|
41
|
+
" We recommend MiKTeX (https://miktex.org/download) "
|
|
42
|
+
"or TexLive (https://tug.org/texlive/)"
|
|
43
|
+
)
|
|
44
|
+
issues.append(("latex", msg))
|
|
45
|
+
|
|
46
|
+
if which("dvipng") is None:
|
|
47
|
+
msg = (
|
|
48
|
+
"- Unable to find png converter 'dvipng'.\n"
|
|
49
|
+
" You may need to install this from your system's package manager or "
|
|
50
|
+
"alternatively your latex library might be able to install this as an "
|
|
51
|
+
"option."
|
|
52
|
+
)
|
|
53
|
+
issues.append(("dvipng", msg))
|
|
54
|
+
|
|
55
|
+
if which("dot") is None:
|
|
56
|
+
msg = (
|
|
57
|
+
"- Unable to find Graphviz renderer 'dot'.\n"
|
|
58
|
+
" See installation instructions (https://graphviz.org/download/)"
|
|
59
|
+
)
|
|
60
|
+
issues.append(("dot", msg))
|
|
61
|
+
|
|
62
|
+
return issues
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def check_dependencies() -> None:
|
|
66
|
+
"""
|
|
67
|
+
Check if the external requirements for drawing diagrams are installed.
|
|
68
|
+
|
|
69
|
+
The results of this check are memorized so it can be called repeatedly
|
|
70
|
+
without adding much overhead.
|
|
71
|
+
|
|
72
|
+
Raises
|
|
73
|
+
------
|
|
74
|
+
ExternalDependencyError
|
|
75
|
+
If some dependencies are missing.
|
|
76
|
+
"""
|
|
77
|
+
if issues := _dependency_issues():
|
|
78
|
+
err = [
|
|
79
|
+
"Rendering IPM diagrams requires you to install some additional programs:",
|
|
80
|
+
*(msg for _, msg in issues),
|
|
81
|
+
]
|
|
82
|
+
raise ExternalDependencyError("\n".join(err), [pkg for pkg, _ in issues])
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# NOTE: the following Protocol-ized CompartmentModel bits are to avoid
|
|
86
|
+
# circular dependency issues.
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class EdgeDef(Protocol):
|
|
90
|
+
"""A simplified `EdgeDef` interface."""
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
@abstractmethod
|
|
94
|
+
def rate(self) -> Expr:
|
|
95
|
+
"""The rate of flow along this edge."""
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
@abstractmethod
|
|
99
|
+
def tuple(self) -> tuple[str, str]:
|
|
100
|
+
"""The edge in tuple form: `(from_name, to_name)`."""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class CompartmentModel(Protocol):
|
|
104
|
+
"""A simplified `CompartmentModel` interface."""
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
@abstractmethod
|
|
108
|
+
def events(self) -> Sequence[EdgeDef]:
|
|
109
|
+
"""The unique transition events in the model."""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@contextmanager
|
|
113
|
+
def construct_digraph(ipm: CompartmentModel) -> Iterator[Digraph]:
|
|
114
|
+
"""
|
|
115
|
+
Construct a graphviz object (`Digraph`) for the compartment model's diagram.
|
|
116
|
+
|
|
117
|
+
The `Digraph` instance is only valid within the managed context because we rely on
|
|
118
|
+
temporary files to render latex expressions.
|
|
119
|
+
|
|
120
|
+
Yields
|
|
121
|
+
------
|
|
122
|
+
:
|
|
123
|
+
The `Digraph` instance, which is valid as soon as the context opens but only
|
|
124
|
+
until the context is closed.
|
|
125
|
+
"""
|
|
126
|
+
check_dependencies()
|
|
127
|
+
|
|
128
|
+
def expr_sum(exprs: Iterable[Expr]) -> Expr:
|
|
129
|
+
"""Sum a bunch of expressions together."""
|
|
130
|
+
return reduce(lambda a, b: a + b, exprs)
|
|
131
|
+
|
|
132
|
+
def edges_group_sum(edges: Iterable[EdgeDef]) -> list[tuple[str, str, Expr]]:
|
|
133
|
+
"""Compute the sum of rate expressions by unique (src,dst) pair."""
|
|
134
|
+
return [
|
|
135
|
+
(src, dst, expr_sum(e.rate for e in group_edges))
|
|
136
|
+
for (src, dst), group_edges in groupby(edges, key=lambda e: e.tuple)
|
|
137
|
+
]
|
|
138
|
+
|
|
139
|
+
with TemporaryDirectory() as tmp_dir:
|
|
140
|
+
graph = Digraph(
|
|
141
|
+
graph_attr={"rankdir": "LR", "latex": "true"},
|
|
142
|
+
node_attr={"shape": "square", "width": ".9", "height": ".8"},
|
|
143
|
+
edge_attr={"minlen": "2.0"},
|
|
144
|
+
)
|
|
145
|
+
for src, dst, rate in edges_group_sum(ipm.events):
|
|
146
|
+
# each rate is a sympy expression which we want to render as latex
|
|
147
|
+
# to do so, we have to `preview` them into temp files
|
|
148
|
+
# then use HTML table markup to place them on the graph
|
|
149
|
+
with NamedTemporaryFile(suffix=".png", dir=tmp_dir, delete=False) as f:
|
|
150
|
+
preview(rate, viewer="file", filename=f.name, euler=False)
|
|
151
|
+
label = f'<<TABLE border="0"><TR><TD><IMG SRC="{f.name}"/></TD></TR></TABLE>>' # noqa: E501
|
|
152
|
+
graph.edge(src, dst, label=label)
|
|
153
|
+
yield graph
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def render_diagram_to_bytes(ipm: CompartmentModel) -> BytesIO:
|
|
157
|
+
"""
|
|
158
|
+
Render a diagram of the given compartment model and return it as the bytes of a
|
|
159
|
+
png-formatted image.
|
|
160
|
+
|
|
161
|
+
Parameters
|
|
162
|
+
----------
|
|
163
|
+
ipm :
|
|
164
|
+
The compartment model to render.
|
|
165
|
+
|
|
166
|
+
Returns
|
|
167
|
+
-------
|
|
168
|
+
:
|
|
169
|
+
The bytes of the image.
|
|
170
|
+
"""
|
|
171
|
+
check_dependencies()
|
|
172
|
+
with construct_digraph(ipm) as graph:
|
|
173
|
+
return BytesIO(graph.pipe(format="png"))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def render_diagram(
|
|
177
|
+
ipm: CompartmentModel,
|
|
178
|
+
*,
|
|
179
|
+
file: str | Path | None = None,
|
|
180
|
+
figsize: tuple[float, float] | None = None,
|
|
181
|
+
) -> None:
|
|
182
|
+
"""
|
|
183
|
+
Render a diagram of the given compartment model and either show it with matplotlib
|
|
184
|
+
(default) or save it to `file` as a png image.
|
|
185
|
+
|
|
186
|
+
Parameters
|
|
187
|
+
----------
|
|
188
|
+
ipm :
|
|
189
|
+
The compartment model to render.
|
|
190
|
+
file :
|
|
191
|
+
Provide a file path to save a png image of the diagram to this path.
|
|
192
|
+
If `file` is None, we will instead use matplotlib to show the diagram.
|
|
193
|
+
figsize :
|
|
194
|
+
The matplotlib figure size to use when displaying the diagram.
|
|
195
|
+
Only used if `file` is not provided.
|
|
196
|
+
"""
|
|
197
|
+
check_dependencies()
|
|
198
|
+
image = render_diagram_to_bytes(ipm)
|
|
199
|
+
if file is not None:
|
|
200
|
+
# Save to file.
|
|
201
|
+
with Path(file).open("wb") as f:
|
|
202
|
+
f.write(image.getvalue())
|
|
203
|
+
else:
|
|
204
|
+
# Display using matplotlib.
|
|
205
|
+
plt.figure(figsize=figsize or (10, 6))
|
|
206
|
+
plt.imshow(imread(image))
|
|
207
|
+
plt.axis("off")
|
|
208
|
+
plt.show()
|