epymorph 1.0.0b0__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 (102) 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 +602 -0
  5. epymorph/adrio/adrio.py +215 -0
  6. epymorph/adrio/cdc.py +781 -0
  7. epymorph/adrio/commuting_flows.py +237 -0
  8. epymorph/adrio/csv.py +387 -0
  9. epymorph/adrio/humidity.py +84 -0
  10. epymorph/adrio/lodes.py +624 -0
  11. epymorph/adrio/numpy.py +119 -0
  12. epymorph/adrio/prism.py +543 -0
  13. epymorph/adrio/respiratory_cdc.py +489 -0
  14. epymorph/adrio/us_tiger.py +217 -0
  15. epymorph/attribute.py +301 -0
  16. epymorph/cache.py +494 -0
  17. epymorph/cli/__init__.py +0 -0
  18. epymorph/cli/cache.py +77 -0
  19. epymorph/cli/main.py +29 -0
  20. epymorph/compartment_model.py +1335 -0
  21. epymorph/data/__init__.py +1 -0
  22. epymorph/data/ipm/__init__.py +22 -0
  23. epymorph/data/ipm/no.py +14 -0
  24. epymorph/data/ipm/pei.py +40 -0
  25. epymorph/data/ipm/seirs.py +50 -0
  26. epymorph/data/ipm/sirh.py +55 -0
  27. epymorph/data/ipm/sirs.py +48 -0
  28. epymorph/data/ipm/sparsemod.py +96 -0
  29. epymorph/data/mm/__init__.py +22 -0
  30. epymorph/data/mm/centroids.py +76 -0
  31. epymorph/data/mm/flat.py +61 -0
  32. epymorph/data/mm/icecube.py +50 -0
  33. epymorph/data/mm/no.py +29 -0
  34. epymorph/data/mm/pei.py +105 -0
  35. epymorph/data/mm/sparsemod.py +73 -0
  36. epymorph/data/pei.py +424 -0
  37. epymorph/data_shape.py +475 -0
  38. epymorph/data_type.py +129 -0
  39. epymorph/data_usage.py +171 -0
  40. epymorph/database.py +1010 -0
  41. epymorph/error.py +183 -0
  42. epymorph/event.py +188 -0
  43. epymorph/geography/__init__.py +0 -0
  44. epymorph/geography/custom.py +61 -0
  45. epymorph/geography/scope.py +214 -0
  46. epymorph/geography/us_census.py +622 -0
  47. epymorph/geography/us_geography.py +278 -0
  48. epymorph/geography/us_tiger.py +755 -0
  49. epymorph/initializer.py +596 -0
  50. epymorph/kit.py +90 -0
  51. epymorph/log/__init__.py +0 -0
  52. epymorph/log/file.py +108 -0
  53. epymorph/log/messaging.py +129 -0
  54. epymorph/log/movement.py +151 -0
  55. epymorph/movement_model.py +274 -0
  56. epymorph/parameter_fitting/__init__.py +0 -0
  57. epymorph/parameter_fitting/distribution.py +68 -0
  58. epymorph/parameter_fitting/dynamics.py +19 -0
  59. epymorph/parameter_fitting/filter/__init__.py +0 -0
  60. epymorph/parameter_fitting/filter/base_filter.py +50 -0
  61. epymorph/parameter_fitting/filter/particle.py +32 -0
  62. epymorph/parameter_fitting/filter/particle_filter.py +296 -0
  63. epymorph/parameter_fitting/likelihood.py +54 -0
  64. epymorph/parameter_fitting/output.py +73 -0
  65. epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
  66. epymorph/parameter_fitting/perturbation.py +19 -0
  67. epymorph/parameter_fitting/utils/__init__.py +0 -0
  68. epymorph/parameter_fitting/utils/data_loader.py +111 -0
  69. epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
  70. epymorph/parameter_fitting/utils/observations.py +63 -0
  71. epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
  72. epymorph/parameter_fitting/utils/params_perturb.py +43 -0
  73. epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
  74. epymorph/parameter_fitting/utils/resampler.py +249 -0
  75. epymorph/parameter_fitting/utils/utils.py +101 -0
  76. epymorph/params.py +248 -0
  77. epymorph/py.typed +0 -0
  78. epymorph/rume.py +700 -0
  79. epymorph/simulation.py +706 -0
  80. epymorph/simulator/__init__.py +0 -0
  81. epymorph/simulator/basic/__init__.py +0 -0
  82. epymorph/simulator/basic/basic_simulator.py +145 -0
  83. epymorph/simulator/basic/ipm_exec.py +406 -0
  84. epymorph/simulator/basic/mm_exec.py +197 -0
  85. epymorph/simulator/basic/output.py +181 -0
  86. epymorph/simulator/world.py +83 -0
  87. epymorph/simulator/world_list.py +196 -0
  88. epymorph/strata.py +12 -0
  89. epymorph/sympy_shim.py +55 -0
  90. epymorph/time.py +649 -0
  91. epymorph/tools/__init__.py +0 -0
  92. epymorph/tools/data.py +218 -0
  93. epymorph/tools/ipm_diagram.py +165 -0
  94. epymorph/tools/out_map.py +426 -0
  95. epymorph/tools/out_plot.py +412 -0
  96. epymorph/tools/out_table.py +575 -0
  97. epymorph/util.py +825 -0
  98. epymorph-1.0.0b0.dist-info/METADATA +57 -0
  99. epymorph-1.0.0b0.dist-info/RECORD +102 -0
  100. epymorph-1.0.0b0.dist-info/WHEEL +5 -0
  101. epymorph-1.0.0b0.dist-info/entry_points.txt +2 -0
  102. epymorph-1.0.0b0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,119 @@
1
+ from os import PathLike
2
+ from pathlib import Path
3
+ from typing import Any, cast
4
+
5
+ import numpy as np
6
+ from numpy.typing import NDArray
7
+ from typing_extensions import override
8
+
9
+ from epymorph.adrio.adrio import ADRIO
10
+ from epymorph.error import DataResourceError
11
+
12
+ _SliceLike = slice | type(Ellipsis)
13
+ _ArraySlice = _SliceLike | tuple[_SliceLike, ...]
14
+
15
+
16
+ class NPY(ADRIO[Any]):
17
+ """Retrieves an array of data from a user-provided .npy file."""
18
+
19
+ file_path: PathLike
20
+ """The path to the .npy file containing data."""
21
+ array_slice: _ArraySlice | None
22
+ """Optional slice(s) of the array to load."""
23
+
24
+ def __init__(
25
+ self, file_path: PathLike, array_slice: _ArraySlice | None = None
26
+ ) -> None:
27
+ """
28
+ Initializes the array of user-provided .npy file of data with a file path and
29
+ optional array slice(s).
30
+
31
+ Parameters
32
+ ----------
33
+ file_path : PathLike
34
+ The path to the .npy file to retrieve the array data from.
35
+ array_slice : _ArraySlice | None
36
+ The optional slice or slices to apply to the array. If None, the entire
37
+ array is returned (default is None).
38
+ """
39
+ if Path(file_path).suffix != ".npy":
40
+ msg = (
41
+ "Incorrect file type. Only .npy files can be loaded through NPY ADRIOs."
42
+ )
43
+ raise DataResourceError(msg)
44
+ self.file_path = file_path
45
+ self.array_slice = array_slice
46
+
47
+ @override
48
+ def evaluate_adrio(self) -> NDArray:
49
+ try:
50
+ data = cast(NDArray, np.load(self.file_path))
51
+ if self.array_slice is not None:
52
+ data = data[self.array_slice]
53
+ return data
54
+ except OSError as e:
55
+ msg = "File not found."
56
+ raise DataResourceError(msg) from e
57
+ except ValueError as e:
58
+ msg = "Object arrays cannot be loaded."
59
+ raise DataResourceError(msg) from e
60
+ except IndexError as e:
61
+ msg = "Specified array slice is invalid for the shape of this data."
62
+ raise DataResourceError(msg) from e
63
+
64
+
65
+ class NPZ(ADRIO[Any]):
66
+ """Retrieves an array of data from a user-defined .npz file."""
67
+
68
+ file_path: PathLike
69
+ """The path to the .npz file containing data."""
70
+ array_name: str
71
+ """The name of the array in the .npz file to load."""
72
+ array_slice: _ArraySlice | None
73
+ """Optional slice(s) of the array to load."""
74
+
75
+ def __init__(
76
+ self,
77
+ file_path: PathLike,
78
+ array_name: str,
79
+ array_slice: _ArraySlice | None = None,
80
+ ) -> None:
81
+ """
82
+ Initializes the array of user-provided .npz file of data with a file path, array
83
+ name, and optional array slice(s).
84
+
85
+ Parameters
86
+ ----------
87
+ file_path : PathLike
88
+ The path to the .npy file to retrieve the array data from.
89
+ array_name: str
90
+ The name of the array to retrieve from the user-given file.
91
+ array_slice : _ArraySlice | None
92
+ The optional slice or slices to apply to the array. If None, the entire
93
+ array is returned (default is None).
94
+ """
95
+ if Path(file_path).suffix != ".npz":
96
+ msg = (
97
+ "Incorrect file type. Only .npz files can be loaded through NPZ ADRIOs."
98
+ )
99
+ raise DataResourceError(msg)
100
+ self.file_path = file_path
101
+ self.array_name = array_name
102
+ self.array_slice = array_slice
103
+
104
+ @override
105
+ def evaluate_adrio(self) -> NDArray:
106
+ try:
107
+ data = cast(NDArray, np.load(self.file_path)[self.array_name])
108
+ if self.array_slice is not None:
109
+ data = data[self.array_slice]
110
+ return data
111
+ except OSError as e:
112
+ msg = "File not found."
113
+ raise DataResourceError(msg) from e
114
+ except ValueError as e:
115
+ msg = "Object arrays cannot be loaded."
116
+ raise DataResourceError(msg) from e
117
+ except IndexError as e:
118
+ msg = "Specified array slice is invalid for the shape of this data."
119
+ raise DataResourceError(msg) from e
@@ -0,0 +1,543 @@
1
+ from abc import ABC, abstractmethod
2
+ from datetime import date as datetype
3
+ from datetime import timedelta
4
+ from io import BytesIO
5
+ from pathlib import Path
6
+ from typing import Generator, Literal
7
+ from warnings import warn
8
+
9
+ import numpy as np
10
+ import rasterio.io as rio
11
+ from dateutil.relativedelta import relativedelta
12
+ from numpy.typing import NDArray
13
+
14
+ from epymorph.adrio.adrio import ADRIO, ProgressCallback, adrio_cache
15
+ from epymorph.attribute import AttributeDef
16
+ from epymorph.cache import check_file_in_cache, load_or_fetch_url, module_cache_path
17
+ from epymorph.data_shape import Shapes
18
+ from epymorph.data_type import CentroidType
19
+ from epymorph.data_usage import AvailableDataEstimate, DataEstimate
20
+ from epymorph.error import DataResourceError
21
+ from epymorph.geography.scope import GeoScope
22
+ from epymorph.geography.us_census import CensusScope
23
+ from epymorph.geography.us_geography import STATE
24
+ from epymorph.geography.us_tiger import CacheEstimate
25
+ from epymorph.time import TimeFrame
26
+
27
+ _PRISM_CACHE_PATH = module_cache_path(__name__)
28
+
29
+
30
+ def _generate_file_name(
31
+ attribute: str,
32
+ latest_date: datetype,
33
+ last_completed_month: datetype,
34
+ date: datetype,
35
+ ) -> tuple[str, str]:
36
+ """
37
+ Generates the url for the given date and climate attribute. Returns a tuple
38
+ of strings with the url and the name of the bil file within the zip file.
39
+ """
40
+
41
+ if date.year == latest_date.year and date.month == latest_date.month:
42
+ stability = "early"
43
+
44
+ # if it is before the last finished month
45
+ elif date > last_completed_month:
46
+ stability = "provisional"
47
+
48
+ # if it is older than 6 completed months
49
+ else:
50
+ stability = "stable"
51
+
52
+ # format the date for the url
53
+ formatted_date = date.strftime("%Y%m%d")
54
+ year = date.year
55
+
56
+ url = f"https://ftp.prism.oregonstate.edu/daily/{attribute}/{year}/PRISM_{attribute}_{stability}_4kmD2_{formatted_date}_bil.zip"
57
+
58
+ bil_name = f"PRISM_{attribute}_{stability}_4kmD2_{formatted_date}_bil.bil"
59
+
60
+ return url, bil_name
61
+
62
+
63
+ def _fetch_raster(
64
+ attribute: str, date_range: TimeFrame, progress: ProgressCallback
65
+ ) -> Generator[BytesIO, None, None]:
66
+ """
67
+ Fetches the raster values at the url with the given attribute and date range.
68
+ """
69
+
70
+ # set some date variables with the date_range
71
+ latest_date = datetype.today() - timedelta(days=1)
72
+ first_day = date_range.start_date
73
+ last_day = date_range.end_date
74
+
75
+ # create the list of days in date_range
76
+ date_list = [
77
+ first_day + timedelta(days=x) for x in range((last_day - first_day).days + 1)
78
+ ]
79
+
80
+ # the stability of PRISM data is defined by date, specified around the 6 month mark
81
+ six_months_ago = datetype.today() + relativedelta(months=-6)
82
+ last_completed_month = six_months_ago.replace(day=1) - timedelta(days=1)
83
+
84
+ # for progress tracking
85
+ processing_steps = len(date_list) + 1
86
+
87
+ for i, single_date in enumerate(date_list):
88
+ url, bil_name = _generate_file_name(
89
+ attribute, latest_date, last_completed_month, single_date
90
+ )
91
+
92
+ # load/fetch the url for the file
93
+ try:
94
+ file = load_or_fetch_url(url, _PRISM_CACHE_PATH / Path(url).name)
95
+
96
+ except Exception as e:
97
+ raise DataResourceError("Unable to fetch PRISM data.") from e
98
+
99
+ # if the progress isnt None
100
+ if progress is not None:
101
+ # progress by one, increasing percentage done
102
+ progress((i + 1) / processing_steps, None)
103
+
104
+ file.name = bil_name
105
+
106
+ yield file
107
+
108
+
109
+ def _make_centroid_strategy_adrio(
110
+ attribute: str, date: TimeFrame, centroids: NDArray, progress: ProgressCallback
111
+ ) -> NDArray[np.float64]:
112
+ """
113
+ Retrieves the raster value at a centroid of a granularity.
114
+ """
115
+ raster_files = _fetch_raster(attribute, date, progress)
116
+ results = []
117
+
118
+ # read in each file
119
+ for raster_file in raster_files:
120
+ with rio.ZipMemoryFile(raster_file) as zip_contents:
121
+ with zip_contents.open(raster_file.name) as dataset:
122
+ values = [x[0] for x in dataset.sample(centroids)]
123
+
124
+ results.append(values)
125
+
126
+ return np.array(results, dtype=np.float64)
127
+
128
+
129
+ def _validate_dates(date_range: TimeFrame) -> TimeFrame:
130
+ latest_date = datetype.today() - timedelta(days=1)
131
+ # PRISM only accounts for dates from 1981 up to yesterday's date
132
+ if date_range.start_date.year < 1981 or latest_date < date_range.end_date:
133
+ msg = (
134
+ "Given date range is out of PRISM scope, please enter dates between "
135
+ f"1981-01-01 and {latest_date}"
136
+ )
137
+ raise DataResourceError(msg)
138
+
139
+ return date_range
140
+
141
+
142
+ def _estimate_prism(
143
+ self, file_size: int, date_range: TimeFrame, attribute: str
144
+ ) -> DataEstimate:
145
+ """
146
+ Calculate estimates for downloading PRISM files.
147
+ """
148
+ est_file_size = file_size
149
+ total_files = date_range.duration_days
150
+
151
+ # setup urls as list to check if theyre in the cache
152
+
153
+ # setup date variables
154
+ first_day = date_range.start_date
155
+ last_day = date_range.end_date
156
+ latest_date = datetype.today() - timedelta(days=1)
157
+ six_months_ago = datetype.today() + relativedelta(months=-6)
158
+ last_completed_month = six_months_ago.replace(day=1) - timedelta(days=1)
159
+ date_list = [
160
+ first_day + timedelta(days=x) for x in range((last_day - first_day).days + 1)
161
+ ]
162
+
163
+ # get url names to check in cache
164
+ urls = [
165
+ _generate_file_name(attribute, latest_date, last_completed_month, day)[0]
166
+ for day in date_list
167
+ ]
168
+
169
+ # sum the files needed to download
170
+ missing_files = total_files - sum(
171
+ 1 for u in urls if check_file_in_cache(_PRISM_CACHE_PATH / Path(u).name)
172
+ )
173
+
174
+ # calculate the cache estimate
175
+ est = CacheEstimate(
176
+ total_cache_size=total_files * est_file_size,
177
+ missing_cache_size=missing_files * est_file_size,
178
+ )
179
+
180
+ key = f"prism:{attribute}:{date_range}"
181
+ return AvailableDataEstimate(
182
+ name=self.full_name,
183
+ cache_key=key,
184
+ new_network_bytes=est.missing_cache_size,
185
+ new_cache_bytes=est.missing_cache_size,
186
+ total_cache_bytes=est.total_cache_size,
187
+ max_bandwidth=None,
188
+ )
189
+
190
+
191
+ class _PRISMAdrio(ADRIO[np.float64], ABC):
192
+ _override_time_frame: TimeFrame | None
193
+ """An override time frame for which to fetch data.
194
+ If None, the simulation time frame will be used."""
195
+
196
+ errors: Literal["raise", "warn", "ignore"]
197
+ """How to handle data errors."""
198
+
199
+ def __init__(
200
+ self,
201
+ time_frame: TimeFrame | None = None,
202
+ errors: Literal["raise", "warn", "ignore"] = "raise",
203
+ ):
204
+ self._override_time_frame = time_frame
205
+ self.errors = errors
206
+
207
+ @property
208
+ def data_time_frame(self) -> TimeFrame:
209
+ """The time frame for which to fetch data."""
210
+ return self._override_time_frame or self.time_frame
211
+
212
+ def _validate_scope(self) -> GeoScope:
213
+ """
214
+ When a scope is a CensusScope, check if there is a given location in Hawaii,
215
+ Alaska, or Puerto Rico.
216
+ """
217
+ scope = self.scope
218
+ if isinstance(scope, CensusScope):
219
+ state_fips = list(STATE.truncate_unique(scope.node_ids))
220
+ excluded_fips = ["72", "02", "15"]
221
+ # scope cannot be in Puerto Rico, Alaska, or Hawaii
222
+ if any(state in excluded_fips for state in state_fips):
223
+ msg = (
224
+ "Alaska, Hawaii, and Puerto Rico cannot be evaluated for PRISM "
225
+ "attributes. Please enter a geoid within the 48 contiguous states."
226
+ )
227
+ raise DataResourceError(msg)
228
+ return scope
229
+
230
+ @abstractmethod
231
+ def retrieve_prism(self) -> NDArray[np.float64]:
232
+ """
233
+ Allow for the PRISM ADRIOs to retrieve their raster data for their climate
234
+ attribute type.
235
+ """
236
+
237
+ def _validate_data(
238
+ self, raster_data: NDArray, centroids: NDArray
239
+ ) -> NDArray[np.float64]:
240
+ """
241
+ Check the fetched data for sentinel values. By default, raise an error on the
242
+ instance of an invalid value. Otherwise, refer to the user parameter
243
+ specification.
244
+ """
245
+ scope = self.scope
246
+ errors = self.errors
247
+ # check for any invalid values, handle error accordingly
248
+ if errors != "ignore":
249
+ (indices,) = np.nonzero(np.any(raster_data == -9999, axis=0))
250
+ if len(indices) > 0:
251
+ # get the points where there are sentinel values
252
+ invalid_centroids = np.unique(centroids[indices])
253
+ invalid_nodes = np.unique(scope.node_ids[indices])
254
+
255
+ # correlate the nodes and centroids to show where the error is occurring
256
+ table_title = ["\nGEOID Centroid"]
257
+ for node, centroid in zip(invalid_nodes, invalid_centroids):
258
+ table_title.append(f"{str(node).ljust(20)}{centroid}")
259
+
260
+ node_table = "\n".join(table_title)
261
+
262
+ __cls = self.__class__.__name__
263
+
264
+ error_msg = (
265
+ "\nOne or more of the centroids provided are outside of the "
266
+ f"geographic bounds defined by PRISM. PRISM {__cls} has not "
267
+ "returned data for the following nodes and centroids:"
268
+ f"\n{node_table}"
269
+ "\n\nThis issue may occur if a centroid is placed in a body of "
270
+ "water or is located outside of the 48 contiguous United States. "
271
+ "\n\nThere are a couple of ways to handle this: "
272
+ "\n1. Adjust the centroids"
273
+ "\n - If feasible, adjust the above centroids accordingly to be on"
274
+ " land, within the 48 adjoining U.S. states."
275
+ "\n\n2. Error Handling"
276
+ "\n - By default, PRISM ADRIOs will default to raise an error when"
277
+ " a centroid does not return valid data. "
278
+ "\n - This setting can be changed by "
279
+ "setting the errors parameter at the end of the PRISM ADRIO calls "
280
+ "to any of the following: "
281
+ "\n\t- `errors='raise'`"
282
+ "\n\t- `errors='warn'`"
283
+ "\n\t- `errors='ignore'`"
284
+ )
285
+
286
+ if errors == "raise":
287
+ raise DataResourceError(error_msg)
288
+ elif errors == "warn":
289
+ warn(error_msg)
290
+
291
+ return raster_data
292
+
293
+ def evaluate_adrio(self) -> NDArray[np.float64]:
294
+ _validate_dates(self.data_time_frame)
295
+ self._validate_scope()
296
+ raster_vals = self.retrieve_prism()
297
+ raster_vals = self._validate_data(raster_vals, self.data("centroid"))
298
+ return raster_vals
299
+
300
+
301
+ @adrio_cache
302
+ class Precipitation(_PRISMAdrio):
303
+ """
304
+ Creates an TxN matrix of floats representing the amount of precipitation in an area,
305
+ represented in millimeters (mm).
306
+ """
307
+
308
+ requirements = [AttributeDef("centroid", type=CentroidType, shape=Shapes.N)]
309
+ """
310
+ An array of centroids is required to fetch for a specific point of
311
+ data.
312
+ """
313
+
314
+ def __init__(
315
+ self,
316
+ time_frame: TimeFrame | None = None,
317
+ errors: Literal["raise", "warn", "ignore"] = "raise",
318
+ ):
319
+ """
320
+ Creates a precipitation ADRIO.
321
+
322
+ Parameters
323
+ ----------
324
+ time_frame : TimeFrame, optional
325
+ The range of dates to fetch precipitation data for.
326
+ Default: the simulation time frame.
327
+ errors : {'raise', 'warn', 'ignore'}, optional
328
+ Error handling for potential out-of-bound centroids.
329
+ - `'raise'`: Raises an error when out-of-bound centroids are given."
330
+ " No resulting matrices will be shown (default).
331
+ - `'warn'`: Issues a warning about invalid centroids, "
332
+ "but displays the resulting matrices.
333
+ - `'ignore'`: Does not display any message concerning invalid centroids"
334
+ " and returns the resulting matrices.
335
+ """
336
+ super().__init__(time_frame, errors)
337
+
338
+ def estimate_data(self) -> DataEstimate:
339
+ file_size = 1_200_000 # no significant change in size, average to about 1.2MB
340
+ est = _estimate_prism(self, file_size, self.data_time_frame, "ppt")
341
+ return est
342
+
343
+ def retrieve_prism(self) -> NDArray[np.float64]:
344
+ centroids = self.data("centroid")
345
+ raster_vals = _make_centroid_strategy_adrio(
346
+ "ppt", self.data_time_frame, centroids, self.progress
347
+ )
348
+ return raster_vals
349
+
350
+
351
+ @adrio_cache
352
+ class DewPoint(_PRISMAdrio):
353
+ """
354
+ Creates an TxN matrix of floats representing the dew point temperature in an area,
355
+ represented in degrees Celsius (°C).
356
+ """
357
+
358
+ requirements = [AttributeDef("centroid", type=CentroidType, shape=Shapes.N)]
359
+ """
360
+ An array of centroids is required to fetch for a specific point of
361
+ data.
362
+ """
363
+
364
+ def __init__(
365
+ self,
366
+ time_frame: TimeFrame | None = None,
367
+ errors: Literal["raise", "warn", "ignore"] = "raise",
368
+ ):
369
+ """
370
+ Creates a dew point ADRIO.
371
+
372
+ Parameters
373
+ ----------
374
+ time_frame : TimeFrame, optional
375
+ The range of dates to fetch dew point temperature data for.
376
+ Default: the simulation time frame.
377
+ errors : {'raise', 'warn', 'ignore'}, optional
378
+ Error handling for potential out-of-bound centroids.
379
+ - `'raise'`: Raises an error when out-of-bound centroids are given."
380
+ " No resulting matrices will be shown (default).
381
+ - `'warn'`: Issues a warning about invalid centroids, "
382
+ "but displays the resulting matrices.
383
+ - `'ignore'`: Does not display any message concerning invalid centroids"
384
+ " and returns the resulting matrices.
385
+ """
386
+ super().__init__(time_frame, errors)
387
+
388
+ def estimate_data(self) -> DataEstimate:
389
+ year = self.data_time_frame.end_date.year
390
+
391
+ # file sizes are larger after the year 2020
392
+ if year > 2020:
393
+ file_size = 1_800_000 # average to 1.8MB after 2020
394
+ else:
395
+ file_size = 1_400_000 # average to 1.4MB 2020 and before
396
+ return _estimate_prism(self, file_size, self.data_time_frame, "tdmean")
397
+
398
+ def retrieve_prism(self) -> NDArray[np.float64]:
399
+ centroids = self.data("centroid")
400
+ raster_vals = _make_centroid_strategy_adrio(
401
+ "tdmean", self.data_time_frame, centroids, self.progress
402
+ )
403
+ return raster_vals
404
+
405
+
406
+ @adrio_cache
407
+ class Temperature(_PRISMAdrio):
408
+ """
409
+ Creates an TxN matrix of floats representing the temperature in an area, represented
410
+ in degrees Celsius (°C).
411
+ """
412
+
413
+ requirements = [AttributeDef("centroid", type=CentroidType, shape=Shapes.N)]
414
+ """
415
+ An array of centroids is required to fetch for a specific point of
416
+ data.
417
+ """
418
+
419
+ TemperatureType = Literal["Minimum", "Mean", "Maximum"]
420
+
421
+ temp_variables: dict[TemperatureType, str] = {
422
+ "Minimum": "tmin",
423
+ "Mean": "tmean",
424
+ "Maximum": "tmax",
425
+ }
426
+
427
+ temp_var: TemperatureType
428
+
429
+ def __init__(
430
+ self,
431
+ temp_var: TemperatureType,
432
+ time_frame: TimeFrame | None = None,
433
+ errors: Literal["raise", "warn", "ignore"] = "raise",
434
+ ):
435
+ """
436
+ Creates a temperature ADRIO for the given statistical measure (min/max/mean).
437
+
438
+ Parameters
439
+ ----------
440
+ temp_var : TemperatureType
441
+ The measure of the temperature for a single date (options: 'Minimum',
442
+ 'Mean', 'Maximum').
443
+ time_frame : TimeFrame, optional
444
+ The range of dates to fetch precipitation data for.
445
+ Default: the simulation time frame.
446
+ errors : {'raise', 'warn', 'ignore'}, optional
447
+ Error handling for potential out-of-bound centroids.
448
+ - `'raise'`: Raises an error when out-of-bound centroids are given."
449
+ " No resulting matrices will be shown (default).
450
+ - `'warn'`: Issues a warning about invalid centroids, "
451
+ "but displays the resulting matrices.
452
+ - `'ignore'`: Does not display any message concerning invalid centroids"
453
+ " and returns the resulting matrices.
454
+ """
455
+ super().__init__(time_frame, errors)
456
+ self.temp_var = temp_var
457
+
458
+ def estimate_data(self) -> DataEstimate:
459
+ year = self.data_time_frame.end_date.year
460
+ temp_var = self.temp_variables[self.temp_var]
461
+
462
+ # file sizes are larger after the year 2020
463
+ if year > 2020:
464
+ file_size = 1_700_000 # average to 1.7MB after 2020
465
+ else:
466
+ file_size = 1_400_000 # average to 1.4MB 2020 and before
467
+ return _estimate_prism(self, file_size, self.data_time_frame, temp_var)
468
+
469
+ def retrieve_prism(self) -> NDArray[np.float64]:
470
+ temp_var = self.temp_variables[self.temp_var]
471
+ centroids = self.data("centroid")
472
+ raster_vals = _make_centroid_strategy_adrio(
473
+ temp_var, self.data_time_frame, centroids, self.progress
474
+ )
475
+ return raster_vals
476
+
477
+
478
+ @adrio_cache
479
+ class VaporPressureDeficit(_PRISMAdrio):
480
+ """
481
+ Creates an TxN matrix of floats representing the vapor pressure deficit in an area,
482
+ represented in hectopascals (hPa).
483
+ """
484
+
485
+ requirements = [AttributeDef("centroid", type=CentroidType, shape=Shapes.N)]
486
+ """
487
+ An array of centroids is required to fetch for a specific point of
488
+ data.
489
+ """
490
+
491
+ VPDType = Literal["Minimum", "Maximum"]
492
+
493
+ vpd_variables: dict[VPDType, str] = {"Minimum": "vpdmin", "Maximum": "vpdmax"}
494
+
495
+ vpd_var: VPDType
496
+
497
+ def __init__(
498
+ self,
499
+ vpd_var: VPDType,
500
+ time_frame: TimeFrame | None = None,
501
+ errors: Literal["raise", "warn", "ignore"] = "raise",
502
+ ):
503
+ """
504
+ Creates a vapor pressure deficit ADRIO for the given statistical measure
505
+ (min/max).
506
+
507
+ Parameters
508
+ ----------
509
+ vpd_var : VPDType
510
+ The measure of the vapor pressure deficit for a single date
511
+ (options: 'Minimum', 'Maximum').
512
+ time_frame : TimeFrame, optional
513
+ The range of dates to fetch precipitation data for.
514
+ Default: the simulation time frame.
515
+ errors : {'raise', 'warn', 'ignore'}, optional
516
+ Error handling for potential out-of-bound centroids.
517
+ - `'raise'`: Raises an error when out-of-bound centroids are given."
518
+ " No resulting matrices will be shown (default).
519
+ - `'warn'`: Issues a warning about invalid centroids, "
520
+ "but displays the resulting matrices.
521
+ - `'ignore'`: Does not display any message concerning invalid centroids"
522
+ " and returns the resulting matrices.
523
+ """
524
+ super().__init__(time_frame, errors)
525
+ self.vpd_var = vpd_var
526
+
527
+ def estimate_data(self) -> DataEstimate:
528
+ year = self.data_time_frame.end_date.year
529
+
530
+ # file sizes are larger after the year 2020
531
+ if year > 2020:
532
+ file_size = 1_700_000 # average to 1.7MB after 2020
533
+ else:
534
+ file_size = 1_300_000 # average to 1.3MB 2020 and before
535
+ return _estimate_prism(self, file_size, self.data_time_frame, self.vpd_var)
536
+
537
+ def retrieve_prism(self) -> NDArray[np.float64]:
538
+ vpd_var = self.vpd_variables[self.vpd_var]
539
+ centroids = self.data("centroid")
540
+ raster_vals = _make_centroid_strategy_adrio(
541
+ vpd_var, self.data_time_frame, centroids, self.progress
542
+ )
543
+ return raster_vals