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.
- epymorph/__init__.py +7 -0
- epymorph/__main__.py +16 -0
- epymorph/adrio/__init__.py +0 -0
- epymorph/adrio/acs5.py +1378 -0
- epymorph/adrio/adrio.py +953 -0
- epymorph/adrio/cdc.py +1826 -0
- epymorph/adrio/commuting_flows.py +283 -0
- epymorph/adrio/csv.py +499 -0
- epymorph/adrio/humidity.py +206 -0
- epymorph/adrio/lodes.py +509 -0
- epymorph/adrio/numpy.py +160 -0
- epymorph/adrio/prism.py +345 -0
- epymorph/adrio/processing.py +1221 -0
- epymorph/adrio/soda.py +602 -0
- epymorph/adrio/us_tiger.py +289 -0
- epymorph/adrio/validation.py +382 -0
- epymorph/attribute.py +614 -0
- epymorph/cache.py +680 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +78 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1873 -0
- epymorph/data/__init__.py +1 -0
- epymorph/data/ipm/__init__.py +22 -0
- epymorph/data/ipm/no.py +14 -0
- epymorph/data/ipm/pei.py +40 -0
- epymorph/data/ipm/seirs.py +50 -0
- epymorph/data/ipm/sirh.py +55 -0
- epymorph/data/ipm/sirs.py +48 -0
- epymorph/data/ipm/sparsemod.py +96 -0
- epymorph/data/mm/__init__.py +22 -0
- epymorph/data/mm/centroids.py +76 -0
- epymorph/data/mm/flat.py +61 -0
- epymorph/data/mm/icecube.py +50 -0
- epymorph/data/mm/no.py +29 -0
- epymorph/data/mm/pei.py +105 -0
- epymorph/data/mm/sparsemod.py +73 -0
- epymorph/data/pei.py +424 -0
- epymorph/data_shape.py +593 -0
- epymorph/data_type.py +185 -0
- epymorph/data_usage.py +258 -0
- epymorph/database.py +1301 -0
- epymorph/error.py +195 -0
- epymorph/event.py +196 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +93 -0
- epymorph/geography/scope.py +457 -0
- epymorph/geography/us_census.py +1056 -0
- epymorph/geography/us_geography.py +502 -0
- epymorph/geography/us_tiger.py +1083 -0
- epymorph/initializer.py +786 -0
- epymorph/kit.py +107 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +128 -0
- epymorph/log/messaging.py +139 -0
- epymorph/log/movement.py +228 -0
- epymorph/movement_model.py +347 -0
- epymorph/parameter_fitting/__init__.py +0 -0
- epymorph/parameter_fitting/distribution.py +68 -0
- epymorph/parameter_fitting/dynamics.py +19 -0
- epymorph/parameter_fitting/filter/__init__.py +0 -0
- epymorph/parameter_fitting/filter/base_filter.py +50 -0
- epymorph/parameter_fitting/filter/particle.py +32 -0
- epymorph/parameter_fitting/filter/particle_filter.py +296 -0
- epymorph/parameter_fitting/likelihood.py +54 -0
- epymorph/parameter_fitting/output.py +73 -0
- epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
- epymorph/parameter_fitting/perturbation.py +19 -0
- epymorph/parameter_fitting/utils/__init__.py +0 -0
- epymorph/parameter_fitting/utils/data_loader.py +97 -0
- epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
- epymorph/parameter_fitting/utils/observations.py +63 -0
- epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
- epymorph/parameter_fitting/utils/params_perturb.py +43 -0
- epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
- epymorph/parameter_fitting/utils/resampler.py +258 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +438 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +871 -0
- epymorph/simulation.py +991 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +171 -0
- epymorph/simulator/basic/ipm_exec.py +437 -0
- epymorph/simulator/basic/mm_exec.py +244 -0
- epymorph/simulator/basic/output.py +213 -0
- epymorph/simulator/world.py +149 -0
- epymorph/simulator/world_list.py +274 -0
- epymorph/strata.py +24 -0
- epymorph/sympy_shim.py +57 -0
- epymorph/time.py +1197 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +297 -0
- epymorph/tools/ipm_diagram.py +208 -0
- epymorph/tools/out_map.py +551 -0
- epymorph/tools/out_plot.py +423 -0
- epymorph/tools/out_table.py +582 -0
- epymorph/util.py +1036 -0
- epymorph-1.0.0.dist-info/METADATA +57 -0
- epymorph-1.0.0.dist-info/RECORD +104 -0
- epymorph-1.0.0.dist-info/WHEEL +5 -0
- epymorph-1.0.0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""ADRIOs that access the US Census TIGER geography files."""
|
|
2
|
+
|
|
3
|
+
from typing import cast
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from numpy.typing import NDArray
|
|
7
|
+
from pandas import to_numeric
|
|
8
|
+
from typing_extensions import override
|
|
9
|
+
|
|
10
|
+
from epymorph.adrio.adrio import (
|
|
11
|
+
ADRIO,
|
|
12
|
+
ADRIOContextError,
|
|
13
|
+
InspectResult,
|
|
14
|
+
adrio_cache,
|
|
15
|
+
adrio_validate_pipe,
|
|
16
|
+
)
|
|
17
|
+
from epymorph.adrio.validation import (
|
|
18
|
+
ResultFormat,
|
|
19
|
+
on_structured,
|
|
20
|
+
validate_dtype,
|
|
21
|
+
validate_numpy,
|
|
22
|
+
validate_shape,
|
|
23
|
+
validate_values_in_range,
|
|
24
|
+
)
|
|
25
|
+
from epymorph.data_shape import Shapes
|
|
26
|
+
from epymorph.data_type import CentroidDType, StructDType
|
|
27
|
+
from epymorph.data_usage import AvailableDataEstimate
|
|
28
|
+
from epymorph.error import MissingContextError
|
|
29
|
+
from epymorph.geography.us_census import CensusScope, StateScope
|
|
30
|
+
from epymorph.geography.us_tiger import check_cache, is_tiger_year
|
|
31
|
+
from epymorph.simulation import Context
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _USTIGERMixin(ADRIO):
|
|
35
|
+
"""Common ADRIO logic for US TIGER ADRIOs."""
|
|
36
|
+
|
|
37
|
+
@override
|
|
38
|
+
def validate_context(self, context: Context) -> None:
|
|
39
|
+
try:
|
|
40
|
+
scope = context.scope # scope is required
|
|
41
|
+
except MissingContextError as e:
|
|
42
|
+
raise ADRIOContextError(self, context, str(e))
|
|
43
|
+
if not isinstance(scope, CensusScope):
|
|
44
|
+
err = "Census scope is required for us_tiger attributes."
|
|
45
|
+
raise ADRIOContextError(self, context, err)
|
|
46
|
+
year = scope.year
|
|
47
|
+
if not is_tiger_year(year):
|
|
48
|
+
err = f"{year} is not a supported year for us_tiger attributes."
|
|
49
|
+
raise ADRIOContextError(self, context, err)
|
|
50
|
+
|
|
51
|
+
@override
|
|
52
|
+
def estimate_data(self) -> AvailableDataEstimate:
|
|
53
|
+
scope = cast(CensusScope, self.scope)
|
|
54
|
+
est = check_cache(scope.granularity, scope.year)
|
|
55
|
+
return AvailableDataEstimate(
|
|
56
|
+
name=self.class_name,
|
|
57
|
+
cache_key=f"us_tiger:{scope.granularity}:{scope.year}",
|
|
58
|
+
new_network_bytes=est.missing_cache_size,
|
|
59
|
+
new_cache_bytes=est.missing_cache_size,
|
|
60
|
+
total_cache_bytes=est.total_cache_size,
|
|
61
|
+
max_bandwidth=None,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@adrio_cache
|
|
66
|
+
class GeometricCentroid(_USTIGERMixin, ADRIO[StructDType, np.float64]):
|
|
67
|
+
"""The centroid of the geographic polygons."""
|
|
68
|
+
|
|
69
|
+
# FROM MIXIN:
|
|
70
|
+
# def validate_context(self, context: Context) -> None:
|
|
71
|
+
# def estimate_data(self) -> AvailableDataEstimate:
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
@override
|
|
75
|
+
def result_format(self) -> ResultFormat:
|
|
76
|
+
return ResultFormat(shape=Shapes.N, dtype=CentroidDType)
|
|
77
|
+
|
|
78
|
+
@override
|
|
79
|
+
def validate_result(self, context: Context, result: NDArray) -> None:
|
|
80
|
+
adrio_validate_pipe(
|
|
81
|
+
self,
|
|
82
|
+
context,
|
|
83
|
+
result,
|
|
84
|
+
validate_numpy(),
|
|
85
|
+
validate_shape(self.result_format.shape.to_tuple(context.dim)),
|
|
86
|
+
validate_dtype(self.result_format.dtype),
|
|
87
|
+
on_structured(validate_values_in_range(-180.0, +180.0)),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
@override
|
|
91
|
+
def inspect(self) -> InspectResult[StructDType, np.float64]:
|
|
92
|
+
self.validate_context(self.context)
|
|
93
|
+
scope = cast(CensusScope, self.scope)
|
|
94
|
+
|
|
95
|
+
source_gdf = scope.geography
|
|
96
|
+
result_np = (
|
|
97
|
+
source_gdf["geometry"]
|
|
98
|
+
.apply(lambda x: x.centroid.coords[0])
|
|
99
|
+
.to_numpy(dtype=CentroidDType)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
self.validate_result(self.context, result_np)
|
|
103
|
+
return InspectResult(
|
|
104
|
+
self,
|
|
105
|
+
source=source_gdf,
|
|
106
|
+
result=result_np,
|
|
107
|
+
dtype=self.result_format.dtype.type,
|
|
108
|
+
shape=self.result_format.shape,
|
|
109
|
+
issues={},
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@adrio_cache
|
|
114
|
+
class InternalPoint(_USTIGERMixin, ADRIO[StructDType, np.float64]):
|
|
115
|
+
"""
|
|
116
|
+
The internal point provided by TIGER data. These points are selected by
|
|
117
|
+
Census workers so as to be guaranteed to be within the geographic polygons,
|
|
118
|
+
while geometric centroids have no such guarantee.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
# FROM MIXIN:
|
|
122
|
+
# def validate_context(self, context: Context) -> None:
|
|
123
|
+
# def estimate_data(self) -> AvailableDataEstimate:
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
@override
|
|
127
|
+
def result_format(self) -> ResultFormat:
|
|
128
|
+
return ResultFormat(shape=Shapes.N, dtype=CentroidDType)
|
|
129
|
+
|
|
130
|
+
@override
|
|
131
|
+
def validate_result(self, context: Context, result: NDArray) -> None:
|
|
132
|
+
adrio_validate_pipe(
|
|
133
|
+
self,
|
|
134
|
+
context,
|
|
135
|
+
result,
|
|
136
|
+
validate_numpy(),
|
|
137
|
+
validate_shape(self.result_format.shape.to_tuple(context.dim)),
|
|
138
|
+
validate_dtype(self.result_format.dtype),
|
|
139
|
+
on_structured(validate_values_in_range(-180.0, +180.0)),
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
@override
|
|
143
|
+
def inspect(self) -> InspectResult[StructDType, np.float64]:
|
|
144
|
+
self.validate_context(self.context)
|
|
145
|
+
scope = cast(CensusScope, self.scope)
|
|
146
|
+
|
|
147
|
+
info_df = scope.get_info()
|
|
148
|
+
centroids = list(
|
|
149
|
+
zip(
|
|
150
|
+
to_numeric(info_df["INTPTLON"]),
|
|
151
|
+
to_numeric(info_df["INTPTLAT"]),
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
result_np = np.array(centroids, dtype=CentroidDType)
|
|
155
|
+
self.validate_result(self.context, result_np)
|
|
156
|
+
|
|
157
|
+
return InspectResult(
|
|
158
|
+
self,
|
|
159
|
+
source=info_df,
|
|
160
|
+
result=result_np,
|
|
161
|
+
dtype=self.result_format.dtype.type,
|
|
162
|
+
shape=self.result_format.shape,
|
|
163
|
+
issues={},
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@adrio_cache
|
|
168
|
+
class Name(_USTIGERMixin, ADRIO[np.str_, np.str_]):
|
|
169
|
+
"""For states and counties, the proper name of the location; otherwise its GEOID."""
|
|
170
|
+
|
|
171
|
+
# FROM ADRIO:
|
|
172
|
+
# def validate_result(self, context: Context, result: NDArray) -> None:
|
|
173
|
+
# FROM MIXIN:
|
|
174
|
+
# def validate_context(self, context: Context) -> None:
|
|
175
|
+
# def estimate_data(self) -> AvailableDataEstimate:
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
@override
|
|
179
|
+
def result_format(self) -> ResultFormat:
|
|
180
|
+
return ResultFormat(shape=Shapes.N, dtype=np.str_)
|
|
181
|
+
|
|
182
|
+
@override
|
|
183
|
+
def inspect(self) -> InspectResult[np.str_, np.str_]:
|
|
184
|
+
self.validate_context(self.context)
|
|
185
|
+
scope = cast(CensusScope, self.scope)
|
|
186
|
+
|
|
187
|
+
# NOTE: info isn't really needed for Tract/CBG scope, but if we special case
|
|
188
|
+
# to avoid loading it then we have to duplicate this logic in cache estimation
|
|
189
|
+
# and invent a "source" for the inspect result. I think better to just load it.
|
|
190
|
+
info_df = scope.get_info()
|
|
191
|
+
|
|
192
|
+
if scope.granularity in ("state", "county"):
|
|
193
|
+
result_np = info_df["NAME"].to_numpy(dtype=np.str_)
|
|
194
|
+
else:
|
|
195
|
+
# There aren't good names for Tracts or CBGs, just use GEOID
|
|
196
|
+
result_np = scope.node_ids
|
|
197
|
+
|
|
198
|
+
self.validate_result(self.context, result_np)
|
|
199
|
+
return InspectResult(
|
|
200
|
+
self,
|
|
201
|
+
source=info_df,
|
|
202
|
+
result=result_np,
|
|
203
|
+
dtype=self.result_format.dtype.type,
|
|
204
|
+
shape=self.result_format.shape,
|
|
205
|
+
issues={},
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@adrio_cache
|
|
210
|
+
class PostalCode(_USTIGERMixin, ADRIO[np.str_, np.str_]):
|
|
211
|
+
"""
|
|
212
|
+
For states only, the postal code abbreviation for the state
|
|
213
|
+
("AZ" for Arizona, and so on).
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
# FROM ADRIO:
|
|
217
|
+
# def validate_result(self, context: Context, result: NDArray) -> None:
|
|
218
|
+
# FROM MIXIN:
|
|
219
|
+
# def estimate_data(self) -> AvailableDataEstimate:
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
@override
|
|
223
|
+
def result_format(self) -> ResultFormat:
|
|
224
|
+
return ResultFormat(shape=Shapes.N, dtype=np.str_)
|
|
225
|
+
|
|
226
|
+
@override
|
|
227
|
+
def validate_context(self, context: Context) -> None:
|
|
228
|
+
if not isinstance(context.scope, StateScope):
|
|
229
|
+
err = "PostalCode is only available for StateScopes."
|
|
230
|
+
raise ADRIOContextError(self, context, err)
|
|
231
|
+
year = context.scope.year
|
|
232
|
+
if not is_tiger_year(year):
|
|
233
|
+
err = f"{year} is not a supported year for us_tiger attributes."
|
|
234
|
+
raise ADRIOContextError(self, context, err)
|
|
235
|
+
|
|
236
|
+
@override
|
|
237
|
+
def inspect(self) -> InspectResult[np.str_, np.str_]:
|
|
238
|
+
self.validate_context(self.context)
|
|
239
|
+
scope = cast(CensusScope, self.scope)
|
|
240
|
+
|
|
241
|
+
info_df = scope.get_info()
|
|
242
|
+
result_np = info_df["STUSPS"].to_numpy(dtype=np.str_)
|
|
243
|
+
|
|
244
|
+
self.validate_result(self.context, result_np)
|
|
245
|
+
return InspectResult(
|
|
246
|
+
self,
|
|
247
|
+
source=info_df,
|
|
248
|
+
result=result_np,
|
|
249
|
+
dtype=self.result_format.dtype.type,
|
|
250
|
+
shape=self.result_format.shape,
|
|
251
|
+
issues={},
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
@adrio_cache
|
|
256
|
+
class LandAreaM2(_USTIGERMixin, ADRIO[np.float64, np.float64]):
|
|
257
|
+
"""
|
|
258
|
+
The land area of the geo node in meters-squared. This is the 'ALAND' attribute
|
|
259
|
+
from the TIGER data files.
|
|
260
|
+
"""
|
|
261
|
+
|
|
262
|
+
# FROM ADRIO:
|
|
263
|
+
# def validate_result(self, context: Context, result: NDArray) -> None:
|
|
264
|
+
# FROM MIXIN:
|
|
265
|
+
# def validate_context(self, context: Context) -> None:
|
|
266
|
+
# def estimate_data(self) -> AvailableDataEstimate:
|
|
267
|
+
|
|
268
|
+
@property
|
|
269
|
+
@override
|
|
270
|
+
def result_format(self) -> ResultFormat:
|
|
271
|
+
return ResultFormat(shape=Shapes.N, dtype=np.float64)
|
|
272
|
+
|
|
273
|
+
@override
|
|
274
|
+
def inspect(self) -> InspectResult[np.float64, np.float64]:
|
|
275
|
+
self.validate_context(self.context)
|
|
276
|
+
scope = cast(CensusScope, self.scope)
|
|
277
|
+
|
|
278
|
+
info_df = scope.get_info()
|
|
279
|
+
result_np = info_df["ALAND"].to_numpy(dtype=np.float64)
|
|
280
|
+
|
|
281
|
+
self.validate_result(self.context, result_np)
|
|
282
|
+
return InspectResult(
|
|
283
|
+
self,
|
|
284
|
+
source=info_df,
|
|
285
|
+
result=result_np,
|
|
286
|
+
dtype=self.result_format.dtype.type,
|
|
287
|
+
shape=self.result_format.shape,
|
|
288
|
+
issues={},
|
|
289
|
+
)
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"""ADRIO result validation utilities."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Callable, Literal
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from numpy.typing import NDArray
|
|
9
|
+
from typing_extensions import override
|
|
10
|
+
|
|
11
|
+
from epymorph.data_shape import DataShape
|
|
12
|
+
from epymorph.simulation import Context
|
|
13
|
+
from epymorph.util import extract_date_value, is_date_value_array
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ValidationResult(ABC):
|
|
17
|
+
"""
|
|
18
|
+
The result of a data validation check.
|
|
19
|
+
|
|
20
|
+
See Also
|
|
21
|
+
--------
|
|
22
|
+
[epymorph.adrio.validation.Valid][] and [epymorph.adrio.validation.Invalid][].
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def is_valid(self) -> bool:
|
|
28
|
+
"""True if this is a valid result, False for invalid."""
|
|
29
|
+
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def __and__(self, other: "ValidationResult") -> "ValidationResult":
|
|
32
|
+
"""
|
|
33
|
+
Combine two results by returning the first invalid result or else `Valid` if
|
|
34
|
+
both are valid.
|
|
35
|
+
|
|
36
|
+
Parameters
|
|
37
|
+
----------
|
|
38
|
+
other :
|
|
39
|
+
The other validation result to consider.
|
|
40
|
+
|
|
41
|
+
Returns
|
|
42
|
+
-------
|
|
43
|
+
:
|
|
44
|
+
The first invalid result or else `Valid` if both are valid.
|
|
45
|
+
"""
|
|
46
|
+
# NOTE: this is `&` not `and`
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Valid(ValidationResult):
|
|
51
|
+
"""The result of passing a validation check."""
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
@override
|
|
55
|
+
def is_valid(self) -> Literal[True]:
|
|
56
|
+
return True
|
|
57
|
+
|
|
58
|
+
@override
|
|
59
|
+
def __and__(self, other: "ValidationResult") -> "ValidationResult":
|
|
60
|
+
return other
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class Invalid(ValidationResult):
|
|
65
|
+
"""The result of failing a validation check."""
|
|
66
|
+
|
|
67
|
+
error: str
|
|
68
|
+
"""The reason why this check failed.."""
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
@override
|
|
72
|
+
def is_valid(self) -> Literal[False]:
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
@override
|
|
76
|
+
def __and__(self, other: "ValidationResult") -> "ValidationResult":
|
|
77
|
+
return self
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
VALID = Valid()
|
|
81
|
+
"""A singleton instance of `Valid`."""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
Validator = Callable[[NDArray], ValidationResult]
|
|
85
|
+
"""The type for a function which validates a numpy result."""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def validate_pipe(*validators: Validator) -> Validator:
|
|
89
|
+
"""
|
|
90
|
+
Create a validator by chaining multiple other validators. Validators are evaluated
|
|
91
|
+
such that they short-circuit on the first invalid result, in which case only that
|
|
92
|
+
invalid result is returned. If all validators pass, `Valid` is returned.
|
|
93
|
+
|
|
94
|
+
Parameters
|
|
95
|
+
----------
|
|
96
|
+
*validators :
|
|
97
|
+
The validator functions in evaluation order.
|
|
98
|
+
|
|
99
|
+
Returns
|
|
100
|
+
-------
|
|
101
|
+
:
|
|
102
|
+
A validator function.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def _validate_pipe(values: NDArray) -> ValidationResult:
|
|
106
|
+
for validate in validators:
|
|
107
|
+
v = validate(values)
|
|
108
|
+
if isinstance(v, Invalid):
|
|
109
|
+
return v
|
|
110
|
+
return VALID
|
|
111
|
+
|
|
112
|
+
return _validate_pipe
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def validate_numpy() -> Validator:
|
|
116
|
+
"""
|
|
117
|
+
Create a validator which checks that the result is a numpy array.
|
|
118
|
+
|
|
119
|
+
Returns
|
|
120
|
+
-------
|
|
121
|
+
:
|
|
122
|
+
A validator function.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def _validate_numpy(values: NDArray) -> ValidationResult:
|
|
126
|
+
if not isinstance(values, np.ndarray):
|
|
127
|
+
return Invalid("result was not a numpy array")
|
|
128
|
+
return VALID
|
|
129
|
+
|
|
130
|
+
return _validate_numpy
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def validate_values_in_range(
|
|
134
|
+
minimum: int | float | None,
|
|
135
|
+
maximum: int | float | None,
|
|
136
|
+
) -> Validator:
|
|
137
|
+
"""
|
|
138
|
+
Create a validator which checks that numeric values fall within the specified
|
|
139
|
+
range.
|
|
140
|
+
|
|
141
|
+
Assumes the values are not structured; if you wish to validate structured data
|
|
142
|
+
combine this function with a wrapper like `on_date_values` or `on_structured`.
|
|
143
|
+
|
|
144
|
+
Parameters
|
|
145
|
+
----------
|
|
146
|
+
minimum :
|
|
147
|
+
The minimum valid value, or `None` if there is no minimum.
|
|
148
|
+
maximum :
|
|
149
|
+
The maximum valid value, or `None` if there is no maximum.
|
|
150
|
+
|
|
151
|
+
Returns
|
|
152
|
+
-------
|
|
153
|
+
:
|
|
154
|
+
A validator function.
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
def _validate_values_in_range(values: NDArray) -> ValidationResult:
|
|
158
|
+
nonlocal minimum, maximum
|
|
159
|
+
match (minimum, maximum):
|
|
160
|
+
case (None, None):
|
|
161
|
+
invalid = np.zeros_like(values, dtype=np.bool_)
|
|
162
|
+
case (minimum, None):
|
|
163
|
+
invalid = values < minimum
|
|
164
|
+
case (None, maximum):
|
|
165
|
+
invalid = values > maximum
|
|
166
|
+
case (minimum, maximum):
|
|
167
|
+
invalid = (values < minimum) | (values > maximum)
|
|
168
|
+
if np.any(invalid):
|
|
169
|
+
invalid_values = np.sort(values[invalid].flatten())
|
|
170
|
+
return Invalid(f"result contains invalid values\ne.g., {invalid_values}")
|
|
171
|
+
return VALID
|
|
172
|
+
|
|
173
|
+
return _validate_values_in_range
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def validate_shape(shape: tuple[int, ...]) -> Validator:
|
|
177
|
+
"""
|
|
178
|
+
Create a validator which checks the given shape.
|
|
179
|
+
|
|
180
|
+
Parameters
|
|
181
|
+
----------
|
|
182
|
+
shape :
|
|
183
|
+
The expected result shape.
|
|
184
|
+
|
|
185
|
+
Returns
|
|
186
|
+
-------
|
|
187
|
+
:
|
|
188
|
+
A validator function.
|
|
189
|
+
"""
|
|
190
|
+
if -1 in shape:
|
|
191
|
+
err = (
|
|
192
|
+
"Cannot check result shapes containing arbitrary axes; "
|
|
193
|
+
"the ADRIO should specify the expected shape as a tuple of axis lengths."
|
|
194
|
+
)
|
|
195
|
+
raise ValueError(err)
|
|
196
|
+
|
|
197
|
+
def _validate_shape(values: NDArray) -> ValidationResult:
|
|
198
|
+
if values.shape != shape:
|
|
199
|
+
return Invalid(
|
|
200
|
+
f"result was an invalid shape:\ngot {values.shape}, expected {shape}"
|
|
201
|
+
)
|
|
202
|
+
return VALID
|
|
203
|
+
|
|
204
|
+
return _validate_shape
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def validate_shape_unchecked_arbitrary(shape: tuple[int, ...]) -> Validator:
|
|
208
|
+
"""
|
|
209
|
+
Create a validator which checks the given shape with the special exception that
|
|
210
|
+
if an axis is specified as -1, any length (one or greater) is permitted. There must
|
|
211
|
+
still be the same number of dimensions in the result.
|
|
212
|
+
|
|
213
|
+
Parameters
|
|
214
|
+
----------
|
|
215
|
+
shape :
|
|
216
|
+
The expected result shape.
|
|
217
|
+
|
|
218
|
+
Returns
|
|
219
|
+
-------
|
|
220
|
+
:
|
|
221
|
+
A validator function.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
def _validate_shape(values: NDArray) -> ValidationResult:
|
|
225
|
+
err = "result was an invalid shape:\ngot {}, expected {}"
|
|
226
|
+
if len(values.shape) != len(shape):
|
|
227
|
+
return Invalid(err.format(values.shape, shape))
|
|
228
|
+
for actual_length, expected_length in zip(values.shape, shape, strict=True):
|
|
229
|
+
if expected_length != -1 and expected_length != actual_length:
|
|
230
|
+
return Invalid(err.format(values.shape, shape))
|
|
231
|
+
return VALID
|
|
232
|
+
|
|
233
|
+
return _validate_shape
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def validate_dtype(dtype: np.dtype | type[np.generic]) -> Validator:
|
|
237
|
+
"""
|
|
238
|
+
Create a validator which checks the given dtype.
|
|
239
|
+
|
|
240
|
+
Assumes the values are not structured; if you wish to validate structured data
|
|
241
|
+
combine this function with a wrapper like `on_date_values` or `on_structured`.
|
|
242
|
+
|
|
243
|
+
Parameters
|
|
244
|
+
----------
|
|
245
|
+
dtype :
|
|
246
|
+
The expected result dtype.
|
|
247
|
+
|
|
248
|
+
Returns
|
|
249
|
+
-------
|
|
250
|
+
:
|
|
251
|
+
A validator function.
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
def _validate_dtype(values: NDArray) -> ValidationResult:
|
|
255
|
+
nonlocal dtype
|
|
256
|
+
if not isinstance(dtype, np.dtype):
|
|
257
|
+
dtype = np.dtype(dtype)
|
|
258
|
+
values_dtype = np.dtype(values.dtype)
|
|
259
|
+
if dtype.kind == "U":
|
|
260
|
+
# for strings, ignore length
|
|
261
|
+
valid = values_dtype.kind == "U"
|
|
262
|
+
else:
|
|
263
|
+
# for other types, match dtype exactly
|
|
264
|
+
valid = values_dtype == dtype
|
|
265
|
+
if not valid:
|
|
266
|
+
return Invalid(
|
|
267
|
+
"result was not the expected data type\n"
|
|
268
|
+
f"got {np.dtype(values.dtype)}, expected {(np.dtype(dtype))}"
|
|
269
|
+
)
|
|
270
|
+
return VALID
|
|
271
|
+
|
|
272
|
+
return _validate_dtype
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def on_date_values(validator: Validator) -> Validator:
|
|
276
|
+
"""
|
|
277
|
+
Wrap a validator function so that it can check the values of a date/value array.
|
|
278
|
+
|
|
279
|
+
Parameters
|
|
280
|
+
----------
|
|
281
|
+
validator :
|
|
282
|
+
The validator function to wrap.
|
|
283
|
+
|
|
284
|
+
Returns
|
|
285
|
+
-------
|
|
286
|
+
:
|
|
287
|
+
The validator function adapted to work for data/value arrays.
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
def _on_date_values(date_values: NDArray) -> ValidationResult:
|
|
291
|
+
if not is_date_value_array(date_values):
|
|
292
|
+
return Invalid("result was not a date/value pair as expected")
|
|
293
|
+
_, values = extract_date_value(date_values)
|
|
294
|
+
return validator(values)
|
|
295
|
+
|
|
296
|
+
return _on_date_values
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def on_structured(validator: Validator) -> Validator:
|
|
300
|
+
"""
|
|
301
|
+
Wrap a validator function so that it can check the values of structured arrays.
|
|
302
|
+
This presumes that the validator can be applied to all elements of the structured
|
|
303
|
+
array in the same way. That is: it will likely work for homogenous types but not
|
|
304
|
+
heterogenous types.
|
|
305
|
+
|
|
306
|
+
Parameters
|
|
307
|
+
----------
|
|
308
|
+
validator :
|
|
309
|
+
The validator function to wrap.
|
|
310
|
+
|
|
311
|
+
Returns
|
|
312
|
+
-------
|
|
313
|
+
:
|
|
314
|
+
The validator function adapated to work for structured arrays.
|
|
315
|
+
"""
|
|
316
|
+
|
|
317
|
+
def _on_structured(values: NDArray) -> ValidationResult:
|
|
318
|
+
if values.dtype.names is None:
|
|
319
|
+
return Invalid("result was not a structured array as expected")
|
|
320
|
+
for name in values.dtype.names:
|
|
321
|
+
v = validator(values[name])
|
|
322
|
+
if isinstance(v, Invalid):
|
|
323
|
+
return v
|
|
324
|
+
return VALID
|
|
325
|
+
|
|
326
|
+
return _on_structured
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@dataclass(frozen=True)
|
|
330
|
+
class ResultFormat:
|
|
331
|
+
"""
|
|
332
|
+
Describes the properties of the expected result of evaluating an ADRIO.
|
|
333
|
+
|
|
334
|
+
Parameters
|
|
335
|
+
----------
|
|
336
|
+
shape :
|
|
337
|
+
The expected shape of the result array.
|
|
338
|
+
dtype :
|
|
339
|
+
The dtype describing the result array.
|
|
340
|
+
"""
|
|
341
|
+
|
|
342
|
+
def __init__(self, shape: DataShape, dtype: np.dtype | type[np.generic]):
|
|
343
|
+
if not isinstance(dtype, np.dtype):
|
|
344
|
+
dtype = np.dtype(dtype)
|
|
345
|
+
object.__setattr__(self, "shape", shape)
|
|
346
|
+
object.__setattr__(self, "dtype", dtype)
|
|
347
|
+
|
|
348
|
+
shape: DataShape
|
|
349
|
+
"""The expected shape of the result array."""
|
|
350
|
+
dtype: np.dtype
|
|
351
|
+
"""The dtype describing the result array."""
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def validate_result(rformat: ResultFormat, context: Context) -> Validator:
|
|
355
|
+
"""
|
|
356
|
+
Create a validator for the given result format declaration. This is a shortcut
|
|
357
|
+
for chaining `validate_shape` and `validate_dtype`.
|
|
358
|
+
|
|
359
|
+
Assumes the values are not structured; if you wish to validate structured data
|
|
360
|
+
combine this function with a wrapper like `on_date_values` or `on_structured`.
|
|
361
|
+
|
|
362
|
+
Parameters
|
|
363
|
+
----------
|
|
364
|
+
rformat :
|
|
365
|
+
The expected result format.
|
|
366
|
+
context :
|
|
367
|
+
The simulation context.
|
|
368
|
+
|
|
369
|
+
Returns
|
|
370
|
+
-------
|
|
371
|
+
:
|
|
372
|
+
A validator function.
|
|
373
|
+
"""
|
|
374
|
+
vshape = validate_shape(rformat.shape.to_tuple(context.dim))
|
|
375
|
+
vdtype = validate_dtype(rformat.dtype)
|
|
376
|
+
|
|
377
|
+
def _validate_result(values: NDArray) -> ValidationResult:
|
|
378
|
+
if isinstance(v := vshape(values), Invalid):
|
|
379
|
+
return v
|
|
380
|
+
return vdtype(values)
|
|
381
|
+
|
|
382
|
+
return _validate_result
|