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
epymorph/data_type.py ADDED
@@ -0,0 +1,185 @@
1
+ """
2
+ In order to assist with proper data type handling in epymorph, we adopt a set of
3
+ conventions that somewhat narrow the possibilities for expressing simulation data
4
+ attributes. This module describes those conventions and provides some utilities for
5
+ working with them. The goal is to simplify and remove certain categories of errors,
6
+ like numerical overflow when simulating reasonable numbers of individuals.
7
+ """
8
+
9
+ from datetime import date
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+ from numpy.typing import NDArray
14
+
15
+ # Types for attribute declarations:
16
+ # these are expressed as Python types for simplicity.
17
+
18
+ # NOTE: In epymorph, we express structured types as tuples-of-tuples;
19
+ # this way they're hashable, which is important for AttributeDef.
20
+ # However numpy expresses them as lists-of-tuples, so we have to convert;
21
+ # thankfully we had an infrastructure for this sort of thing already.
22
+
23
+ ScalarType = type[int | float | str | date]
24
+ """Supported scalar value types."""
25
+ StructType = tuple[tuple[str, ScalarType], ...]
26
+ """Supported structured types."""
27
+ AttributeType = ScalarType | StructType
28
+ """The allowed type declarations for epymorph attributes."""
29
+
30
+ ScalarValue = int | float | str | date
31
+ """Supported scalar values."""
32
+ StructValue = tuple[ScalarValue, ...]
33
+ """Supported structured values."""
34
+ AttributeValue = ScalarValue | StructValue
35
+ """
36
+ The allowed values types for epymorph attribute values
37
+ (most notably used as attribute defaults).
38
+ """
39
+
40
+ ScalarDType = np.int64 | np.float64 | np.str_ | np.datetime64
41
+ """Numpy equivalents to supported scalar values."""
42
+ StructDType = np.void
43
+ """Numpy equivalents to supported structured values."""
44
+ AttributeDType = ScalarDType | StructDType
45
+ """The allowed numpy dtypes for use in epymorph: these map 1:1 with `AttributeType`."""
46
+
47
+ AttributeArray = NDArray[AttributeDType]
48
+ """A type describing all supported numpy array forms for attribute data."""
49
+
50
+
51
+ def dtype_as_np(dtype: AttributeType) -> np.dtype:
52
+ """
53
+ Convert a python-style dtype to its numpy-equivalent using epymorph typing
54
+ conventions.
55
+
56
+ Parameters
57
+ ----------
58
+ dtype :
59
+ The attribute type in Python form, e.g., `int`
60
+
61
+ Returns
62
+ -------
63
+ :
64
+ The numpy equivalent, e.g., `np.int64`
65
+ """
66
+ if dtype is int:
67
+ return np.dtype(np.int64)
68
+ if dtype is float:
69
+ return np.dtype(np.float64)
70
+ if dtype is str:
71
+ return np.dtype(np.str_)
72
+ if dtype is date:
73
+ return np.dtype("datetime64[D]")
74
+ if isinstance(dtype, tuple):
75
+ fields = list(dtype)
76
+ if len(fields) == 0:
77
+ raise ValueError(f"Unsupported dtype: {dtype}")
78
+ try:
79
+ return np.dtype(
80
+ [
81
+ (field_name, dtype_as_np(field_dtype))
82
+ for field_name, field_dtype in fields
83
+ ]
84
+ )
85
+ except (TypeError, ValueError):
86
+ raise ValueError(f"Unsupported dtype: {dtype}") from None
87
+ raise ValueError(f"Unsupported dtype: {dtype}")
88
+
89
+
90
+ def dtype_str(dtype: AttributeType) -> str:
91
+ """
92
+ Return a human-readable description of the given attribute data type.
93
+
94
+ Parameters
95
+ ----------
96
+ dtype :
97
+ The attribute type in Python form, e.g., `int`
98
+
99
+ Returns
100
+ -------
101
+ :
102
+ The friendly string representation of the type.
103
+ """
104
+ if dtype is int:
105
+ return "int"
106
+ if dtype is float:
107
+ return "float"
108
+ if dtype is str:
109
+ return "str"
110
+ if dtype is date:
111
+ return "date"
112
+ if isinstance(dtype, tuple):
113
+ fields = list(dtype)
114
+ if len(fields) == 0:
115
+ raise ValueError(f"Unsupported dtype: {dtype}")
116
+ try:
117
+ values = [
118
+ f"({field_name}, {dtype_str(field_dtype)})"
119
+ for field_name, field_dtype in fields
120
+ ]
121
+ return f"[{', '.join(values)}]"
122
+ except (TypeError, ValueError):
123
+ raise ValueError(f"Unsupported dtype: {dtype}") from None
124
+ raise ValueError(f"Unsupported dtype: {dtype}")
125
+
126
+
127
+ def dtype_check(dtype: AttributeType, value: Any) -> bool:
128
+ """
129
+ Check that a singular Python value conforms to the given attribute data type.
130
+ This is not intended to check numpy arrays, only scalars and tuples.
131
+
132
+ Parameters
133
+ ----------
134
+ dtype :
135
+ The attribute type in Python form, e.g., `int`
136
+ value :
137
+ A value to check.
138
+
139
+ Returns
140
+ -------
141
+ :
142
+ True if the values matches the dtype.
143
+ """
144
+ if dtype in (int, float, str, date):
145
+ return isinstance(value, dtype)
146
+ if isinstance(dtype, tuple):
147
+ fields = list(dtype)
148
+ if not isinstance(value, tuple):
149
+ return False
150
+ if len(value) != len(fields):
151
+ return False
152
+ return all(
153
+ (
154
+ dtype_check(field_dtype, field_value)
155
+ for ((_, field_dtype), field_value) in zip(fields, value)
156
+ )
157
+ )
158
+ raise ValueError(f"Unsupported dtype: {dtype}")
159
+
160
+
161
+ CentroidType: AttributeType = (("longitude", float), ("latitude", float))
162
+ """Structured epymorph type declaration for longitude/latitude coordinates."""
163
+ CentroidDType: np.dtype[np.void] = dtype_as_np(CentroidType)
164
+ """
165
+ The numpy equivalent of `CentroidType`
166
+ (structured dtype for longitude/latitude coordinates).
167
+ """
168
+
169
+ SimDType = np.int64
170
+ """
171
+ This is the numpy datatype that should be used to represent internal simulation data.
172
+ Where segments of the application maintain compartment and/or event counts,
173
+ they should take pains to use this type at all times (if possible).
174
+ """
175
+ # NOTE: SimDType being centrally-located means we can change it reliably.
176
+
177
+ SimArray = NDArray[SimDType]
178
+ """Type alias for a numpy array of `SimDType`."""
179
+
180
+ __all__ = [
181
+ "AttributeType",
182
+ "AttributeArray",
183
+ "CentroidType",
184
+ "SimDType",
185
+ ]
epymorph/data_usage.py ADDED
@@ -0,0 +1,258 @@
1
+ """Data usage estimation and reporting."""
2
+
3
+ from abc import abstractmethod
4
+ from dataclasses import dataclass
5
+ from functools import partial
6
+ from math import floor, inf
7
+ from pathlib import Path
8
+ from shutil import disk_usage
9
+ from typing import Protocol, Sequence, runtime_checkable
10
+
11
+ from humanize import naturaldelta, naturalsize
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class EmptyDataEstimate:
16
+ """
17
+ When an entity is not capable of making a data usage estimate, it returns
18
+ `EmptyDataEstimate` as a placeholder.
19
+
20
+ Parameters
21
+ ----------
22
+ name :
23
+ The name of the entity that provided the estimate.
24
+ """
25
+
26
+ name: str
27
+ """The name of the entity that provided the estimate."""
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class AvailableDataEstimate:
32
+ """
33
+ An estimate for the data usage of a data fetch operation.
34
+
35
+ Operations may download data and may utilize disk caching, so we would like
36
+ to be able to estimate ahead of time how much data to expect. Because these are
37
+ estimates, accuracy is not guaranteed.
38
+
39
+ For example, an ADRIO which fetches data from a third-party source may be able to
40
+ estimate ahead of time how much data needs to be downloaded and stored.
41
+
42
+ Parameters
43
+ ----------
44
+ name :
45
+ The name of the entity that provided the estimate.
46
+ cache_key :
47
+ A unique identifier for the data this estimate is about.
48
+ new_network_bytes :
49
+ How much new data (in bytes) will need to be downloaded.
50
+ max_bandwidth :
51
+ A source-specific limit on download bandwidth in bytes per second.
52
+ new_cache_bytes :
53
+ How much new data (in bytes) will be written to disk cache.
54
+ total_cache_bytes :
55
+ The total data (in bytes) that will be in the cache after fetch.
56
+ This includes newly-cached and previously-cached files.
57
+ """
58
+
59
+ name: str
60
+ """The name of the entity that provided the estimate."""
61
+ cache_key: str
62
+ """
63
+ A unique identifier for the data this estimate is about.
64
+
65
+ Multiple entities may load the same set of data; although both would report the same
66
+ estimate, the actual data usage only happens for the first one to load. The rest
67
+ would find and return the cached data. This key is used to distinguish this case --
68
+ if two estimates share the same key, we can assume the estimate should only be
69
+ counted once. Cache keys are only comparable within a single simulation context,
70
+ so we don't need to perfectly distinguish between different scopes or time frames.
71
+ """
72
+ new_network_bytes: int
73
+ """How much new data (in bytes) will need to be downloaded."""
74
+ max_bandwidth: int | None
75
+ """
76
+ A source-specific limit on download bandwidth in bytes per second.
77
+ (In case data sources impose known limits on download speed.)
78
+ """
79
+ new_cache_bytes: int
80
+ """How much new data (in bytes) will be written to disk cache."""
81
+ total_cache_bytes: int
82
+ """
83
+ The total data (in bytes) that will be in the cache after fetch.
84
+ This includes newly-cached and previously-cached files.
85
+ """
86
+
87
+
88
+ DataEstimate = EmptyDataEstimate | AvailableDataEstimate
89
+ """`DataEstimate`s can be either empty or non-empty."""
90
+
91
+
92
+ @runtime_checkable
93
+ class CanEstimateData(Protocol):
94
+ """A checkable protocol which indicates entities that can produce data estimates."""
95
+
96
+ @abstractmethod
97
+ def estimate_data(self) -> DataEstimate:
98
+ """
99
+ Estimate the data usage for this entity.
100
+
101
+ If a reasonable estimate cannot be made, return an `EmptyDataEstimate`.
102
+
103
+ Returns
104
+ -------
105
+ :
106
+ The data estimate.
107
+ """
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class DataEstimateTotal:
112
+ """
113
+ The computed total of one or more estimates.
114
+
115
+ Parameters
116
+ ----------
117
+ new_network_bytes :
118
+ How much new data (in bytes) will need to be downloaded.
119
+ new_cache_bytes :
120
+ How much new data (in bytes) will be written to disk cache.
121
+ total_cache_bytes :
122
+ The total data (in bytes) that will be in the cache after fetch.
123
+ download_time :
124
+ The estimated time (in seconds) to download all new data.
125
+ """
126
+
127
+ new_network_bytes: int
128
+ """How much new data (in bytes) will need to be downloaded."""
129
+ new_cache_bytes: int
130
+ """How much new data (in bytes) will be written to disk cache."""
131
+ total_cache_bytes: int
132
+ """The total data (in bytes) that will be in the cache after fetch."""
133
+ download_time: float
134
+ """The estimated time (in seconds) to download all new data."""
135
+
136
+
137
+ def estimate_total(
138
+ estimates: Sequence[DataEstimate],
139
+ max_bandwidth: int,
140
+ ) -> DataEstimateTotal:
141
+ """
142
+ Compute the total of a set of data estimates.
143
+
144
+ A download time estimate is also provided, taking into account the assumed bandwidth
145
+ limit (`max_bandwidth`) as well as any source-specific bandwidth limits.
146
+
147
+ Parameters
148
+ ----------
149
+ estimates :
150
+ The estimates to combine.
151
+ max_bandwidth :
152
+ The assumed maximum download bandwidth, in bytes per second.
153
+
154
+ Returns
155
+ -------
156
+ :
157
+ The estimate total.
158
+ """
159
+ new_net = 0
160
+ new_cache = 0
161
+ tot_cache = 0
162
+ download_time = 0.0
163
+
164
+ cache_keys = set[str]()
165
+ for e in estimates:
166
+ if not isinstance(e, AvailableDataEstimate):
167
+ continue
168
+ if e.cache_key in cache_keys:
169
+ continue
170
+ cache_keys.add(e.cache_key)
171
+ new_net += e.new_network_bytes
172
+ new_cache += e.new_cache_bytes
173
+ tot_cache += e.total_cache_bytes
174
+ download_time += e.new_network_bytes / (
175
+ min(max_bandwidth, e.max_bandwidth or inf)
176
+ )
177
+
178
+ return DataEstimateTotal(new_net, new_cache, tot_cache, download_time)
179
+
180
+
181
+ def estimate_report(
182
+ cache_path: Path,
183
+ estimates: Sequence[DataEstimate],
184
+ max_bandwidth: int,
185
+ ) -> list[str]:
186
+ """
187
+ Generate a report from the given set of data estimates.
188
+
189
+ The report describes an itemized list of how much data will be downloaded and how
190
+ much new data will be written to cache, then totals that up and reports how long
191
+ that will take and whether or not there is enough available disk space.
192
+
193
+ Parameters
194
+ ----------
195
+ cache_path :
196
+ The path of epymorph's cache folder.
197
+ estimates :
198
+ The data estimates.
199
+ max_bandwidth :
200
+ The assumed maximum download bandwidth, in bytes per second.
201
+
202
+ Returns
203
+ -------
204
+ :
205
+ The report, as a list of lines.
206
+ """
207
+ # short-hand formatting functions
208
+ ff = partial(naturalsize, binary=False) # format file size
209
+ ft = naturaldelta # format time duration
210
+
211
+ cache_keys = set[str]()
212
+ result = list[str]()
213
+ for e in estimates:
214
+ if isinstance(e, AvailableDataEstimate):
215
+ if e.cache_key in cache_keys or (
216
+ (e.new_network_bytes) == 0 or (e.new_cache_bytes) == 0
217
+ ):
218
+ line = f"- {e.name} will be pulled from cache"
219
+ else:
220
+ line = f"- {e.name} will download {ff(e.new_network_bytes)} of new data"
221
+ cache_keys.add(e.cache_key)
222
+ else:
223
+ line = f"- {e.name} (no estimate available)"
224
+ result.append(line)
225
+
226
+ total = estimate_total(estimates, max_bandwidth)
227
+ result.append("In total we will:")
228
+
229
+ if total.new_network_bytes == 0:
230
+ result.append("- Download no additional data")
231
+ else:
232
+ result.append(
233
+ f"- Download {ff(total.new_network_bytes)}, "
234
+ f"taking {ft(total.download_time)} "
235
+ f"(assuming {ff(max_bandwidth)}/s)"
236
+ )
237
+
238
+ available_space = disk_usage(cache_path).free
239
+ if total.new_cache_bytes == 0:
240
+ result.append("- Write no new data to disk cache")
241
+ elif total.new_cache_bytes < floor(available_space * 0.9):
242
+ result.append(
243
+ f"- Write {ff(total.new_cache_bytes)} to disk cache "
244
+ f"(you have {ff(available_space)} free space)"
245
+ )
246
+ elif total.new_cache_bytes < available_space:
247
+ result.append(f"- Write {ff(total.new_cache_bytes)} to disk cache")
248
+ result.append(
249
+ "WARNING: this is very close to exceeding available free space "
250
+ f"of {ff(available_space)}!"
251
+ )
252
+ else:
253
+ result.append(f"- Write {ff(total.new_cache_bytes)} to disk cache")
254
+ result.append(
255
+ f"ERROR: this exceeds available free space of {ff(available_space)}!"
256
+ )
257
+
258
+ return result