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
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Any, Dict, List, Tuple, Type
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
from epymorph.parameter_fitting.dynamics import (
|
|
8
|
+
GeometricBrownianMotion,
|
|
9
|
+
)
|
|
10
|
+
from epymorph.parameter_fitting.filter.base_filter import BaseFilter
|
|
11
|
+
from epymorph.parameter_fitting.filter.particle import Particle
|
|
12
|
+
from epymorph.parameter_fitting.likelihood import Likelihood
|
|
13
|
+
from epymorph.parameter_fitting.output import ParticleFilterOutput
|
|
14
|
+
from epymorph.parameter_fitting.perturbation import Calvetti
|
|
15
|
+
from epymorph.parameter_fitting.utils import utils
|
|
16
|
+
from epymorph.parameter_fitting.utils.epymorph_simulation import EpymorphSimulation
|
|
17
|
+
from epymorph.parameter_fitting.utils.observations import ModelLink
|
|
18
|
+
from epymorph.parameter_fitting.utils.parameter_estimation import EstimateParameters
|
|
19
|
+
from epymorph.parameter_fitting.utils.params_perturb import Perturb
|
|
20
|
+
from epymorph.parameter_fitting.utils.particle_initializer import ParticleInitializer
|
|
21
|
+
from epymorph.parameter_fitting.utils.resampler import WeightsResampling
|
|
22
|
+
from epymorph.rume import RUME
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ParticleFilter(BaseFilter):
|
|
26
|
+
"""
|
|
27
|
+
A class to run the particle filter for estimating parameters.
|
|
28
|
+
|
|
29
|
+
Attributes
|
|
30
|
+
----------
|
|
31
|
+
num_particles : int
|
|
32
|
+
Number of particles.
|
|
33
|
+
param_quantiles : Dict[str, List[np.ndarray]]
|
|
34
|
+
Quantiles of parameters over time.
|
|
35
|
+
param_values : Dict[str, List[np.ndarray]]
|
|
36
|
+
Mean values of parameters over time.
|
|
37
|
+
resampler: Type[WeightsResampling]
|
|
38
|
+
The resampling method to use.
|
|
39
|
+
rng : np.random.Generator
|
|
40
|
+
Random number generator for simulations and resampling.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self, num_particles: int, resampler: Type[WeightsResampling] = WeightsResampling
|
|
45
|
+
) -> None:
|
|
46
|
+
"""
|
|
47
|
+
Initializes the ParticleFilter with the given number of particles.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
num_particles : int
|
|
52
|
+
Number of particles for the particle filter.
|
|
53
|
+
resampler : Type[WeightsResampling], optional
|
|
54
|
+
The resampler to use in the particle filter.
|
|
55
|
+
"""
|
|
56
|
+
self.num_particles = num_particles
|
|
57
|
+
self.param_quantiles = {}
|
|
58
|
+
self.param_values = {}
|
|
59
|
+
self.resampler = resampler
|
|
60
|
+
|
|
61
|
+
def propagate_particles(
|
|
62
|
+
self,
|
|
63
|
+
particles: List[Particle],
|
|
64
|
+
rume: RUME,
|
|
65
|
+
simulation: EpymorphSimulation,
|
|
66
|
+
date: str,
|
|
67
|
+
duration: int,
|
|
68
|
+
model_link: ModelLink,
|
|
69
|
+
params_space: Dict[str, EstimateParameters],
|
|
70
|
+
rng: np.random.Generator,
|
|
71
|
+
) -> Tuple[List[Particle], List[np.ndarray]]:
|
|
72
|
+
"""
|
|
73
|
+
Propagates particles through the simulation model.
|
|
74
|
+
|
|
75
|
+
Parameters
|
|
76
|
+
----------
|
|
77
|
+
particles : List[Particle]
|
|
78
|
+
The particles which represent the current estimate of the filter.
|
|
79
|
+
rume : Rume
|
|
80
|
+
Model parameters including population size and geographical information.
|
|
81
|
+
simulation : EpymorphSimulation
|
|
82
|
+
The object which propagates the particles.
|
|
83
|
+
date : str
|
|
84
|
+
Current date.
|
|
85
|
+
duration : int
|
|
86
|
+
Duration of propagation in days.
|
|
87
|
+
model_link : ModelLink
|
|
88
|
+
Information used to match the model output with the observations.
|
|
89
|
+
params_space : Dict[str, EstimateParameters]
|
|
90
|
+
The parameters to be estimated and the methods used to estimate them.
|
|
91
|
+
|
|
92
|
+
Returns
|
|
93
|
+
-------
|
|
94
|
+
Tuple
|
|
95
|
+
- A list of propagated Particle objects with updated observations.
|
|
96
|
+
- A list of expected observations for each particle after propagation.
|
|
97
|
+
"""
|
|
98
|
+
propagated_particles = []
|
|
99
|
+
expected_observations = []
|
|
100
|
+
|
|
101
|
+
# Initialize perturbation handler
|
|
102
|
+
params_perturb = Perturb(duration)
|
|
103
|
+
|
|
104
|
+
# Propagate each particle through the model
|
|
105
|
+
for particle in particles:
|
|
106
|
+
# Use the particle's state and parameters for propagation
|
|
107
|
+
new_state, observation = simulation.propagate(
|
|
108
|
+
particle.state,
|
|
109
|
+
particle.parameters,
|
|
110
|
+
rume,
|
|
111
|
+
date,
|
|
112
|
+
duration,
|
|
113
|
+
model_link,
|
|
114
|
+
rng,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# Update the parameters using their dynamics
|
|
118
|
+
new_parameters = {}
|
|
119
|
+
for param, val in particle.parameters.items():
|
|
120
|
+
dynamics = params_space[param].dynamics
|
|
121
|
+
if isinstance(dynamics, GeometricBrownianMotion):
|
|
122
|
+
new_parameters[param] = params_perturb.gbm(
|
|
123
|
+
val, dynamics.volatility, rng
|
|
124
|
+
)
|
|
125
|
+
else:
|
|
126
|
+
new_parameters[param] = val
|
|
127
|
+
|
|
128
|
+
# Create a new particle with the propagated state and updated parameters
|
|
129
|
+
propagated_particles.append(Particle(new_state, new_parameters))
|
|
130
|
+
|
|
131
|
+
expected_observations.append(observation)
|
|
132
|
+
|
|
133
|
+
return propagated_particles, expected_observations
|
|
134
|
+
|
|
135
|
+
def run(
|
|
136
|
+
self,
|
|
137
|
+
rume: RUME,
|
|
138
|
+
likelihood_fn: Likelihood,
|
|
139
|
+
params_space: Dict[str, EstimateParameters],
|
|
140
|
+
model_link: ModelLink,
|
|
141
|
+
dates: Any,
|
|
142
|
+
cases: List[np.ndarray],
|
|
143
|
+
rng: np.random.Generator,
|
|
144
|
+
) -> ParticleFilterOutput:
|
|
145
|
+
"""
|
|
146
|
+
Runs the particle filter to estimate parameters.
|
|
147
|
+
|
|
148
|
+
Parameters
|
|
149
|
+
----------
|
|
150
|
+
rume : Rume
|
|
151
|
+
Model parameters, including population size and geographical information.
|
|
152
|
+
likelihood_fn : Likelihood
|
|
153
|
+
The likelihood function to use in the resampling.
|
|
154
|
+
params_space : Dict[str, EstimateParameters]
|
|
155
|
+
The parameters to estimate and the methods to estimate them.
|
|
156
|
+
model_link : ModelLink
|
|
157
|
+
Link to the model used for simulations.
|
|
158
|
+
index : int
|
|
159
|
+
Index of the parameter to estimate.
|
|
160
|
+
dates : Any
|
|
161
|
+
Dates for which observations are available.
|
|
162
|
+
cases : List[int]
|
|
163
|
+
Observed case data over time.
|
|
164
|
+
|
|
165
|
+
Returns
|
|
166
|
+
-------
|
|
167
|
+
ParticleFilterOutput
|
|
168
|
+
The result of the particle filter containing parameter estimates, quantiles,
|
|
169
|
+
and model data.
|
|
170
|
+
"""
|
|
171
|
+
start_time = time.time()
|
|
172
|
+
dates = pd.to_datetime(dates)
|
|
173
|
+
data = np.array(cases)
|
|
174
|
+
|
|
175
|
+
# Ensure data is 2D for compatibility
|
|
176
|
+
if len(data.shape) == 1:
|
|
177
|
+
data = data[:, np.newaxis] # Reshape to 2D array (N, 1)
|
|
178
|
+
|
|
179
|
+
print("Running Particle Filter simulation") # noqa: T201
|
|
180
|
+
print(f"• {dates[0]} to {dates[-1]} ({rume.time_frame.duration_days} days)") # noqa: T201
|
|
181
|
+
print(f"• {self.num_particles} particles") # noqa: T201
|
|
182
|
+
|
|
183
|
+
num_observations = len(data)
|
|
184
|
+
|
|
185
|
+
# Initialize the particles, simulation, and resampling tools
|
|
186
|
+
initializer = ParticleInitializer(self.num_particles, rume, params_space)
|
|
187
|
+
particles = initializer.initialize_particles(rng)
|
|
188
|
+
simulation = EpymorphSimulation(rume, dates[0])
|
|
189
|
+
weights_resampling = self.resampler(
|
|
190
|
+
self.num_particles,
|
|
191
|
+
likelihood_fn,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
# Prepare containers for storing results
|
|
195
|
+
for key in params_space.keys():
|
|
196
|
+
self.param_quantiles[key] = []
|
|
197
|
+
self.param_values[key] = []
|
|
198
|
+
|
|
199
|
+
model_data = []
|
|
200
|
+
|
|
201
|
+
# Iterate through each time step and perform filtering
|
|
202
|
+
for t in range(num_observations):
|
|
203
|
+
n = 1 # Number of days to look back for the previous observation
|
|
204
|
+
if t > 0:
|
|
205
|
+
duration = (dates[t] - dates[t - n]).days
|
|
206
|
+
else:
|
|
207
|
+
duration = 1
|
|
208
|
+
|
|
209
|
+
# Propagate particles and update their states
|
|
210
|
+
propagated_particles, expected_observations = self.propagate_particles(
|
|
211
|
+
particles,
|
|
212
|
+
rume,
|
|
213
|
+
simulation,
|
|
214
|
+
dates[t].strftime("%Y-%m-%d"),
|
|
215
|
+
duration,
|
|
216
|
+
model_link,
|
|
217
|
+
params_space,
|
|
218
|
+
rng,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
# Append model data (mean of particle states) for this time step
|
|
222
|
+
model_data.append(
|
|
223
|
+
np.mean(
|
|
224
|
+
[obs for obs in expected_observations],
|
|
225
|
+
axis=0,
|
|
226
|
+
).astype(int) # Ensure the final mean is also an integer
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
if np.all(np.isnan(data[t, ...])):
|
|
230
|
+
particles = propagated_particles.copy()
|
|
231
|
+
|
|
232
|
+
else:
|
|
233
|
+
# Now pass all observations for the current time step
|
|
234
|
+
# Pass the entire observation (all columns for that time step)
|
|
235
|
+
new_weights = weights_resampling.compute_weights(
|
|
236
|
+
data[t, ...], # This will pass all data for the current time step
|
|
237
|
+
expected_observations,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
if np.any(np.isnan(new_weights)):
|
|
241
|
+
raise ValueError("NaN values found in computed weights.")
|
|
242
|
+
particles = weights_resampling.resample_particles(
|
|
243
|
+
propagated_particles, new_weights, rng
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
for param in particles[0].parameters.keys():
|
|
247
|
+
perturbation = params_space[param].perturbation
|
|
248
|
+
if isinstance(perturbation, Calvetti):
|
|
249
|
+
param_vals = np.array(
|
|
250
|
+
[particle.parameters[param] for particle in particles]
|
|
251
|
+
)
|
|
252
|
+
param_mean = np.mean(np.log(param_vals), axis=0)
|
|
253
|
+
param_cov = np.cov(np.log(param_vals), rowvar=False)
|
|
254
|
+
a = perturbation.a
|
|
255
|
+
h = np.sqrt(1 - a**2)
|
|
256
|
+
if len(param_cov.shape) < 2:
|
|
257
|
+
param_cov = np.broadcast_to(param_cov, shape=(1, 1))
|
|
258
|
+
rvs = rng.multivariate_normal(
|
|
259
|
+
(1 - a) * param_mean, h**2 * param_cov, size=len(particles)
|
|
260
|
+
)
|
|
261
|
+
for i in range(len(particles)):
|
|
262
|
+
particles[i].parameters[param] = np.exp(
|
|
263
|
+
a * np.log(particles[i].parameters[param]) + rvs[i, ...]
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
# Collect parameter values for quantiles and means
|
|
267
|
+
key_values = {key: [] for key in self.param_quantiles.keys()}
|
|
268
|
+
for particle in particles:
|
|
269
|
+
for key in key_values.keys():
|
|
270
|
+
if key in particle.parameters:
|
|
271
|
+
key_values[key].append(particle.parameters[key])
|
|
272
|
+
|
|
273
|
+
# Store quantiles and means for each parameter
|
|
274
|
+
for key, values in key_values.items():
|
|
275
|
+
if values:
|
|
276
|
+
self.param_quantiles[key].append(utils.quantiles(np.array(values)))
|
|
277
|
+
self.param_values[key].append(np.mean(values))
|
|
278
|
+
|
|
279
|
+
parameters_estimated = list(self.param_quantiles.keys())
|
|
280
|
+
# Calculate total runtime
|
|
281
|
+
total_runtime = time.time() - start_time
|
|
282
|
+
print(f"\nSimulation completed in {total_runtime:.2f}s") # noqa: T201
|
|
283
|
+
print(f"\nParameters estimated: {parameters_estimated}") # noqa: T201
|
|
284
|
+
|
|
285
|
+
# Prepare the output object
|
|
286
|
+
out = ParticleFilterOutput(
|
|
287
|
+
self.num_particles,
|
|
288
|
+
parameters_estimated,
|
|
289
|
+
str(rume.time_frame.duration_days) + " days",
|
|
290
|
+
self.param_quantiles,
|
|
291
|
+
self.param_values,
|
|
292
|
+
true_data=np.array(data),
|
|
293
|
+
model_data=np.array(model_data),
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
return out
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
from scipy.stats import poisson
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Likelihood(ABC):
|
|
7
|
+
"""
|
|
8
|
+
Abstract base class for likelihood functions for computing the likelihood of
|
|
9
|
+
observational data predicted by a model.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
@abstractmethod
|
|
13
|
+
def compute(self, observed: int, expected: int):
|
|
14
|
+
"""
|
|
15
|
+
Computes the likelihood of the observed data given the data expected by a model.
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
observed : int
|
|
20
|
+
The observational data.
|
|
21
|
+
expected : int
|
|
22
|
+
The data predicted by the model.
|
|
23
|
+
"""
|
|
24
|
+
raise NotImplementedError("Subclasses should implement this method.")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Poisson(Likelihood):
|
|
28
|
+
"""
|
|
29
|
+
Encapsulatees the Poisson likelihood function for observational data. The expected
|
|
30
|
+
value of the observation is used as the parameter for the Poisson distribution. The
|
|
31
|
+
observed values must be nonnegative integers.
|
|
32
|
+
|
|
33
|
+
Attributes
|
|
34
|
+
----------
|
|
35
|
+
jitter : float
|
|
36
|
+
A small number added to the expected value to avoid the degenerate case when the
|
|
37
|
+
expected value is zero.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, jitter: float = 0.0001):
|
|
41
|
+
self.jitter = jitter
|
|
42
|
+
|
|
43
|
+
def compute(self, observed, expected):
|
|
44
|
+
"""
|
|
45
|
+
Computes the Poisson likelihood.
|
|
46
|
+
|
|
47
|
+
Parameters
|
|
48
|
+
----------
|
|
49
|
+
observed : int
|
|
50
|
+
The observational data.
|
|
51
|
+
expected : int
|
|
52
|
+
The data predicted by the model.
|
|
53
|
+
"""
|
|
54
|
+
return poisson.pmf(observed, expected + self.jitter)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Dict, List
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class ParticleFilterOutput:
|
|
9
|
+
"""
|
|
10
|
+
Encapulates the particle filter output.
|
|
11
|
+
|
|
12
|
+
Attributes
|
|
13
|
+
----------
|
|
14
|
+
num_particles : int
|
|
15
|
+
The number of particles used in the particle filter.
|
|
16
|
+
parameters_estimated : list
|
|
17
|
+
The parameters which were estimated.
|
|
18
|
+
duration : str
|
|
19
|
+
The total duration of the particle filter simulation.
|
|
20
|
+
param_quantiles : Dict[str, List[float]]
|
|
21
|
+
The estimated quantiles of each parameter at each observation time.
|
|
22
|
+
param_values : Dict[str, List[float]]
|
|
23
|
+
The estimated average of each parameter at each observation time.
|
|
24
|
+
true_data : np.ndarray
|
|
25
|
+
The observed data which was used by the particle filter.
|
|
26
|
+
model_data : np.ndarray
|
|
27
|
+
The prediced data from the particle filter.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
num_particles: int
|
|
31
|
+
parameters_estimated: list
|
|
32
|
+
duration: str
|
|
33
|
+
param_quantiles: Dict[str, List[float]]
|
|
34
|
+
param_values: Dict[str, List[float]]
|
|
35
|
+
true_data: np.ndarray
|
|
36
|
+
model_data: np.ndarray
|
|
37
|
+
|
|
38
|
+
def __str__(self) -> str:
|
|
39
|
+
output = []
|
|
40
|
+
|
|
41
|
+
# General Header Information
|
|
42
|
+
output.append("Particle Filter Output")
|
|
43
|
+
output.append("-----------------------")
|
|
44
|
+
output.append(f"\nNumber of Particles: {self.num_particles}")
|
|
45
|
+
output.append(f"\nDuration: {self.duration}")
|
|
46
|
+
output.append(f"\nParameters estimated: {self.parameters_estimated}")
|
|
47
|
+
|
|
48
|
+
# General description of parameter quantiles
|
|
49
|
+
output.append(
|
|
50
|
+
"\nParameter Quantiles: represent the statistical range of parameter "
|
|
51
|
+
"estimates at different percentiles (e.g., 5th, 50th, 95th percentiles)."
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# General description of parameter values
|
|
55
|
+
output.append(
|
|
56
|
+
"\nParameter Values: represent the values of model parameters"
|
|
57
|
+
"estimated in the simulation."
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# True Data description
|
|
61
|
+
output.append(
|
|
62
|
+
"\nTrue Data: represents the actual observed data used for comparison."
|
|
63
|
+
)
|
|
64
|
+
output.append(f" Data length: {len(self.true_data)} entries.")
|
|
65
|
+
|
|
66
|
+
# Model Data description
|
|
67
|
+
output.append(
|
|
68
|
+
"\nModel Estimated Data: represents the data generated by the model for"
|
|
69
|
+
"comparison against the true data."
|
|
70
|
+
)
|
|
71
|
+
output.append(f" Data length: {len(self.model_data)} entries.")
|
|
72
|
+
|
|
73
|
+
return "\n".join(output)
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This module provides a simulation class for running particle filters on
|
|
3
|
+
epidemiological data.
|
|
4
|
+
|
|
5
|
+
The `FilterSimulation` class initializes with the necessary parameters,
|
|
6
|
+
validates inputs, and runs the particle filter simulation.
|
|
7
|
+
|
|
8
|
+
Dependencies:
|
|
9
|
+
- numpy: For numerical operations.
|
|
10
|
+
- pandas: For data manipulation.
|
|
11
|
+
- epymorph: Custom package providing filter and likelihood functionalities.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from typing import Dict
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from epymorph import * # noqa: F403
|
|
19
|
+
from epymorph.parameter_fitting.filter.base_filter import BaseFilter
|
|
20
|
+
from epymorph.parameter_fitting.likelihood import Likelihood
|
|
21
|
+
from epymorph.parameter_fitting.output import ParticleFilterOutput
|
|
22
|
+
from epymorph.parameter_fitting.utils.data_loader import DataLoader
|
|
23
|
+
from epymorph.parameter_fitting.utils.observations import ModelLink, Observations
|
|
24
|
+
from epymorph.parameter_fitting.utils.parameter_estimation import EstimateParameters
|
|
25
|
+
from epymorph.rume import RUME
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class FilterSimulation:
|
|
29
|
+
"""
|
|
30
|
+
A class to run particle filter simulations on epidemiological data.
|
|
31
|
+
|
|
32
|
+
This class is initialized with epidemiological parameters, likelihood function,
|
|
33
|
+
filter type, parameter space, and observational data. It validates these inputs
|
|
34
|
+
and runs the particle filter to produce simulation results.
|
|
35
|
+
|
|
36
|
+
Attributes
|
|
37
|
+
----------
|
|
38
|
+
rume : Rume
|
|
39
|
+
Runtime environment for the simulation,
|
|
40
|
+
containing necessary parameters.
|
|
41
|
+
likelihood_fn : Likelihood
|
|
42
|
+
The likelihood function to be used.
|
|
43
|
+
filter_type : BaseFilter
|
|
44
|
+
Type of filter (e.g., Particle Filter) to be
|
|
45
|
+
used in the simulation.
|
|
46
|
+
params_space : Dict[str, EstimateParameters]
|
|
47
|
+
Parameter estimates for the simulation.
|
|
48
|
+
observations : Observations
|
|
49
|
+
Observational data to be used in the simulation.
|
|
50
|
+
dataloader : DataLoader
|
|
51
|
+
A DataLoader instance to handle loading of
|
|
52
|
+
observational data.
|
|
53
|
+
dates : np.ndarray
|
|
54
|
+
The dates associated with the observational data.
|
|
55
|
+
cases : np.ndarray
|
|
56
|
+
The case counts associated with the observational data.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
rume: RUME,
|
|
62
|
+
filter_type: BaseFilter,
|
|
63
|
+
params_space: Dict[str, EstimateParameters],
|
|
64
|
+
observations: Observations,
|
|
65
|
+
):
|
|
66
|
+
"""
|
|
67
|
+
Initializes the FilterSimulation class.
|
|
68
|
+
|
|
69
|
+
Parameters
|
|
70
|
+
----------
|
|
71
|
+
rume : Rume
|
|
72
|
+
Runtime environment or configuration for the epidemiological
|
|
73
|
+
model.
|
|
74
|
+
filter_type : BaseFilter
|
|
75
|
+
Type of particle filter to be used.
|
|
76
|
+
params_space : Dict[str, EstimateParameters]
|
|
77
|
+
The parameters to estimate.
|
|
78
|
+
observations : Observations
|
|
79
|
+
An object containing observational data.
|
|
80
|
+
|
|
81
|
+
Raises
|
|
82
|
+
------
|
|
83
|
+
ValueError
|
|
84
|
+
If any of the input arguments are invalid.
|
|
85
|
+
"""
|
|
86
|
+
self.rume = rume
|
|
87
|
+
self.observations = observations
|
|
88
|
+
self.likelihood_fn = observations.likelihood
|
|
89
|
+
self.filter_type = filter_type
|
|
90
|
+
self.params_space = params_space
|
|
91
|
+
|
|
92
|
+
# Initialize simulation-related attributes
|
|
93
|
+
self.ipm = self.rume.ipm
|
|
94
|
+
self.model_link: ModelLink = self.observations.model_link
|
|
95
|
+
self.compartments = [compartment.name for compartment in self.ipm.compartments]
|
|
96
|
+
self.events = [e.name.full for e in self.ipm.events]
|
|
97
|
+
|
|
98
|
+
# Initialize DataLoader to handle data fetching
|
|
99
|
+
self.dataloader = DataLoader(self.rume)
|
|
100
|
+
|
|
101
|
+
# Validate the inputs
|
|
102
|
+
self.validate()
|
|
103
|
+
|
|
104
|
+
# Load observational data
|
|
105
|
+
self.dates, self.cases = self.dataloader.load_data(self.observations)
|
|
106
|
+
|
|
107
|
+
if len(self.cases.shape) < 2:
|
|
108
|
+
self.cases = self.cases[..., np.newaxis]
|
|
109
|
+
|
|
110
|
+
def validate(self) -> None:
|
|
111
|
+
"""
|
|
112
|
+
Validates the input parameters for the simulation.
|
|
113
|
+
|
|
114
|
+
Ensures that the likelihood function, filter type, model link, and parameter
|
|
115
|
+
estimates are valid.
|
|
116
|
+
|
|
117
|
+
Raises
|
|
118
|
+
------
|
|
119
|
+
ValueError
|
|
120
|
+
If any required field is missing or if the types are incorrect.
|
|
121
|
+
"""
|
|
122
|
+
# Validate likelihood function
|
|
123
|
+
if not isinstance(self.likelihood_fn, Likelihood):
|
|
124
|
+
raise ValueError("The 'likelihood_fn' must be an instance of Likelihood.")
|
|
125
|
+
|
|
126
|
+
# Validate filter type
|
|
127
|
+
if not isinstance(self.filter_type, BaseFilter):
|
|
128
|
+
raise ValueError("The 'filter_type' must be an instance of BaseFilter.")
|
|
129
|
+
|
|
130
|
+
# Validate parameter space
|
|
131
|
+
if not isinstance(self.params_space, dict):
|
|
132
|
+
raise ValueError("The 'params_space' must be a dictionary.")
|
|
133
|
+
|
|
134
|
+
for key, value in self.params_space.items():
|
|
135
|
+
if not isinstance(value, EstimateParameters):
|
|
136
|
+
raise ValueError(
|
|
137
|
+
"Each value in 'params_space' must be an instance of"
|
|
138
|
+
f" EstimateParameters Invalid entry for '{key}'."
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# Validate observations
|
|
142
|
+
if not isinstance(self.observations, Observations):
|
|
143
|
+
raise ValueError("The 'observations' must be an instance of Observations.")
|
|
144
|
+
|
|
145
|
+
def run(self, rng: np.random.Generator | None = None) -> ParticleFilterOutput:
|
|
146
|
+
"""
|
|
147
|
+
Runs the particle filter simulation.
|
|
148
|
+
|
|
149
|
+
Parameters
|
|
150
|
+
----------
|
|
151
|
+
rng : np.random.Generator | None, optional
|
|
152
|
+
The random number generator used by the particle filter. It is also passed
|
|
153
|
+
to the simulator during particle propagation.
|
|
154
|
+
|
|
155
|
+
Returns
|
|
156
|
+
-------
|
|
157
|
+
ParticleFilterOutput
|
|
158
|
+
The output of the filter simulation containing
|
|
159
|
+
results.
|
|
160
|
+
"""
|
|
161
|
+
|
|
162
|
+
if not rng:
|
|
163
|
+
rng = np.random.default_rng()
|
|
164
|
+
|
|
165
|
+
output = self.filter_type.run(
|
|
166
|
+
self.rume,
|
|
167
|
+
self.likelihood_fn,
|
|
168
|
+
self.params_space,
|
|
169
|
+
self.model_link,
|
|
170
|
+
self.dates,
|
|
171
|
+
self.cases,
|
|
172
|
+
rng,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
return output
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from abc import ABC
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Perturbation(ABC): ...
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Calvetti(Perturbation):
|
|
8
|
+
"""
|
|
9
|
+
Encapsulates the hyperparameters for the Calvetti static parameter estimation
|
|
10
|
+
method.
|
|
11
|
+
|
|
12
|
+
Attributes
|
|
13
|
+
----------
|
|
14
|
+
a : float, optional
|
|
15
|
+
The weight on the prior particle cloud.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, a=0.9):
|
|
19
|
+
self.a = a
|
|
File without changes
|