epymorph 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. epymorph/__init__.py +7 -0
  2. epymorph/__main__.py +16 -0
  3. epymorph/adrio/__init__.py +0 -0
  4. epymorph/adrio/acs5.py +1378 -0
  5. epymorph/adrio/adrio.py +953 -0
  6. epymorph/adrio/cdc.py +1826 -0
  7. epymorph/adrio/commuting_flows.py +283 -0
  8. epymorph/adrio/csv.py +499 -0
  9. epymorph/adrio/humidity.py +206 -0
  10. epymorph/adrio/lodes.py +509 -0
  11. epymorph/adrio/numpy.py +160 -0
  12. epymorph/adrio/prism.py +345 -0
  13. epymorph/adrio/processing.py +1221 -0
  14. epymorph/adrio/soda.py +602 -0
  15. epymorph/adrio/us_tiger.py +289 -0
  16. epymorph/adrio/validation.py +382 -0
  17. epymorph/attribute.py +614 -0
  18. epymorph/cache.py +680 -0
  19. epymorph/cli/__init__.py +0 -0
  20. epymorph/cli/cache.py +78 -0
  21. epymorph/cli/main.py +29 -0
  22. epymorph/compartment_model.py +1873 -0
  23. epymorph/data/__init__.py +1 -0
  24. epymorph/data/ipm/__init__.py +22 -0
  25. epymorph/data/ipm/no.py +14 -0
  26. epymorph/data/ipm/pei.py +40 -0
  27. epymorph/data/ipm/seirs.py +50 -0
  28. epymorph/data/ipm/sirh.py +55 -0
  29. epymorph/data/ipm/sirs.py +48 -0
  30. epymorph/data/ipm/sparsemod.py +96 -0
  31. epymorph/data/mm/__init__.py +22 -0
  32. epymorph/data/mm/centroids.py +76 -0
  33. epymorph/data/mm/flat.py +61 -0
  34. epymorph/data/mm/icecube.py +50 -0
  35. epymorph/data/mm/no.py +29 -0
  36. epymorph/data/mm/pei.py +105 -0
  37. epymorph/data/mm/sparsemod.py +73 -0
  38. epymorph/data/pei.py +424 -0
  39. epymorph/data_shape.py +593 -0
  40. epymorph/data_type.py +185 -0
  41. epymorph/data_usage.py +258 -0
  42. epymorph/database.py +1301 -0
  43. epymorph/error.py +195 -0
  44. epymorph/event.py +196 -0
  45. epymorph/geography/__init__.py +0 -0
  46. epymorph/geography/custom.py +93 -0
  47. epymorph/geography/scope.py +457 -0
  48. epymorph/geography/us_census.py +1056 -0
  49. epymorph/geography/us_geography.py +502 -0
  50. epymorph/geography/us_tiger.py +1083 -0
  51. epymorph/initializer.py +786 -0
  52. epymorph/kit.py +107 -0
  53. epymorph/log/__init__.py +0 -0
  54. epymorph/log/file.py +128 -0
  55. epymorph/log/messaging.py +139 -0
  56. epymorph/log/movement.py +228 -0
  57. epymorph/movement_model.py +347 -0
  58. epymorph/parameter_fitting/__init__.py +0 -0
  59. epymorph/parameter_fitting/distribution.py +68 -0
  60. epymorph/parameter_fitting/dynamics.py +19 -0
  61. epymorph/parameter_fitting/filter/__init__.py +0 -0
  62. epymorph/parameter_fitting/filter/base_filter.py +50 -0
  63. epymorph/parameter_fitting/filter/particle.py +32 -0
  64. epymorph/parameter_fitting/filter/particle_filter.py +296 -0
  65. epymorph/parameter_fitting/likelihood.py +54 -0
  66. epymorph/parameter_fitting/output.py +73 -0
  67. epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
  68. epymorph/parameter_fitting/perturbation.py +19 -0
  69. epymorph/parameter_fitting/utils/__init__.py +0 -0
  70. epymorph/parameter_fitting/utils/data_loader.py +97 -0
  71. epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
  72. epymorph/parameter_fitting/utils/observations.py +63 -0
  73. epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
  74. epymorph/parameter_fitting/utils/params_perturb.py +43 -0
  75. epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
  76. epymorph/parameter_fitting/utils/resampler.py +258 -0
  77. epymorph/parameter_fitting/utils/utils.py +101 -0
  78. epymorph/params.py +438 -0
  79. epymorph/py.typed +0 -0
  80. epymorph/rume.py +871 -0
  81. epymorph/simulation.py +991 -0
  82. epymorph/simulator/__init__.py +0 -0
  83. epymorph/simulator/basic/__init__.py +0 -0
  84. epymorph/simulator/basic/basic_simulator.py +171 -0
  85. epymorph/simulator/basic/ipm_exec.py +437 -0
  86. epymorph/simulator/basic/mm_exec.py +244 -0
  87. epymorph/simulator/basic/output.py +213 -0
  88. epymorph/simulator/world.py +149 -0
  89. epymorph/simulator/world_list.py +274 -0
  90. epymorph/strata.py +24 -0
  91. epymorph/sympy_shim.py +57 -0
  92. epymorph/time.py +1197 -0
  93. epymorph/tools/__init__.py +0 -0
  94. epymorph/tools/data.py +297 -0
  95. epymorph/tools/ipm_diagram.py +208 -0
  96. epymorph/tools/out_map.py +551 -0
  97. epymorph/tools/out_plot.py +423 -0
  98. epymorph/tools/out_table.py +582 -0
  99. epymorph/util.py +1036 -0
  100. epymorph-1.0.0.dist-info/METADATA +57 -0
  101. epymorph-1.0.0.dist-info/RECORD +104 -0
  102. epymorph-1.0.0.dist-info/WHEEL +5 -0
  103. epymorph-1.0.0.dist-info/entry_points.txt +2 -0
  104. epymorph-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,953 @@
1
+ """
2
+ Implements the base class for all ADRIOs, as well as some general-purpose
3
+ ADRIO implementations.
4
+ """
5
+
6
+ import functools
7
+ from abc import abstractmethod
8
+ from dataclasses import dataclass
9
+ from time import perf_counter
10
+ from typing import (
11
+ Callable,
12
+ Generic,
13
+ Mapping,
14
+ Sequence,
15
+ TypeVar,
16
+ final,
17
+ )
18
+ from urllib.error import HTTPError
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+ from numpy.core.records import fromarrays
23
+ from numpy.typing import NDArray
24
+ from sparklines import sparklines
25
+ from typing_extensions import override
26
+
27
+ from epymorph.adrio.processing import PipelineResult
28
+ from epymorph.adrio.validation import (
29
+ Invalid,
30
+ ResultFormat,
31
+ Validator,
32
+ validate_dtype,
33
+ validate_numpy,
34
+ validate_pipe,
35
+ validate_shape,
36
+ )
37
+ from epymorph.attribute import NAME_PLACEHOLDER, AbsoluteName, AttributeDef
38
+ from epymorph.compartment_model import BaseCompartmentModel
39
+ from epymorph.data_shape import DataShape, Shapes
40
+ from epymorph.data_type import AttributeArray
41
+ from epymorph.data_usage import DataEstimate, EmptyDataEstimate
42
+ from epymorph.database import DataResolver, evaluate_param
43
+ from epymorph.error import MissingContextError
44
+ from epymorph.event import ADRIOProgress, DownloadActivity, EventBus
45
+ from epymorph.geography.scope import GeoScope
46
+ from epymorph.simulation import Context, SimulationFunction
47
+ from epymorph.time import DateRange, TimeFrame
48
+ from epymorph.util import (
49
+ dtype_name,
50
+ extract_date_value,
51
+ is_date_value_array,
52
+ is_numeric,
53
+ )
54
+
55
+ ResultDType = TypeVar("ResultDType", bound=np.generic)
56
+ """The result type of an ADRIO."""
57
+
58
+ ProgressCallback = Callable[[float, DownloadActivity | None], None]
59
+ """
60
+ The type of a callback function used by ADRIO implementations to report data fetching
61
+ progress.
62
+ """
63
+
64
+ _events = EventBus()
65
+
66
+
67
+ #########
68
+ # ADRIO #
69
+ #########
70
+
71
+
72
+ _ADRIOClassT = TypeVar("_ADRIOClassT", bound="ADRIO")
73
+
74
+
75
+ def adrio_cache(cls: type[_ADRIOClassT]) -> type[_ADRIOClassT]:
76
+ """
77
+ `ADRIO` class decorator to add result-caching behavior.
78
+
79
+ Examples
80
+ --------
81
+ >>> @adrio_cache
82
+ >>> class MyADRIO(ADRIO[np.int64]):
83
+ >>> # Now this ADRIO will cache its results.
84
+ >>> # ...
85
+ """
86
+
87
+ orig_with_context = cls.with_context_internal
88
+ orig_evaluate = cls.evaluate
89
+ ctx_cache_key = "__with_context_cache__"
90
+ eval_cache_key = "__evaluate_cache__"
91
+
92
+ @functools.wraps(orig_with_context)
93
+ def with_context_internal(self, context: Context):
94
+ curr_hash = context.hash(self.requirements)
95
+ cached_hash, cached_instance = getattr(self, ctx_cache_key, (None, None))
96
+ if cached_instance is None or cached_hash != curr_hash:
97
+ cached_instance = orig_with_context(self, context)
98
+ cached_hash = curr_hash
99
+ setattr(self, ctx_cache_key, (cached_hash, cached_instance))
100
+ setattr(self, eval_cache_key, None)
101
+ return cached_instance
102
+
103
+ @functools.wraps(orig_evaluate)
104
+ def evaluate(self):
105
+ cached_value = getattr(self, eval_cache_key, None)
106
+ if cached_value is None:
107
+ cached_value = orig_evaluate(self)
108
+ setattr(self, eval_cache_key, cached_value)
109
+ return cached_value
110
+
111
+ cls.with_context_internal = with_context_internal
112
+ cls.evaluate = evaluate
113
+ return cls
114
+
115
+
116
+ def _adrio_name(adrio: "ADRIO", context: Context) -> str:
117
+ if context.name == NAME_PLACEHOLDER:
118
+ return adrio.class_name
119
+ else:
120
+ return f"{context.name} ({adrio.name})"
121
+
122
+
123
+ class ADRIOError(Exception):
124
+ """
125
+ Error while loading or processing data with an ADRIO.
126
+
127
+ Parameters
128
+ ----------
129
+ adrio :
130
+ The ADRIO being evaluated.
131
+ context :
132
+ The evaluation context.
133
+ message :
134
+ An error description.
135
+ """
136
+
137
+ adrio: "ADRIO"
138
+ """The ADRIO being evaluated."""
139
+ context: Context
140
+ """The evaluation context."""
141
+
142
+ def __init__(self, adrio: "ADRIO", context: Context, message: str):
143
+ self.adrio = adrio
144
+ self.context = context
145
+ # If message contains "{adrio_name}", fill it in.
146
+ message = message.format(adrio_name=_adrio_name(adrio, context))
147
+ super().__init__(message)
148
+
149
+
150
+ class ADRIOContextError(ADRIOError):
151
+ """
152
+ Error if the simulation context is invalid for evaluating the ADRIO.
153
+
154
+ Parameters
155
+ ----------
156
+ adrio :
157
+ The ADRIO being evaluated.
158
+ context :
159
+ The evaluation context.
160
+ message :
161
+ An error description, or else a default message will be used.
162
+ """
163
+
164
+ def __init__(
165
+ self,
166
+ adrio: "ADRIO",
167
+ context: Context,
168
+ message: str | None = None,
169
+ ):
170
+ if message is None:
171
+ message = "the ADRIO encountered an unexpected error"
172
+ message = "Invalid context for {adrio_name}: " + message
173
+ super().__init__(adrio, context, message)
174
+
175
+
176
+ class ADRIOCommunicationError(ADRIOError):
177
+ """
178
+ Error if the ADRIO could not communicate with the external resource.
179
+
180
+ Parameters
181
+ ----------
182
+ adrio :
183
+ The ADRIO being evaluated.
184
+ context :
185
+ The evaluation context.
186
+ message :
187
+ An error description, or else a default message will be used.
188
+ """
189
+
190
+ def __init__(
191
+ self,
192
+ adrio: "ADRIO",
193
+ context: Context,
194
+ message: str | None = None,
195
+ ):
196
+ if message is None:
197
+ message = "the ADRIO was unable to communicate with the external resource"
198
+ message = "Error loading {adrio_name}: " + message
199
+ super().__init__(adrio, context, message)
200
+
201
+
202
+ class ADRIOProcessingError(ADRIOError):
203
+ """
204
+ An unexpected error occurred while processing ADRIO data.
205
+
206
+ Parameters
207
+ ----------
208
+ adrio :
209
+ The ADRIO being evaluated.
210
+ context :
211
+ The evaluation context.
212
+ message :
213
+ An error description, or else a default message will be used.
214
+ """
215
+
216
+ def __init__(
217
+ self,
218
+ adrio: "ADRIO",
219
+ context: Context,
220
+ message: str | None = None,
221
+ ):
222
+ if message is None:
223
+ message = "the ADRIO encountered an unexpected error processing results"
224
+ message = "Error processing {adrio_name}: " + message
225
+ super().__init__(adrio, context, message)
226
+
227
+
228
+ ResultT = TypeVar("ResultT", bound=np.generic)
229
+ """The dtype of an ADRIO result."""
230
+ ValueT = TypeVar("ValueT", bound=np.generic)
231
+ """The dtype of an ADRIO result's values, which may differ from the result type."""
232
+
233
+
234
+ @dataclass(frozen=True)
235
+ class InspectResult(Generic[ResultT, ValueT]):
236
+ """
237
+ Inspection is the process by which an ADRIO fetches data and analyzes its quality.
238
+
239
+ The result encapsulates the source data, the processed result data, and any
240
+ outstanding data issues. ADRIOs will provide methods for correcting these issues
241
+ as is appropriate for the task, but often these will be optional. A result which
242
+ contains unresolved data issues will be represented as a masked numpy array. Values
243
+ which are not impacted by any of the data issues will be unmasked. Individual issues
244
+ are tracked along with masks specific to the issue.
245
+
246
+ For example: if data is not available for every geo node requested, some values will
247
+ be represented as missing. Missing values will be masked in the result, and an issue
248
+ will be included (likely called "missing") with a boolean mask indicating the
249
+ missing values. The ADRIO will likely provide a fill method option which allows
250
+ users the option to fill missing values, for instance with zeros.
251
+ Providing a fill method and inspecting the ADRIO a second time should resolve the
252
+ "missing" issue and, assuming no other issues remain, produce a non-masked numpy
253
+ array as a result.
254
+
255
+ `InspectResult` is generic on the result and value type (`ResultT` and `ValueT`) of
256
+ the ADRIO.
257
+
258
+ Parameters
259
+ ----------
260
+ adrio :
261
+ A reference to the ADRIO which produced this result.
262
+ source :
263
+ The data as fetched from the source. This can be useful for debugging data
264
+ issues.
265
+ result :
266
+ The final result produced by the ADRIO.
267
+ dtype :
268
+ The dtype of the data values.
269
+ shape :
270
+ The shape of the result.
271
+ issues :
272
+ The set of issues in the data along with a mask which indicates which values
273
+ are impacted by the issue. The keys of this mapping are specific to the ADRIO,
274
+ as ADRIOs tend to deal with unique data challenges.
275
+
276
+ Examples
277
+ --------
278
+ --8<-- "docs/_examples/adrio_adrio_InspectResult.md"
279
+ """
280
+
281
+ adrio: "ADRIO[ResultT, ValueT]"
282
+ """A reference to the ADRIO which produced this result."""
283
+ source: pd.DataFrame | NDArray | None
284
+ """
285
+ The data as fetched from the source. This can be useful for debugging data issues.
286
+ May be `None` if the source data isn't suitable for being included with the result
287
+ (maybe it's too large or in an awkward format, etc.)
288
+ """
289
+ result: NDArray[ResultT]
290
+ """The final result produced by the ADRIO."""
291
+ dtype: type[ValueT]
292
+ """The dtype of the data values."""
293
+ shape: DataShape
294
+ """The shape of the result."""
295
+ issues: Mapping[str, NDArray[np.bool_]]
296
+ """
297
+ The set of issues in the data along with a mask which indicates which values
298
+ are impacted by the issue. The keys of this mapping are specific to the ADRIO,
299
+ as ADRIOs tend to deal with unique data challenges.
300
+ """
301
+
302
+ def __post_init__(self):
303
+ for issue_name, mask in self.issues.items():
304
+ if mask.shape != self.result.shape:
305
+ err = (
306
+ f"The shape of the mask for '{issue_name}' {mask.shape} did "
307
+ f"not match the shape of the result data {self.result.shape}."
308
+ )
309
+ raise ValueError(err)
310
+
311
+ @functools.cached_property
312
+ def values(self) -> NDArray[ValueT]:
313
+ """
314
+ The values in the result. If the result is date/value tuples, the values are
315
+ first extracted.
316
+ """
317
+ values = self.result
318
+ if is_date_value_array(values, value_dtype=self.dtype):
319
+ _, values = extract_date_value(values, self.dtype)
320
+ return values # type: ignore
321
+
322
+ @property
323
+ def unmasked_count(self) -> int:
324
+ """The number of unmasked values in the result."""
325
+ vs = self.values # NOTE: the values accessor unwraps date/values
326
+ mask = np.ma.getmaskarray(vs)
327
+ if mask.dtype.names is None:
328
+ # values mask is not structured
329
+ return np.ma.count(vs)
330
+
331
+ # values mask is structured! (but not date/value)
332
+ # consider a value masked if any part of it is masked (mask boolean or)
333
+ combined_mask = np.zeros(vs.shape, dtype=np.bool_)
334
+ for name in mask.dtype.names:
335
+ combined_mask |= mask[name]
336
+ return np.invert(combined_mask).sum()
337
+
338
+ @property
339
+ def quantify(self) -> Sequence[tuple[str, float]]:
340
+ """
341
+ Quantifies properties of the data: what percentage of the values are impacted by
342
+ each data issue (if any), how many are zero, and how many are "unmasked" (that
343
+ is, not affected by any issues). The value is a sequence of tuples which contain
344
+ the name of the quality and the percentage of values.
345
+ """
346
+ vs = self.values
347
+ size = vs.size
348
+ unmasked_count = self.unmasked_count
349
+ quant = []
350
+ if unmasked_count > 0 and is_numeric(vs):
351
+ zero_value = vs.dtype.type(0)
352
+ quant.append(("zero", (vs == zero_value).sum() / size))
353
+ for name, mask in self.issues.items():
354
+ quant.append((name, mask.sum() / size))
355
+ quant.append(("unmasked", unmasked_count / size))
356
+ return quant
357
+
358
+ def __str__(self) -> str:
359
+ extra_info = []
360
+ if is_date_value_array(self.result):
361
+ # calc display values for date/value data
362
+ dates, vs = extract_date_value(self.result)
363
+ dtname = f"date/value ({dtype_name(np.dtype(vs.dtype))})"
364
+ match len(dates):
365
+ case 1:
366
+ extra_info.append(f" Date range: {dates[0]}")
367
+ case x if x > 1:
368
+ deltas = np.unique((dates[1:] - dates[:-1]))
369
+ period = str(deltas[0]) if len(deltas) == 1 else "irregular"
370
+ extra_info.append(
371
+ f" Date range: {dates.min()} to {dates.max()}"
372
+ f", period: {period}"
373
+ )
374
+ case _:
375
+ # might happen if there are zero data points
376
+ pass
377
+ else:
378
+ # calc display values for simple value data (not date/value)
379
+ vs = self.result
380
+ dtname = dtype_name(np.dtype(vs.dtype))
381
+
382
+ # Value statistics and histogram: only possible with numeric data.
383
+ stats = []
384
+ if is_numeric(vs):
385
+ if self.unmasked_count == 0:
386
+ stats.extend(
387
+ [
388
+ " Values:",
389
+ " N/A (all values are masked)",
390
+ ]
391
+ )
392
+ else:
393
+ # stats methods don't really support masked arrays
394
+ stats_vs = vs if not np.ma.is_masked(vs) else np.ma.compressed(vs)
395
+ qs = np.quantile(stats_vs, [0.25, 0.50, 0.75])
396
+ qs_str = ", ".join(f"{q:.1f}" for q in qs)
397
+
398
+ minimum = vs.min()
399
+ maximum = vs.max()
400
+ spark = sparklines(
401
+ np.histogram(vs, bins=20, range=(minimum, maximum))[0],
402
+ num_lines=1,
403
+ )[0]
404
+ histogram = f"{minimum} {spark} {maximum}"
405
+
406
+ stats.extend(
407
+ [
408
+ " Values:",
409
+ f" histogram: {histogram}",
410
+ f" quartiles: {qs_str} (IQR: {(qs[-1] - qs[0]):.1f})",
411
+ f" std dev: {np.std(stats_vs):.1f}",
412
+ ]
413
+ )
414
+
415
+ lines = [
416
+ f"ADRIO inspection for {self.adrio.class_name}:",
417
+ f" Result shape: {self.shape} {vs.shape}; dtype: {dtname}; size: {vs.size}", # noqa: E501
418
+ *extra_info,
419
+ *stats,
420
+ *[
421
+ f" percent {issue}: {percent:.1%}"
422
+ for issue, percent in self.quantify
423
+ ],
424
+ ]
425
+ return "\n".join(lines)
426
+
427
+
428
+ class ADRIO(SimulationFunction[NDArray[ResultT]], Generic[ResultT, ValueT]):
429
+ """
430
+ ADRIOs (or Abstract Data Resource Interface Objects) are functions which are
431
+ intended to load data from external sources for epymorph simulations. This may be
432
+ from web APIs, local files or databases, or anything imaginable.
433
+
434
+ ADRIO is an abstract base class. It is generic in both the form of the result
435
+ (`ResultT`) and the type of the values in the result (`ValueT`). Both represent
436
+ numpy dtypes.
437
+
438
+ When the ADRIO's result is simple, like a numpy array of 64-bit
439
+ integers, both `ResultT` and `ValueT` will be the same -- `np.int64`. If the result
440
+ is a structured type, however, like with numpy arrays containing date/value tuples,
441
+ `ResultT` will reflect the "outer" structured type and `ValueT` will reflect type
442
+ of the "inner" data values. As a common example, a date/value array with 64-bit
443
+ integer values will have `ResultT` equal to
444
+ `[("date", np.datetime64), ("value", np.int64)]` and `ValueT` equal to `np.int64`.
445
+ (This complexity is necessary to work around weaknesses in Python's type system.)
446
+
447
+ Implementation Notes
448
+ --------------------
449
+ Implement this class by overriding `result_format` to describe the expected results,
450
+ `validate_context` to check the provided context (happens prior to loading data),
451
+ and `inspect` to implement the data loading logic. Do not override `evaluate` unless
452
+ you need to change the base behavior. Override `estimate_data` if it's possible to
453
+ estimate data usage ahead of time.
454
+
455
+ When evaluating an ADRIO, call `evaluate` or `inspect`.
456
+
457
+ See Also
458
+ --------
459
+ You may prefer to extend [epymorph.adrio.adrio.FetchADRIO][], which provides more
460
+ scaffolding for ADRIOs that fetch data from external sources like web APIs.
461
+ """
462
+
463
+ @property
464
+ @abstractmethod
465
+ def result_format(self) -> ResultFormat:
466
+ """Information about the expected format of the ADRIO's resulting data."""
467
+
468
+ @abstractmethod
469
+ def validate_context(self, context: Context) -> None:
470
+ """
471
+ Validate the context before ADRIO evaluation.
472
+
473
+ Parameters
474
+ ----------
475
+ context :
476
+ The context to validate.
477
+
478
+ Raises
479
+ ------
480
+ ADRIOContextError
481
+ If this ADRIO cannot be evaluated in the given context.
482
+ """
483
+
484
+ def validate_result(
485
+ self,
486
+ context: Context,
487
+ result: NDArray[ResultT],
488
+ ) -> None:
489
+ """
490
+ Validate that the result of evaluating the ADRIO adheres to the
491
+ expected result format.
492
+
493
+ Parameters
494
+ ----------
495
+ context :
496
+ The context in which the result has been evaluated.
497
+ result :
498
+ The result produced by the ADRIO.
499
+
500
+ Raises
501
+ ------
502
+ ADRIOProcessingError
503
+ If the result is invalid, indicating the processing logic has a bug.
504
+ """
505
+ adrio_validate_pipe(
506
+ self,
507
+ context,
508
+ result,
509
+ validate_numpy(),
510
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
511
+ validate_dtype(self.result_format.dtype),
512
+ )
513
+
514
+ def evaluate(self) -> NDArray[ResultT]:
515
+ """
516
+ Evaluate the ADRIO in the current context.
517
+
518
+ Returns
519
+ -------
520
+ :
521
+ The result value.
522
+ """
523
+ return self.inspect().result
524
+
525
+ @abstractmethod
526
+ def inspect(self) -> InspectResult[ResultT, ValueT]:
527
+ """
528
+ Produce an inspection of the ADRIO's data for the current context.
529
+
530
+ When implementing an ADRIO, override this method to provide data fetching and
531
+ processing logic. Use self methods and properties to access the simulation
532
+ context or defer processing to another function.
533
+
534
+ NOTE: if you are implementing this method, make sure to call `validate_context`
535
+ first and `_validate_result` last.
536
+
537
+ Returns
538
+ -------
539
+ :
540
+ The data inspection results for the ADRIO's current context.
541
+ """
542
+
543
+ def estimate_data(self) -> DataEstimate:
544
+ """
545
+ Estimate the data usage for this ADRIO in the current context.
546
+
547
+ Returns
548
+ -------
549
+ :
550
+ The estimated data usage for this ADRIO's current context.
551
+ If a reasonable estimate cannot be made, returns `EmptyDataEstimate`.
552
+ """
553
+ return EmptyDataEstimate(self.class_name)
554
+
555
+ @final
556
+ def _report_progress(
557
+ self,
558
+ ratio: float,
559
+ *,
560
+ download: DownloadActivity | None = None,
561
+ ) -> None:
562
+ """
563
+ Emit an intermediate progress event.
564
+
565
+ Parameters
566
+ ----------
567
+ ratio :
568
+ The ratio of how much work the ADRIO has completed in total;
569
+ 0 meaning no progress and 1 meaning it is finished.
570
+ download :
571
+ Describes current network activity. If there is no network activity
572
+ to report or if it cannot be measured, provide `None`.
573
+ """
574
+ _events.on_adrio_progress.publish(
575
+ ADRIOProgress(
576
+ adrio_name=self.class_name,
577
+ attribute=self.name,
578
+ final=False,
579
+ ratio_complete=min(ratio, 1.0),
580
+ download=download,
581
+ duration=None,
582
+ )
583
+ )
584
+
585
+ @final
586
+ def _report_complete(
587
+ self,
588
+ duration: float,
589
+ *,
590
+ download: DownloadActivity | None = None,
591
+ ) -> None:
592
+ """
593
+ Emit a final progress event.
594
+
595
+ Parameters
596
+ ----------
597
+ duration :
598
+ How long, in seconds, did processing take?
599
+ download :
600
+ Describes current network activity. If there is no network activity
601
+ to report or if it cannot be measured, provide `None`.
602
+ """
603
+ _events.on_adrio_progress.publish(
604
+ ADRIOProgress(
605
+ adrio_name=self.class_name,
606
+ attribute=self.name,
607
+ final=True,
608
+ ratio_complete=1.0,
609
+ download=download,
610
+ duration=duration,
611
+ )
612
+ )
613
+
614
+
615
+ @evaluate_param.register
616
+ def _(
617
+ value: ADRIO,
618
+ name: AbsoluteName,
619
+ data: DataResolver,
620
+ scope: GeoScope | None,
621
+ time_frame: TimeFrame | None,
622
+ ipm: BaseCompartmentModel | None,
623
+ rng: np.random.Generator | None,
624
+ ) -> AttributeArray:
625
+ # depth-first evaluation guarantees `data` has our dependencies.
626
+ ctx = Context.of(name, data, scope, time_frame, ipm, rng)
627
+ sim_func = value.with_context_internal(ctx)
628
+ return sim_func.evaluate()
629
+
630
+
631
+ class FetchADRIO(ADRIO[ResultT, ValueT]):
632
+ """
633
+ A specialization of `ADRIO` that adds structure for ADRIOs that load data from
634
+ an external source, such as a web API.
635
+
636
+ Implementation Notes
637
+ --------------------
638
+ `FetchADRIO` provides an implementation of `inspect`, and requires that you
639
+ implement methods `_fetch` and `_process` instead.
640
+ """
641
+
642
+ @abstractmethod
643
+ def _fetch(self, context: Context) -> pd.DataFrame:
644
+ """
645
+ Fetch the source data from the external source (or cache).
646
+
647
+ Parameters
648
+ ----------
649
+ context :
650
+ The evaluation context.
651
+
652
+ Returns
653
+ -------
654
+ :
655
+ A dataframe of the source data, as close to its original form as practical.
656
+ """
657
+
658
+ @abstractmethod
659
+ def _process(
660
+ self, context: Context, data_df: pd.DataFrame
661
+ ) -> PipelineResult[ResultT]:
662
+ """
663
+ Process the source data through a data pipeline.
664
+
665
+ Parameters
666
+ ----------
667
+ context :
668
+ The evaluation context.
669
+ data_df :
670
+ The source data (from `_fetch`).
671
+
672
+ Returns
673
+ -------
674
+ :
675
+ The result of processing the data.
676
+
677
+ See Also
678
+ --------
679
+ [epymorph.adrio.processing.DataPipeline][] which is a toolkit for writing
680
+ standardizing data processing workflows.
681
+ """
682
+
683
+ def inspect(self) -> InspectResult[ResultT, ValueT]:
684
+ """
685
+ Produce an inspection of the ADRIO's data for the current context.
686
+
687
+ Returns
688
+ -------
689
+ :
690
+ The data inspection results for the ADRIO's current context.
691
+ """
692
+ ctx = self.context
693
+ try:
694
+ self.validate_context(ctx)
695
+ except ADRIOError:
696
+ raise
697
+ except MissingContextError as e:
698
+ raise ADRIOContextError(self, ctx, str(e))
699
+ except Exception as e:
700
+ raise ADRIOContextError(self, ctx) from e
701
+
702
+ self._report_progress(0.0)
703
+ start_time = perf_counter()
704
+
705
+ try:
706
+ source_df = self._fetch(ctx)
707
+ except ADRIOCommunicationError as e:
708
+ e2 = e.__cause__
709
+ if isinstance(e2, HTTPError) and e2.code == 414:
710
+ err = (
711
+ "the attempted request URI was too long to send. "
712
+ "The root cause for this can vary, but it usually suggests "
713
+ "your query involves too many locations."
714
+ )
715
+ raise ADRIOCommunicationError(e.adrio, e.context, err) from e2
716
+ else:
717
+ raise e
718
+ except ADRIOError:
719
+ raise
720
+ except MissingContextError as e:
721
+ raise ADRIOContextError(self, ctx, str(e))
722
+ except Exception as e:
723
+ raise ADRIOProcessingError(self, ctx) from e
724
+
725
+ try:
726
+ proc_res = self._process(ctx, source_df)
727
+ result_np = proc_res.value_as_masked
728
+ self.validate_result(ctx, result_np)
729
+ except ADRIOError:
730
+ raise
731
+ except MissingContextError as e:
732
+ raise ADRIOContextError(self, ctx, str(e))
733
+ except Exception as e:
734
+ raise ADRIOProcessingError(self, ctx) from e
735
+
736
+ finish_time = perf_counter()
737
+ self._report_complete(finish_time - start_time)
738
+
739
+ return InspectResult[ResultT, ValueT](
740
+ self,
741
+ source_df,
742
+ result_np,
743
+ self.result_format.dtype.type,
744
+ self.result_format.shape,
745
+ proc_res.issues,
746
+ )
747
+
748
+
749
+ def adrio_validate_pipe(
750
+ adrio: ADRIO,
751
+ context: Context,
752
+ result: NDArray[ResultT],
753
+ *validators: Validator,
754
+ ) -> None:
755
+ """
756
+ Apply a sequence of validator function to the result of an ADRIO,
757
+ using that ADRIO's context and raising an appropriate error if the
758
+ result is invalid.
759
+
760
+ Parameters
761
+ ----------
762
+ adrio :
763
+ The ADRIO instance.
764
+ context :
765
+ The current simulation context.
766
+ result :
767
+ The ADRIO result array.
768
+ *validators :
769
+ The sequence of validation checks to apply.
770
+
771
+ Raises
772
+ ------
773
+ ADRIOProcessingError
774
+ If the result is invalid.
775
+ """
776
+ v = validate_pipe(*validators)(result)
777
+ if isinstance(v, Invalid):
778
+ raise ADRIOProcessingError(adrio, context, v.error)
779
+
780
+
781
+ def validate_time_frame(
782
+ adrio: ADRIO,
783
+ context: Context,
784
+ time_range: DateRange,
785
+ ) -> None:
786
+ """
787
+ Validate that the context time frame is within the specified `DateRange`.
788
+
789
+ Parameters
790
+ ----------
791
+ adrio :
792
+ The ADRIO instance doing the validation.
793
+ context :
794
+ The evaluation context.
795
+ time_range :
796
+ The valid range of dates.
797
+
798
+ Raises
799
+ ------
800
+ ADRIOContextError
801
+ If the context time frame is not valid.
802
+ """
803
+ start = time_range.start_date
804
+ end = time_range.end_date
805
+ tf = context.time_frame
806
+ if tf.start_date < start or tf.end_date > end:
807
+ err = f"This ADRIO is only valid for time frames between {start} and {end}."
808
+ raise ADRIOContextError(adrio, context, err)
809
+ if time_range.overlap(tf) is None:
810
+ err = "The supplied time frame does not include any available dates."
811
+ raise ADRIOContextError(adrio, context, err)
812
+
813
+
814
+ ##################
815
+ # UTILITY ADRIOS #
816
+ ##################
817
+
818
+
819
+ class NodeID(ADRIO[np.str_, np.str_]):
820
+ """An ADRIO that provides the node IDs as they exist in the geo scope."""
821
+
822
+ @property
823
+ @override
824
+ def result_format(self) -> ResultFormat:
825
+ return ResultFormat(shape=Shapes.N, dtype=np.str_)
826
+
827
+ @override
828
+ def validate_context(self, context: Context) -> None:
829
+ try:
830
+ context.scope # scope is required
831
+ except MissingContextError as e:
832
+ raise ADRIOContextError(self, self.context, str(e))
833
+
834
+ @override
835
+ def inspect(self) -> InspectResult[np.str_, np.str_]:
836
+ try:
837
+ self.validate_context(self.context)
838
+ except MissingContextError as e:
839
+ raise ADRIOContextError(self, self.context, str(e))
840
+ result = self.scope.node_ids
841
+ self.validate_result(self.context, result)
842
+ return InspectResult(
843
+ adrio=self,
844
+ source=None,
845
+ result=result,
846
+ shape=self.result_format.shape,
847
+ dtype=self.result_format.dtype.type,
848
+ issues={},
849
+ )
850
+
851
+
852
+ class Scale(ADRIO[np.float64, np.float64]):
853
+ """
854
+ Scales the result of another ADRIO by multiplying values by the given factor.
855
+
856
+ Parameters
857
+ ----------
858
+ parent :
859
+ The ADRIO whose results will be scaled.
860
+ factor :
861
+ The factor to multiply all resulting ADRIO values by.
862
+ """
863
+
864
+ _parent: ADRIO[np.float64, np.float64]
865
+ """The ADRIO whose results will be scaled."""
866
+ _factor: float
867
+ """The factor to multiply all resulting ADRIO values by."""
868
+
869
+ def __init__(self, parent: ADRIO[np.float64, np.float64], factor: float):
870
+ self._parent = parent
871
+ self._factor = factor
872
+
873
+ @property
874
+ @override
875
+ def result_format(self) -> ResultFormat:
876
+ return ResultFormat(shape=self._parent.result_format.shape, dtype=np.float64)
877
+
878
+ @override
879
+ def validate_context(self, context: Context) -> None:
880
+ # if parent scope is valid, we're good
881
+ self._parent.validate_context(context)
882
+
883
+ @override
884
+ def inspect(self) -> InspectResult[np.float64, np.float64]:
885
+ try:
886
+ self.validate_context(self.context)
887
+ except MissingContextError as e:
888
+ raise ADRIOContextError(self, self.context, str(e))
889
+ defer_result = self.defer_context(self._parent).inspect()
890
+ result = defer_result.result.astype(np.float64) * self._factor
891
+ self.validate_result(self.context, result)
892
+ return InspectResult(
893
+ adrio=self,
894
+ source=defer_result.result,
895
+ result=result,
896
+ shape=defer_result.shape,
897
+ dtype=np.float64,
898
+ issues=defer_result.issues,
899
+ )
900
+
901
+
902
+ class PopulationPerKM2(ADRIO[np.float64, np.float64]):
903
+ """
904
+ Calculates population density by combining the values from data attributes
905
+ for population and land area.
906
+
907
+ This ADRIO requires two data attributes:
908
+
909
+ - "population": the population of the node
910
+ - "land_area_km2": the land area of the node in square kilometers
911
+ """
912
+
913
+ POPULATION = AttributeDef("population", int, Shapes.N)
914
+ LAND_AREA_KM2 = AttributeDef("land_area_km2", float, Shapes.N)
915
+
916
+ requirements = (POPULATION, LAND_AREA_KM2)
917
+
918
+ @property
919
+ @override
920
+ def result_format(self) -> ResultFormat:
921
+ return ResultFormat(shape=Shapes.N, dtype=np.float64)
922
+
923
+ @override
924
+ def validate_context(self, context: Context) -> None:
925
+ try:
926
+ context.scope # scope is required
927
+ except MissingContextError as e:
928
+ raise ADRIOContextError(self, self.context, str(e))
929
+
930
+ @override
931
+ def inspect(self) -> InspectResult[np.float64, np.float64]:
932
+ self.validate_context(self.context)
933
+ pop = self.data(self.POPULATION)
934
+ area = self.data(self.LAND_AREA_KM2)
935
+ issues = {}
936
+ if np.any(pop_mask := np.ma.getmaskarray(pop)):
937
+ issues["population_masked", pop_mask]
938
+ if np.any(area_mask := np.ma.getmaskarray(area)):
939
+ issues["land_area_km2_masked", area_mask]
940
+
941
+ result = (pop / area).astype(dtype=np.float64)
942
+ self.validate_result(self.context, result)
943
+ return InspectResult(
944
+ adrio=self,
945
+ source=fromarrays(
946
+ [pop, area],
947
+ names=["population", "land_area_km2"], # type: ignore
948
+ ),
949
+ result=result,
950
+ dtype=self.result_format.dtype.type,
951
+ shape=self.result_format.shape,
952
+ issues=issues,
953
+ )