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/adrio/csv.py ADDED
@@ -0,0 +1,499 @@
1
+ """ADRIOs that load data from locally available CSV files."""
2
+ # ruff: noqa: A005
3
+
4
+ from itertools import product
5
+ from os import PathLike
6
+ from pathlib import Path
7
+ from typing import Literal
8
+
9
+ import numpy as np
10
+ from numpy.typing import NDArray
11
+ from pandas import DataFrame, Series, read_csv, to_datetime
12
+ from typing_extensions import override
13
+
14
+ from epymorph.adrio.adrio import (
15
+ ADRIO,
16
+ ADRIOContextError,
17
+ ADRIOProcessingError,
18
+ InspectResult,
19
+ adrio_validate_pipe,
20
+ )
21
+ from epymorph.adrio.validation import (
22
+ ResultFormat,
23
+ validate_dtype,
24
+ validate_numpy,
25
+ validate_shape_unchecked_arbitrary,
26
+ )
27
+ from epymorph.data_shape import Shapes
28
+ from epymorph.error import MissingContextError
29
+ from epymorph.geography.us_census import CountyScope, StateScope
30
+ from epymorph.geography.us_tiger import get_counties, get_states
31
+ from epymorph.simulation import Context, validate_context_for_shape
32
+ from epymorph.time import DateRange
33
+ from epymorph.util import identity
34
+
35
+ GeoKeyType = Literal["state_abbrev", "county_state", "geoid"]
36
+ """
37
+ The format to use when interpreting values in a geo node identity column.
38
+
39
+ - `state_abbrev` handles postal codes; e.g., "NY" for New York
40
+ - `county_state` handles county name comma state postal code; e.g., "Albany, NY"
41
+ - `geoid` handles FIPS code, a.k.a. GEOID, format; e.g., "36001" for Albany, New York
42
+ """
43
+
44
+
45
+ class _CSVMixin(ADRIO):
46
+ key_type: GeoKeyType
47
+
48
+ @override
49
+ def validate_context(self, context: Context) -> None:
50
+ try:
51
+ validate_context_for_shape(context, self.result_format.shape)
52
+ except MissingContextError as e:
53
+ raise ADRIOContextError(self, self.context, str(e))
54
+
55
+ def parse_geo_key(self, csv_df: DataFrame, key_cols: list[str]) -> DataFrame:
56
+ """
57
+ Convert all columns in `key_cols` using this ADRIO's key type. Returns a copy
58
+ of the `DataFrame` where the values have been converted to GEOID format.
59
+ """
60
+ match self.key_type:
61
+ case "state_abbrev":
62
+ map_keys = self.parse_state_abbrev
63
+ case "county_state":
64
+ map_keys = self.parse_county_state
65
+ case "geoid":
66
+ map_keys = identity
67
+
68
+ result_df = csv_df.copy()
69
+ for j in key_cols:
70
+ result_df[j] = map_keys(csv_df[j])
71
+ return result_df
72
+
73
+ def parse_state_abbrev(self, keys: Series) -> Series:
74
+ # Parse state postal codes, e.g., AZ
75
+ if not isinstance(self.scope, StateScope):
76
+ err = "State scope is required to use state abbreviation key format."
77
+ raise ADRIOProcessingError(self, self.context, err)
78
+
79
+ state_mapping = get_states(self.scope.year).state_code_to_fips
80
+ new_keys = Series([state_mapping.get(x) for x in keys])
81
+ if new_keys.isna().any():
82
+ err = "Invalid state code in key column."
83
+ raise ADRIOProcessingError(self, self.context, err)
84
+ return new_keys
85
+
86
+ def parse_county_state(self, keys: Series) -> Series:
87
+ # Parse county name and state postal code, e.g., Maricopa, AZ
88
+ if not isinstance(self.scope, CountyScope):
89
+ err = "County scope is required to use county, state key format."
90
+ raise ADRIOProcessingError(self, self.context, err)
91
+
92
+ geoid_to_name = get_counties(self.scope.year).county_fips_to_name
93
+ name_to_geoid = {v: k for k, v in geoid_to_name.items()}
94
+ new_keys = Series([name_to_geoid.get(x) for x in keys])
95
+ if new_keys.isna().any():
96
+ err = "Invalid county name in key column."
97
+ raise ADRIOProcessingError(self, self.context, err)
98
+ return new_keys
99
+
100
+
101
+ class CSVFileN(_CSVMixin, ADRIO[np.generic, np.generic]):
102
+ """
103
+ Loads an N-shaped array of data from a user-provided CSV file.
104
+
105
+ Parameters
106
+ ----------
107
+ file_path :
108
+ The path to the CSV file containing data.
109
+ dtype :
110
+ The data type of values in the data column.
111
+ key_col :
112
+ Numerical index of the column containing information to identify geographies.
113
+ key_type :
114
+ The type of geographic identifier in the key column.
115
+ data_col :
116
+ Numerical index of the column containing the data of interest.
117
+ skiprows :
118
+ Number of header rows in the file to be skipped.
119
+ """
120
+
121
+ file_path: Path
122
+ """The path to the CSV file containing data."""
123
+ dtype: np.dtype
124
+ """The data type of values in the data column."""
125
+ key_col: int
126
+ """Numerical index of the column containing information to identify geographies."""
127
+ key_type: GeoKeyType
128
+ """The type of geographic identifier in the key column."""
129
+ data_col: int
130
+ """Numerical index of the column containing the data of interest."""
131
+ skiprows: int | None
132
+ """Number of header rows in the file to be skipped."""
133
+
134
+ def __init__(
135
+ self,
136
+ *,
137
+ file_path: str | Path,
138
+ dtype: np.dtype | type[np.generic],
139
+ key_col: int,
140
+ key_type: GeoKeyType,
141
+ data_col: int,
142
+ skiprows: int | None = None,
143
+ ):
144
+ if key_col == data_col:
145
+ msg = "Key column and data column must not be the same."
146
+ raise ValueError(msg)
147
+
148
+ self.file_path = file_path if isinstance(file_path, Path) else Path(file_path)
149
+ self.dtype = dtype if isinstance(dtype, np.dtype) else np.dtype(dtype)
150
+ self.key_col = key_col
151
+ self.key_type = key_type
152
+ self.data_col = data_col
153
+ self.skiprows = skiprows
154
+
155
+ @property
156
+ @override
157
+ def result_format(self) -> ResultFormat:
158
+ return ResultFormat(shape=Shapes.N, dtype=self.dtype)
159
+
160
+ @override
161
+ def inspect(self) -> InspectResult[np.generic, np.generic]:
162
+ self.validate_context(self.context)
163
+
164
+ if not self.file_path.is_file():
165
+ err = f"File {self.file_path} not found or not a file."
166
+ raise ADRIOProcessingError(self, self.context, err)
167
+
168
+ kwarg_options = {}
169
+ if self.skiprows is not None:
170
+ kwarg_options["skiprows"] = self.skiprows
171
+ csv_df = read_csv(
172
+ self.file_path,
173
+ header=None,
174
+ dtype={self.key_col: str},
175
+ usecols=[self.key_col, self.data_col],
176
+ names=["key", "data"],
177
+ **kwarg_options,
178
+ )
179
+
180
+ work_df = self.parse_geo_key(csv_df, ["key"])
181
+ work_df = work_df.sort_values(by="key")
182
+ # Filter to requested geo
183
+ work_df = work_df[work_df["key"].isin(self.scope.node_ids)]
184
+
185
+ if not np.array_equal(self.scope.node_ids, work_df["key"]):
186
+ err = (
187
+ "Either required geographies are missing from the CSV file "
188
+ "or some geographies have multiple values."
189
+ )
190
+ raise ADRIOProcessingError(self, self.context, err)
191
+ if work_df["data"].isna().any():
192
+ err = "Data for required geographies missing from CSV file."
193
+ raise ADRIOProcessingError(self, self.context, err)
194
+
195
+ result_np = work_df["data"].to_numpy(dtype=self.dtype)
196
+ self.validate_result(self.context, result_np)
197
+ return InspectResult(
198
+ adrio=self,
199
+ source=csv_df,
200
+ result=result_np,
201
+ dtype=self.result_format.dtype.type,
202
+ shape=self.result_format.shape,
203
+ issues={},
204
+ )
205
+
206
+
207
+ class CSVFileTxN(_CSVMixin, ADRIO[np.generic, np.generic]):
208
+ """
209
+ Loads a TxN-shaped array of data from a user-provided CSV file.
210
+
211
+ Parameters
212
+ ----------
213
+ file_path :
214
+ The path to the CSV file containing data.
215
+ dtype :
216
+ The data type of values in the data column.
217
+ key_col :
218
+ Numerical index of the column containing information to identify geographies.
219
+ key_type :
220
+ The type of geographic identifier in the key column.
221
+ time_col :
222
+ The numerical index of the column containing time information.
223
+ data_col :
224
+ Numerical index of the column containing the data of interest.
225
+ skiprows :
226
+ Number of header rows in the file to be skipped.
227
+ date_range :
228
+ The time period encompassed by data in the file.
229
+ """
230
+
231
+ file_path: Path
232
+ """The path to the CSV file containing data."""
233
+ dtype: np.dtype
234
+ """The data type of values in the data column."""
235
+ key_col: int
236
+ """Numerical index of the column containing information to identify geographies."""
237
+ key_type: GeoKeyType
238
+ """The type of geographic identifier in the key column."""
239
+ time_col: int
240
+ """The numerical index of the column containing time information."""
241
+ data_col: int
242
+ """Numerical index of the column containing the data of interest."""
243
+ skiprows: int | None
244
+ """Number of header rows in the file to be skipped."""
245
+ date_range: DateRange | None
246
+ """The time period encompassed by data in the file."""
247
+
248
+ def __init__(
249
+ self,
250
+ *,
251
+ file_path: str | Path,
252
+ dtype: np.dtype | type[np.generic],
253
+ key_col: int,
254
+ key_type: GeoKeyType,
255
+ time_col: int,
256
+ data_col: int,
257
+ skiprows: int | None = None,
258
+ date_range: DateRange | None = None,
259
+ ):
260
+ if len({key_col, data_col, time_col}) != 3:
261
+ err = "Key, data, and time columns must all be unique."
262
+ raise ValueError(err)
263
+
264
+ self.file_path = file_path if isinstance(file_path, Path) else Path(file_path)
265
+ self.dtype = dtype if isinstance(dtype, np.dtype) else np.dtype(dtype)
266
+ self.key_col = key_col
267
+ self.data_col = data_col
268
+ self.key_type = key_type
269
+ self.skiprows = skiprows
270
+ self.date_range = date_range
271
+ self.time_col = time_col
272
+
273
+ @property
274
+ @override
275
+ def result_format(self) -> ResultFormat:
276
+ # result shape is really AxN to support loading irregular time series
277
+ return ResultFormat(shape=Shapes.AxN, dtype=self.dtype)
278
+
279
+ @override
280
+ def inspect(self) -> InspectResult:
281
+ self.validate_context(self.context)
282
+
283
+ if not self.file_path.is_file():
284
+ err = f"File {self.file_path} not found or not a file."
285
+ raise ADRIOProcessingError(self, self.context, err)
286
+
287
+ columns = [self.key_col, self.time_col, self.data_col]
288
+ kwarg_options = {}
289
+ if self.skiprows is not None:
290
+ kwarg_options["skiprows"] = self.skiprows
291
+ csv_df = read_csv(
292
+ self.file_path,
293
+ header=None,
294
+ dtype={self.key_col: str},
295
+ parse_dates=[self.time_col],
296
+ usecols=columns,
297
+ **kwarg_options,
298
+ )
299
+
300
+ work_df = csv_df[columns]
301
+ work_df.columns = ["key", "time", "data"]
302
+ work_df = self.parse_geo_key(work_df, ["key"])
303
+ work_df = work_df.sort_values(by=["time", "key"])
304
+ # Filter to requested geo
305
+ work_df = work_df[work_df["key"].isin(self.scope.node_ids)]
306
+ # Filter to specified date range
307
+ # TODO: this should probably just use context time_frame...
308
+ if self.date_range is not None:
309
+ start_date = to_datetime(self.date_range.start_date)
310
+ end_date = to_datetime(self.date_range.end_date)
311
+ work_df = work_df[
312
+ (work_df["time"] >= start_date) & (work_df["time"] <= end_date)
313
+ ]
314
+
315
+ nodes_in_data = np.sort(work_df["key"].unique())
316
+ if (
317
+ work_df.duplicated(subset=["key", "time"]).any() # check duplicate keys
318
+ or not np.array_equal(nodes_in_data, self.scope.node_ids) # check nodes
319
+ ):
320
+ err = (
321
+ "Either required geographies are missing from the CSV file "
322
+ "or there are some duplicate key/values."
323
+ )
324
+ raise ADRIOProcessingError(self, self.context, err)
325
+ if work_df["data"].isna().any():
326
+ err = "Data for required geographies missing from CSV file."
327
+ raise ADRIOProcessingError(self, self.context, err)
328
+
329
+ result_np = work_df.pivot_table(
330
+ index="time",
331
+ columns="key",
332
+ values="data",
333
+ fill_value=None,
334
+ )
335
+ if np.any(np.isnan(result_np)):
336
+ err = (
337
+ "Some data are missing from the CSV file; "
338
+ "not all pairs of date/location are present."
339
+ )
340
+ raise ADRIOProcessingError(self, self.context, err)
341
+
342
+ result_np = result_np.to_numpy(dtype=self.dtype)
343
+ self.validate_result(self.context, result_np)
344
+ return InspectResult(
345
+ adrio=self,
346
+ source=csv_df,
347
+ result=result_np,
348
+ dtype=self.result_format.dtype.type,
349
+ shape=self.result_format.shape,
350
+ issues={},
351
+ )
352
+
353
+ @override
354
+ def validate_result(self, context: Context, result: NDArray[np.generic]) -> None:
355
+ adrio_validate_pipe(
356
+ self,
357
+ context,
358
+ result,
359
+ validate_numpy(),
360
+ validate_shape_unchecked_arbitrary(
361
+ self.result_format.shape.to_tuple(context.dim)
362
+ ),
363
+ validate_dtype(self.dtype),
364
+ )
365
+
366
+
367
+ class CSVFileNxN(_CSVMixin, ADRIO[np.generic, np.generic]):
368
+ """
369
+ Loads an NxN-shaped array of data from a user-provided CSV file.
370
+
371
+ Parameters
372
+ ----------
373
+ file_path :
374
+ The path to the CSV file containing data.
375
+ dtype :
376
+ The data type of values in the data column.
377
+ from_key_col :
378
+ Index of the column identifying source geographies.
379
+ to_key_col :
380
+ Index of the column identifying destination geographies.
381
+ key_type :
382
+ The type of geographic identifier in the key columns.
383
+ data_col :
384
+ Index of the column containing the data of interest.
385
+ skiprows :
386
+ Number of header rows in the file to be skipped.
387
+ """
388
+
389
+ file_path: Path
390
+ """The path to the CSV file containing data."""
391
+ dtype: np.dtype
392
+ """The data type of values in the data column."""
393
+ from_key_col: int
394
+ """Index of the column identifying source geographies."""
395
+ to_key_col: int
396
+ """Index of the column identifying destination geographies."""
397
+ key_type: GeoKeyType
398
+ """The type of geographic identifier in the key columns."""
399
+ data_col: int
400
+ """Index of the column containing the data of interest."""
401
+ skiprows: int | None
402
+ """Number of header rows in the file to be skipped."""
403
+
404
+ def __init__(
405
+ self,
406
+ *,
407
+ file_path: PathLike,
408
+ dtype: np.dtype | type[np.generic],
409
+ from_key_col: int,
410
+ to_key_col: int,
411
+ key_type: GeoKeyType,
412
+ data_col: int,
413
+ skiprows: int | None,
414
+ ):
415
+ if len({from_key_col, to_key_col, data_col}) != 3:
416
+ err = "From key column, to key column, and data column must all be unique."
417
+ raise ValueError(err)
418
+
419
+ self.file_path = file_path if isinstance(file_path, Path) else Path(file_path)
420
+ self.dtype = dtype if isinstance(dtype, np.dtype) else np.dtype(dtype)
421
+ self.from_key_col = from_key_col
422
+ self.to_key_col = to_key_col
423
+ self.key_type = key_type
424
+ self.data_col = data_col
425
+ self.skiprows = skiprows
426
+
427
+ @property
428
+ @override
429
+ def result_format(self) -> ResultFormat:
430
+ return ResultFormat(shape=Shapes.NxN, dtype=self.dtype)
431
+
432
+ @override
433
+ def inspect(self) -> InspectResult:
434
+ self.validate_context(self.context)
435
+
436
+ if not self.file_path.is_file():
437
+ err = f"File {self.file_path} not found or not a file."
438
+ raise ADRIOProcessingError(self, self.context, err)
439
+
440
+ kwarg_options = {}
441
+ if self.skiprows is not None:
442
+ kwarg_options["skiprows"] = self.skiprows
443
+ csv_df = read_csv(
444
+ self.file_path,
445
+ header=None,
446
+ dtype={self.from_key_col: str, self.to_key_col: str},
447
+ usecols=[self.from_key_col, self.to_key_col, self.data_col],
448
+ names=["from_key", "to_key", "data"],
449
+ **kwarg_options,
450
+ )
451
+
452
+ work_df = self.parse_geo_key(csv_df, ["from_key", "to_key"])
453
+ work_df = work_df.sort_values(by=["from_key", "to_key"])
454
+
455
+ # Filter to requested geo
456
+ node_ids = self.scope.node_ids
457
+ work_df = work_df[
458
+ work_df["from_key"].isin(node_ids) & work_df["to_key"].isin(node_ids)
459
+ ]
460
+
461
+ n = self.scope.nodes
462
+ if (n * n) != len(work_df):
463
+ err = (
464
+ "Either required geographies are missing from the CSV file "
465
+ "or some geographies have multiple values."
466
+ )
467
+ raise ADRIOProcessingError(self, self.context, err)
468
+
469
+ expected_ids = product(node_ids, node_ids)
470
+ rows = work_df.itertuples(index=False, name=None)
471
+ if any(
472
+ a != x or b != y
473
+ for (a, b), (x, y, _) in zip(expected_ids, rows, strict=True)
474
+ ):
475
+ err = (
476
+ "Either required geographies are missing from the CSV file "
477
+ "or some geographies have multiple values."
478
+ )
479
+ raise ADRIOProcessingError(self, self.context, err)
480
+
481
+ if work_df["data"].isna().any():
482
+ err = "Data for required geographies missing from CSV file."
483
+ raise ADRIOProcessingError(self, self.context, err)
484
+
485
+ result_np = work_df.pivot_table(
486
+ index="from_key",
487
+ columns="to_key",
488
+ values="data",
489
+ sort=True,
490
+ ).to_numpy(dtype=self.dtype)
491
+ self.validate_result(self.context, result_np)
492
+ return InspectResult(
493
+ adrio=self,
494
+ source=csv_df,
495
+ result=result_np,
496
+ dtype=self.result_format.dtype.type,
497
+ shape=self.result_format.shape,
498
+ issues={},
499
+ )
@@ -0,0 +1,206 @@
1
+ """ADRIOs for caculating absolute or relative humidity."""
2
+
3
+ import numpy as np
4
+ from numpy.core.records import fromarrays
5
+ from numpy.typing import NDArray
6
+ from typing_extensions import override
7
+
8
+ from epymorph.adrio.adrio import (
9
+ ADRIO,
10
+ ADRIOContextError,
11
+ InspectResult,
12
+ adrio_cache,
13
+ )
14
+ from epymorph.adrio.validation import ResultFormat
15
+ from epymorph.attribute import AttributeDef
16
+ from epymorph.data_shape import Shapes
17
+ from epymorph.error import MissingContextError
18
+ from epymorph.simulation import Context
19
+
20
+
21
+ def calculate_relative_humidity(
22
+ temperature: NDArray[np.float64],
23
+ dewpoint: NDArray[np.float64],
24
+ ) -> NDArray[np.float64]:
25
+ """
26
+ Calculate relative humidity in percent (0 to 100). The calculation is designed to
27
+ be vectorized over the input arrays, so they must be compatible shapes.
28
+
29
+ Note: results may exceed 100% if temperature and dew point close in value.
30
+ There are atmospheric conditions where this can be the case, but in typical usage
31
+ might be more accurately thought of as data inconsistencies. Thus models that use
32
+ humidity may wish to cap values in the model.
33
+
34
+ Parameters
35
+ ----------
36
+ temperature :
37
+ Air temperature in degrees Celsius.
38
+ dewpoint :
39
+ Dew point temperature in degrees Celsius.
40
+
41
+ Returns
42
+ -------
43
+ :
44
+ Relative humidity according to the element-wise pairs of the temperature and
45
+ dew point inputs. The size of the result array is governed by numpy's
46
+ broadcasting rules.
47
+ """
48
+ # equation for calculating relative humidity provided by following url
49
+ # https://qed.epa.gov/hms/meteorology/humidity/algorithms/#:~:text=Relative%20humidity%20is%20calculated%20using,is%20air%20temperature%20(celsius).
50
+ return 100 * (
51
+ np.exp((17.625 * dewpoint) / (243.04 + dewpoint))
52
+ / np.exp((17.625 * temperature) / (243.04 + temperature))
53
+ )
54
+
55
+
56
+ _AH_CONSTANTS = 6.112 * 2.16679
57
+
58
+
59
+ def calculate_absolute_humidity(
60
+ temperature: NDArray[np.float64],
61
+ dewpoint: NDArray[np.float64],
62
+ ) -> NDArray[np.float64]:
63
+ """
64
+ Calculate absolute humidity in kilograms per cubic meter. The calculation is
65
+ designed to be vectorized over the input arrays, so they must be compatible shapes.
66
+
67
+ Parameters
68
+ ----------
69
+ temperature :
70
+ Air temperature in degrees Celsius.
71
+ dewpoint :
72
+ Dew point temperature in degrees Celsius.
73
+
74
+ Returns
75
+ -------
76
+ :
77
+ Absolute humidity according to the element-wise pairs of the temperature and
78
+ dew point inputs. The size of the result array is governed by numpy's
79
+ broadcasting rules.
80
+ """
81
+ # equation from relative humidity to absolute humidity provided by following url
82
+ # https://carnotcycle.wordpress.com/2012/08/04/how-to-convert-relative-humidity-to-absolute-humidity/
83
+ # values 17.67 and 243.5 are changed to 17.625 and 243.04 respectively to cover
84
+ # a larger range of temperature values with a smaller margin of error
85
+ # (Alduchov and Eskridge 1996)
86
+ return (
87
+ (
88
+ _AH_CONSTANTS
89
+ * np.exp((17.625 * temperature) / (temperature + 243.04))
90
+ * calculate_relative_humidity(temperature, dewpoint)
91
+ )
92
+ / (273.15 + temperature)
93
+ / 1000 # convert to kilograms
94
+ )
95
+
96
+
97
+ _TEMPERATURE = AttributeDef("temperature", type=float, shape=Shapes.TxN)
98
+ _DEWPOINT = AttributeDef("dewpoint", type=float, shape=Shapes.TxN)
99
+
100
+
101
+ @adrio_cache
102
+ class AbsoluteHumidity(ADRIO[np.float64, np.float64]):
103
+ """
104
+ Calculates absolute humidity (in kilograms per cubic meter) calculated from
105
+ from air temperature and dew point temperature.
106
+
107
+ This ADRIO requires two data attributes:
108
+
109
+ - "temperature": the air temperature in degrees Celsius
110
+ - "dewpoint": the dew-point temperature in degress Celsius
111
+ """
112
+
113
+ requirements = (_TEMPERATURE, _DEWPOINT)
114
+
115
+ @property
116
+ @override
117
+ def result_format(self) -> ResultFormat:
118
+ return ResultFormat(shape=Shapes.TxN, dtype=np.float64)
119
+
120
+ @override
121
+ def validate_context(self, context: Context) -> None:
122
+ # need scope and time_frame in order to validate result shape
123
+ try:
124
+ context.scope
125
+ context.time_frame
126
+ except MissingContextError as e:
127
+ raise ADRIOContextError(self, self.context, str(e))
128
+
129
+ @override
130
+ def inspect(self) -> InspectResult[np.float64, np.float64]:
131
+ self.validate_context(self.context)
132
+ temperature = self.data(_TEMPERATURE)
133
+ dewpoint = self.data(_DEWPOINT)
134
+ issues = {}
135
+ if np.any(temperature_mask := np.ma.getmaskarray(temperature)):
136
+ issues["temperature_masked", temperature_mask]
137
+ if np.any(dewpoint_mask := np.ma.getmaskarray(dewpoint)):
138
+ issues["dewpoint_masked", dewpoint_mask]
139
+
140
+ result = calculate_absolute_humidity(temperature, dewpoint)
141
+ self.validate_result(self.context, result)
142
+ return InspectResult(
143
+ adrio=self,
144
+ source=fromarrays(
145
+ [temperature, dewpoint],
146
+ names=["temperature", "dewpoint"], # type: ignore
147
+ ),
148
+ result=result,
149
+ dtype=self.result_format.dtype.type,
150
+ shape=self.result_format.shape,
151
+ issues=issues,
152
+ )
153
+
154
+
155
+ @adrio_cache
156
+ class RelativeHumidity(ADRIO[np.float64, np.float64]):
157
+ """
158
+ Calculates relative humidity as a percentage from air temperature and
159
+ dew point temperature.
160
+
161
+ This ADRIO requires two data attributes:
162
+
163
+ - "temperature": the air temperature in degrees Celsius
164
+ - "dewpoint": the dew-point temperature in degress Celsius
165
+ """
166
+
167
+ requirements = (_TEMPERATURE, _DEWPOINT)
168
+
169
+ @property
170
+ @override
171
+ def result_format(self) -> ResultFormat:
172
+ return ResultFormat(shape=Shapes.TxN, dtype=np.float64)
173
+
174
+ @override
175
+ def validate_context(self, context: Context) -> None:
176
+ # need scope and time_frame in order to validate result shape
177
+ try:
178
+ context.scope
179
+ context.time_frame
180
+ except MissingContextError as e:
181
+ raise ADRIOContextError(self, self.context, str(e))
182
+
183
+ @override
184
+ def inspect(self) -> InspectResult[np.float64, np.float64]:
185
+ self.validate_context(self.context)
186
+ temperature = self.data(_TEMPERATURE)
187
+ dewpoint = self.data(_DEWPOINT)
188
+ issues = {}
189
+ if np.any(temperature_mask := np.ma.getmaskarray(temperature)):
190
+ issues["temperature_masked", temperature_mask]
191
+ if np.any(dewpoint_mask := np.ma.getmaskarray(dewpoint)):
192
+ issues["dewpoint_masked", dewpoint_mask]
193
+
194
+ result = calculate_relative_humidity(temperature, dewpoint)
195
+ self.validate_result(self.context, result)
196
+ return InspectResult(
197
+ adrio=self,
198
+ source=fromarrays(
199
+ [temperature, dewpoint],
200
+ names=["temperature", "dewpoint"], # type: ignore
201
+ ),
202
+ result=result,
203
+ dtype=self.result_format.dtype.type,
204
+ shape=self.result_format.shape,
205
+ issues=issues,
206
+ )