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.
Files changed (104) hide show
  1. epymorph/__init__.py +7 -0
  2. epymorph/__main__.py +16 -0
  3. epymorph/adrio/__init__.py +0 -0
  4. epymorph/adrio/acs5.py +1378 -0
  5. epymorph/adrio/adrio.py +953 -0
  6. epymorph/adrio/cdc.py +1826 -0
  7. epymorph/adrio/commuting_flows.py +283 -0
  8. epymorph/adrio/csv.py +499 -0
  9. epymorph/adrio/humidity.py +206 -0
  10. epymorph/adrio/lodes.py +509 -0
  11. epymorph/adrio/numpy.py +160 -0
  12. epymorph/adrio/prism.py +345 -0
  13. epymorph/adrio/processing.py +1221 -0
  14. epymorph/adrio/soda.py +602 -0
  15. epymorph/adrio/us_tiger.py +289 -0
  16. epymorph/adrio/validation.py +382 -0
  17. epymorph/attribute.py +614 -0
  18. epymorph/cache.py +680 -0
  19. epymorph/cli/__init__.py +0 -0
  20. epymorph/cli/cache.py +78 -0
  21. epymorph/cli/main.py +29 -0
  22. epymorph/compartment_model.py +1873 -0
  23. epymorph/data/__init__.py +1 -0
  24. epymorph/data/ipm/__init__.py +22 -0
  25. epymorph/data/ipm/no.py +14 -0
  26. epymorph/data/ipm/pei.py +40 -0
  27. epymorph/data/ipm/seirs.py +50 -0
  28. epymorph/data/ipm/sirh.py +55 -0
  29. epymorph/data/ipm/sirs.py +48 -0
  30. epymorph/data/ipm/sparsemod.py +96 -0
  31. epymorph/data/mm/__init__.py +22 -0
  32. epymorph/data/mm/centroids.py +76 -0
  33. epymorph/data/mm/flat.py +61 -0
  34. epymorph/data/mm/icecube.py +50 -0
  35. epymorph/data/mm/no.py +29 -0
  36. epymorph/data/mm/pei.py +105 -0
  37. epymorph/data/mm/sparsemod.py +73 -0
  38. epymorph/data/pei.py +424 -0
  39. epymorph/data_shape.py +593 -0
  40. epymorph/data_type.py +185 -0
  41. epymorph/data_usage.py +258 -0
  42. epymorph/database.py +1301 -0
  43. epymorph/error.py +195 -0
  44. epymorph/event.py +196 -0
  45. epymorph/geography/__init__.py +0 -0
  46. epymorph/geography/custom.py +93 -0
  47. epymorph/geography/scope.py +457 -0
  48. epymorph/geography/us_census.py +1056 -0
  49. epymorph/geography/us_geography.py +502 -0
  50. epymorph/geography/us_tiger.py +1083 -0
  51. epymorph/initializer.py +786 -0
  52. epymorph/kit.py +107 -0
  53. epymorph/log/__init__.py +0 -0
  54. epymorph/log/file.py +128 -0
  55. epymorph/log/messaging.py +139 -0
  56. epymorph/log/movement.py +228 -0
  57. epymorph/movement_model.py +347 -0
  58. epymorph/parameter_fitting/__init__.py +0 -0
  59. epymorph/parameter_fitting/distribution.py +68 -0
  60. epymorph/parameter_fitting/dynamics.py +19 -0
  61. epymorph/parameter_fitting/filter/__init__.py +0 -0
  62. epymorph/parameter_fitting/filter/base_filter.py +50 -0
  63. epymorph/parameter_fitting/filter/particle.py +32 -0
  64. epymorph/parameter_fitting/filter/particle_filter.py +296 -0
  65. epymorph/parameter_fitting/likelihood.py +54 -0
  66. epymorph/parameter_fitting/output.py +73 -0
  67. epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
  68. epymorph/parameter_fitting/perturbation.py +19 -0
  69. epymorph/parameter_fitting/utils/__init__.py +0 -0
  70. epymorph/parameter_fitting/utils/data_loader.py +97 -0
  71. epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
  72. epymorph/parameter_fitting/utils/observations.py +63 -0
  73. epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
  74. epymorph/parameter_fitting/utils/params_perturb.py +43 -0
  75. epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
  76. epymorph/parameter_fitting/utils/resampler.py +258 -0
  77. epymorph/parameter_fitting/utils/utils.py +101 -0
  78. epymorph/params.py +438 -0
  79. epymorph/py.typed +0 -0
  80. epymorph/rume.py +871 -0
  81. epymorph/simulation.py +991 -0
  82. epymorph/simulator/__init__.py +0 -0
  83. epymorph/simulator/basic/__init__.py +0 -0
  84. epymorph/simulator/basic/basic_simulator.py +171 -0
  85. epymorph/simulator/basic/ipm_exec.py +437 -0
  86. epymorph/simulator/basic/mm_exec.py +244 -0
  87. epymorph/simulator/basic/output.py +213 -0
  88. epymorph/simulator/world.py +149 -0
  89. epymorph/simulator/world_list.py +274 -0
  90. epymorph/strata.py +24 -0
  91. epymorph/sympy_shim.py +57 -0
  92. epymorph/time.py +1197 -0
  93. epymorph/tools/__init__.py +0 -0
  94. epymorph/tools/data.py +297 -0
  95. epymorph/tools/ipm_diagram.py +208 -0
  96. epymorph/tools/out_map.py +551 -0
  97. epymorph/tools/out_plot.py +423 -0
  98. epymorph/tools/out_table.py +582 -0
  99. epymorph/util.py +1036 -0
  100. epymorph-1.0.0.dist-info/METADATA +57 -0
  101. epymorph-1.0.0.dist-info/RECORD +104 -0
  102. epymorph-1.0.0.dist-info/WHEEL +5 -0
  103. epymorph-1.0.0.dist-info/entry_points.txt +2 -0
  104. epymorph-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,258 @@
1
+ import numpy as np
2
+
3
+ from epymorph.parameter_fitting.filter.particle import Particle
4
+
5
+
6
+ class WeightsResampling:
7
+ """
8
+ A class for computing and resampling weights in particle filtering.
9
+
10
+ Attributes
11
+ ----------
12
+ N : int
13
+ Number of particles.
14
+ static_params : dict
15
+ Static parameters from the rume dictionary.
16
+ likelihood_fn : object
17
+ An object responsible for computing the
18
+ likelihood of observations.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ N: int,
24
+ likelihood_fn,
25
+ ) -> None:
26
+ """
27
+ Initializes the WeightsResampling class with provided parameters.
28
+
29
+ Parameters
30
+ ----------
31
+ N : int
32
+ Number of particles.
33
+ likelihood_fn : object
34
+ An object for computing the likelihood of
35
+ observations.
36
+ """
37
+ self.N = N
38
+ self.likelihood_fn = likelihood_fn
39
+
40
+ def compute_weights(
41
+ self, current_obs_data: np.ndarray, expected_observations: list
42
+ ) -> np.ndarray:
43
+ """
44
+ Computes the weights for each particle based on the likelihood of the
45
+ current observation.
46
+
47
+ Parameters
48
+ ----------
49
+ current_obs_data : np.ndarray
50
+ The current observation data.
51
+ expected_observations : list
52
+ The expected observations corresponding
53
+ to each particle.
54
+
55
+ Returns
56
+ -------
57
+ np.ndarray
58
+ An array of computed weights normalized to sum to 1.
59
+ """
60
+ log_weights = np.zeros(self.N)
61
+
62
+ for i in range(self.N):
63
+ expected = expected_observations[i]
64
+ try:
65
+ log_weights[i] = np.nansum(
66
+ np.log(self.likelihood_fn.compute(current_obs_data, expected))
67
+ )
68
+ except (ValueError, FloatingPointError):
69
+ log_weights[i] = -np.inf
70
+
71
+ # Compute the softmax of log_weights, which yields the normalized weights.
72
+ try:
73
+ shifted_log_weights = log_weights - np.max(log_weights, keepdims=True)
74
+ except FloatingPointError:
75
+ shifted_log_weights = np.zeros(shape=log_weights.shape)
76
+ underflow_lower_bound = -(10**2)
77
+ clipped_log_weights = np.clip(
78
+ shifted_log_weights, a_min=underflow_lower_bound, a_max=None
79
+ )
80
+ weights = np.exp(clipped_log_weights)
81
+ weights = weights / np.sum(weights, keepdims=True)
82
+
83
+ return np.squeeze(weights)
84
+
85
+ def resample_particles(
86
+ self, particles: list, weights: np.ndarray, rng: np.random.Generator
87
+ ) -> list:
88
+ """
89
+ Resamples particles based on the computed weights.
90
+
91
+ Parameters
92
+ ----------
93
+ particles : list
94
+ Particles which represent the estimated state of the system.
95
+ weights : np.ndarray
96
+ Wights corresponding to each particle.
97
+
98
+ Returns
99
+ -------
100
+ list
101
+ The resampled particles.
102
+ """
103
+ resampled_particles = []
104
+ resampled_indices = rng.choice(
105
+ np.arange(self.N), size=self.N, replace=True, p=weights
106
+ )
107
+ [resampled_particles.append(particles[idx]) for idx in resampled_indices]
108
+ return resampled_particles
109
+
110
+ def update_weights(self, weights: np.ndarray, new_weights: np.ndarray) -> list:
111
+ """
112
+ Updates the weights by multiplying current weights with new weights.
113
+
114
+ Parameters
115
+ ----------
116
+ weights : np.ndarray
117
+ The current weights of the particles.
118
+ new_weights : np.ndarray
119
+ The new weights to be multiplied with the
120
+ current weights.
121
+
122
+ Returns
123
+ -------
124
+ list
125
+ The updated weights.
126
+ """
127
+ updated_weights = [
128
+ new_weight * weight for weight, new_weight in zip(weights, new_weights)
129
+ ]
130
+ return updated_weights
131
+
132
+
133
+ class ResamplingByNode(WeightsResampling):
134
+ """
135
+ Uses an approximate resampling algorithm which is efficient for multi-node systems.
136
+ The weights for each node are computed separately. During resampling the particles
137
+ are decomposed by node, each node is resampled separately, and new particles are
138
+ reconstructed treating nodes independently.
139
+
140
+ Attributes
141
+ ----------
142
+ N : int
143
+ Number of particles.
144
+ static_params : dict
145
+ Static parameters from the rume dictionary.
146
+ likelihood_fn : object
147
+ An object responsible for computing the
148
+ likelihood of observations.
149
+ """
150
+
151
+ def compute_weights(
152
+ self, current_obs_data: np.ndarray, expected_observations: list
153
+ ) -> np.ndarray:
154
+ """
155
+ Computes the weights for each node for each particle based on the likelihood of
156
+ the current observation.
157
+
158
+ Parameters
159
+ ----------
160
+ current_obs_data : np.ndarray
161
+ The current observation data.
162
+ expected_observations : list
163
+ The expected observations corresponding
164
+ to each particle.
165
+
166
+ Returns
167
+ -------
168
+ np.ndarray
169
+ An array of computed weights with each row normalized to sum to 1.
170
+ """
171
+ n_nodes = expected_observations[0].shape[0]
172
+ log_weights = np.zeros(shape=(n_nodes, self.N))
173
+ shifted_log_weights = np.zeros(shape=(n_nodes, self.N))
174
+
175
+ for i_node in range(n_nodes):
176
+ if not np.isnan(current_obs_data[i_node]):
177
+ for i_particle in range(self.N):
178
+ expected = expected_observations[i_particle][i_node]
179
+ try:
180
+ log_weights[i_node, i_particle] = np.log(
181
+ self.likelihood_fn.compute(
182
+ current_obs_data[i_node], expected
183
+ )
184
+ )
185
+ except (ValueError, FloatingPointError):
186
+ log_weights[i_node, i_particle] = -np.inf
187
+ try:
188
+ shifted_log_weights[i_node, :] = log_weights[i_node, :] - np.max(
189
+ log_weights[i_node, :], keepdims=True
190
+ )
191
+ except FloatingPointError:
192
+ shifted_log_weights[i_node, :] = 0
193
+
194
+ underflow_lower_bound = -(10**2)
195
+ clipped_log_weights = np.clip(
196
+ shifted_log_weights, a_min=underflow_lower_bound, a_max=None
197
+ )
198
+ weights = np.exp(clipped_log_weights)
199
+ weights = weights / np.sum(weights, axis=1, keepdims=True)
200
+
201
+ return weights
202
+
203
+ def resample_particles(
204
+ self, particles: list[Particle], weights: np.ndarray, rng: np.random.Generator
205
+ ) -> list:
206
+ """
207
+ Resamples particles using an approximate algorithm based on the computed
208
+ weights. The particles are deconstructed by node, each node is resampled
209
+ independently, then new particles are reconstructed.
210
+
211
+ Parameters
212
+ ----------
213
+ particles : list
214
+ Particles which represent the estimated state of the system.
215
+ weights : np.ndarray
216
+ Wights corresponding to each node for each particle.
217
+
218
+ Returns
219
+ -------
220
+ list
221
+ The resampled particles.
222
+ """
223
+ n_nodes = weights.shape[0]
224
+
225
+ resampled_indices = np.zeros(shape=(n_nodes, self.N), dtype=np.int_)
226
+ for i_node in range(n_nodes):
227
+ resampled_indices[i_node, :] = rng.choice(
228
+ np.arange(self.N, dtype=np.int_),
229
+ size=self.N,
230
+ replace=True,
231
+ p=weights[i_node, :],
232
+ )
233
+
234
+ resampled_particles = []
235
+ for i_particle in range(self.N):
236
+ new_state = np.zeros_like(particles[i_particle].state)
237
+ new_parameters = {}
238
+
239
+ for i_node in range(n_nodes):
240
+ new_state[i_node, :] = particles[
241
+ resampled_indices[i_node, i_particle]
242
+ ].state[i_node, :]
243
+
244
+ for key, value in particles[i_particle].parameters.items():
245
+ new_value = np.zeros_like(value)
246
+ for i_node in range(n_nodes):
247
+ idx = resampled_indices[i_node, i_particle]
248
+ new_value[i_node] = particles[idx].parameters[key][i_node]
249
+ new_parameters[key] = new_value
250
+
251
+ resampled_particles.append(
252
+ Particle(
253
+ new_state,
254
+ new_parameters,
255
+ )
256
+ )
257
+
258
+ return resampled_particles
@@ -0,0 +1,101 @@
1
+ """
2
+ This module provides utility functions for quantile computation and data saving.
3
+
4
+ It contains the Utils class with static methods to calculate quantiles and save data to
5
+ CSV files.
6
+ """
7
+
8
+ from typing import Dict, List
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ # class Utils:
14
+ # """
15
+ # A class providing utility functions for statistical calculations and data
16
+ # management.
17
+
18
+ # Methods:
19
+ # quantiles(items: List[float]) -> List[float]:
20
+ # Computes specified quantiles for a list of items.
21
+
22
+ # save_data(observations_quantiles: Dict[str, List[float]],
23
+ # observations_values: Dict[str, List[float]]):
24
+ # Saves quantiles and average values of observations to CSV files.
25
+ # """
26
+
27
+
28
+ # @staticmethod
29
+ def quantiles(items: np.ndarray) -> List[float]:
30
+ """
31
+ Computes specified quantiles for a list of items.
32
+
33
+ Parameters
34
+ ----------
35
+ items : List[float]
36
+ Numerical values to compute quantiles of.
37
+
38
+ Returns
39
+ -------
40
+ List[float]
41
+ Quantile values for the provided items.
42
+ """
43
+ qtl_mark = 1.00 * np.array(
44
+ [
45
+ 0.010,
46
+ 0.025,
47
+ 0.050,
48
+ 0.100,
49
+ 0.150,
50
+ 0.200,
51
+ 0.250,
52
+ 0.300,
53
+ 0.350,
54
+ 0.400,
55
+ 0.450,
56
+ 0.500,
57
+ 0.550,
58
+ 0.600,
59
+ 0.650,
60
+ 0.700,
61
+ 0.750,
62
+ 0.800,
63
+ 0.850,
64
+ 0.900,
65
+ 0.950,
66
+ 0.975,
67
+ 0.990,
68
+ ]
69
+ )
70
+ return np.quantile(items, qtl_mark, axis=0)
71
+
72
+
73
+ # @staticmethod
74
+ def save_data(observations: Dict[str, List[float]] | List, quantiles: bool) -> None:
75
+ """
76
+ Saves quantiles and average values of observations to CSV files.
77
+
78
+ Parameters
79
+ ----------
80
+ observations_quantiles : Dict[str, List[float]]
81
+ Quantiles of the predicted data.
82
+ observations_values : Dict[str, List[float]]
83
+ Average of the predicted data
84
+ """
85
+ if isinstance(observations, dict):
86
+ for key in observations.keys():
87
+ # Save average values
88
+ if quantiles:
89
+ # Save quantiles
90
+ pd.DataFrame(observations[key]).to_csv(
91
+ f"./epymorph/parameter_fitting/data/{key}_quantiles.csv"
92
+ )
93
+ else:
94
+ pd.DataFrame(observations[key]).to_csv(
95
+ f"./epymorph/parameter_fitting/data/{key}_values.csv"
96
+ )
97
+ elif isinstance(observations, List):
98
+ # Assuming the lists are aligned, save quantiles and values by index
99
+ pd.DataFrame(observations).to_csv(
100
+ "./epymorph/parameter_fitting/data/observations.csv", index=False
101
+ )