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,1221 @@
1
+ """Data processing utilities for ADRIOs."""
2
+
3
+ import dataclasses
4
+ from abc import ABC, abstractmethod
5
+ from dataclasses import dataclass, field
6
+ from functools import partial, reduce
7
+ from typing import (
8
+ Any,
9
+ Callable,
10
+ Generic,
11
+ Literal,
12
+ Mapping,
13
+ NamedTuple,
14
+ Protocol,
15
+ Self,
16
+ Sequence,
17
+ TypeVar,
18
+ cast,
19
+ )
20
+
21
+ import numpy as np
22
+ import pandas as pd
23
+ from numpy.typing import NDArray
24
+ from typing_extensions import override
25
+
26
+ from epymorph.util import DateValueType, to_date_value_array
27
+
28
+ DataT = TypeVar("DataT", bound=np.generic)
29
+ """A numpy array dtype."""
30
+
31
+
32
+ class HasRandomness(Protocol):
33
+ """Protocol for an object containing a numpy random number generator."""
34
+
35
+ @property
36
+ @abstractmethod
37
+ def rng(self) -> np.random.Generator:
38
+ """The random number generator instance."""
39
+
40
+
41
+ #######
42
+ # Fix #
43
+ #######
44
+
45
+
46
+ class Fix(ABC, Generic[DataT]):
47
+ """
48
+ A method for fixing data issues as part of a `DataPipeline`. `Fix` instances act as
49
+ functions (they have call semantics).
50
+
51
+ `Fix` is generic in the dtype of the data it fixes (`DataT`).
52
+ """
53
+
54
+ @abstractmethod
55
+ def __call__(
56
+ self,
57
+ rng: HasRandomness,
58
+ replace: DataT,
59
+ columns: tuple[str, ...],
60
+ data_df: pd.DataFrame,
61
+ ) -> pd.DataFrame:
62
+ """
63
+ Apply this fix to some data.
64
+
65
+ Parameters
66
+ ----------
67
+ rng : HasRandomness
68
+ A source of randomness.
69
+ replace : DataT
70
+ The value to replace.
71
+ columns : tuple[str, ...]
72
+ The names of the columns to fix.
73
+ data_df : DataFrame
74
+ The data to fix.
75
+
76
+ Returns
77
+ -------
78
+ DataFrame
79
+ The data with the fix applied (a copy if modified).
80
+ """
81
+
82
+ @staticmethod
83
+ def of_int64(fix: "FixLikeInt") -> "Fix[np.int64]":
84
+ """
85
+ Construct for a `Fix` for `int64` data. The type of `Fix`
86
+ returned depends on the type of argument provided.
87
+
88
+ Parameters
89
+ ----------
90
+ fix :
91
+ A value which implies the type of fix to apply:
92
+
93
+ - `Fix[np.int64]`: is returned unchanged (no-op)
94
+ - `int`: returns a `ConstantFix`, to replace bad values with a constant
95
+ - `Callable[[], int]`: return a `FunctionFix`, to replace bad values
96
+ with values obtained from the given callable
97
+ - `False`: return a `DontFix`, indicating not to replace bad values
98
+
99
+ Returns
100
+ -------
101
+ :
102
+ A Fix instance as determined by the type of the argument.
103
+ """
104
+ if fix is False:
105
+ return DontFix()
106
+ elif isinstance(fix, Fix):
107
+ return fix # for convenience, no-op if arg is a Fix
108
+ elif isinstance(fix, int):
109
+ return ConstantFix[np.int64](fix) # type: ignore
110
+ elif callable(fix):
111
+ return FunctionFix[np.int64](fix) # type: ignore
112
+ raise ValueError("Not a valid fix.")
113
+
114
+ @staticmethod
115
+ def of_float64(fix: "FixLikeFloat") -> "Fix[np.float64]":
116
+ """
117
+ Construct for a `Fix` for `float64` data. The type of `Fix`
118
+ returned depends on the type of argument provided.
119
+
120
+ Parameters
121
+ ----------
122
+ fix :
123
+ A value which implies the type of fix to apply.
124
+
125
+ - `Fix[np.float64]`: is returned unchanged (no-op)
126
+ - `float`: returns a `ConstantFix`, to replace bad values with a constant
127
+ - `Callable[[], float]`: return a `FunctionFix`, to replace bad values
128
+ with values obtained from the given callable
129
+ - `False`: return a `DontFix`, indicating not to replace bad values
130
+
131
+ Returns
132
+ -------
133
+ :
134
+ A `Fix` instance as determined by the type of the argument.
135
+ """
136
+ if fix is False:
137
+ return DontFix()
138
+ elif isinstance(fix, Fix):
139
+ return fix # for convenience, no-op if arg is a Fix
140
+ elif isinstance(fix, float):
141
+ return ConstantFix[np.float64](fix) # type: ignore
142
+ elif callable(fix):
143
+ return FunctionFix[np.float64](fix) # type: ignore
144
+ raise ValueError("Not a valid fix.")
145
+
146
+
147
+ @dataclass(frozen=True)
148
+ class ConstantFix(Fix[DataT]):
149
+ """
150
+ A `Fix` which replaces values with a constant value.
151
+
152
+ `ConstantFix` is generic in the dtype of the data it fixes (`DataT`).
153
+
154
+ Parameters
155
+ ----------
156
+ with_value :
157
+ The value to use to replace bad values.
158
+ """
159
+
160
+ with_value: DataT
161
+ """The value to use to replace bad values."""
162
+
163
+ @override
164
+ def __call__(self, rng, replace, columns, data_df):
165
+ return data_df.assign(
166
+ **{
167
+ col: data_df[col].replace(replace, self.with_value) # type: ignore
168
+ for col in columns
169
+ }
170
+ )
171
+
172
+
173
+ @dataclass(frozen=True)
174
+ class FunctionFix(Fix[DataT]):
175
+ """
176
+ A `Fix` which replaces values with values generated by the given function.
177
+
178
+ `FunctionFix` is generic in the dtype of the data it fixes (`DataT`).
179
+
180
+ Parameters
181
+ ----------
182
+ with_function :
183
+ The function that generates replacement values.
184
+ """
185
+
186
+ with_function: Callable[[], DataT]
187
+ """The function that generates replacement values."""
188
+
189
+ @override
190
+ def __call__(self, rng, replace, columns, data_df):
191
+ return FunctionFix.apply(data_df, replace, columns, self.with_function)
192
+
193
+ @staticmethod
194
+ def apply(
195
+ data_df: pd.DataFrame,
196
+ replace: DataT,
197
+ columns: tuple[str, ...],
198
+ with_function: Callable[[], DataT],
199
+ ) -> pd.DataFrame:
200
+ """
201
+ Apply a `FunctionFix` to a data frame.
202
+
203
+ This method can be useful in creating other `Fix` instances, when their
204
+ replacement value logic can be expressed as a no-parameter function.
205
+
206
+ Parameters
207
+ ----------
208
+ data_df :
209
+ The data to fix.
210
+ replace :
211
+ The value to replace.
212
+ columns :
213
+ The data columns to fix.
214
+ with_function :
215
+ The function used to generate replacement values.
216
+
217
+ Returns
218
+ -------
219
+ :
220
+ A copy of the data with bad values fixed.
221
+ """
222
+
223
+ def replace_col(col: str) -> pd.Series:
224
+ is_replace = data_df[col] == replace
225
+ num_replace = is_replace.sum()
226
+ replacements = np.array([with_function() for _ in range(num_replace)])
227
+ updated = data_df[col].copy()
228
+ updated[is_replace] = replacements
229
+ return updated
230
+
231
+ return data_df.assign(**{col: replace_col(col) for col in columns})
232
+
233
+
234
+ @dataclass(frozen=True)
235
+ class RandomFix(Fix[DataT]):
236
+ """
237
+ A `Fix` which replaces values with randomly-generated values.
238
+
239
+ `RandomFix` is generic in the dtype of the data it fixes (`DataT`).
240
+
241
+ Parameters
242
+ ----------
243
+ with_random :
244
+ A function for generating replacement values using the given numpy random number
245
+ generator.
246
+ """
247
+
248
+ with_random: Callable[[np.random.Generator], DataT]
249
+ """
250
+ A function for generating replacement values using the given numpy random number
251
+ generator.
252
+ """
253
+
254
+ @override
255
+ def __call__(self, rng, replace, columns, data_df):
256
+ random_fn = partial(self.with_random, rng.rng)
257
+ return FunctionFix.apply(data_df, replace, columns, random_fn)
258
+
259
+ @staticmethod
260
+ def from_range(low: int, high: int) -> "RandomFix[np.int64]":
261
+ """
262
+ Construct for a `RandomFix` which replaces values
263
+ with values sampled uniformly from a discrete range of integers.
264
+
265
+ Parameters
266
+ ----------
267
+ low :
268
+ The lowest replacement value.
269
+ high :
270
+ The highest replacement value.
271
+
272
+ Returns
273
+ -------
274
+ :
275
+ The fix instance.
276
+ """
277
+ return RandomFix(
278
+ lambda rng: rng.integers(low, high, endpoint=True), # type: ignore
279
+ )
280
+
281
+ @staticmethod
282
+ def from_range_float(low: float, high: float) -> "RandomFix[np.float64]":
283
+ """
284
+ Construct for a `RandomFix` which replaces values
285
+ with values sampled uniformly from a continuous range.
286
+
287
+ Parameters
288
+ ----------
289
+ low :
290
+ The low end of the range of replacement values.
291
+ high :
292
+ The high end of the range of replacement values.
293
+ (Not included in the possible values.)
294
+
295
+ Returns
296
+ -------
297
+ :
298
+ The fix instance.
299
+ """
300
+ return RandomFix(
301
+ lambda rng: rng.uniform(low, high), # type: ignore
302
+ )
303
+
304
+
305
+ @dataclass(frozen=True)
306
+ class DontFix(Fix[Any]):
307
+ """A special `Fix` which simply returns the data as-is (no-op)."""
308
+
309
+ @override
310
+ def __call__(self, rng, replace, columns, data_df):
311
+ return data_df
312
+
313
+
314
+ FixLikeInt = Fix[np.int64] | int | Callable[[], int] | Literal[False]
315
+ """A value which can be coerced into a `Fix` for integers."""
316
+
317
+ FixLikeFloat = Fix[np.float64] | float | Callable[[], float] | Literal[False]
318
+ """A value which can be coerced into a `Fix` for floats."""
319
+
320
+
321
+ ########
322
+ # Fill #
323
+ ########
324
+
325
+
326
+ class Fill(ABC, Generic[DataT]):
327
+ """
328
+ A method for filling-in missing data as part of a `DataPipeline`. `Fill` instances
329
+ act as functions (they have call semantics).
330
+
331
+ `Fill` is generic in the dtype of the data it fixes (`DataT`).
332
+ """
333
+
334
+ @abstractmethod
335
+ def __call__(
336
+ self,
337
+ rng: HasRandomness,
338
+ data_np: NDArray[DataT],
339
+ missing_mask: NDArray[np.bool_],
340
+ ) -> tuple[NDArray[DataT], NDArray[np.bool_] | None]:
341
+ """
342
+ Apply this fix to some data.
343
+
344
+ Parameters
345
+ ----------
346
+ rng :
347
+ A source of randomness.
348
+ data_np :
349
+ The data to fix.
350
+ missing_mask :
351
+ A mask indicating values which should be considered missing.
352
+
353
+ Returns
354
+ -------
355
+ :
356
+ A tuple containing two values:
357
+
358
+ - a copy of the data with the fill applied (a copy if modified),
359
+ - an updated missing values mask. `Fill` methods may or may not
360
+ replace all missing values; if all missing values have been filled,
361
+ this will be `None`.
362
+ """
363
+
364
+ @staticmethod
365
+ def of_int64(fill: "FillLikeInt") -> "Fill[np.int64]":
366
+ """
367
+ Construct for a `Fill` for `int64` data. The type of `Fill`
368
+ returned depends on the type of argument provided.
369
+
370
+ Parameters
371
+ ----------
372
+ fill :
373
+ A value which implies the type of fix to apply.
374
+
375
+ - `Fill[np.int64]`: is returned unchanged (no-op)
376
+ - `int`: returns a `ConstantFill`, to replace missing values with a constant
377
+ - `Callable[[], int]`: return a `FunctionFill`, to replace missing values
378
+ with values obtained from the given callable
379
+ - `False`: return a `DontFill`, indicating not to replace missing values
380
+
381
+ Returns
382
+ -------
383
+ :
384
+ A `Fill` instance as determined by the type of the argument.
385
+ """
386
+ if fill is False:
387
+ return DontFill()
388
+ elif isinstance(fill, Fill):
389
+ return fill # for convenience, no-op if arg is a Fill
390
+ elif isinstance(fill, int):
391
+ return ConstantFill[np.int64](fill) # type: ignore
392
+ elif callable(fill):
393
+ return FunctionFill[np.int64](fill) # type: ignore
394
+ raise ValueError("Not a valid fill.")
395
+
396
+ @staticmethod
397
+ def of_float64(fill: "FillLikeFloat") -> "Fill[np.float64]":
398
+ """
399
+ Construct for a `Fill` for `float64` data. The type of `Fill`
400
+ returned depends on the type of argument provided.
401
+
402
+ Parameters
403
+ ----------
404
+ fill :
405
+ A value which implies the type of fix to apply.
406
+
407
+ - `Fill[np.float64]`: is returned unchanged (no-op)
408
+ - `float` or `int`: returns a `ConstantFill`, to replace missing values
409
+ with a constant
410
+ - `Callable[[], float]`: return a `FunctionFill`, to replace missing values
411
+ with values obtained from the given callable
412
+ - `False`: return a `DontFill`, indicating not to replace missing values
413
+
414
+ Returns
415
+ -------
416
+ :
417
+ A `Fill` instance as determined by the type of the argument.
418
+ """
419
+ if fill is False:
420
+ return DontFill()
421
+ elif isinstance(fill, Fill):
422
+ return fill # for convenience, no-op if arg is a Fill
423
+ elif isinstance(fill, float | int):
424
+ return ConstantFill[np.float64](float(fill)) # type: ignore
425
+ elif callable(fill):
426
+ return FunctionFill[np.float64](fill) # type: ignore
427
+ raise ValueError("Not a valid fill.")
428
+
429
+
430
+ @dataclass(frozen=True)
431
+ class ConstantFill(Fill[DataT]):
432
+ """
433
+ A `Fill` which replaces missing values with a constant value.
434
+
435
+ `ConstantFill` is generic in the dtype of the data it fixes (`DataT`).
436
+
437
+ Parameters
438
+ ----------
439
+ with_value :
440
+ The value to use to replace missing values.
441
+ """
442
+
443
+ with_value: DataT
444
+ """The value to use to replace missing values."""
445
+
446
+ @override
447
+ def __call__(
448
+ self, rng, data_np, missing_mask
449
+ ) -> tuple[NDArray[DataT], NDArray[np.bool_] | None]:
450
+ if missing_mask.any():
451
+ result_np = data_np.copy()
452
+ result_np[missing_mask] = self.with_value
453
+ else:
454
+ result_np = data_np
455
+ return result_np, None
456
+
457
+
458
+ @dataclass(frozen=True)
459
+ class FunctionFill(Fill[DataT]):
460
+ """
461
+ A `Fill` which replaces missing values with values generated by the given function.
462
+
463
+ `FunctionFill` is generic in the dtype of the data it fixes (`DataT`).
464
+
465
+ Parameters
466
+ ----------
467
+ with_function :
468
+ The function that generates replacement values.
469
+ """
470
+
471
+ with_function: Callable[[], DataT]
472
+ """The function that generates replacement values."""
473
+
474
+ @override
475
+ def __call__(
476
+ self, rng, data_np, missing_mask
477
+ ) -> tuple[NDArray[DataT], NDArray[np.bool_] | None]:
478
+ return FunctionFill.apply(data_np, missing_mask, self.with_function)
479
+
480
+ @staticmethod
481
+ def apply(
482
+ data_np: NDArray[DataT],
483
+ missing_mask: NDArray[np.bool_],
484
+ with_function: Callable[[], DataT],
485
+ ) -> tuple[NDArray[DataT], NDArray[np.bool_] | None]:
486
+ """
487
+ Apply a `FunctionFill` to numpy data.
488
+
489
+ This method can be useful in creating other `Fill` instances, when their
490
+ replacement value logic can be expressed as a no-parameter function.
491
+
492
+ Parameters
493
+ ----------
494
+ data_np :
495
+ The data to fix.
496
+ missing_mask :
497
+ A mask indicating values which should be considered missing.
498
+ with_function :
499
+ The function used to generate replacement values.
500
+
501
+ Returns
502
+ -------
503
+ :
504
+ The fill apply result (updated data and missing mask).
505
+ """
506
+ num_replace = missing_mask.sum()
507
+ replacements = np.array([with_function() for _ in range(num_replace)])
508
+ result_np = data_np.copy()
509
+ result_np[missing_mask] = replacements
510
+ return result_np, None
511
+
512
+
513
+ @dataclass(frozen=True)
514
+ class RandomFill(Fill[DataT]):
515
+ """
516
+ A `Fill` which replaces missing values with randomly-generated values.
517
+
518
+ `RandomFill` is generic in the dtype of the data it fixes (`DataT`).
519
+
520
+ Parameters
521
+ ----------
522
+ with_random :
523
+ A function for generating replacement values using the given numpy random number
524
+ generator.
525
+ """
526
+
527
+ with_random: Callable[[np.random.Generator], DataT]
528
+ """
529
+ A function for generating replacement values using the given numpy random number
530
+ generator.
531
+ """
532
+
533
+ @override
534
+ def __call__(self, rng, data_np, missing_mask):
535
+ random_fn = partial(self.with_random, rng.rng)
536
+ return FunctionFill.apply(data_np, missing_mask, random_fn)
537
+
538
+ @staticmethod
539
+ def from_range(low: int, high: int) -> "RandomFill[np.int64]":
540
+ """
541
+ Construct for a `RandomFill` which replaces values
542
+ with values sampled uniformly from a discrete range of integers.
543
+
544
+ Parameters
545
+ ----------
546
+ low :
547
+ The lowest replacement value.
548
+ high :
549
+ The highest replacement value.
550
+
551
+ Returns
552
+ -------
553
+ :
554
+ The fill instance.
555
+ """
556
+ return RandomFill(
557
+ lambda rng: rng.integers(low, high, endpoint=True), # type: ignore
558
+ )
559
+
560
+ @staticmethod
561
+ def from_range_float(low: float, high: float) -> "RandomFill[np.float64]":
562
+ """
563
+ Construct for a `RandomFill` which replaces values
564
+ with values sampled uniformly from a continuous range.
565
+
566
+ Parameters
567
+ ----------
568
+ low :
569
+ The low end of the range of replacement values.
570
+ high :
571
+ The high end of the range of replacement values.
572
+ (Not included in the possible values.)
573
+
574
+ Returns
575
+ -------
576
+ :
577
+ The fill instance.
578
+ """
579
+ return RandomFill(
580
+ lambda rng: rng.uniform(low, high), # type: ignore
581
+ )
582
+
583
+
584
+ @dataclass(frozen=True)
585
+ class DontFill(Fill[DataT]):
586
+ """
587
+ A special `Fill` which does not replace missing values and simply returns the data
588
+ as-is (no-op).
589
+
590
+ `DontFill` is generic in the dtype of the data it fixes (`DataT`).
591
+ """
592
+
593
+ @override
594
+ def __call__(
595
+ self, rng, data_np, missing_mask
596
+ ) -> tuple[NDArray[DataT], NDArray[np.bool_] | None]:
597
+ return data_np, missing_mask
598
+
599
+
600
+ FillLikeInt = Fill[np.int64] | int | Callable[[], int] | Literal[False]
601
+ """A value which can be coerced into a `Fill` for integers."""
602
+
603
+ FillLikeFloat = Fill[np.float64] | float | Callable[[], float] | Literal[False]
604
+ """A value which can be coerced into a `Fill` for floats."""
605
+
606
+
607
+ #################
608
+ # DataPipelines #
609
+ #################
610
+
611
+
612
+ def _add_issue(
613
+ issues: Mapping[str, NDArray[np.bool_]],
614
+ issue_name: str,
615
+ issue_mask: NDArray[np.bool_] | None,
616
+ ) -> Mapping[str, NDArray[np.bool_]]:
617
+ """
618
+ Add an issue to a list of issues.
619
+
620
+ But only if the mask is not `None` and not "no mask" or all-`False`.
621
+ """
622
+ if issue_mask is not None and issue_mask.any():
623
+ return {**issues, issue_name: issue_mask}
624
+ return issues
625
+
626
+
627
+ def _all_issues_mask(issues: Mapping[str, NDArray[np.bool_]]):
628
+ """Compute the logical union of the masks of a set of issues."""
629
+ return reduce(
630
+ np.logical_or,
631
+ [m for _, m in issues.items()],
632
+ np.ma.nomask,
633
+ )
634
+
635
+
636
+ @dataclass(frozen=True)
637
+ class PipelineResult(Generic[DataT]):
638
+ """
639
+ An object containing the result of processing data through a `DataPipeline`.
640
+
641
+ `PipelineResult` is generic in the dtype of the resulting numpy array (`DataT`).
642
+
643
+ Parameters
644
+ ----------
645
+ value :
646
+ The resulting numpy array. In this form, the array will never masked, even if
647
+ there are issues. If you want a masked array, see the `value_as_masked`
648
+ property.
649
+ issues :
650
+ The set of outstanding issues in the underlying data, with issue-specific masks.
651
+ """
652
+
653
+ value: NDArray[DataT]
654
+ """
655
+ The resulting numpy array. In this form, the array will never masked, even if
656
+ there are issues. If you want a masked array, see the `value_as_masked`
657
+ property.
658
+ """
659
+ issues: Mapping[str, NDArray[np.bool_]]
660
+ """
661
+ The set of outstanding issues in the underlying data, with issue-specific masks.
662
+ """
663
+
664
+ def __post_init__(self):
665
+ if np.ma.is_masked(self.value):
666
+ err = "PipelineResult `value` should not be masked directly."
667
+ raise ValueError(err)
668
+
669
+ @property
670
+ def value_as_masked(self) -> NDArray[DataT]:
671
+ """
672
+ The resulting numpy array which will be masked if-and-only-if there are issues.
673
+ The mask is computed as the logical union of the individual issue masks.
674
+ """
675
+ if len(self.issues) == 0:
676
+ return self.value
677
+ mask = _all_issues_mask(self.issues)
678
+ if not np.any(mask):
679
+ return self.value
680
+ return np.ma.masked_array(data=self.value, mask=mask)
681
+
682
+ def with_issue(
683
+ self,
684
+ issue_name: str,
685
+ issue_mask: NDArray[np.bool_] | None,
686
+ ) -> Self:
687
+ """
688
+ Update the result by adding a data issue.
689
+
690
+ Parameters
691
+ ----------
692
+ issue_name :
693
+ The name of the issue.
694
+ issue_mask :
695
+ The mask indicating which values are affected by the issue. For convenience,
696
+ the mask may be None or "no mask" to indicate the data does not have the
697
+ named issue in fact, in which case the issue will not be added.
698
+
699
+ Returns
700
+ -------
701
+ :
702
+ The updated copy of the result.
703
+ """
704
+ return dataclasses.replace(
705
+ self,
706
+ issues=_add_issue(self.issues, issue_name, issue_mask),
707
+ )
708
+
709
+ def to_date_value(
710
+ self,
711
+ dates: NDArray[np.datetime64],
712
+ ) -> "PipelineResult[DateValueType]":
713
+ """
714
+ Convert the result to a date-value-tuple array.
715
+
716
+ Parameters
717
+ ----------
718
+ dates :
719
+ The one-dimensional array of dates.
720
+
721
+ Returns
722
+ -------
723
+ :
724
+ The updated copy of the result.
725
+
726
+ See Also
727
+ --------
728
+ [epymorph.util.to_date_value_array][] for more detail
729
+ on how dates and values are combined,
730
+ and [epymorph.util.extract_date_value][] for a convenient
731
+ way to separate the dates and values when needed.
732
+ """
733
+ value = to_date_value_array(dates, self.value)
734
+ return PipelineResult(value, self.issues)
735
+
736
+ @staticmethod
737
+ def sum(
738
+ left: "PipelineResult[DataT]",
739
+ right: "PipelineResult[DataT]",
740
+ *,
741
+ left_prefix: str,
742
+ right_prefix: str,
743
+ ) -> "PipelineResult[DataT]":
744
+ """
745
+ Combine two `PipelineResults` by summing unmasked data values.
746
+ The result will include both lists of data issues by prefixing the issue names.
747
+
748
+ Parameters
749
+ ----------
750
+ left :
751
+ The first addend.
752
+ right :
753
+ The second addend.
754
+ left_prefix :
755
+ A prefix to assign to any left-side issues.
756
+ right_prefix :
757
+ A prefix to assign to any right-side issues.
758
+
759
+ Returns
760
+ -------
761
+ :
762
+ The combined result as a new instance.
763
+ """
764
+ if left.value.shape != right.value.shape:
765
+ err = "When summing PipelineResults, their data shapes must be the same."
766
+ raise ValueError(err)
767
+ if np.dtype(left.value.dtype) != np.dtype(right.value.dtype):
768
+ err = "When summing PipelineResults, their dtypes must be the same."
769
+ raise ValueError(err)
770
+ if not (
771
+ np.issubdtype(left.value.dtype, np.integer)
772
+ or np.issubdtype(left.value.dtype, np.floating)
773
+ ):
774
+ err = (
775
+ "When summing PipelineResults, their dtypes must be integer or "
776
+ "floating point numbers."
777
+ )
778
+ raise ValueError(err)
779
+
780
+ new_issues = {
781
+ **{f"{left_prefix}{iss}": m for iss, m in left.issues.items()},
782
+ **{f"{right_prefix}{iss}": m for iss, m in right.issues.items()},
783
+ }
784
+ unmasked = ~_all_issues_mask(new_issues)
785
+ new_value = np.zeros_like(left.value, dtype=left.value.dtype)
786
+ new_value[unmasked] = left.value[unmasked] + right.value[unmasked]
787
+ return PipelineResult(value=new_value, issues=new_issues)
788
+
789
+
790
+ class PivotAxis(NamedTuple):
791
+ """Describes an axis on which to pivot a `DataFrame` to become a numpy array."""
792
+
793
+ column: str
794
+ """The name of the column in a `DataFrame`."""
795
+ values: list | NDArray
796
+ """
797
+ The set of values we expect to find in the column. This will be used to expand and
798
+ reorder the resulting pivot table. If values are in this set and not in the data,
799
+ the table will contain missing values -- which is better than not knowing which
800
+ values are missing!
801
+ """
802
+
803
+
804
+ class _PipelineState(NamedTuple):
805
+ """The state of a data pipeline."""
806
+
807
+ data_df: pd.DataFrame
808
+ """The data being worked on."""
809
+ issues: Mapping[str, NDArray[np.bool_]] = {}
810
+ """A map of outstanding issues that have been discovered in the data."""
811
+
812
+ def next(self, updated_df: pd.DataFrame) -> "_PipelineState":
813
+ """
814
+ Advances the state by updating the working data. Pipeline steps should avoid
815
+ mutating the previous state's data and instead work on a new copy.
816
+
817
+ Parameters
818
+ ----------
819
+ updated_df :
820
+ The updated working data.
821
+
822
+ Returns
823
+ -------
824
+ :
825
+ The updated copy of the state.
826
+ """
827
+ return _PipelineState(updated_df, self.issues)
828
+
829
+ def next_with_issue(
830
+ self,
831
+ updated_df: pd.DataFrame,
832
+ issue_name: str,
833
+ issue_mask: NDArray[np.bool_] | None,
834
+ ) -> "_PipelineState":
835
+ """
836
+ Advances the state by updating the working data and adding a data issue.
837
+ Pipeline steps should avoid mutating the previous state's data and instead
838
+ work on a new copy.
839
+
840
+ Parameters
841
+ ----------
842
+ updated_df :
843
+ The updated working data.
844
+ issue_name :
845
+ The name of the issue.
846
+ issue_mask :
847
+ The mask indicating which values are affected by the issue. For convenience,
848
+ the mask may be None or "no mask" to indicate the data does not have the
849
+ named issue in fact, in which case the issue will not be added.
850
+
851
+ Returns
852
+ -------
853
+ :
854
+ The updated copy of the state.
855
+ """
856
+ return _PipelineState(
857
+ data_df=updated_df,
858
+ issues=_add_issue(self.issues, issue_name, issue_mask),
859
+ )
860
+
861
+
862
+ _PipelineStep = Callable[[_PipelineState], _PipelineState]
863
+ """A step in a data pipeline is just a function from one state to another."""
864
+
865
+
866
+ @dataclass(frozen=True)
867
+ class DataPipeline(Generic[DataT]):
868
+ """
869
+ `DataPipeline` is a factory class for assembling data processing pipelines.
870
+
871
+ Using builder-style syntax you define the processing steps that the data should
872
+ flow through. Finalizing the pipeline yields a function that takes a `DataFrame`,
873
+ executes the pipeline steps in sequence, and returns a `PipelineResult` containing
874
+ the processed data and any unresolved data issues discovered along the way.
875
+ The `DataPipeline` instance itself can be discarded after the processing function
876
+ is finalized.
877
+
878
+ `DataPipeline` was designed to produce arrays with one or two dimensions. When
879
+ there is more than one value in the "columns" dimension, it's obvious we should
880
+ have a 2D array. But when there's only one column, a 1D or 2D array layout are
881
+ both valid. Because of this ambiguity, it's up to you to provide the number
882
+ of dimensions you expect. If you specify `ndims` as 1 and the data has more than
883
+ one column, this will result in an error.
884
+
885
+ `DataPipeline` generic in the dtype of the data it processes (`DataT`).
886
+
887
+ Parameters
888
+ ----------
889
+ axes :
890
+ The definition of the axes which will be used to tabulate the data.
891
+ The first axis represents rows in the result, and the second columns.
892
+ ndims :
893
+ The number of dimensions expected in the result: 1 or 2.
894
+ dtype :
895
+ The dtype of the data values in the result.
896
+ rng :
897
+ A source of randomness.
898
+ pipeline_steps :
899
+ The accumulated pipeline steps.
900
+
901
+ Examples
902
+ --------
903
+ --8<-- "docs/_examples/adrio_processing_DataPipeline.md"
904
+ """
905
+
906
+ axes: tuple[PivotAxis, PivotAxis]
907
+ """
908
+ The definition of the axes which will be used to tabulate the data.
909
+ The first axis represents rows in the result, and the second columns.
910
+
911
+ """
912
+ ndims: Literal[1, 2]
913
+ """The number of dimensions expected in the result: 1 or 2."""
914
+ dtype: type[DataT]
915
+ """The dtype of the data values in the result."""
916
+ rng: HasRandomness
917
+ """A source of randomness."""
918
+
919
+ pipeline_steps: Sequence[_PipelineStep] = field(default_factory=list)
920
+ """The accumulated pipeline steps."""
921
+
922
+ def __post_init__(self):
923
+ if self.ndims == 1 and len(self.axes[1].values) > 1:
924
+ err = (
925
+ "If `ndims` is 1, the second axis definition in `axes` must contain "
926
+ "exactly one value."
927
+ )
928
+ raise ValueError(err)
929
+ if any(len(x.values) == 0 for x in self.axes):
930
+ err = "All axis definitions in `axes` must contain at least one value."
931
+ raise ValueError(err)
932
+
933
+ def _and_then(self, f: _PipelineStep) -> Self:
934
+ """Return a copy of this pipeline with a pipeline step appended."""
935
+ return dataclasses.replace(self, pipeline_steps=[*self.pipeline_steps, f])
936
+
937
+ def _process(self, data_df: pd.DataFrame) -> _PipelineState:
938
+ """Apply all of the pipeline steps to an input."""
939
+ state = _PipelineState(data_df)
940
+ for f in self.pipeline_steps:
941
+ state = f(state)
942
+ return state
943
+
944
+ def map_series(
945
+ self,
946
+ column: str,
947
+ map_fn: Callable[[pd.Series], pd.Series] | None = None,
948
+ ) -> Self:
949
+ """
950
+ Add a pipeline step that transforms a column of the `DataFrame`
951
+ by applying a mapping function to the series.
952
+
953
+ Parameters
954
+ ----------
955
+ column :
956
+ The name of the column to transform.
957
+ map_fn :
958
+ The series mapping function. As a convenience you may pass `None`,
959
+ in which case this is a no-op.
960
+
961
+ Returns
962
+ -------
963
+ :
964
+ A copy of this pipeline with the step added.
965
+ """
966
+ if map_fn is None:
967
+ return self
968
+
969
+ def map_series(state: _PipelineState) -> _PipelineState:
970
+ series = map_fn(state.data_df[column])
971
+ data_df = state.data_df.assign(**{column: series})
972
+ return state.next(data_df)
973
+
974
+ return self._and_then(map_series)
975
+
976
+ def map_column(
977
+ self,
978
+ column: str,
979
+ map_fn: Callable | None = None,
980
+ ) -> Self:
981
+ """
982
+ Add a pipeline step that transforms a column of the `DataFrame`
983
+ by applying a mapping function to all values in the series.
984
+
985
+ Parameters
986
+ ----------
987
+ column :
988
+ The name of the column to transform.
989
+ map_fn :
990
+ The value mapping function. As a convenience you may pass `None`,
991
+ in which case this is a no-op.
992
+
993
+ Returns
994
+ -------
995
+ :
996
+ A copy of this pipeline with the step added.
997
+ """
998
+ if map_fn is None:
999
+ return self
1000
+
1001
+ return self.map_series(
1002
+ column=column,
1003
+ map_fn=lambda xs: xs.apply(map_fn),
1004
+ )
1005
+
1006
+ def strip_sentinel(
1007
+ self,
1008
+ sentinel_name: str,
1009
+ sentinel_value: DataT,
1010
+ fix: "Fix[DataT]",
1011
+ ) -> Self:
1012
+ """
1013
+ Add a pipeline step for dealing with sentinel values in the `DataFrame`.
1014
+ First we apply the given `Fix`, then check for any remaining sentinel values.
1015
+ If sentinel values still remain in the data, these are recorded as a data
1016
+ issue with an associated mask.
1017
+
1018
+ Parameters
1019
+ ----------
1020
+ sentinel_name :
1021
+ The name used for the data issue if any sentinel values remain.
1022
+ sentinel_value :
1023
+ The value considered a sentinel.
1024
+ fix :
1025
+ The fix to apply to attempt to replace sentinel values.
1026
+
1027
+ Returns
1028
+ -------
1029
+ :
1030
+ A copy of this pipeline with the step added.
1031
+ """
1032
+
1033
+ def strip_sentinel(state: _PipelineState) -> _PipelineState:
1034
+ # Apply fix.
1035
+ work_df = fix(self.rng, sentinel_value, ("value",), state.data_df)
1036
+
1037
+ # Compute the mask for any remaining sentinels.
1038
+ is_sentinel = work_df["value"] == sentinel_value
1039
+ mask = (
1040
+ work_df.loc[is_sentinel]
1041
+ .pivot_table(
1042
+ index=self.axes[0].column,
1043
+ columns=self.axes[1].column,
1044
+ values="value",
1045
+ aggfunc=lambda _: True,
1046
+ fill_value=False,
1047
+ )
1048
+ .reindex(
1049
+ index=self.axes[0].values,
1050
+ columns=self.axes[1].values,
1051
+ fill_value=False,
1052
+ )
1053
+ .to_numpy(dtype=np.bool_)
1054
+ )
1055
+
1056
+ # pivot_table produces 2D results; adjust if we expect a 1D result.
1057
+ if self.ndims == 1:
1058
+ if mask.shape[1] > 1:
1059
+ err = (
1060
+ "You specified `ndims` as 1, but the data contains more than "
1061
+ "one column so it is impossible to convert it to this form."
1062
+ )
1063
+ raise Exception(err)
1064
+ mask = mask[:, 0]
1065
+
1066
+ # Strip out sentinel values.
1067
+ work_df = work_df.loc[~is_sentinel]
1068
+ return state.next_with_issue(work_df, sentinel_name, mask)
1069
+
1070
+ return self._and_then(strip_sentinel)
1071
+
1072
+ def strip_na_as_sentinel(
1073
+ self,
1074
+ column: str,
1075
+ sentinel_name: str,
1076
+ sentinel_value: DataT,
1077
+ fix: "Fix[DataT]",
1078
+ ) -> Self:
1079
+ """
1080
+ Add a pipeline step for dealing with NaN/NA/null values in the `DataFrame`.
1081
+ First replace NA values with a user-defined sentinel value, then apply the
1082
+ given `Fix`. Finally check for any remaining such values. If sentinel values
1083
+ still remain in the data, these are recorded as a data issue with an associated
1084
+ mask.
1085
+
1086
+ Parameters
1087
+ ----------
1088
+ column :
1089
+ The name of the column to transform.
1090
+ sentinel_name :
1091
+ The name used for the data issue if any NA/sentinel values remain.
1092
+ sentinel_value :
1093
+ The value to use to replace NA values. We want to replace NAs so that
1094
+ we can universally convert the data column to the desired type --
1095
+ np.int64 doesn't support NA values like np.float64 does, so this allows
1096
+ the input DataFrame to start with something like Pandas' "Int64" data type
1097
+ while the pipeline produces np.int64 results.
1098
+ The sentinel value chosen for this must not already exist in the data.
1099
+ fix :
1100
+ The fix to apply to attempt to replace NA/sentinel values.
1101
+
1102
+ Returns
1103
+ -------
1104
+ :
1105
+ A copy of this pipeline with the step added.
1106
+
1107
+ Raises
1108
+ ------
1109
+ Exception
1110
+ If the data naturally contains the chosen sentinel value.
1111
+ """
1112
+
1113
+ def replace_na(state: _PipelineState) -> _PipelineState:
1114
+ series = state.data_df[column]
1115
+ if (series == sentinel_value).any():
1116
+ # the below S608 Ruff warning is a false positive;
1117
+ # apparently it thinks this error message looks like a SQL statement
1118
+ err = (
1119
+ "The data contains the proposed artificial sentinel value " # noqa: S608
1120
+ f"({sentinel_value}), so if we replace NA values with this value "
1121
+ "we'll get missing values mixed up with others. Please choose a "
1122
+ "sentinel value that is guaranteed not to be in the data naturally."
1123
+ )
1124
+ raise Exception(err)
1125
+
1126
+ series = series.fillna(sentinel_value).astype(self.dtype) # type: ignore
1127
+ data_df = state.data_df.assign(**{column: series})
1128
+ return state.next(data_df)
1129
+
1130
+ return self._and_then(replace_na).strip_sentinel(
1131
+ sentinel_name, sentinel_value, fix
1132
+ )
1133
+
1134
+ def finalize(
1135
+ self,
1136
+ fill_missing: "Fill[DataT]",
1137
+ ) -> Callable[[pd.DataFrame], PipelineResult[DataT]]:
1138
+ """
1139
+ Completes construction of the pipeline.
1140
+
1141
+ Parameters
1142
+ ----------
1143
+ fill_missing :
1144
+ A method for filling in missing data.
1145
+
1146
+ Returns
1147
+ -------
1148
+ :
1149
+ The prepared pipeline: a function that processes a `DataFrame` and produces
1150
+ a result.
1151
+ """
1152
+
1153
+ def pipeline(data_df: pd.DataFrame) -> PipelineResult[DataT]:
1154
+ # Run the accumulated processing pipeline.
1155
+ state = self._process(data_df)
1156
+
1157
+ # Tabulate data; reindexing step can expose missing values.
1158
+ result_np = cast(
1159
+ NDArray[DataT],
1160
+ (
1161
+ state.data_df.pivot_table(
1162
+ index=self.axes[0].column,
1163
+ columns=self.axes[1].column,
1164
+ values="value",
1165
+ aggfunc="sum",
1166
+ fill_value=0,
1167
+ )
1168
+ .reindex(
1169
+ index=self.axes[0].values,
1170
+ columns=self.axes[1].values,
1171
+ fill_value=0,
1172
+ )
1173
+ .to_numpy(dtype=self.dtype)
1174
+ ),
1175
+ )
1176
+ missing_mask = cast(
1177
+ NDArray[np.bool_],
1178
+ (
1179
+ state.data_df.assign(value=False)
1180
+ .pivot_table(
1181
+ index=self.axes[0].column,
1182
+ columns=self.axes[1].column,
1183
+ values="value",
1184
+ aggfunc=lambda _: False,
1185
+ fill_value=True,
1186
+ )
1187
+ .reindex(
1188
+ index=self.axes[0].values,
1189
+ columns=self.axes[1].values,
1190
+ fill_value=True,
1191
+ )
1192
+ ).to_numpy(dtype=np.bool_),
1193
+ )
1194
+
1195
+ # pivot_table produces 2D results; adjust if we expect a 1D result.
1196
+ if self.ndims == 1:
1197
+ if missing_mask.shape[1] > 1 or result_np.shape[1] > 1:
1198
+ err = (
1199
+ "You specified `ndims` as 1, but the data contains more than "
1200
+ "one column so it is impossible to convert it to this form."
1201
+ )
1202
+ raise Exception(err)
1203
+ result_np = result_np[:, 0]
1204
+ missing_mask = missing_mask[:, 0]
1205
+
1206
+ # If a value is present in an issue mask it's not missing,
1207
+ # but for calculation purposes we may have removed it
1208
+ # (e.g., stripping sentinels.). Correct that now.
1209
+ all_issues_mask = reduce(
1210
+ np.logical_or,
1211
+ [m for _, m in state.issues.items()],
1212
+ np.ma.nomask,
1213
+ )
1214
+ missing_mask = missing_mask & ~all_issues_mask
1215
+
1216
+ # Discover and fill missing data.
1217
+ result_np, missing_mask = fill_missing(self.rng, result_np, missing_mask)
1218
+ state = state.next_with_issue(state.data_df, "missing", missing_mask)
1219
+ return PipelineResult(result_np, state.issues)
1220
+
1221
+ return pipeline