epymorph 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. epymorph/__init__.py +7 -0
  2. epymorph/__main__.py +16 -0
  3. epymorph/adrio/__init__.py +0 -0
  4. epymorph/adrio/acs5.py +1378 -0
  5. epymorph/adrio/adrio.py +953 -0
  6. epymorph/adrio/cdc.py +1826 -0
  7. epymorph/adrio/commuting_flows.py +283 -0
  8. epymorph/adrio/csv.py +499 -0
  9. epymorph/adrio/humidity.py +206 -0
  10. epymorph/adrio/lodes.py +509 -0
  11. epymorph/adrio/numpy.py +160 -0
  12. epymorph/adrio/prism.py +345 -0
  13. epymorph/adrio/processing.py +1221 -0
  14. epymorph/adrio/soda.py +602 -0
  15. epymorph/adrio/us_tiger.py +289 -0
  16. epymorph/adrio/validation.py +382 -0
  17. epymorph/attribute.py +614 -0
  18. epymorph/cache.py +680 -0
  19. epymorph/cli/__init__.py +0 -0
  20. epymorph/cli/cache.py +78 -0
  21. epymorph/cli/main.py +29 -0
  22. epymorph/compartment_model.py +1873 -0
  23. epymorph/data/__init__.py +1 -0
  24. epymorph/data/ipm/__init__.py +22 -0
  25. epymorph/data/ipm/no.py +14 -0
  26. epymorph/data/ipm/pei.py +40 -0
  27. epymorph/data/ipm/seirs.py +50 -0
  28. epymorph/data/ipm/sirh.py +55 -0
  29. epymorph/data/ipm/sirs.py +48 -0
  30. epymorph/data/ipm/sparsemod.py +96 -0
  31. epymorph/data/mm/__init__.py +22 -0
  32. epymorph/data/mm/centroids.py +76 -0
  33. epymorph/data/mm/flat.py +61 -0
  34. epymorph/data/mm/icecube.py +50 -0
  35. epymorph/data/mm/no.py +29 -0
  36. epymorph/data/mm/pei.py +105 -0
  37. epymorph/data/mm/sparsemod.py +73 -0
  38. epymorph/data/pei.py +424 -0
  39. epymorph/data_shape.py +593 -0
  40. epymorph/data_type.py +185 -0
  41. epymorph/data_usage.py +258 -0
  42. epymorph/database.py +1301 -0
  43. epymorph/error.py +195 -0
  44. epymorph/event.py +196 -0
  45. epymorph/geography/__init__.py +0 -0
  46. epymorph/geography/custom.py +93 -0
  47. epymorph/geography/scope.py +457 -0
  48. epymorph/geography/us_census.py +1056 -0
  49. epymorph/geography/us_geography.py +502 -0
  50. epymorph/geography/us_tiger.py +1083 -0
  51. epymorph/initializer.py +786 -0
  52. epymorph/kit.py +107 -0
  53. epymorph/log/__init__.py +0 -0
  54. epymorph/log/file.py +128 -0
  55. epymorph/log/messaging.py +139 -0
  56. epymorph/log/movement.py +228 -0
  57. epymorph/movement_model.py +347 -0
  58. epymorph/parameter_fitting/__init__.py +0 -0
  59. epymorph/parameter_fitting/distribution.py +68 -0
  60. epymorph/parameter_fitting/dynamics.py +19 -0
  61. epymorph/parameter_fitting/filter/__init__.py +0 -0
  62. epymorph/parameter_fitting/filter/base_filter.py +50 -0
  63. epymorph/parameter_fitting/filter/particle.py +32 -0
  64. epymorph/parameter_fitting/filter/particle_filter.py +296 -0
  65. epymorph/parameter_fitting/likelihood.py +54 -0
  66. epymorph/parameter_fitting/output.py +73 -0
  67. epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
  68. epymorph/parameter_fitting/perturbation.py +19 -0
  69. epymorph/parameter_fitting/utils/__init__.py +0 -0
  70. epymorph/parameter_fitting/utils/data_loader.py +97 -0
  71. epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
  72. epymorph/parameter_fitting/utils/observations.py +63 -0
  73. epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
  74. epymorph/parameter_fitting/utils/params_perturb.py +43 -0
  75. epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
  76. epymorph/parameter_fitting/utils/resampler.py +258 -0
  77. epymorph/parameter_fitting/utils/utils.py +101 -0
  78. epymorph/params.py +438 -0
  79. epymorph/py.typed +0 -0
  80. epymorph/rume.py +871 -0
  81. epymorph/simulation.py +991 -0
  82. epymorph/simulator/__init__.py +0 -0
  83. epymorph/simulator/basic/__init__.py +0 -0
  84. epymorph/simulator/basic/basic_simulator.py +171 -0
  85. epymorph/simulator/basic/ipm_exec.py +437 -0
  86. epymorph/simulator/basic/mm_exec.py +244 -0
  87. epymorph/simulator/basic/output.py +213 -0
  88. epymorph/simulator/world.py +149 -0
  89. epymorph/simulator/world_list.py +274 -0
  90. epymorph/strata.py +24 -0
  91. epymorph/sympy_shim.py +57 -0
  92. epymorph/time.py +1197 -0
  93. epymorph/tools/__init__.py +0 -0
  94. epymorph/tools/data.py +297 -0
  95. epymorph/tools/ipm_diagram.py +208 -0
  96. epymorph/tools/out_map.py +551 -0
  97. epymorph/tools/out_plot.py +423 -0
  98. epymorph/tools/out_table.py +582 -0
  99. epymorph/util.py +1036 -0
  100. epymorph-1.0.0.dist-info/METADATA +57 -0
  101. epymorph-1.0.0.dist-info/RECORD +104 -0
  102. epymorph-1.0.0.dist-info/WHEEL +5 -0
  103. epymorph-1.0.0.dist-info/entry_points.txt +2 -0
  104. epymorph-1.0.0.dist-info/top_level.txt +1 -0
epymorph/util.py ADDED
@@ -0,0 +1,1036 @@
1
+ """epymorph general utility functions and classes."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from collections.abc import ItemsView, KeysView, Mapping, ValuesView
5
+ from contextlib import contextmanager
6
+ from dataclasses import dataclass
7
+ from enum import Enum
8
+ from functools import cache, wraps
9
+ from math import floor
10
+ from re import compile as re_compile
11
+ from typing import (
12
+ Any,
13
+ Callable,
14
+ Generator,
15
+ Generic,
16
+ Iterable,
17
+ Literal,
18
+ NamedTuple,
19
+ ParamSpec,
20
+ Protocol,
21
+ Self,
22
+ TypeGuard,
23
+ TypeVar,
24
+ overload,
25
+ )
26
+
27
+ import numpy as np
28
+ from numpy.typing import DTypeLike, NDArray
29
+
30
+ acceptable_name = re_compile(r"^[a-zA-Z][a-zA-Z0-9_-]*$")
31
+ """A pattern that matches generally acceptable names for use across epymorph."""
32
+
33
+
34
+ def normalize_str(value: str) -> str:
35
+ """Normalize a string for permissive search."""
36
+ return value.strip().lower()
37
+
38
+
39
+ def normalize_list(values: list[str]) -> list[str]:
40
+ """Normalize a list of strings for permissive search."""
41
+ return list(map(normalize_str, values))
42
+
43
+
44
+ class ANSIColor(Enum):
45
+ # Standard Colors
46
+ BLACK = 30
47
+ RED = 31
48
+ GREEN = 32
49
+ YELLOW = 33
50
+ BLUE = 34
51
+ MAGENTA = 35
52
+ CYAN = 36
53
+ WHITE = 37
54
+ # Bright Colors
55
+ BRIGHT_BLACK = 90
56
+ BRIGHT_RED = 91
57
+ BRIGHT_GREEN = 92
58
+ BRIGHT_YELLOW = 93
59
+ BRIGHT_BLUE = 94
60
+ BRIGHT_MAGENTA = 95
61
+ BRIGHT_CYAN = 96
62
+ BRIGHT_WHITE = 97
63
+
64
+
65
+ class ANSIStyle(Enum):
66
+ RESET = 0 # Reset all styles
67
+ BOLD = 1 # Bold text
68
+ DIM = 2 # Dim text
69
+ ITALIC = 3 # Italic text
70
+ UNDERLINE = 4 # Underlined text
71
+ STRIKETHROUGH = 9 # Strikethrough text
72
+
73
+
74
+ def ansi_stylize(
75
+ text: str,
76
+ color: ANSIColor | None = ANSIColor.WHITE,
77
+ style: ANSIStyle | None = None,
78
+ ) -> str:
79
+ """Uses ANSI escape codes to stylize a given text, which may not work everywhere.
80
+ Any applied color or style are reset after the text.
81
+
82
+ Parameters
83
+ ----------
84
+ color : AnsiColor, optional
85
+ The text color to apply.
86
+ style : AnsiStyle, optional
87
+ The text style to apply.
88
+ """
89
+ # ANSI reference: https://en.wikipedia.org/wiki/ANSI_escape_code
90
+ codes = [str(x.value) for x in (color, style) if x is not None]
91
+ if len(codes) == 0:
92
+ return text
93
+ return f"\033[{';'.join(codes)}m{text}\033[{ANSIStyle.RESET.value}m"
94
+
95
+
96
+ # function utilities
97
+
98
+
99
+ T = TypeVar("T")
100
+ A = TypeVar("A")
101
+ B = TypeVar("B")
102
+
103
+
104
+ def identity(x: T) -> T:
105
+ """A function which just returns the argument it is called with."""
106
+ return x
107
+
108
+
109
+ def constant(x: T) -> Callable[..., T]:
110
+ """
111
+ A function which returns a constant value,
112
+ regardless of what arguments its called with.
113
+ """
114
+ return lambda *_: x
115
+
116
+
117
+ def noop():
118
+ """A function which does nothing."""
119
+
120
+
121
+ def call_all(*fs: Callable[[], Any]) -> None:
122
+ """Given a list of no-arg functions, call all of the functions and return None."""
123
+ for f in fs:
124
+ f()
125
+
126
+
127
+ P = ParamSpec("P")
128
+
129
+
130
+ def cache_transparent(func: Callable[P, T]) -> Callable[P, T]:
131
+ """Decorates a function with functools.cache but maintains its signature."""
132
+ # cache() transforms the function into an _lru_cache_wrapper,
133
+ # which is technically correct but mostly unhelpful.
134
+ # Generally we don't want the user to know or care that a function is cached.
135
+ return wraps(func)(cache(func)) # type: ignore
136
+
137
+
138
+ # collection utilities
139
+
140
+
141
+ def index_where(it: Iterable[T], predicate: Callable[[T], bool]) -> int:
142
+ """
143
+ Find the first index of `it` where `predicate` evaluates to True.
144
+ Return -1 if no such value exists.
145
+ """
146
+ for i, x in enumerate(it):
147
+ if predicate(x):
148
+ return i
149
+ return -1
150
+
151
+
152
+ def index_of(it: Iterable[T], item: T) -> int:
153
+ """
154
+ Find the first index of `it` where `item` evaluates as equal.
155
+ Return -1 if no such value exists.
156
+ """
157
+ for i, x in enumerate(it):
158
+ if x == item:
159
+ return i
160
+ return -1
161
+
162
+
163
+ def list_not_none(it: Iterable[T | None]) -> list[T]:
164
+ """Convert an iterable to a list, skipping any entries that are None."""
165
+ return [x for x in it if x is not None]
166
+
167
+
168
+ def are_unique(xs: Iterable[T]) -> bool:
169
+ """Returns True if all items in the iterable are unique."""
170
+ xset = set[T]()
171
+ for x in xs:
172
+ if x in xset:
173
+ return False
174
+ xset.add(x)
175
+ return True
176
+
177
+
178
+ @overload
179
+ def are_instances(xs: list[Any], of_type: type[T]) -> TypeGuard[list[T]]: ...
180
+ @overload
181
+ def are_instances(xs: tuple[Any], of_type: type[T]) -> TypeGuard[tuple[T]]: ...
182
+
183
+
184
+ def are_instances(
185
+ xs: list[Any] | tuple[Any], of_type: type[T]
186
+ ) -> TypeGuard[list[T] | tuple[T]]:
187
+ """
188
+ TypeGuards a collection to check that all items are
189
+ instances of the given type (`of_type`).
190
+ """
191
+ # NOTE: TypeVars can't be generic so we can't do TypeGuard[C[T]] :(
192
+ # Thus this only supports the types of collections we specify explicitly.
193
+ return all(isinstance(x, of_type) for x in xs)
194
+
195
+
196
+ def filter_unique(xs: Iterable[T]) -> list[T]:
197
+ """
198
+ Convert an iterable to a list, keeping only the unique values and
199
+ maintaining the order as first-seen.
200
+ """
201
+ xset = set[T]()
202
+ ys = list[T]()
203
+ for x in xs:
204
+ if x not in xset:
205
+ ys.append(x)
206
+ xset.add(x)
207
+ return ys
208
+
209
+
210
+ def filter_with_mask(
211
+ xs: Iterable[A], predicate: Callable[[A], TypeGuard[B]]
212
+ ) -> tuple[list[B], list[bool]]:
213
+ """
214
+ Filters the given iterable for items which match `predicate`, and also
215
+ returns a boolean mask the same length as the iterable with the results of
216
+ `predicate` for each item.
217
+ """
218
+ matched = list[B]()
219
+ mask = list[bool]()
220
+ for x in xs:
221
+ is_match = predicate(x)
222
+ mask.append(is_match)
223
+ if is_match:
224
+ matched.append(x)
225
+ return matched, mask
226
+
227
+
228
+ def zip_list(xs: Iterable[A], ys: Iterable[B]) -> list[tuple[A, B]]:
229
+ """Zip (strict) two iterables together as a list."""
230
+ return list(zip(xs, ys, strict=True))
231
+
232
+
233
+ K = TypeVar("K")
234
+ V = TypeVar("V")
235
+
236
+
237
+ class KeyValue(Generic[K, V], NamedTuple):
238
+ """A generic named tuple for key/value pairs."""
239
+
240
+ key: K
241
+ value: V
242
+
243
+
244
+ K_co = TypeVar("K_co", covariant=True)
245
+ V_co = TypeVar("V_co", covariant=True)
246
+
247
+
248
+ class CovariantMapping(Protocol[K_co, V_co]):
249
+ """A type for covariant mappings, which restricts usage
250
+ to only those methods which are safe under covariance.
251
+ For many use-cases these limitations are acceptable and
252
+ wind up simplifying type expression."""
253
+
254
+ @abstractmethod
255
+ def keys(self) -> KeysView[K_co]: ...
256
+
257
+ @abstractmethod
258
+ def items(self) -> ItemsView[K_co, V_co]: ...
259
+
260
+ @abstractmethod
261
+ def values(self) -> ValuesView[V_co]: ...
262
+
263
+ @abstractmethod
264
+ def __len__(self) -> int: ...
265
+
266
+
267
+ def as_dict(mapping: CovariantMapping[K, V]) -> dict[K, V]:
268
+ return {k: v for k, v in mapping.items()}
269
+
270
+
271
+ def map_values(f: Callable[[A], B], xs: Mapping[K, A]) -> dict[K, B]:
272
+ """Maps the values of a Mapping into a dict by applying the given function."""
273
+ return {k: f(v) for k, v in xs.items()}
274
+
275
+
276
+ # numpy utilities
277
+
278
+
279
+ N = TypeVar("N", bound=np.number)
280
+
281
+ NDIndices = NDArray[np.intp]
282
+
283
+
284
+ def normalize(arr: NDArray[N]) -> NDArray[N]:
285
+ """
286
+ Normalize the values in an array by subtracting the min and dividing by the range.
287
+ """
288
+ min_val = arr.min()
289
+ max_val = arr.max()
290
+ return (arr - min_val) / (max_val - min_val)
291
+
292
+
293
+ def row_normalize(
294
+ arr: NDArray[N], row_sums: NDArray[N] | None = None, dtype: DTypeLike = None
295
+ ) -> NDArray[N]:
296
+ """
297
+ Assuming `arr` is a 2D array, normalize values across each row by dividing
298
+ by the row sum. If you've already calculated row sums, you can pass those in,
299
+ otherwise they will be computed.
300
+ """
301
+ if row_sums is None:
302
+ row_sums = arr.sum(axis=1, dtype=dtype)
303
+ # We do a maximum(1, ...) here to protect against div-by-zero:
304
+ # if we assume `arr` is strictly non-negative and if a row-sum is zero,
305
+ # then every entry in the row is zero therefore dividing by 1 is fine.
306
+ return arr / np.maximum(1, row_sums[:, np.newaxis]) # type: ignore
307
+ # numpy's types are garbage
308
+
309
+
310
+ def prefix(length: int) -> Callable[[NDArray[np.str_]], NDArray[np.str_]]:
311
+ """
312
+ A vectorized operation to return the prefix of each value in an NDArray of strings.
313
+ """
314
+ return np.vectorize(lambda x: x[0:length], otypes=[np.str_])
315
+
316
+
317
+ def mask(length: int, selection: slice | list[int]) -> NDArray[np.bool_]:
318
+ """
319
+ Creates a boolean mask of a given `length` where all elements identified
320
+ by `selection` are True and all others are False. The selection can be
321
+ a slice or a list of indices.
322
+ """
323
+ mask = np.zeros(shape=length, dtype=np.bool_)
324
+ mask[selection] = True
325
+ return mask
326
+
327
+
328
+ # values from: https://www.themathdoctors.org/distances-on-earth-2-the-haversine-formula
329
+ _EARTH_RADIUS = {
330
+ "miles": 3963.1906,
331
+ "kilometers": 6378.1370,
332
+ }
333
+
334
+
335
+ def pairwise_haversine(
336
+ coordinates: NDArray | tuple[NDArray[np.float64], NDArray[np.float64]],
337
+ *,
338
+ units: Literal["miles", "kilometers"] = "miles",
339
+ radius: float | None = None,
340
+ ) -> NDArray[np.float64]:
341
+ """Compute the distances between all pairs of coordinates.
342
+
343
+ Parameters
344
+ ----------
345
+ coordinates : NDArray | tuple[NDArray, NDArray]
346
+ The coordinates, given in one of two forms: either a structured numpy array
347
+ with dtype `[("longitude", np.float64), ("latitude", np.float64)]` or a tuple
348
+ of two numpy arrays, the first containing longitudes and the second latitudes.
349
+ The coordinates must be given in degrees.
350
+ units : Literal["miles", "kilometers"] = "miles",
351
+ The units of distance to use for the result, unless radius is given.
352
+ radius : float, optional
353
+ The radius of the Earth to use in calculating the results. If not given,
354
+ we will use an appropriate value for the given `units`.
355
+ Since the value of radius implies the distance units being used, if you
356
+ specify `radius` the value of `units` is ignored.
357
+
358
+ Returns
359
+ -------
360
+ NDArray[np.float64] :
361
+ An NxN array of distances where N is the number of coordinates given,
362
+ representing the distance between each pair of coordinates. The output
363
+ maintains the same ordering of coordinates as the input.
364
+
365
+ Raises
366
+ ------
367
+ ValueError :
368
+ if coordinates are not given in an expected format
369
+ """
370
+ # https://www.themathdoctors.org/distances-on-earth-2-the-haversine-formula
371
+ if isinstance(coordinates, np.ndarray) and coordinates.dtype == np.dtype(
372
+ [("longitude", np.float64), ("latitude", np.float64)]
373
+ ):
374
+ lng = coordinates["longitude"]
375
+ lat = coordinates["latitude"]
376
+ elif isinstance(coordinates, tuple) and len(coordinates) == 2:
377
+ lng = coordinates[0]
378
+ lat = coordinates[1]
379
+ else:
380
+ err = "Unable to interpret the given `coordinates`."
381
+ raise ValueError(err)
382
+
383
+ lngrad = np.radians(lng)
384
+ latrad = np.radians(lat)
385
+ dlng = lngrad[:, np.newaxis] - lngrad[np.newaxis, :]
386
+ dlat = latrad[:, np.newaxis] - latrad[np.newaxis, :]
387
+ cos_lat = np.cos(latrad)
388
+
389
+ a = (
390
+ np.sin(dlat / 2.0) ** 2
391
+ + (cos_lat[:, np.newaxis] * cos_lat[np.newaxis, :]) * np.sin(dlng / 2.0) ** 2
392
+ )
393
+ r = radius if radius is not None else _EARTH_RADIUS[units]
394
+ return 2 * r * np.arcsin(np.sqrt(a))
395
+
396
+
397
+ def top(size: int, arr: NDArray) -> NDIndices:
398
+ """
399
+ Find the top `size` elements in `arr` and return their indices.
400
+ Assumes the array is flat and the kind of thing that can be order-compared.
401
+ """
402
+ return np.argpartition(arr, -size)[-size:]
403
+
404
+
405
+ def bottom(size: int, arr: NDArray) -> NDIndices:
406
+ """
407
+ Find the bottom `size` elements in `arr` and return their indices.
408
+ Assumes the array is flat and the kind of thing that can be order-compared.
409
+ """
410
+ return np.argpartition(arr, size)[:size]
411
+
412
+
413
+ def is_square(arr: NDArray) -> bool:
414
+ """Is this numpy array 2 dimensions and square in shape?"""
415
+ return arr.ndim == 2 and arr.shape[0] == arr.shape[1]
416
+
417
+
418
+ def is_numeric(arr: NDArray) -> TypeGuard[NDArray[np.integer | np.floating]]:
419
+ """Is this numpy array a numeric (non-complex) type?"""
420
+ return np.issubdtype(arr.dtype, np.integer) or np.issubdtype(arr.dtype, np.floating)
421
+
422
+
423
+ def shape_matches(arr: NDArray, expected: tuple[int | Literal["?"], ...]) -> bool:
424
+ """
425
+ Does the shape of the given array match this expression?
426
+ Shape expressions are a tuple where each dimension is either an integer
427
+ or a '?' character to signify any length is allowed.
428
+ """
429
+ if len(arr.shape) != len(expected):
430
+ return False
431
+ for actual, exp in zip(arr.shape, expected):
432
+ if exp == "?":
433
+ continue
434
+ if exp != actual:
435
+ return False
436
+ return True
437
+
438
+
439
+ class NumpyTypeError(Exception):
440
+ """Describes an error checking the type or shape of a numpy array."""
441
+
442
+
443
+ def dtype_name(d: np.dtype) -> str:
444
+ """Tries to return the most-human-readable name for a numpy dtype."""
445
+ if np.issubdtype(d, np.str_):
446
+ return "str_"
447
+ if d.isbuiltin:
448
+ return d.name
449
+ return str(d)
450
+
451
+
452
+ ####################
453
+ # DATE/VALUE TYPES #
454
+ ####################
455
+
456
+
457
+ DataT = TypeVar("DataT", bound=np.generic)
458
+
459
+ DateValueType = np.void
460
+ """
461
+ The numpy dtype used for structured arrays of date and value.
462
+ numpy doesn't let us type these very explicitly, so this alias
463
+ is used to express intention, but know it comes with few guarantees.
464
+
465
+ So basically it implies: `[("date", "datetime64[D]"), ("value", DataT)]`
466
+ """
467
+
468
+
469
+ def date_value_dtype(value_dtype: DTypeLike) -> np.dtype:
470
+ return np.dtype([("date", "datetime64[D]"), ("value", value_dtype)])
471
+
472
+
473
+ def is_date_value_dtype(
474
+ dtype: np.dtype | type[np.generic],
475
+ *,
476
+ value_dtype: np.dtype | type[np.generic] | None = None,
477
+ ) -> TypeGuard[DateValueType]:
478
+ """
479
+ Check if the given dtype is structured with 'date' and 'value' fields.
480
+
481
+ Parameters
482
+ ----------
483
+ dtype :
484
+ The dtype to check.
485
+ value_dtype :
486
+ The optional expected dtype of the 'value' field. If None (default),
487
+ the dtype of the 'value' field is not checked.
488
+
489
+ Returns
490
+ -------
491
+ :
492
+ True if the dtype is date/value, false otherwise.
493
+
494
+ See Also
495
+ --------
496
+ [epymorph.util.is_date_value_array][] for examples.
497
+ """
498
+
499
+ if not isinstance(dtype, np.dtype):
500
+ dtype = np.dtype(dtype)
501
+ if dtype.names != ("date", "value"):
502
+ return False
503
+ if dtype["date"] != np.dtype("datetime64[D]"):
504
+ return False
505
+ if value_dtype:
506
+ if not isinstance(value_dtype, np.dtype):
507
+ value_dtype = np.dtype(value_dtype)
508
+ if dtype["value"] != value_dtype:
509
+ return False
510
+ return True
511
+
512
+
513
+ def is_date_value_array(
514
+ array: NDArray,
515
+ *,
516
+ value_dtype: type[DataT] | None = None,
517
+ ) -> TypeGuard[NDArray[DateValueType]]:
518
+ """
519
+ Check if the given array is a structured array with 'date' and 'value' fields.
520
+
521
+ Parameters
522
+ ----------
523
+ array : NDArray
524
+ The array to check.
525
+ value_dtype : type[DataT], optional
526
+ The optional expected dtype of the 'value' field. If None (default),
527
+ the dtype of the 'value' field is not checked.
528
+
529
+ Returns
530
+ -------
531
+ TypeGuard[NDArray[DateValueType]]
532
+ True if the array is a date/value array, false otherwise.
533
+
534
+ Examples
535
+ --------
536
+ >>> import numpy as np
537
+ >>> array = np.array([('2021-01-01', 10), ('2021-01-02', 20)],
538
+ dtype=[('date', 'datetime64[D]'), ('value', np.int64)])
539
+ >>> is_date_value_array(array)
540
+ True
541
+ >>> is_date_value_array(array, value_dtype=np.int64)
542
+ True
543
+ """
544
+ return is_date_value_dtype(array.dtype, value_dtype=value_dtype)
545
+
546
+
547
+ def to_date_value_array(
548
+ dates: NDArray[np.datetime64],
549
+ values: NDArray[DataT],
550
+ ) -> NDArray[DateValueType]:
551
+ """
552
+ Combine separate arrays of dates and values to create a structured date/value array
553
+ with named fields. The given dates will be broadcast against the given values,
554
+ so they must have the same first-dimension.
555
+
556
+ Parameters
557
+ ----------
558
+ dates : NDArray[np.datetime64]
559
+ An 1D array of dates.
560
+ values : NDArray[DataT]
561
+ An array of values corresponding to the dates,
562
+ the first dimension of this array must be equal to the number of dates.
563
+
564
+ Returns
565
+ -------
566
+ NDArray[DateValueType]
567
+ A structured array with fields 'date' and 'value'.
568
+
569
+ Raises
570
+ ------
571
+ ValueError
572
+ If the dimensionality of the arrays is not compatible.
573
+
574
+ Examples
575
+ --------
576
+ >>> import numpy as np
577
+ >>> dates = np.array(['2021-01-01', '2021-01-02'], dtype='datetime64[D]')
578
+ >>> values = np.array([[10, 20], [30, 40]])
579
+ >>> to_date_value_array(dates, values)
580
+ array(
581
+ [
582
+ [('2021-01-01', 10), ('2021-01-01', 20)],
583
+ [('2021-01-02', 30), ('2021-01-02', 40)],
584
+ ],
585
+ dtype=[('date', 'datetime64[D]'), ('value', '<i8')],
586
+ )
587
+ """
588
+ if dates.ndim != 1:
589
+ raise ValueError("`dates` must be a 1D array.")
590
+ if dates.shape[0] != values.shape[0]:
591
+ err = "The first axis of `dates` and `values` must be the same length."
592
+ raise ValueError(err)
593
+ value_dtype = np.dtype(values.dtype).type
594
+ result = np.empty(
595
+ values.shape,
596
+ dtype=[("date", "datetime64[D]"), ("value", value_dtype)],
597
+ )
598
+ result["date"] = dates.reshape(dates.shape + (1,) * (values.ndim - 1))
599
+ result["value"] = values
600
+ return result
601
+
602
+
603
+ def extract_date_value(
604
+ date_values: NDArray[DateValueType],
605
+ value_dtype: type[DataT] | None = None,
606
+ ) -> tuple[NDArray[np.datetime64], NDArray[DataT]]:
607
+ """
608
+ Extract separate arrays of dates and values from a structured date/value array.
609
+
610
+ Parameters
611
+ ----------
612
+ date_values : NDArray[DateValueType]
613
+ A structured array with fields 'date' and 'value'.
614
+ value_dtype : type[DataT], optional
615
+ The expected dtype of the 'value' field. If None (default),
616
+ the dtype of the 'value' field is not checked.
617
+
618
+ Returns
619
+ -------
620
+ tuple[NDArray[np.datetime64], NDArray[DataT]]
621
+ A tuple containing two arrays: dates and values.
622
+
623
+ Raises
624
+ ------
625
+ ValueError
626
+ If `value_dtype` is provided and the dtype of the 'value' field does not match.
627
+
628
+ Examples
629
+ --------
630
+ >>> import numpy as np
631
+ >>> date_values = np.array([('2021-01-01', 10), ('2021-01-02', 20)],
632
+ dtype=[('date', 'datetime64[D]'), ('value', np.int64)])
633
+ >>> extract_date_value(date_values)
634
+ (array(['2021-01-01', '2021-01-02'], dtype='datetime64[D]'),
635
+ array([10, 20]))
636
+ """
637
+ # For dates: get the first axis and then the 0th element of all other axes
638
+ # in other words, `[:, 0, 0, 0]` for however many 0s are necessary
639
+ date_slice = np.index_exp[:] + np.index_exp[0] * (date_values.ndim - 1)
640
+ dates = np.ma.getdata(date_values["date"][date_slice])
641
+ values = date_values["value"]
642
+ if value_dtype and np.dtype(values.dtype) != np.dtype(value_dtype):
643
+ err = "Date/value array's values did not match expected dtype."
644
+ raise ValueError(err)
645
+ return dates, values
646
+
647
+
648
+ # Matchers
649
+
650
+
651
+ MatcherValueType_contra = TypeVar("MatcherValueType_contra", contravariant=True)
652
+ """The type of a value matcher by a `Matcher`."""
653
+
654
+
655
+ class Matcher(Generic[MatcherValueType_contra], ABC):
656
+ """
657
+ The root class for a family of predicates on values; `Matcher` child classes
658
+ are written to match specific types of values, and encode conditions against which
659
+ values are tested. Once you have a concrete `Matcher` instance, you use it like a
660
+ function (it implements `__call__` semantics) to test a value.
661
+ """
662
+
663
+ # Note: Matchers are contravariant: you can substitute a Matcher of a broader type
664
+ # when something asks for a Matcher of a more specific type.
665
+ # For example, a Matcher[Any] can be provided in place of a Matcher[str].
666
+
667
+ @abstractmethod
668
+ def expected(self) -> str:
669
+ """
670
+ The description of what this matcher's expected valid value(s) are.
671
+
672
+ Returns
673
+ -------
674
+ :
675
+ The value(s) we expect to match, as a string.
676
+ """
677
+
678
+ @abstractmethod
679
+ def __call__(self, value: Any) -> bool:
680
+ """
681
+ Test whether or not the given value matches this matcher.
682
+
683
+ Parameters
684
+ ----------
685
+ value :
686
+ The value to match.
687
+
688
+ Returns
689
+ -------
690
+ :
691
+ Whether or not the match is successful.
692
+ """
693
+
694
+
695
+ class MatchAny(Matcher[Any]):
696
+ """Always matches (returns True)."""
697
+
698
+ def expected(self) -> str:
699
+ return "any value"
700
+
701
+ def __call__(self, _value: Any) -> bool:
702
+ return True
703
+
704
+
705
+ class MatchEqual(Matcher[MatcherValueType_contra]):
706
+ """Matches a specific value by checking for equality (==)."""
707
+
708
+ _acceptable: MatcherValueType_contra
709
+
710
+ def __init__(self, acceptable: MatcherValueType_contra):
711
+ self._acceptable = acceptable
712
+
713
+ def expected(self) -> str:
714
+ return str(self._acceptable)
715
+
716
+ def __call__(self, value: Any) -> bool:
717
+ return value == self._acceptable
718
+
719
+
720
+ class MatchAnyIn(Matcher[MatcherValueType_contra]):
721
+ """Matches for presence in a list of values (in)."""
722
+
723
+ _acceptable: list[MatcherValueType_contra]
724
+
725
+ def __init__(self, acceptable: list[MatcherValueType_contra]):
726
+ self._acceptable = acceptable
727
+
728
+ def expected(self) -> str:
729
+ return f"one of [{', '.join((str(x) for x in self._acceptable))}]"
730
+
731
+ def __call__(self, value: MatcherValueType_contra) -> bool:
732
+ return value in self._acceptable
733
+
734
+
735
+ class MatchDType(Matcher[DTypeLike]):
736
+ """Matches one or more numpy dtypes using `np.issubdtype()`."""
737
+
738
+ _acceptable: list[np.dtype]
739
+
740
+ def __init__(self, *acceptable: DTypeLike):
741
+ if len(acceptable) == 0:
742
+ raise ValueError("Cannot match against no dtypes.")
743
+ self._acceptable = [np.dtype(x) for x in acceptable]
744
+
745
+ def expected(self) -> str:
746
+ if len(self._acceptable) == 1:
747
+ return dtype_name(self._acceptable[0])
748
+ else:
749
+ return f"one of [{', '.join((dtype_name(x) for x in self._acceptable))}]"
750
+
751
+ def __call__(self, value: DTypeLike) -> bool:
752
+ return any((np.issubdtype(value, x) for x in self._acceptable))
753
+
754
+
755
+ class MatchDTypeCast(Matcher[DTypeLike]):
756
+ """Matches one or more numpy dtypes using `np.can_cast(casting='safe')`."""
757
+
758
+ _acceptable: list[np.dtype]
759
+
760
+ def __init__(self, *acceptable: DTypeLike):
761
+ if len(acceptable) == 0:
762
+ raise ValueError("Cannot match against no dtypes.")
763
+ self._acceptable = [np.dtype(x) for x in acceptable]
764
+
765
+ def expected(self) -> str:
766
+ if len(self._acceptable) == 1:
767
+ return dtype_name(self._acceptable[0])
768
+ else:
769
+ return f"one of [{', '.join((dtype_name(x) for x in self._acceptable))}]"
770
+
771
+ def __call__(self, value: DTypeLike) -> bool:
772
+ return any((np.can_cast(value, x, casting="safe") for x in self._acceptable))
773
+
774
+
775
+ class MatchShapeLiteral(Matcher[NDArray]):
776
+ """
777
+ Matches a numpy array shape to a known literal value.
778
+ (For matching relative to simulation dimensions, you want DataShapeMatcher.)
779
+ """
780
+
781
+ _acceptable: tuple[int, ...]
782
+
783
+ def __init__(self, acceptable: tuple[int, ...]):
784
+ self._acceptable = acceptable
785
+
786
+ def expected(self) -> str:
787
+ """Describes what the expected value is."""
788
+ return str(self._acceptable)
789
+
790
+ def __call__(self, value: NDArray) -> bool:
791
+ return self._acceptable == value.shape
792
+
793
+
794
+ class MatchDimensions(Matcher[NDArray]):
795
+ """
796
+ Matches a numpy array purely on the number of dimensions.
797
+ """
798
+
799
+ _acceptable: int
800
+
801
+ def __init__(self, acceptable: int):
802
+ if acceptable < 0:
803
+ err = "Dimensions must be greater than or equal to zero."
804
+ raise ValueError(err)
805
+ self._acceptable = acceptable
806
+
807
+ def expected(self) -> str:
808
+ """Describes what the expected value is."""
809
+ return f"{self._acceptable}-dimensional array"
810
+
811
+ def __call__(self, value: NDArray) -> bool:
812
+ return self._acceptable == value.ndim
813
+
814
+
815
+ @dataclass(frozen=True)
816
+ class _Matchers:
817
+ """Convenience constructors for various matchers."""
818
+
819
+ any = MatchAny()
820
+ """A matcher that matches any value. (Singleton instance of MatchAny.)"""
821
+
822
+ def equal(self, value: T) -> Matcher[T]:
823
+ """Creates a MatchEqual instance."""
824
+ return MatchEqual(value)
825
+
826
+ def any_in(self, values: list[T]) -> Matcher[T]:
827
+ """Creates a MatchAnyIn instance."""
828
+ return MatchAnyIn(values)
829
+
830
+ def dtype(self, *dtypes: DTypeLike) -> Matcher[DTypeLike]:
831
+ """Creates a MatchDType instance."""
832
+ return MatchDType(*dtypes)
833
+
834
+ def dtype_cast(self, *dtypes: DTypeLike) -> Matcher[DTypeLike]:
835
+ """Creates a MatchDTypeCast instance."""
836
+ return MatchDTypeCast(*dtypes)
837
+
838
+ def shape_literal(self, shape: tuple[int, ...]) -> Matcher[NDArray]:
839
+ """Creates a MatchShapeLiteral instance."""
840
+ return MatchShapeLiteral(shape)
841
+
842
+ def dimensions(self, dimensions: int) -> Matcher[NDArray]:
843
+ """Creates a MatchDimensions instance."""
844
+ return MatchDimensions(dimensions)
845
+
846
+
847
+ match = _Matchers()
848
+ """Convenience constructors for various matchers."""
849
+
850
+
851
+ def check_ndarray(
852
+ value: Any,
853
+ *,
854
+ dtype: Matcher[DTypeLike] = MatchAny(),
855
+ shape: Matcher[NDArray] = MatchAny(),
856
+ ) -> None:
857
+ """
858
+ Checks that a value is a numpy array matching the given dtype and shape Matchers.
859
+ Raises a NumpyTypeError if a check doesn't pass.
860
+ """
861
+ if value is None:
862
+ raise NumpyTypeError("Value is None.")
863
+
864
+ if not isinstance(value, np.ndarray):
865
+ raise NumpyTypeError("Not a numpy array.")
866
+
867
+ if not dtype(value.dtype):
868
+ msg = (
869
+ "Not a numpy dtype match; "
870
+ f"got {dtype_name(value.dtype)}, required {dtype.expected()}"
871
+ )
872
+ raise NumpyTypeError(msg)
873
+
874
+ if not shape(value):
875
+ msg = f"Not a numpy shape match: got {value.shape}, expected {shape.expected()}"
876
+ raise NumpyTypeError(msg)
877
+
878
+
879
+ # console decorations
880
+
881
+
882
+ def progress(percent: float, length: int = 20) -> str:
883
+ """Creates a progress bar string."""
884
+ if length < 1:
885
+ raise ValueError("progress bar length cannot be less than 1")
886
+ p = max(0.0, min(percent, 1.0))
887
+ n = floor(length * p)
888
+ bar = ("#" * n) + (" " * (length - n))
889
+ return f"|{bar}| {(100 * p):.0f}% "
890
+
891
+
892
+ # pub-sub events
893
+
894
+
895
+ class Event(Generic[T]):
896
+ """A typed pub-sub event."""
897
+
898
+ _subscribers: list[Callable[[T], None]]
899
+
900
+ def __init__(self):
901
+ self._subscribers = []
902
+
903
+ def subscribe(self, sub: Callable[[T], None]) -> Callable[[], None]:
904
+ """Subscribe a handler to this event. Returns an unsubscribe function."""
905
+ self._subscribers.append(sub)
906
+
907
+ def unsubscribe() -> None:
908
+ self._subscribers.remove(sub)
909
+
910
+ return unsubscribe
911
+
912
+ def publish(self, event: T) -> None:
913
+ """Publish an event occurrence to all current subscribers."""
914
+ for subscriber in self._subscribers:
915
+ subscriber(event)
916
+
917
+ @property
918
+ def has_subscribers(self) -> bool:
919
+ """True if at least one listener is subscribed to this event."""
920
+ return len(self._subscribers) > 0
921
+
922
+
923
+ class Subscriber:
924
+ """
925
+ Utility class to track a list of subscriptions for ease of unsubscription.
926
+ Consider using this via the `subscriptions()` context.
927
+ """
928
+
929
+ _unsubscribers: list[Callable[[], None]]
930
+
931
+ def __init__(self):
932
+ self._unsubscribers = []
933
+
934
+ def subscribe(self, event: Event[T], handler: Callable[[T], None]) -> None:
935
+ """Subscribe through this Subscriber to the given event."""
936
+ unsub = event.subscribe(handler)
937
+ self._unsubscribers.append(unsub)
938
+
939
+ def unsubscribe(self) -> None:
940
+ """Unsubscribe from all of this Subscriber's subscriptions."""
941
+ for unsub in self._unsubscribers:
942
+ unsub()
943
+ self._unsubscribers.clear()
944
+
945
+
946
+ @contextmanager
947
+ def subscriptions() -> Generator[Subscriber, None, None]:
948
+ """
949
+ Manage a subscription context, where all subscriptions added through the returned
950
+ Subscriber will be automatically unsubscribed when the context closes.
951
+ """
952
+ sub = Subscriber()
953
+ try:
954
+ yield sub
955
+ finally:
956
+ sub.unsubscribe()
957
+
958
+
959
+ # singletons
960
+
961
+ SingletonT = TypeVar("SingletonT", bound="Singleton")
962
+
963
+
964
+ class Singleton(type):
965
+ """A metaclass for classes you want to treat as singletons."""
966
+
967
+ _instances = {}
968
+
969
+ def __call__(cls, *args, **kwargs):
970
+ if cls not in cls._instances:
971
+ cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
972
+ return cls._instances[cls]
973
+
974
+
975
+ # string builders
976
+
977
+
978
+ class StringBuilder:
979
+ _lines: list[str]
980
+ _indent: str
981
+
982
+ def __init__(self, indent: str = ""):
983
+ self._lines = []
984
+ self._indent = indent
985
+
986
+ def line(self, line: str = "") -> Self:
987
+ self._lines.append(line)
988
+ return self
989
+
990
+ def line_if(self, condition: bool, line: str = "") -> Self:
991
+ if condition:
992
+ self._lines.append(line)
993
+ return self
994
+
995
+ def lines(self, lines: Iterable[str]) -> Self:
996
+ self._lines.extend(lines)
997
+ return self
998
+
999
+ @contextmanager
1000
+ def block(
1001
+ self,
1002
+ indent: str = " ",
1003
+ *,
1004
+ opener: str | None = None,
1005
+ closer: str | None = None,
1006
+ ) -> Generator["StringBuilder", None, None]:
1007
+ if opener is not None:
1008
+ # opener is printed at the parent's indent level
1009
+ self.line(opener)
1010
+
1011
+ new_indent = f"{self._indent}{indent}"
1012
+ s = StringBuilder(new_indent)
1013
+ yield s
1014
+ self._lines.extend((f"{new_indent}{line}" for line in s.to_lines()))
1015
+
1016
+ if closer is not None:
1017
+ # closer is printed at the parent's indent level
1018
+ self.line(closer)
1019
+
1020
+ def build(self) -> str:
1021
+ return "\n".join(self._lines)
1022
+
1023
+ def to_lines(self) -> Iterable[str]:
1024
+ return self._lines
1025
+
1026
+
1027
+ @contextmanager
1028
+ def string_builder(
1029
+ indent: str = "", *, opener: str | None = None, closer: str | None = None
1030
+ ) -> Generator[StringBuilder, None, None]:
1031
+ s = StringBuilder(indent)
1032
+ if opener is not None:
1033
+ s.line(opener)
1034
+ yield s
1035
+ if closer is not None:
1036
+ s.line(closer)