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,345 @@
1
+ """ADRIOs that access PRISM files for climate data."""
2
+
3
+ from abc import abstractmethod
4
+ from datetime import date, timedelta
5
+ from pathlib import Path
6
+ from typing import Iterable, Literal, NamedTuple, Protocol
7
+
8
+ import numpy as np
9
+ import rasterio.io as rio
10
+ from dateutil.relativedelta import relativedelta
11
+ from numpy.typing import NDArray
12
+ from typing_extensions import override
13
+
14
+ from epymorph.adrio.adrio import (
15
+ ADRIO,
16
+ ADRIOCommunicationError,
17
+ ADRIOContextError,
18
+ InspectResult,
19
+ adrio_cache,
20
+ )
21
+ from epymorph.adrio.validation import (
22
+ ResultFormat,
23
+ )
24
+ from epymorph.attribute import AttributeDef
25
+ from epymorph.cache import check_file_in_cache, load_or_fetch_url, module_cache_path
26
+ from epymorph.data_shape import Shapes
27
+ from epymorph.data_type import CentroidType
28
+ from epymorph.data_usage import AvailableDataEstimate, DataEstimate
29
+ from epymorph.geography.us_census import CensusScope
30
+ from epymorph.geography.us_geography import STATE
31
+ from epymorph.simulation import Context
32
+ from epymorph.time import TimeFrame
33
+
34
+ _PRISM_CACHE_PATH = module_cache_path(__name__)
35
+
36
+ TemperatureType = Literal["Minimum", "Mean", "Maximum"]
37
+ """A daily temperature measurement provided in the PRISM data."""
38
+
39
+ VPDType = Literal["Minimum", "Maximum"]
40
+ """A daily vapor pressure deficit measurement provided in the PRISM data."""
41
+
42
+
43
+ class _PrismFile(NamedTuple):
44
+ url: str
45
+ bil_name: str
46
+ cache_path: Path
47
+
48
+
49
+ def _prism_files(time_frame: TimeFrame, attribute: str) -> list[_PrismFile]:
50
+ """Compute the complete list of PRISM files needed."""
51
+ latest_date = date.today() - timedelta(days=1)
52
+ six_months_ago = date.today() + relativedelta(months=-6)
53
+ last_completed_month = six_months_ago.replace(day=1) - timedelta(days=1)
54
+
55
+ files = []
56
+ for file_date in time_frame:
57
+ if file_date.year == latest_date.year and file_date.month == latest_date.month:
58
+ stability = "early"
59
+ elif file_date > last_completed_month:
60
+ # if it is before the last finished month
61
+ stability = "provisional"
62
+ else:
63
+ # if it is older than 6 completed months
64
+ stability = "stable"
65
+
66
+ name = f"PRISM_{attribute}_{stability}_4kmD2_{file_date.strftime('%Y%m%d')}_bil"
67
+ files.append(
68
+ _PrismFile(
69
+ url=f"https://ftp.prism.oregonstate.edu/daily/{attribute}/{file_date.year}/{name}.zip",
70
+ bil_name=f"{name}.bil",
71
+ cache_path=_PRISM_CACHE_PATH / f"{name}.zip",
72
+ )
73
+ )
74
+ return files
75
+
76
+
77
+ class _Sampler(Protocol):
78
+ """A strategy for sampling values from the rasterized PRISM files."""
79
+
80
+ # NOTE: although currently there's only one implementation of _Sampler,
81
+ # in future, it may be possible to choose or provide a sampler to the PRISM ADRIOs.
82
+
83
+ @abstractmethod
84
+ def sample(self, raster: rio.DatasetReader, centroids: NDArray) -> list[float]:
85
+ pass
86
+
87
+
88
+ class _CentroidSampler(_Sampler):
89
+ """A sampler that uses the data value of the pixel containing each centroid."""
90
+
91
+ @override
92
+ def sample(self, raster: rio.DatasetReader, centroids: NDArray) -> list[float]:
93
+ return [x[0] for x in raster.sample(centroids)]
94
+
95
+
96
+ class _PrismADRIOMixin(ADRIO[np.float64, np.float64]):
97
+ """Shared functionality for PRISM ADRIOs."""
98
+
99
+ _CENTROID = AttributeDef("centroid", type=CentroidType, shape=Shapes.N)
100
+
101
+ requirements = (_CENTROID,)
102
+
103
+ @property
104
+ @override
105
+ def result_format(self) -> ResultFormat:
106
+ return ResultFormat(shape=Shapes.TxN, dtype=np.float64)
107
+
108
+ @override
109
+ def validate_context(self, context: Context) -> None:
110
+ scope = self.scope
111
+ if isinstance(scope, CensusScope):
112
+ # Hawaii, Alaska, and Puerto Rico aren't included in the standard dataset
113
+ states = list(STATE.truncate_unique(scope.node_ids))
114
+ if any(x in ("72", "02", "15") for x in states):
115
+ err = (
116
+ "Alaska, Hawaii, and Puerto Rico cannot be evaluated for PRISM "
117
+ "attributes. Please use geo scopes within the 48 contiguous states."
118
+ )
119
+ raise ADRIOContextError(self, context, err)
120
+
121
+ # PRISM only accounts for dates from 1981 up to yesterday's date
122
+ earliest_date = date(1981, 1, 1)
123
+ latest_date = date.today() - timedelta(days=1)
124
+ tf = self.time_frame
125
+ if tf.start_date < earliest_date or tf.end_date > latest_date:
126
+ err = (
127
+ "Given date range is out of PRISM scope, please enter dates between "
128
+ f"1981-01-01 and {latest_date}"
129
+ )
130
+ raise ADRIOContextError(self, context, err)
131
+
132
+ @property
133
+ @abstractmethod
134
+ def _attribute_name(self) -> str:
135
+ pass
136
+
137
+ @property
138
+ @abstractmethod
139
+ def _file_size(self) -> int:
140
+ pass
141
+
142
+ @override
143
+ def estimate_data(self) -> DataEstimate:
144
+ time_frame = self.time_frame
145
+ attribute = self._attribute_name
146
+
147
+ files = _prism_files(time_frame, attribute)
148
+ total_files = len(files)
149
+ missing_files = sum(1 for _, _, path in files if not check_file_in_cache(path))
150
+
151
+ est_file_size = self._file_size
152
+ total = total_files * est_file_size
153
+ missing = missing_files * est_file_size
154
+
155
+ return AvailableDataEstimate(
156
+ name=self.class_name,
157
+ cache_key=f"prism:{attribute}:{time_frame}",
158
+ new_network_bytes=missing,
159
+ new_cache_bytes=missing,
160
+ total_cache_bytes=total,
161
+ max_bandwidth=None,
162
+ )
163
+
164
+ def _fetch_all(self, files: Iterable[_PrismFile]) -> Iterable[rio.DatasetReader]:
165
+ for url, bil_name, cache_path in files:
166
+ try:
167
+ file = load_or_fetch_url(url, cache_path)
168
+ with rio.ZipMemoryFile(file) as zip_contents:
169
+ with zip_contents.open(bil_name) as dataset:
170
+ yield dataset
171
+ except Exception as e:
172
+ err = "Unable to fetch PRISM data."
173
+ raise ADRIOCommunicationError(self, self.context, err) from e
174
+
175
+ @override
176
+ def inspect(self) -> InspectResult[np.float64, np.float64]:
177
+ self.validate_context(self.context)
178
+
179
+ centroids = self.data(self._CENTROID)
180
+ attribute = self._attribute_name
181
+ files = _prism_files(self.time_frame, attribute)
182
+
183
+ sampler = _CentroidSampler()
184
+
185
+ processing_steps = len(files) + 1
186
+ daily_values = []
187
+ for i, raster in enumerate(self._fetch_all(files)):
188
+ vals = sampler.sample(raster, centroids)
189
+ daily_values.append(vals)
190
+ self._report_progress((i + 1) / processing_steps)
191
+ result_np = np.array(daily_values, dtype=np.float64)
192
+
193
+ # sentinel value -9999 means undefined
194
+ issues = {}
195
+ undefined_mask = np.isclose(result_np, -9999.0)
196
+ if np.any(undefined_mask):
197
+ issues["undefined"] = undefined_mask
198
+ result_np = np.ma.masked_array(result_np, mask=undefined_mask)
199
+
200
+ self.validate_result(self.context, result_np)
201
+ return InspectResult(
202
+ adrio=self,
203
+ source=None, # source data isn't suitable to share
204
+ result=result_np,
205
+ dtype=self.result_format.dtype.type,
206
+ shape=self.result_format.shape,
207
+ issues=issues,
208
+ )
209
+
210
+
211
+ @adrio_cache
212
+ class Precipitation(_PrismADRIOMixin, ADRIO[np.float64, np.float64]):
213
+ """
214
+ Loads daily precipitation data (in millimeters) from PRISM data files.
215
+
216
+ PRISM ADRIOs require you to provide centroids as a data attribute, which is where
217
+ we'll sample a value from the source file for each node. If the PRISM model is not
218
+ defined for a particular centroid, you'll get an "undefined" data issue in the
219
+ result. This is common for locations outside of the US, as PRISM only covers the
220
+ contiguous 48 United States; but it also happens for centroids located on bodies of
221
+ water. In this case, you may need to adjust centroids to get values.
222
+ """
223
+
224
+ @property
225
+ @override
226
+ def _attribute_name(self) -> str:
227
+ return "ppt"
228
+
229
+ @property
230
+ @override
231
+ def _file_size(self) -> int:
232
+ return 1_200_000
233
+
234
+
235
+ @adrio_cache
236
+ class DewPoint(_PrismADRIOMixin, ADRIO[np.float64, np.float64]):
237
+ """
238
+ Loads daily dew point data (in degrees Celsius) from PRISM data files.
239
+
240
+ PRISM ADRIOs require you to provide centroids as a data attribute, which is where
241
+ we'll sample a value from the source file for each node. If the PRISM model is not
242
+ defined for a particular centroid, you'll get an "undefined" data issue in the
243
+ result. This is common for locations outside of the US, as PRISM only covers the
244
+ contiguous 48 United States; but it also happens for centroids located on bodies of
245
+ water. In this case, you may need to adjust centroids to get values.
246
+ """
247
+
248
+ @property
249
+ @override
250
+ def _attribute_name(self) -> str:
251
+ return "tdmean"
252
+
253
+ @property
254
+ @override
255
+ def _file_size(self) -> int:
256
+ if self.time_frame.start_date.year > 2020:
257
+ return 1_800_000 # average to 1.8MB after 2020
258
+ else:
259
+ return 1_400_000 # average to 1.4MB 2020 and before
260
+
261
+
262
+ @adrio_cache
263
+ class Temperature(_PrismADRIOMixin, ADRIO[np.float64, np.float64]):
264
+ """
265
+ Loads daily temperature data (in degrees Celsius) from PRISM data files.
266
+ You can select either the minimum, maximum, or mean daily temperature.
267
+
268
+ PRISM ADRIOs require you to provide centroids as a data attribute, which is where
269
+ we'll sample a value from the source file for each node. If the PRISM model is not
270
+ defined for a particular centroid, you'll get an "undefined" data issue in the
271
+ result. This is common for locations outside of the US, as PRISM only covers the
272
+ contiguous 48 United States; but it also happens for centroids located on bodies of
273
+ water. In this case, you may need to adjust centroids to get values.
274
+
275
+ Parameters
276
+ ----------
277
+ temp_var :
278
+ Which daily temperature measure to select (min, max, mean).
279
+ """
280
+
281
+ _temp_var: TemperatureType
282
+
283
+ def __init__(self, temp_var: TemperatureType):
284
+ self._temp_var = temp_var
285
+
286
+ @property
287
+ @override
288
+ def _attribute_name(self) -> str:
289
+ match self._temp_var:
290
+ case "Minimum":
291
+ return "tmin"
292
+ case "Mean":
293
+ return "tmean"
294
+ case "Maximum":
295
+ return "tmax"
296
+
297
+ @property
298
+ @override
299
+ def _file_size(self) -> int:
300
+ if self.time_frame.start_date.year > 2020:
301
+ return 1_700_000 # average to 1.7MB after 2020
302
+ else:
303
+ return 1_400_000 # average to 1.4MB 2020 and before
304
+
305
+
306
+ @adrio_cache
307
+ class VaporPressureDeficit(_PrismADRIOMixin, ADRIO[np.float64, np.float64]):
308
+ """
309
+ Loads daily vapor pressure deficit data (in hectopascals) from PRISM data files.
310
+ You can select either the minimum or maximum daily vapor pressure deficit.
311
+
312
+ PRISM ADRIOs require you to provide centroids as a data attribute, which is where
313
+ we'll sample a value from the source file for each node. If the PRISM model is not
314
+ defined for a particular centroid, you'll get an "undefined" data issue in the
315
+ result. This is common for locations outside of the US, as PRISM only covers the
316
+ contiguous 48 United States; but it also happens for centroids located on bodies of
317
+ water. In this case, you may need to adjust centroids to get values.
318
+
319
+ Parameters
320
+ ----------
321
+ vpd_var :
322
+ Which daily vapor pressure deficit measure to select (min, max).
323
+ """
324
+
325
+ _vpd_var: VPDType
326
+
327
+ def __init__(self, vpd_var: VPDType):
328
+ self._vpd_var = vpd_var
329
+
330
+ @property
331
+ @override
332
+ def _attribute_name(self) -> str:
333
+ match self._vpd_var:
334
+ case "Minimum":
335
+ return "vpdmin"
336
+ case "Maximum":
337
+ return "vpdmax"
338
+
339
+ @property
340
+ @override
341
+ def _file_size(self) -> int:
342
+ if self.time_frame.start_date.year > 2020:
343
+ return 1_700_000 # average to 1.7MB after 2020
344
+ else:
345
+ return 1_300_000 # average to 1.3MB 2020 and before