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,97 @@
1
+ from typing import Tuple
2
+
3
+ import numpy as np
4
+ from pandas import read_csv
5
+
6
+ from epymorph.adrio.adrio import ADRIO
7
+ from epymorph.adrio.csv import CSVFileTxN
8
+ from epymorph.parameter_fitting.utils.observations import Observations
9
+ from epymorph.rume import RUME
10
+ from epymorph.simulation import Context
11
+ from epymorph.util import extract_date_value, is_date_value_dtype
12
+
13
+
14
+ class DataLoader:
15
+ """
16
+ A class responsible for loading data from various sources such as
17
+ simulations or CSV files.
18
+
19
+ Attributes
20
+ ----------
21
+ rume : Rume
22
+ Simulation parameters and configuration.
23
+ """
24
+
25
+ def __init__(self, rume: RUME) -> None:
26
+ """
27
+ Initializes the DataLoader with simulation parameters.
28
+
29
+ Parameters
30
+ ----------
31
+ rume : Rume
32
+ Simulation runtime environment or configuration object.
33
+ """
34
+ self.rume = rume
35
+
36
+ def load_data(self, observations: Observations) -> Tuple[np.ndarray, np.ndarray]:
37
+ """
38
+ Loads the data from a given source.
39
+
40
+ This method handles two types of sources:
41
+ 1. CSVTimeSeries: Data is loaded from a CSV file.
42
+ 2. Any of the CDC adrios.
43
+
44
+ Parameters
45
+ ----------
46
+ observations : Observations
47
+ The data source.
48
+
49
+ Returns
50
+ -------
51
+ Tuple[np.ndarray, np.ndarray]
52
+ A tuple containing two numpy arrays:
53
+ - dates: An array of date values.
54
+ - sim_data: Simulated or observed case counts, generated using a Poisson
55
+ distribution.
56
+
57
+ Raises
58
+ ------
59
+ ValueError
60
+ Raised if the data source is not supported.
61
+ """
62
+ rng = np.random.default_rng()
63
+ data = self.rume.evaluate_params(rng)
64
+ source = observations.source
65
+
66
+ if isinstance(source, CSVFileTxN):
67
+ csv_df = read_csv(source.file_path)
68
+
69
+ cases = source.with_context_internal(
70
+ Context.of(data=data, scope=self.rume.scope, rng=rng)
71
+ ).evaluate()
72
+
73
+ dates = csv_df.pivot_table(index=csv_df.columns[0]).index.to_numpy()
74
+
75
+ return dates, cases
76
+
77
+ if isinstance(source, ADRIO) and is_date_value_dtype(
78
+ source.result_format.dtype
79
+ ):
80
+ ctx = Context.of(
81
+ data=data,
82
+ time_frame=self.rume.time_frame,
83
+ scope=self.rume.scope,
84
+ rng=rng,
85
+ )
86
+ result = source.with_context_internal(ctx).evaluate()
87
+ if np.ma.is_masked(result):
88
+ err = (
89
+ f"Observation data from {source.class_name} contains unresolved "
90
+ "issues. Use ADRIO constructor options to address all data issues "
91
+ "as appropriate before execution."
92
+ )
93
+ raise ValueError(err)
94
+
95
+ return extract_date_value(result)
96
+
97
+ raise ValueError("Unsupported data source provided.")
@@ -0,0 +1,119 @@
1
+ """
2
+ This module defines the EpymorphSimulation class for initializing and running
3
+ simulations using the Epymorph library.
4
+
5
+ The EpymorphSimulation class is responsible for setting up the simulation environment
6
+ and propagating simulations based on provided observations and parameters.
7
+ """
8
+
9
+ import dataclasses
10
+ from typing import Tuple
11
+
12
+ import numpy as np
13
+
14
+ from epymorph import initializer
15
+ from epymorph.parameter_fitting.utils.observations import ModelLink
16
+ from epymorph.rume import RUME
17
+ from epymorph.simulator.basic.basic_simulator import BasicSimulator
18
+ from epymorph.time import TimeFrame
19
+ from epymorph.tools.data import munge # noqa: F403
20
+
21
+
22
+ class EpymorphSimulation:
23
+ """
24
+ A class to initialize and run simulations using the Epymorph library.
25
+
26
+ Attributes
27
+ ----------
28
+ rume : Rume
29
+ Contains the model and simulation parameters,
30
+ start_date : str
31
+ The start date for the simulation in 'YYYY-MM-DD' format.
32
+ """
33
+
34
+ def __init__(self, rume: RUME, start_date: str):
35
+ """
36
+ Initializes the EpymorphSimulation class with the provided parameters.
37
+
38
+ Parameters
39
+ ----------
40
+ rume : Rume
41
+ Parameters required for the simulation, including model settings.
42
+ start_date : str
43
+ The start date for the simulation in 'YYYY-MM-DD' format.
44
+ """
45
+ self.rume = rume
46
+ self.start_date = start_date
47
+
48
+ def propagate(
49
+ self,
50
+ state: np.ndarray,
51
+ parameters: dict,
52
+ rume: RUME,
53
+ date: str,
54
+ duration: int,
55
+ model_link: ModelLink,
56
+ rng: np.random.Generator,
57
+ ) -> Tuple[np.ndarray, np.ndarray]:
58
+ """
59
+ Propagates the simulation for a specified duration and returns the final state.
60
+
61
+ Parameters
62
+ ----------
63
+ state : np.ndarray
64
+ Initial state of the system (e.g., SIRH compartments)
65
+ to be used in the simulation.
66
+ observations : dict)
67
+ A dictionary containing the parameter values
68
+ (such as beta, gamma, etc.) to update in the simulation.
69
+ rume : Rume
70
+ The model configuration to run the simulation.
71
+ date : str
72
+ The starting date for the simulation in 'YYYY-MM-DD' format.
73
+ duration : int
74
+ The number of days the simulation should be propagated.
75
+ model_link : ModelLink
76
+ Specifies which model output to return, either from
77
+ compartments or events.
78
+
79
+ Returns
80
+ -------
81
+ Tuple[np.ndarray, np.ndarray]
82
+ A tuple containing the final compartment
83
+ state and the processed state (either the sum or last day).
84
+ """
85
+
86
+ # Create a copy of the RUME model with updated parameters and time frame
87
+ rume_propagate = dataclasses.replace(
88
+ self.rume,
89
+ time_frame=TimeFrame.of(date, duration), # Set simulation duration
90
+ strata=[
91
+ dataclasses.replace(
92
+ g, init=initializer.Explicit(initials=state)
93
+ ) # Initialize with state values
94
+ for g in rume.strata # For each stratum, set the initial state
95
+ ],
96
+ )
97
+
98
+ # Initialize the simulation using the BasicSimulator from the Epymorph library
99
+ sim = BasicSimulator(rume_propagate)
100
+
101
+ # Run the simulation and collect the output based on observations
102
+ # (dynamic params)
103
+ output = sim.run(parameters, rng_factory=(lambda: rng))
104
+
105
+ data_df = munge(
106
+ output,
107
+ geo=model_link.geo,
108
+ time=dataclasses.replace(
109
+ model_link.time, time_frame=rume_propagate.time_frame
110
+ ),
111
+ quantity=model_link.quantity,
112
+ )
113
+
114
+ expected_observation = data_df.iloc[-rume.scope.nodes :, -1].to_numpy()
115
+
116
+ # Return the final propagated state as an integer array
117
+ propagated_x = np.array(output.compartments[-1, ...], dtype=np.int64)
118
+
119
+ return propagated_x, expected_observation
@@ -0,0 +1,63 @@
1
+ from typing import Any
2
+
3
+ from epymorph.adrio.adrio import ADRIO
4
+ from epymorph.compartment_model import QuantityAggregation, QuantitySelection
5
+ from epymorph.geography.scope import GeoAggregation, GeoSelection
6
+ from epymorph.parameter_fitting.likelihood import Likelihood
7
+ from epymorph.time import TimeAggregation, TimeSelection
8
+
9
+
10
+ class ModelLink:
11
+ """
12
+ Contains the information needed to compute the expected observation from a
13
+ simulation output.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ time: TimeSelection | TimeAggregation,
19
+ geo: GeoSelection | GeoAggregation,
20
+ quantity: QuantitySelection | QuantityAggregation,
21
+ ):
22
+ self.time = time
23
+ self.geo = geo
24
+ self.quantity = quantity
25
+
26
+
27
+ class Observations:
28
+ """
29
+ The `Observations` class is used to handle observational data for the simulation.
30
+
31
+ Attributes
32
+ ----------
33
+ source : ADRIO[Any, Any] | ADRIOLegacy[Any]
34
+ The data source containing the observational data.
35
+ model_link : ModelLink
36
+ The link that maps the observations to specific
37
+ compartments or events in the model.
38
+ likelihood : Likelihood
39
+ The likelihood function used to compare observed data with model outputs.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ source: ADRIO[Any, Any],
45
+ model_link: ModelLink,
46
+ likelihood: Likelihood,
47
+ ):
48
+ """
49
+ Initializes the Observations class.
50
+
51
+ Parameters
52
+ ----------
53
+ source : ADRIO[Any, Any]
54
+ The data source.
55
+ model_link : ModelLink
56
+ Represents the connection between the observational data and the model's
57
+ compartment or event.
58
+ likelihood : Likelihood
59
+ The likelihood function used to compare observed data with model outputs.
60
+ """
61
+ self.source = source
62
+ self.model_link = model_link
63
+ self.likelihood = likelihood
@@ -0,0 +1,49 @@
1
+ from typing import Literal
2
+
3
+ from epymorph.parameter_fitting.distribution import Distribution
4
+ from epymorph.parameter_fitting.dynamics import Dynamics
5
+ from epymorph.parameter_fitting.perturbation import Perturbation
6
+
7
+
8
+ class EstimateParameters:
9
+ """
10
+ Contains the information needed to estimate a single parameter.
11
+
12
+ Attributes
13
+ ----------
14
+ distribution : Distribution
15
+ The prior (initial) distribution for a static (time varying) parameter.
16
+ dynamics : Dynamics
17
+ The dynamics of the parameter.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ distribution: Distribution,
23
+ dynamics: Dynamics | None,
24
+ perturbation: Perturbation | None,
25
+ ):
26
+ self.distribution = distribution
27
+ self.dynamics = dynamics
28
+ self.perturbation = perturbation
29
+
30
+ @classmethod
31
+ def TimeVarying( # noqa: N802
32
+ cls,
33
+ distribution: Distribution,
34
+ dynamics: Dynamics,
35
+ perturbation: Perturbation | None = None,
36
+ ):
37
+ return cls(distribution, dynamics=dynamics, perturbation=perturbation)
38
+
39
+ @classmethod
40
+ def Static( # noqa: N802
41
+ cls, distribution: Distribution, perturbation: Perturbation | None = None
42
+ ):
43
+ return cls(distribution, dynamics=None, perturbation=perturbation)
44
+
45
+
46
+ class PropagateParams:
47
+ @classmethod
48
+ def propagate_param(cls, approach: Literal["GBM"]):
49
+ return None
@@ -0,0 +1,43 @@
1
+ import numpy as np
2
+
3
+
4
+ class Perturb:
5
+ """
6
+ The `Perturb` class provides methods to apply perturbation to model parameters
7
+ using different stochastic processes. In this case, a geometric Brownian motion
8
+ (GBM) is used to perturb a parameter based on volatility and time duration.
9
+
10
+ Attributes
11
+ ----------
12
+ duration : int
13
+ The time duration over which the perturbation is applied.
14
+ """
15
+
16
+ def __init__(self, duration: int) -> None:
17
+ """
18
+ Initializes the Perturb class with a specified duration.
19
+
20
+ Parameters
21
+ ----------
22
+ duration : int
23
+ The time duration for which the perturbation will be applied.
24
+ """
25
+ self.duration = duration
26
+
27
+ def gbm(self, param, volatility: float, rng: np.random.Generator) -> float:
28
+ """
29
+ Applies geometric Brownian motion (GBM) to perturb the given parameter.
30
+
31
+ Parameters
32
+ ----------
33
+ param : float
34
+ The initial parameter value to be perturbed.
35
+ volatility : float
36
+ The volatility factor that affects the degree of perturbation.
37
+
38
+ Returns
39
+ -------
40
+ float
41
+ The perturbed parameter after applying GBM.
42
+ """
43
+ return np.exp(rng.normal(np.log(param), volatility * np.sqrt(self.duration)))
@@ -0,0 +1,95 @@
1
+ """
2
+ This module provides the ParticleInitializer class for
3
+ initializing particles in the particle filter.
4
+ Each particle is initialized with a state and corresponding
5
+ observations based on specified parameters.
6
+ """
7
+
8
+ from typing import Dict, List
9
+
10
+ import numpy as np
11
+
12
+ from epymorph.parameter_fitting.filter.particle import Particle
13
+ from epymorph.parameter_fitting.utils.parameter_estimation import EstimateParameters
14
+ from epymorph.rume import RUME
15
+
16
+
17
+ class ParticleInitializer:
18
+ """
19
+ A class to initialize particles for the particle filter.
20
+
21
+ Attributes
22
+ ----------
23
+ num_particles : int
24
+ Number of particles.
25
+ num_population : int
26
+ Number of population.
27
+ seed_size : int
28
+ Seed size.
29
+ static_params : Dict[str, Any])
30
+ Static parameters.
31
+ dynamic_params : Dict[str, EstimateParameters]
32
+ Dynamic parameters with their ranges.
33
+ geo : Dict[str, Any]
34
+ Geographical information.
35
+ nodes : int
36
+ Number of nodes in the geographical network.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ num_particles: int,
42
+ rume: RUME,
43
+ dynamic_params: Dict[str, EstimateParameters],
44
+ ) -> None:
45
+ """
46
+ Initializes the ParticleInitializer with the given parameters.
47
+
48
+ Parameters
49
+ ----------
50
+ num_particles : int
51
+ Number of particles.
52
+ rume : Rume
53
+ Model parameters including population size, seed size, static parameters,
54
+ and geographical information.
55
+ dynamic_params : Dict[str, EstimateParameters]
56
+ Dynamic parameters and their ranges.
57
+ """
58
+ self.num_particles = num_particles
59
+ self.rume = rume
60
+ self.dynamic_params = dynamic_params
61
+ self.rng = np.random.default_rng()
62
+
63
+ def initialize_particles(self, rng) -> List[Particle]:
64
+ """
65
+ Initializes particles with random values within the specified ranges for dynamic
66
+ parameters.
67
+
68
+ Returns
69
+ -------
70
+ List[Particle]
71
+ The initialized particles.
72
+ """
73
+
74
+ data = self.rume.evaluate_params(rng)
75
+ initial_state = self.rume.initialize(data, rng)
76
+
77
+ particles = []
78
+
79
+ for _ in range(self.num_particles):
80
+ parameters = {
81
+ _: self.dynamic_params[_].distribution.rvs(
82
+ size=self.rume.scope.nodes, random_state=rng
83
+ )
84
+ for _ in self.dynamic_params.keys()
85
+ }
86
+
87
+ # Create a Particle instance with the initial state and parameters
88
+ particle = Particle(
89
+ state=initial_state,
90
+ parameters=parameters,
91
+ )
92
+
93
+ particles.append(particle)
94
+
95
+ return particles