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,237 @@
1
+ """ADRIOs that access the US Census ACS Commuting Flows files."""
2
+
3
+ from warnings import warn
4
+
5
+ import numpy as np
6
+ from numpy.typing import NDArray
7
+ from pandas import read_excel
8
+ from typing_extensions import override
9
+
10
+ from epymorph.adrio.adrio import ADRIO, adrio_cache
11
+ from epymorph.cache import check_file_in_cache, load_or_fetch_url, module_cache_path
12
+ from epymorph.data_usage import AvailableDataEstimate, DataEstimate
13
+ from epymorph.error import DataResourceError
14
+ from epymorph.geography.scope import GeoScope
15
+ from epymorph.geography.us_census import (
16
+ BlockGroupScope,
17
+ CensusScope,
18
+ StateScope,
19
+ TractScope,
20
+ )
21
+ from epymorph.geography.us_tiger import CacheEstimate
22
+
23
+ _COMMFLOWS_CACHE_PATH = module_cache_path(__name__)
24
+
25
+
26
+ def _validate_year(scope: CensusScope):
27
+ year = scope.year
28
+ if year not in [2010, 2015, 2020]:
29
+ # if invalid year is close to a valid year, fetch valid data and notify user
30
+ passed_year = year
31
+ if year in range(2010, 2015):
32
+ year = 2010
33
+ elif year in range(2015, 2020):
34
+ year = 2015
35
+ elif year in range(2020, 2024):
36
+ year = 2020
37
+ else:
38
+ msg = "Invalid year. Commuting data is only available for 2010-2023"
39
+ raise DataResourceError(msg)
40
+
41
+ warn(
42
+ f"Commuting data cannot be retrieved for {passed_year}, "
43
+ f"fetching {year} data instead."
44
+ )
45
+
46
+ return year
47
+
48
+
49
+ def _validate_scope(scope: GeoScope) -> CensusScope:
50
+ if not isinstance(scope, CensusScope):
51
+ msg = "Census scope is required for commuting flows data."
52
+ raise DataResourceError(msg)
53
+
54
+ # check for invalid granularity
55
+ if isinstance(scope, TractScope | BlockGroupScope):
56
+ msg = (
57
+ "Commuting data cannot be retrieved for tract "
58
+ "or block group granularities"
59
+ )
60
+ raise DataResourceError(msg)
61
+
62
+ year = scope.year
63
+ node_ids = scope.node_ids
64
+ # a discrepancy exists in data for Connecticut counties in 2020 and 2021
65
+ # raise an exception if this data is requested for these years.
66
+ if year in [2020, 2021] and any(
67
+ connecticut_county in node_ids
68
+ for connecticut_county in [
69
+ "09001",
70
+ "09003",
71
+ "09005",
72
+ "09007",
73
+ "09009",
74
+ "09011",
75
+ "09013",
76
+ "09015",
77
+ ]
78
+ ):
79
+ msg = (
80
+ "Commuting flows data cannot be retrieved for Connecticut counties "
81
+ "for years 2020 or 2021."
82
+ )
83
+ raise DataResourceError(msg)
84
+
85
+ return scope
86
+
87
+
88
+ @adrio_cache
89
+ class Commuters(ADRIO[np.int64]):
90
+ """
91
+ Creates an NxN matrix of integers representing commuters from the ACS commuting
92
+ flow data.
93
+ """
94
+
95
+ def estimate_data(self) -> DataEstimate:
96
+ scope = _validate_scope(self.scope)
97
+ year = _validate_year(scope)
98
+
99
+ est_file_size = 0
100
+
101
+ # file size is dependant on the year
102
+ if year == 2010:
103
+ est_file_size = 7_200_000 # 2010 table1 is 7.2MB
104
+ elif year == 2015:
105
+ est_file_size = 6_700_000 # 2015 table1 is 6.7MB
106
+ elif year == 2020:
107
+ est_file_size = 5_800_000 # 2020 table1 is 5.8MB
108
+
109
+ # only one url, just check if in cache or not
110
+ missing_files = (
111
+ 0 if check_file_in_cache(_COMMFLOWS_CACHE_PATH / f"{year}.xlsx") else 1
112
+ )
113
+
114
+ # cache estimate
115
+ est = CacheEstimate(
116
+ total_cache_size=est_file_size,
117
+ missing_cache_size=missing_files * est_file_size,
118
+ )
119
+
120
+ key = f"commflows:{year}"
121
+ return AvailableDataEstimate(
122
+ name=self.class_name,
123
+ cache_key=key,
124
+ new_network_bytes=est.missing_cache_size,
125
+ new_cache_bytes=est.missing_cache_size,
126
+ total_cache_bytes=est.total_cache_size,
127
+ max_bandwidth=None,
128
+ )
129
+
130
+ @override
131
+ def evaluate_adrio(self) -> NDArray[np.int64]:
132
+ scope = _validate_scope(self.scope)
133
+ year = _validate_year(scope)
134
+ progress = self.progress
135
+
136
+ # start progress tracking, +1 for post processing
137
+ processing_steps = 2
138
+
139
+ if year != 2010:
140
+ url = f"https://www2.census.gov/programs-surveys/demo/tables/metro-micro/{year}/commuting-flows-{year}/table1.xlsx"
141
+
142
+ # organize dataframe column names
143
+ group_fields = ["state_code", "county_code", "state", "county"]
144
+
145
+ all_fields = (
146
+ ["res_" + field for field in group_fields]
147
+ + ["wrk_" + field for field in group_fields]
148
+ + ["workers", "moe"]
149
+ )
150
+
151
+ header_num = 7
152
+
153
+ else:
154
+ url = "https://www2.census.gov/programs-surveys/demo/tables/metro-micro/2010/commuting-employment-2010/table1.xlsx"
155
+
156
+ all_fields = [
157
+ "res_state_code",
158
+ "res_county_code",
159
+ "wrk_state_code",
160
+ "wrk_county_code",
161
+ "workers",
162
+ "moe",
163
+ "res_state",
164
+ "res_county",
165
+ "wrk_state",
166
+ "wrk_county",
167
+ ]
168
+
169
+ header_num = 4
170
+
171
+ node_ids = scope.node_ids
172
+
173
+ try:
174
+ cache_path = _COMMFLOWS_CACHE_PATH / f"{year}.xlsx"
175
+ commuter_file = load_or_fetch_url(url, cache_path)
176
+ except Exception as e:
177
+ raise DataResourceError("Unable to fetch commuting flows data.") from e
178
+
179
+ # increment progress, just one step here
180
+ if progress is not None:
181
+ progress(1 / processing_steps, None)
182
+
183
+ # download communter data spreadsheet as a pandas dataframe
184
+ data_df = read_excel(
185
+ commuter_file,
186
+ header=header_num,
187
+ names=all_fields,
188
+ dtype={
189
+ "res_state_code": str,
190
+ "wrk_state_code": str,
191
+ "res_county_code": str,
192
+ "wrk_county_code": str,
193
+ },
194
+ )
195
+
196
+ match scope.granularity:
197
+ case "state":
198
+ data_df = data_df.rename(
199
+ columns={
200
+ "res_state_code": "res_geoid",
201
+ "wrk_state_code": "wrk_geoid",
202
+ }
203
+ )
204
+
205
+ case "county":
206
+ data_df["res_geoid"] = (
207
+ data_df["res_state_code"] + data_df["res_county_code"]
208
+ )
209
+ data_df["wrk_geoid"] = (
210
+ data_df["wrk_state_code"] + data_df["wrk_county_code"]
211
+ )
212
+
213
+ case _:
214
+ raise DataResourceError("Unsupported query.")
215
+
216
+ # Filter out GEOIDs that aren't in our scope.
217
+ res_selection = data_df["res_geoid"].isin(node_ids)
218
+ wrk_selection = data_df["wrk_geoid"].isin(["0" + x for x in node_ids])
219
+ data_df = data_df[res_selection & wrk_selection]
220
+
221
+ if isinstance(scope, StateScope):
222
+ # Data is county level; group and aggregate to get state level
223
+ data_df = (
224
+ data_df.groupby(["res_geoid", "wrk_geoid"])
225
+ .agg({"workers": "sum"})
226
+ .reset_index()
227
+ )
228
+
229
+ return (
230
+ data_df.pivot_table(
231
+ index="res_geoid",
232
+ columns="wrk_geoid",
233
+ values="workers",
234
+ )
235
+ .fillna(0)
236
+ .to_numpy(dtype=np.int64)
237
+ )
epymorph/adrio/csv.py ADDED
@@ -0,0 +1,387 @@
1
+ """ADRIOs that load data from locally available CSV files."""
2
+ # ruff: noqa: A005
3
+
4
+ from datetime import date
5
+ from os import PathLike
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ from numpy.typing import DTypeLike, NDArray
10
+ from pandas import DataFrame, Series, read_csv
11
+ from typing_extensions import override
12
+
13
+ from epymorph.adrio.adrio import ADRIO
14
+ from epymorph.error import DataResourceError
15
+ from epymorph.geography.scope import GeoScope
16
+ from epymorph.geography.us_census import CensusScope, CountyScope, StateScope
17
+ from epymorph.geography.us_geography import CensusGranularity
18
+ from epymorph.geography.us_tiger import get_counties, get_states
19
+ from epymorph.time import TimeFrame
20
+
21
+ KeySpecifier = Literal["state_abbrev", "county_state", "geoid"]
22
+
23
+
24
+ def _parse_label(
25
+ key_type: KeySpecifier,
26
+ scope: GeoScope,
27
+ df: DataFrame,
28
+ key_col: int,
29
+ key_col2: int | None = None,
30
+ ) -> DataFrame:
31
+ """
32
+ Reads labels from a dataframe according to key type specified and replaces them
33
+ with a uniform value to sort by.
34
+ Returns dataframe with values replaced in the label column.
35
+ """
36
+ match key_type:
37
+ case "state_abbrev":
38
+ result = _parse_abbrev(scope, df, key_col, key_col2)
39
+
40
+ case "county_state":
41
+ result = _parse_county_state(scope, df, key_col, key_col2)
42
+
43
+ case "geoid":
44
+ result = _parse_geoid(scope, df, key_col, key_col2)
45
+
46
+ _validate_result(scope, result[key_col])
47
+
48
+ if key_col2 is not None:
49
+ _validate_result(scope, result[key_col2])
50
+
51
+ return result
52
+
53
+
54
+ def _parse_abbrev(
55
+ scope: GeoScope, df: DataFrame, key_col: int, key_col2: int | None = None
56
+ ) -> DataFrame:
57
+ """
58
+ Replaces values in label column containing state abreviations (i.e. AZ) with state
59
+ fips codes and filters out any not in the specified geographic scope.
60
+ """
61
+ if not isinstance(scope, StateScope):
62
+ msg = "State scope is required to use state abbreviation key format."
63
+ raise DataResourceError(msg)
64
+
65
+ state_mapping = get_states(scope.year).state_code_to_fips
66
+
67
+ result_df = df.copy()
68
+ result_df[key_col] = [state_mapping.get(x) for x in result_df[key_col]]
69
+ if result_df[key_col].isna().any():
70
+ raise DataResourceError("Invalid state code in key column.")
71
+ result_df = result_df[result_df[key_col].isin(scope.node_ids)]
72
+
73
+ if key_col2 is not None:
74
+ result_df[key_col2] = [state_mapping.get(x) for x in result_df[key_col2]]
75
+ if result_df[key_col2].isna().any():
76
+ raise DataResourceError("Invalid state code in second key column.")
77
+ result_df = result_df[result_df[key_col2].isin(scope.node_ids)]
78
+
79
+ return result_df
80
+
81
+
82
+ def _parse_county_state(
83
+ scope: GeoScope, df: DataFrame, key_col: int, key_col2: int | None = None
84
+ ) -> DataFrame:
85
+ """
86
+ Replaces values in label column containing county and state names
87
+ (i.e. Maricopa, Arizona) with state county fips codes and filters out
88
+ any not in the specified geographic scope.
89
+ """
90
+ if not isinstance(scope, CountyScope):
91
+ msg = "County scope is required to use county, state key format."
92
+ raise DataResourceError(msg)
93
+
94
+ node_ids = scope.node_ids
95
+ geoid_to_name = get_counties(scope.year).county_fips_to_name
96
+ name_to_geoid = {v: k for k, v in geoid_to_name.items() if k in node_ids}
97
+
98
+ # filter to scope
99
+ result_df = df[df[key_col].isin(name_to_geoid.keys())]
100
+ if key_col2 is not None:
101
+ result_df = df[df[key_col2].isin(name_to_geoid.keys())]
102
+
103
+ # convert keys to geoid
104
+ result_df[key_col] = result_df[key_col].map(name_to_geoid)
105
+ if key_col2 is not None:
106
+ result_df[key_col2] = result_df[key_col2].map(name_to_geoid)
107
+
108
+ return result_df
109
+
110
+
111
+ def _parse_geoid(
112
+ scope: GeoScope, df: DataFrame, key_col: int, key_col2: int | None = None
113
+ ) -> DataFrame:
114
+ """
115
+ Replaces values in label column containing state abreviations (i.e. AZ)
116
+ with state fips codes and filters out any not in the specified geographic scope.
117
+ """
118
+ if not isinstance(scope, CensusScope):
119
+ msg = "Census scope is required to use geoid key format."
120
+ raise DataResourceError(msg)
121
+
122
+ granularity = CensusGranularity.of(scope.granularity)
123
+ if not all(granularity.matches(x) for x in df[key_col]):
124
+ raise DataResourceError("Invalid geoid in key column.")
125
+
126
+ result_df = df.copy()
127
+ result_df = result_df[result_df[key_col].isin(scope.node_ids)]
128
+ if key_col2 is not None:
129
+ result_df = result_df[result_df[key_col2].isin(scope.node_ids)]
130
+
131
+ return result_df
132
+
133
+
134
+ def _validate_result(scope: GeoScope, data: Series) -> None:
135
+ """
136
+ Ensures that the key column for an attribute contains at least one entry
137
+ for every node in the scope.
138
+ """
139
+ if set(data) != set(scope.node_ids):
140
+ msg = (
141
+ "Key column missing keys for geographies in scope "
142
+ "or contains unrecognized keys."
143
+ )
144
+ raise DataResourceError(msg)
145
+
146
+
147
+ class CSV(ADRIO[Any]):
148
+ """Retrieves an N-shaped array of any type from a user-provided CSV file."""
149
+
150
+ file_path: PathLike
151
+ """The path to the CSV file containing data."""
152
+ key_col: int
153
+ """Numerical index of the column containing information to identify geographies."""
154
+ data_col: int
155
+ """Numerical index of the column containing the data of interest."""
156
+ data_type: DTypeLike
157
+ """The data type of values in the data column."""
158
+ key_type: KeySpecifier
159
+ """The type of geographic identifier in the key column."""
160
+ skiprows: int | None
161
+ """Number of header rows in the file to be skipped."""
162
+
163
+ def __init__(
164
+ self,
165
+ file_path: PathLike,
166
+ key_col: int,
167
+ data_col: int,
168
+ data_type: DTypeLike,
169
+ key_type: KeySpecifier,
170
+ skiprows: int | None,
171
+ ):
172
+ self.file_path = file_path
173
+ self.key_col = key_col
174
+ self.data_col = data_col
175
+ self.data_type = data_type
176
+ self.key_type = key_type
177
+ self.skiprows = skiprows
178
+
179
+ if self.key_col == self.data_col:
180
+ msg = "Key column and data column must not be the same."
181
+ raise ValueError(msg)
182
+
183
+ @override
184
+ def evaluate_adrio(self) -> NDArray[Any]:
185
+ path = Path(self.file_path)
186
+ # workaround for bad pandas type definitions
187
+ skiprows: int = self.skiprows # type: ignore
188
+ if path.exists():
189
+ csv_df = read_csv(
190
+ path,
191
+ skiprows=skiprows,
192
+ header=None,
193
+ dtype={self.key_col: str},
194
+ )
195
+ parsed_df = _parse_label(
196
+ self.key_type,
197
+ self.scope,
198
+ csv_df,
199
+ self.key_col,
200
+ )
201
+
202
+ if parsed_df[self.data_col].isna().any():
203
+ msg = (
204
+ "Data for required geographies missing from CSV file "
205
+ "or could not be found."
206
+ )
207
+ raise DataResourceError(msg)
208
+
209
+ sorted_df = parsed_df.rename(columns={self.key_col: "key"}).sort_values(
210
+ by="key"
211
+ )
212
+ return sorted_df[self.data_col].to_numpy(dtype=self.data_type)
213
+
214
+ else:
215
+ msg = f"File {self.file_path} not found"
216
+ raise DataResourceError(msg)
217
+
218
+
219
+ class CSVTimeSeries(ADRIO[Any]):
220
+ """Retrieves a TxN-shaped array of any type from a user-provided CSV file."""
221
+
222
+ file_path: PathLike
223
+ """The path to the CSV file containing data."""
224
+ key_col: int
225
+ """Numerical index of the column containing information to identify geographies."""
226
+ data_col: int
227
+ """Numerical index of the column containing the data of interest."""
228
+ data_type: DTypeLike
229
+ """The data type of values in the data column."""
230
+ key_type: KeySpecifier
231
+ """The type of geographic identifier in the key column."""
232
+ skiprows: int | None
233
+ """Number of header rows in the file to be skipped."""
234
+ file_time_frame: TimeFrame
235
+ """The time period encompassed by data in the file."""
236
+ time_col: int
237
+ """The numerical index of the column containing time information."""
238
+
239
+ def __init__(
240
+ self,
241
+ file_path: PathLike,
242
+ key_col: int,
243
+ data_col: int,
244
+ data_type: DTypeLike,
245
+ key_type: KeySpecifier,
246
+ skiprows: int | None,
247
+ time_frame: TimeFrame,
248
+ time_col: int,
249
+ ):
250
+ self.file_path = file_path
251
+ self.key_col = key_col
252
+ self.data_col = data_col
253
+ self.data_type = data_type
254
+ self.key_type = key_type
255
+ self.skiprows = skiprows
256
+ self.file_time_frame = time_frame
257
+ self.time_col = time_col
258
+
259
+ if self.key_col == self.data_col:
260
+ msg = "Key column and data column must not be the same."
261
+ raise ValueError(msg)
262
+
263
+ @override
264
+ def evaluate_adrio(self) -> NDArray[Any]:
265
+ path = Path(self.file_path)
266
+ skiprows: int = self.skiprows # type: ignore
267
+ if path.exists():
268
+ csv_df = read_csv(
269
+ path,
270
+ skiprows=skiprows,
271
+ header=None,
272
+ dtype={self.key_col: str},
273
+ )
274
+ parsed_df = _parse_label(
275
+ self.key_type,
276
+ self.scope,
277
+ csv_df,
278
+ self.key_col,
279
+ )
280
+
281
+ if parsed_df[self.data_col].isna().any():
282
+ msg = (
283
+ "Data for required geographies missing from CSV file "
284
+ "or could not be found."
285
+ )
286
+ raise DataResourceError(msg)
287
+
288
+ parsed_df[self.time_col] = parsed_df[self.time_col].apply(
289
+ date.fromisoformat
290
+ )
291
+
292
+ is_before = parsed_df[self.time_col] < self.file_time_frame.start_date
293
+ is_after = parsed_df[self.time_col] > self.file_time_frame.end_date
294
+ if any(is_before | is_after):
295
+ msg = "Found time column value(s) outside of provided date range."
296
+ raise DataResourceError(msg)
297
+
298
+ sorted_df = (
299
+ parsed_df.rename(
300
+ columns={
301
+ self.key_col: "key",
302
+ self.data_col: "data",
303
+ self.time_col: "time",
304
+ },
305
+ )
306
+ .sort_values(by=["time", "key"])
307
+ .pivot_table(index="time", columns="key", values="data")
308
+ )
309
+ return sorted_df.to_numpy(dtype=self.data_type)
310
+
311
+ else:
312
+ msg = f"File {self.file_path} not found"
313
+ raise DataResourceError(msg)
314
+
315
+
316
+ class CSVMatrix(ADRIO[Any]):
317
+ """Retrieves an NxN-shaped array of any type from a user-provided CSV file."""
318
+
319
+ file_path: PathLike
320
+ """The path to the CSV file containing data."""
321
+ from_key_col: int
322
+ """Index of the column identifying source geographies."""
323
+ to_key_col: int
324
+ """Index of the column identifying destination geographies."""
325
+ data_col: int
326
+ """Index of the column containing the data of interest."""
327
+ data_type: DTypeLike
328
+ """The data type of values in the data column."""
329
+ key_type: KeySpecifier
330
+ """The type of geographic identifier in the key columns."""
331
+ skiprows: int | None
332
+ """Number of header rows in the file to be skipped."""
333
+
334
+ def __init__(
335
+ self,
336
+ file_path: PathLike,
337
+ from_key_col: int,
338
+ to_key_col: int,
339
+ data_col: int,
340
+ data_type: DTypeLike,
341
+ key_type: KeySpecifier,
342
+ skiprows: int | None,
343
+ ):
344
+ self.file_path = file_path
345
+ self.from_key_col = from_key_col
346
+ self.to_key_col = to_key_col
347
+ self.data_col = data_col
348
+ self.data_type = data_type
349
+ self.key_type = key_type
350
+ self.skiprows = skiprows
351
+
352
+ if len({self.from_key_col, self.to_key_col, self.data_col}) != 3:
353
+ msg = "From key column, to key column, and data column must all be unique."
354
+ raise ValueError(msg)
355
+
356
+ @override
357
+ def evaluate_adrio(self) -> NDArray[Any]:
358
+ path = Path(self.file_path)
359
+ if not path.exists():
360
+ msg = f"File {self.file_path} not found"
361
+ raise DataResourceError(msg)
362
+
363
+ skiprows: int = self.skiprows # type: ignore
364
+ csv_df = read_csv(
365
+ path,
366
+ skiprows=skiprows,
367
+ header=None,
368
+ dtype={self.from_key_col: str, self.to_key_col: str},
369
+ )
370
+ parsed_df = _parse_label(
371
+ self.key_type,
372
+ self.scope,
373
+ csv_df,
374
+ self.from_key_col,
375
+ self.to_key_col,
376
+ )
377
+ return (
378
+ parsed_df.pivot_table(
379
+ index=parsed_df.columns[self.from_key_col],
380
+ columns=parsed_df.columns[self.to_key_col],
381
+ values=parsed_df.columns[self.data_col],
382
+ )
383
+ .sort_index(axis=0)
384
+ .sort_index(axis=1)
385
+ .fillna(0)
386
+ .to_numpy(dtype=self.data_type)
387
+ )
@@ -0,0 +1,84 @@
1
+ from warnings import warn
2
+
3
+ import numpy as np
4
+ from numpy.typing import NDArray
5
+ from typing_extensions import override
6
+
7
+ from epymorph.adrio.adrio import ADRIO, adrio_cache
8
+ from epymorph.attribute import AttributeDef
9
+ from epymorph.data_shape import Shapes
10
+
11
+
12
+ @adrio_cache
13
+ class AbsoluteHumidity(ADRIO[np.float64]):
14
+ """
15
+ Creates a TxN matrix of floats representing absolute humidity in kilograms per cubic
16
+ meter calculated from a relative humidity, which is calculated from a given
17
+ temperature and dew point temperature, both in degrees Celsius.
18
+ """
19
+
20
+ requirements = [
21
+ AttributeDef("temperature", type=float, shape=Shapes.TxN),
22
+ AttributeDef("dewpoint", type=float, shape=Shapes.TxN),
23
+ ]
24
+ """The temperature and dew point temperature from the PRISM ADRIO are required to
25
+ calculate the absolute humidity."""
26
+
27
+ @override
28
+ def evaluate_adrio(self) -> NDArray[np.float64]:
29
+ temperature = self.data("temperature")
30
+ rel_h = self.defer(RelativeHumidity())
31
+ np_humidity = []
32
+
33
+ # equation from relative humidity to absolute humidity provided by following url
34
+ # https://carnotcycle.wordpress.com/2012/08/04/how-to-convert-relative-humidity-to-absolute-humidity/
35
+ # values 17.67 and 243.5 are changed to 17.625 and 243.04 respectively to cover
36
+ # a larger range of temperature values with a smaller margin of error
37
+ # (Alduchov and Eskridge 1996)
38
+ constants = 6.112 * 2.16679
39
+ np_humidity = (
40
+ (
41
+ constants
42
+ * np.exp((17.625 * temperature) / (temperature + 243.04))
43
+ * (rel_h)
44
+ )
45
+ / (273.15 + temperature)
46
+ / 1000 # convert to kilograms
47
+ )
48
+
49
+ return np_humidity
50
+
51
+
52
+ @adrio_cache
53
+ class RelativeHumidity(ADRIO[np.float64]):
54
+ """
55
+ Creates a TxN matrix of floats representing relative humidity as a percentage
56
+ which is calculated from a given temperature and dew point temperature, both in
57
+ degrees Celsius.
58
+ """
59
+
60
+ requirements = [
61
+ AttributeDef("temperature", type=float, shape=Shapes.TxN),
62
+ AttributeDef("dewpoint", type=float, shape=Shapes.TxN),
63
+ ]
64
+ """The temperature and dew point temperature from the PRISM ADRIO are required to
65
+ calculate the relative humidity."""
66
+
67
+ @override
68
+ def evaluate_adrio(self) -> NDArray[np.float64]:
69
+ temperature = self.data("temperature")
70
+ dewpoint = self.data("dewpoint")
71
+ np_humidity = []
72
+
73
+ # equation for calculating relative humidity provided by following url
74
+ # https://qed.epa.gov/hms/meteorology/humidity/algorithms/#:~:text=Relative%20humidity%20is%20calculated%20using,is%20air%20temperature%20(celsius).
75
+ np_humidity = 100 * (
76
+ np.exp((17.625 * dewpoint) / (243.04 + dewpoint))
77
+ / np.exp((17.625 * temperature) / (243.04 + temperature))
78
+ )
79
+
80
+ # if the humidity exceeds 100%, warn users
81
+ if (np_humidity > 100).any():
82
+ warn("At least one value of relative humidity exceeds 100%.")
83
+
84
+ return np.array(np_humidity, dtype=np.float64)