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/time.py ADDED
@@ -0,0 +1,1197 @@
1
+ """Modeling time in epymorph."""
2
+
3
+ # ruff: noqa: A005
4
+ from abc import ABC, abstractmethod
5
+ from dataclasses import dataclass, field
6
+ from datetime import date, timedelta
7
+ from typing import Generic, Iterator, Literal, NamedTuple, Self, TypeVar
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from numpy.typing import NDArray
12
+ from typing_extensions import override
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class DateRange:
17
+ """
18
+ A sequence of calendar dates, with a fixed interval between dates (default 1 day).
19
+
20
+ Parameters
21
+ ----------
22
+ start_date :
23
+ The first date in the range.
24
+ end_date :
25
+ The last date in the range. Must be an exact multiple of steps after start_date.
26
+ step :
27
+ The step between dates in the range, as a number of days. Must be 1 or greater.
28
+ """
29
+
30
+ start_date: date
31
+ """The first date in the range."""
32
+ end_date: date
33
+ """The last date in the range."""
34
+ step: int = field(default=1)
35
+ """The step between dates in the range, as a number of days."""
36
+
37
+ @classmethod
38
+ def until_date(cls, start_date: date, max_end_date: date, step: int) -> Self:
39
+ """
40
+ Alternative constructor for cases where you aren't sure of the precise end
41
+ date: that is, you know roughly when the range ends but aren't sure if that
42
+ date is an exact number of steps after start date.
43
+
44
+ Parameters
45
+ ----------
46
+ start_date :
47
+ The first date in the range.
48
+ max_end_date :
49
+ The latest possible date in the range. If `max_end_date` is already an exact
50
+ multiple of steps away from `start_date`, it will be the `DateRange`'s end
51
+ date. Otherwise, we will calculate the latest date that is before
52
+ `max_end_date` and also an exact multiple of steps after start date.
53
+ step :
54
+ The interval between dates in the range, as a number of days.
55
+ Must be 1 or greater.
56
+
57
+ Returns
58
+ -------
59
+ :
60
+ A new `DateRange`.
61
+ """
62
+ diff = (max_end_date - start_date).days % step
63
+ end_date = max_end_date - timedelta(days=diff)
64
+ return cls(start_date, end_date, step)
65
+
66
+ def __post_init__(self):
67
+ if self.start_date > self.end_date:
68
+ raise ValueError("`start_date` must be before or equal to `end_date`")
69
+ if self.step < 1:
70
+ raise ValueError("`step` must be 1 or greater")
71
+ if (self.end_date - self.start_date).days % self.step != 0:
72
+ err = "`end_date` must be a multiple of `step` days from `start_date`"
73
+ raise ValueError(err)
74
+
75
+ def _next_date(self, from_date: date) -> date | None:
76
+ """
77
+ If `from_date` is in the range, return it.
78
+ Otherwise return the next date that is in the range.
79
+ Returns `None` if no date satisfies these conditions.
80
+ """
81
+ s = self.step
82
+ diff = (s - (from_date - self.start_date).days % s) % s
83
+ result = max(self.start_date, from_date + timedelta(days=diff))
84
+ return result if result <= self.end_date else None
85
+
86
+ def _prev_date(self, from_date: date) -> date | None:
87
+ """
88
+ If `from_date` is in the range, return it.
89
+ Otherwise return the most recent date that is in the range.
90
+ Returns `None` if no date satisfies these conditions.
91
+ """
92
+ diff = (from_date - self.start_date).days % self.step
93
+ result = min(self.end_date, from_date - timedelta(days=diff))
94
+ return result if result >= self.start_date else None
95
+
96
+ def between(self, min_date: date, max_date: date) -> "DateRange | None":
97
+ """
98
+ Compute a new `DateRange` that represents the subset of dates in this range
99
+ that are also between `min_date` and `max_date` (inclusive).
100
+
101
+ Parameters
102
+ ----------
103
+ min_date :
104
+ The earliest date to include in the subset.
105
+ max_date :
106
+ The latest date to include in the subset.
107
+
108
+ Returns
109
+ -------
110
+ :
111
+ The subset `DateRange`, or `None` if that subset would be empty -- when
112
+ there's no overlap between this range and the min/max dates.
113
+ """
114
+ if min_date > max_date:
115
+ raise ValueError("`min_date` must be before or equal to `max_date`")
116
+ new_start_date = self._next_date(min_date)
117
+ new_end_date = self._prev_date(max_date)
118
+ if (
119
+ new_start_date is None
120
+ or new_end_date is None
121
+ or new_start_date > new_end_date
122
+ ):
123
+ return None
124
+ return DateRange(new_start_date, new_end_date, self.step)
125
+
126
+ def overlap(self, time_frame: "TimeFrame") -> "DateRange | None":
127
+ """
128
+ Compute a new `DateRange` that represents the subset of dates in this range
129
+ that are also in the given TimeFrame.
130
+
131
+ Parameters
132
+ ----------
133
+ time_frame :
134
+ The time frame to overlap.
135
+
136
+ Returns
137
+ -------
138
+ :
139
+ The subset DateRange, or None if that subset would be empty -- when there's
140
+ no overlap between this DateRange and the time frame.
141
+ """
142
+ return self.between(time_frame.start_date, time_frame.end_date)
143
+
144
+ def overlap_or_raise(self, time_frame: "TimeFrame") -> "DateRange":
145
+ """
146
+ Compute a new `DateRange` that represents the subset of dates in this range
147
+ that are also in the given `TimeFrame`. If there is no overlap, raise an error.
148
+
149
+ Parameters
150
+ ----------
151
+ time_frame :
152
+ The time frame to overlap.
153
+
154
+ Returns
155
+ -------
156
+ :
157
+ The subset `DateRange`.
158
+
159
+ Raises
160
+ ------
161
+ ValueError
162
+ When there's no overlap between this `DateRange` and the time frame.
163
+ """
164
+ if (date_range := self.overlap(time_frame)) is None:
165
+ err = "There is no overlap between the date range and time frame."
166
+ raise ValueError(err)
167
+ return date_range
168
+
169
+ def __len__(self) -> int:
170
+ delta_days = (self.end_date - self.start_date).days
171
+ return (delta_days // self.step) + 1
172
+
173
+ def to_pandas(self) -> pd.DatetimeIndex:
174
+ """
175
+ Convert the `DateRange` to a Pandas datetime index.
176
+
177
+ Returns
178
+ -------
179
+ :
180
+ The index containing all dates in the range in order.
181
+ """
182
+ return pd.date_range(
183
+ start=self.start_date,
184
+ end=self.end_date,
185
+ freq=timedelta(days=self.step),
186
+ inclusive="both",
187
+ )
188
+
189
+ def to_numpy(self) -> NDArray[np.datetime64]:
190
+ """
191
+ Convert the `DateRange` to a numpy datetime64 array.
192
+
193
+ Returns
194
+ -------
195
+ :
196
+ The one-dimensional array containing all dates in the range in order.
197
+ """
198
+ step = timedelta(days=self.step)
199
+ return np.arange(
200
+ start=self.start_date,
201
+ stop=self.end_date + step,
202
+ step=step,
203
+ dtype="datetime64[D]",
204
+ )
205
+
206
+
207
+ def iso8601(value: date | str) -> date:
208
+ """
209
+ Adapt ISO 8601 strings to dates; leave dates as they are.
210
+
211
+ Parameters
212
+ ----------
213
+ value :
214
+ The value to parse (if string) or pass through unchanged (if date).
215
+
216
+ Returns
217
+ -------
218
+ :
219
+ The equivalent date.
220
+ """
221
+ if isinstance(value, date):
222
+ return value
223
+ return date.fromisoformat(value)
224
+
225
+
226
+ @dataclass(frozen=True)
227
+ class TimeFrame:
228
+ """
229
+ Describes a time frame as a contiguous set of calendar dates,
230
+ primarily used to define the time frame of a simulation.
231
+
232
+ Parameters
233
+ ----------
234
+ start_date :
235
+ The first date included in the time frame.
236
+ duration_days :
237
+ The number of days included in the time frame.
238
+
239
+ Examples
240
+ --------
241
+ --8<-- "docs/_examples/time_TimeFrame.md"
242
+ """
243
+
244
+ @classmethod
245
+ def of(cls, start_date: date | str, duration_days: int) -> Self:
246
+ """
247
+ Alternate constructor: start date (accepts ISO-8601 strings)
248
+ and a given duration in days.
249
+
250
+ Parameters
251
+ ----------
252
+ start_date :
253
+ The starting date.
254
+ If a date is passed as a string, it will be parsed using ISO-8601 format.
255
+ duration_days :
256
+ The number of days in the time frame, including the first day.
257
+
258
+ Returns
259
+ -------
260
+ :
261
+ The new `TimeFrame`.
262
+ """
263
+ start_date = iso8601(start_date)
264
+ return cls(start_date, duration_days)
265
+
266
+ @classmethod
267
+ def range(cls, start_date: date | str, end_date: date | str) -> Self:
268
+ """
269
+ Alternate constructor: start and end date (inclusive).
270
+
271
+ Parameters
272
+ ----------
273
+ start_date :
274
+ The starting date.
275
+ If a date is passed as a string, it will be parsed using ISO-8601 format.
276
+ end_date :
277
+ The final date included in the time frame.
278
+ If a date is passed as a string, it will be parsed using ISO-8601 format.
279
+
280
+ Returns
281
+ -------
282
+ :
283
+ The new `TimeFrame`.
284
+ """
285
+ start_date = iso8601(start_date)
286
+ end_date = iso8601(end_date)
287
+ duration = (end_date - start_date).days + 1
288
+ return cls(start_date, duration)
289
+
290
+ @classmethod
291
+ def rangex(cls, start_date: date | str, end_date_exclusive: date | str) -> Self:
292
+ """
293
+ Alternate constructor: start and end date (exclusive).
294
+
295
+ Parameters
296
+ ----------
297
+ start_date :
298
+ The starting date.
299
+ If a date is passed as a string, it will be parsed using ISO-8601 format.
300
+ end_date_exclusive :
301
+ The stop date, which is to say the first date not in the time frame.
302
+ If a date is passed as a string, it will be parsed using ISO-8601 format.
303
+
304
+ Returns
305
+ -------
306
+ :
307
+ The new `TimeFrame`.
308
+ """
309
+ start_date = iso8601(start_date)
310
+ end_date_exclusive = iso8601(end_date_exclusive)
311
+ duration = (end_date_exclusive - start_date).days
312
+ return cls(start_date, duration)
313
+
314
+ @classmethod
315
+ def year(cls, year: int) -> Self:
316
+ """
317
+ Alternate constructor: an entire calendar year.
318
+
319
+ Parameters
320
+ ----------
321
+ year :
322
+ The year of the time frame, from January 1st through December 31st.
323
+ Includes 365 days, or 366 days on a leap year.
324
+
325
+ Returns
326
+ -------
327
+ :
328
+ The new `TimeFrame`.
329
+ """
330
+ return cls.rangex(date(year, 1, 1), date(year + 1, 1, 1))
331
+
332
+ start_date: date
333
+ """The first date in the time frame."""
334
+ duration_days: int
335
+ """The number of days included in the time frame."""
336
+ end_date: date = field(init=False)
337
+ """The last date included in the time frame."""
338
+
339
+ def __post_init__(self):
340
+ if self.duration_days < 1:
341
+ err = (
342
+ "TimeFrame's end date cannot be before its start date. "
343
+ "(Its duration in days must be at least 1.)"
344
+ )
345
+ raise ValueError(err)
346
+ end_date = self.start_date + timedelta(days=self.duration_days - 1)
347
+ object.__setattr__(self, "end_date", end_date)
348
+
349
+ def is_subset(self, other: "TimeFrame") -> bool:
350
+ """
351
+ Check if the given `TimeFrame` is a subset of this one.
352
+
353
+ Parameters
354
+ ----------
355
+ other :
356
+ The other time frame to consider.
357
+
358
+ Returns
359
+ -------
360
+ :
361
+ True if the other time frame is a subset of this time frame.
362
+ """
363
+ return self.start_date <= other.start_date and self.end_date >= other.end_date
364
+
365
+ @property
366
+ def days(self) -> int:
367
+ """
368
+ The number of days included in the time frame.
369
+
370
+ Alias for `duration_days`.
371
+ """
372
+ return self.duration_days
373
+
374
+ def __iter__(self) -> Iterator[date]:
375
+ """Iterate over the sequence of dates in the time frame."""
376
+ step = timedelta(days=1)
377
+ curr = self.start_date
378
+ for _ in range(self.duration_days):
379
+ yield curr
380
+ curr += step
381
+
382
+ def __str__(self) -> str:
383
+ if self.duration_days == 1:
384
+ return f"{self.start_date} (1D)"
385
+ return f"{self.start_date}/{self.end_date} ({self.duration_days}D)"
386
+
387
+ def to_numpy(self) -> NDArray[np.datetime64]:
388
+ """
389
+ Return a numpy array of the dates in this time frame.
390
+
391
+ Returns
392
+ -------
393
+ :
394
+ The equivalent numpy array.
395
+ """
396
+ return np.array(list(self), dtype=np.datetime64)
397
+
398
+ def to_date_range(self) -> DateRange:
399
+ """
400
+ Return a date range that corresponds to this time frame's
401
+ start and end date.
402
+
403
+ Returns
404
+ -------
405
+ :
406
+ A matching date range.
407
+ """
408
+ return DateRange(
409
+ start_date=self.start_date,
410
+ end_date=self.end_date,
411
+ )
412
+
413
+ @property
414
+ def select(self) -> "TimeSelector":
415
+ """
416
+ Create a time-axis strategy from this time frame.
417
+
418
+ In most cases, this will be used to process a simulation result
419
+ and so you should use a selection on the time frame used in the
420
+ RUME that produced the result.
421
+ """
422
+ return TimeSelector(self)
423
+
424
+
425
+ #############
426
+ # Epi Weeks #
427
+ #############
428
+
429
+
430
+ class EpiWeek(NamedTuple):
431
+ """
432
+ Identifies a specific epi week, a CDC-defined system for labeling weeks of the year
433
+ in a consistent way.
434
+
435
+ See Also
436
+ --------
437
+ [This reference on epi weeks.](https://www.cmmcp.org/mosquito-surveillance-data/pages/epi-week-calendars-2008-2024)
438
+ """
439
+
440
+ year: int
441
+ """Four-digit year"""
442
+ week: int
443
+ """Week number, in the range [1,53]"""
444
+
445
+ def __str__(self) -> str:
446
+ return f"{self.year}-{self.week}"
447
+
448
+ @property
449
+ def start(self) -> pd.Timestamp:
450
+ """The first date in this epi week."""
451
+ day1 = epi_year_first_day(self.year)
452
+ return day1 + pd.offsets.Week(n=self.week - 1)
453
+
454
+
455
+ def epi_year_first_day(year: int) -> pd.Timestamp:
456
+ """
457
+ Calculate the first day in an epi-year.
458
+
459
+ Parameters
460
+ ----------
461
+ year :
462
+ The year to consider.
463
+
464
+ Returns
465
+ -------
466
+ :
467
+ The first day of the first epi week in the given year.
468
+ """
469
+ first_saturday = pd.Timestamp(year, 1, 1) + pd.offsets.Week(weekday=5)
470
+ if first_saturday.day < 4:
471
+ first_saturday = first_saturday + pd.offsets.Week(weekday=5)
472
+ first_epi_day = first_saturday - pd.offsets.Week(weekday=6)
473
+ return first_epi_day
474
+
475
+
476
+ def epi_week(check_date: date) -> EpiWeek:
477
+ """
478
+ Calculate which epi week the given date belongs to.
479
+
480
+ Parameters
481
+ ----------
482
+ check_date :
483
+ The date to consider.
484
+
485
+ Returns
486
+ -------
487
+ :
488
+ The `EpiWeek` that contains the given date.
489
+ """
490
+ d = pd.Timestamp(check_date.year, check_date.month, check_date.day)
491
+ last_year_day1 = epi_year_first_day(d.year - 1)
492
+ this_year_day1 = epi_year_first_day(d.year)
493
+ next_year_day1 = epi_year_first_day(d.year + 1)
494
+ if d < this_year_day1:
495
+ # in last years' epi weeks
496
+ origin = last_year_day1
497
+ year = d.year - 1
498
+ elif d >= next_year_day1:
499
+ # in next years' epi weeks
500
+ origin = next_year_day1
501
+ year = d.year + 1
502
+ else:
503
+ # in this years' epi weeks
504
+ origin = this_year_day1
505
+ year = d.year
506
+ return EpiWeek(year, (d - origin).days // 7 + 1)
507
+
508
+
509
+ #####################################
510
+ # Time frame select/group/aggregate #
511
+ #####################################
512
+
513
+
514
+ GroupKeyType = TypeVar("GroupKeyType", bound=np.generic)
515
+ """The numpy type used to represent the group keys of a `TimeGrouping`."""
516
+
517
+
518
+ class Dim(NamedTuple):
519
+ """
520
+ Describes data dimensions for a time-grouping operation;
521
+ i.e., after subselections and geo-grouping.
522
+ """
523
+
524
+ nodes: int
525
+ """The number of unique nodes or node-groups."""
526
+ days: int
527
+ """The number of days, after any sub-selection."""
528
+ tau_steps: int
529
+ """The number of tau steps per day."""
530
+
531
+
532
+ class TimeGrouping(ABC, Generic[GroupKeyType]):
533
+ """
534
+ Base class for time-axis grouping schemes. This is essentially a function that maps
535
+ the simulation time axis info (ticks and dates) into a new series which describes
536
+ the group membership of each time axis row.
537
+
538
+ TimeGrouping is generic in the type of the key it uses for its
539
+ time groups (`GroupKeyType`) -- e.g., a grouping that groups weeks
540
+ using the Monday of the week is datetime64 typed, while a grouping that groups
541
+ days into arbitrary buckets might use integers to identify groups.
542
+ """
543
+
544
+ group_format: Literal["date", "tick", "day", "other"]
545
+ """
546
+ What scale describes the result of the grouping?
547
+ Are the group keys dates? Simulation ticks? Simulation days?
548
+ Or some arbitrary other type?
549
+ """
550
+
551
+ @abstractmethod
552
+ def map(
553
+ self,
554
+ dim: Dim,
555
+ ticks: NDArray[np.int64],
556
+ dates: NDArray[np.datetime64],
557
+ ) -> NDArray[GroupKeyType]:
558
+ """
559
+ Produce a column that describes the group membership of each "row",
560
+ where each entry of `ticks` and `dates` describes a row of the time series.
561
+ This column will be used as the basis of a `groupby` operation.
562
+
563
+ The result must correspond element-wise to the given `ticks` and `dates` arrays.
564
+ `dim` contains dimensional info relevant to this grouping operation.
565
+ Note that we may have sub-selected the geo and/or the time frame, so these
566
+ dimensions may differ from those of the simulation as a whole.
567
+
568
+ `ticks` and `dates` will be `nodes * days * tau_steps` in length.
569
+ Values will be in order, but each tick will be represented `nodes` times,
570
+ and each date will be represented `nodes * tau_steps` times.
571
+ Since we may be grouping a slice of the simulation time frame, ticks may start
572
+ after 0 and end before the last tick of the simulation.
573
+
574
+ Parameters
575
+ ----------
576
+ dim :
577
+ The simulation dimensions for time grouping.
578
+ ticks :
579
+ The series of simulation ticks.
580
+ dates :
581
+ The series of calendar dates corresponding to simulation ticks.
582
+
583
+ Returns
584
+ -------
585
+ :
586
+ The group membership of each tick. For example, if the first three
587
+ ticks were in group 0 and the next three ticks were in group 1, etc.,
588
+ the returned array would contain `[0,0,0,1,1,1,...]`.
589
+ """
590
+
591
+
592
+ class ByTick(TimeGrouping[np.int64]):
593
+ """
594
+ A kind of `TimeGrouping` to group by simulation tick.
595
+ Effectively the same as no grouping.
596
+ """
597
+
598
+ group_format = "tick"
599
+
600
+ @override
601
+ def map(self, dim, ticks, dates):
602
+ return ticks
603
+
604
+
605
+ class ByDate(TimeGrouping[np.datetime64]):
606
+ """A kind of `TimeGrouping` to group by date."""
607
+
608
+ group_format = "date"
609
+
610
+ @override
611
+ def map(self, dim, ticks, dates):
612
+ return dates
613
+
614
+
615
+ class ByWeek(TimeGrouping[np.datetime64]):
616
+ """
617
+ A kind of `TimeGrouping` to group by week, using a configurable start of the week.
618
+
619
+ Parameters
620
+ ----------
621
+ start_of_week :
622
+ Which day of the week is the begins each weekly group?
623
+ This uses the Python standard numbering for week days,
624
+ so 0=Monday and 6=Sunday.
625
+ """
626
+
627
+ _NP_START_OF_WEEK: int = 3
628
+ """Numpy starts its weeks on Thursday, because the unix epoch 0
629
+ is on a Thursday."""
630
+
631
+ group_format = "date"
632
+
633
+ start_of_week: int
634
+ """Which day of the week should we group on? 0=Monday through 6=Sunday"""
635
+
636
+ def __init__(self, start_of_week: int = 0):
637
+ if not (0 <= start_of_week <= 6):
638
+ raise ValueError("Invalid day of the week.")
639
+ self.start_of_week = start_of_week
640
+
641
+ @override
642
+ def map(self, dim, ticks, dates) -> NDArray[np.datetime64]:
643
+ delta = ByWeek._NP_START_OF_WEEK - self.start_of_week
644
+ result = (dates + delta).astype("datetime64[W]").astype("datetime64[D]") - delta
645
+ return result # type: ignore
646
+
647
+
648
+ class ByMonth(TimeGrouping[np.datetime64]):
649
+ """A kind `TimeGrouping` to group by month, using the first day of the month."""
650
+
651
+ group_format = "date"
652
+
653
+ @override
654
+ def map(self, dim, ticks, dates):
655
+ return dates.astype("datetime64[M]").astype("datetime64[D]")
656
+
657
+
658
+ class EveryNDays(TimeGrouping[np.datetime64]):
659
+ """
660
+ A kind of `TimeGrouping` to group every 'n' days from the start of the time range.
661
+
662
+ Parameters
663
+ ----------
664
+ days :
665
+ How many days should be in each group?
666
+ """
667
+
668
+ group_format = "date"
669
+
670
+ days: int
671
+ """How many days are in each group?"""
672
+
673
+ def __init__(self, days: int):
674
+ self.days = days
675
+
676
+ @override
677
+ def map(self, dim, ticks, dates):
678
+ n = self.days * dim.tau_steps * dim.nodes
679
+ # careful we don't return too many date values
680
+ return (dates[::n].repeat(n))[0 : len(dates)]
681
+
682
+
683
+ class NBins(TimeGrouping[np.int64]):
684
+ """
685
+ A kind of `TimeGrouping` to group the time series into a number of bins
686
+ where bin boundaries must align with simulation days.
687
+
688
+ If the time series is not evenly divisible into the given number of bins,
689
+ you may get more bins than requested (data will not be truncated).
690
+ You will never get more than one bin per day.
691
+
692
+ Parameters
693
+ ----------
694
+ bins :
695
+ Approximately how many bins should be in the result?
696
+ """
697
+
698
+ group_format = "other"
699
+
700
+ bins: int
701
+ """Approximately how many bins should be in the result?"""
702
+
703
+ def __init__(self, bins: int):
704
+ self.bins = bins
705
+
706
+ @override
707
+ def map(self, dim, ticks, dates):
708
+ bin_size = max(1, dim.days // self.bins) * dim.tau_steps
709
+ return (ticks - ticks[0]) // bin_size
710
+
711
+
712
+ class ByEpiWeek(TimeGrouping[np.str_]):
713
+ """A kind of `TimeGrouping` to group the time series by epi week."""
714
+
715
+ group_format = "other"
716
+
717
+ @override
718
+ def map(self, dim, ticks, dates):
719
+ return np.array([str(epi_week(d.astype(date))) for d in dates], dtype=np.str_)
720
+
721
+
722
+ AggMethod = Literal["sum", "max", "min", "mean", "median", "last", "first"]
723
+ """A method for aggregating time series data."""
724
+
725
+
726
+ class TimeAggMethod(NamedTuple):
727
+ """
728
+ A time-axis aggregation scheme. There may be one aggregation method for
729
+ compartments and another for events.
730
+ """
731
+
732
+ compartments: AggMethod
733
+ """The method for aggregating compartment values."""
734
+ events: AggMethod
735
+ """The method for aggregating event values."""
736
+
737
+
738
+ DEFAULT_TIME_AGG = TimeAggMethod("last", "sum")
739
+ """By default, time series should be aggregated using 'last' for compartments
740
+ and 'sum' for events."""
741
+
742
+
743
+ @dataclass(frozen=True)
744
+ class TimeStrategy:
745
+ """
746
+ A strategy for dealing with the time axis, e.g., in processing results.
747
+ Strategies can include selection of a subset, grouping, and aggregation.
748
+
749
+ Typically you will create one of these by calling methods on a
750
+ `TimeSelector` instance.
751
+
752
+ Parameters
753
+ ----------
754
+ time_frame :
755
+ The original simulation time frame.
756
+ selection :
757
+ The selected subset of the time frame: described as a date slice
758
+ and an optional tau step index.
759
+ grouping :
760
+ A method for grouping the time series data.
761
+ aggregation :
762
+ A method for aggregating the time series data
763
+ (if no grouping is specified, the time series is reduced to a scalar).
764
+ """
765
+
766
+ time_frame: TimeFrame
767
+ """The original time frame."""
768
+ selection: tuple[slice, int | None]
769
+ """The selected subset of the time frame: described as a date slice
770
+ and an optional tau step index."""
771
+ grouping: TimeGrouping | None
772
+ """A method for grouping the time series data."""
773
+ aggregation: TimeAggMethod | None
774
+ """
775
+ A method for aggregating the time series data
776
+ (if no grouping is specified, the time series is reduced to a scalar).
777
+ """
778
+
779
+ @property
780
+ @abstractmethod
781
+ def group_format(self) -> Literal["date", "tick", "day", "other"]:
782
+ """
783
+ The scale that describes the result of the grouping.
784
+
785
+ Are the group keys dates? Simulation ticks? Simulation days?
786
+ Or some arbitrary other type?
787
+ """
788
+
789
+ @property
790
+ def date_bounds(self) -> tuple[date, date]:
791
+ """The bounds of the selection, given as the first and last date included."""
792
+ date_slice, _ = self.selection
793
+ start = date_slice.start or 0
794
+ stop = date_slice.stop or self.time_frame.duration_days
795
+ first_date = self.time_frame.start_date + timedelta(days=start)
796
+ last_date = self.time_frame.start_date + timedelta(days=stop - 1)
797
+ return (first_date, last_date)
798
+
799
+ def to_time_frame(self) -> TimeFrame:
800
+ """
801
+ Create a `TimeFrame` that has the same bounds as this `TimeStrategy`.
802
+
803
+ NOTE: this does not mean the `TimeFrame` contains the same number of entries
804
+ (group keys) as the result of applying this strategy -- groups can skip days
805
+ whereas `TimeFrames` are contiguous.
806
+
807
+ Returns
808
+ -------
809
+ :
810
+ The corresponding time frame.
811
+ """
812
+ first, last = self.date_bounds
813
+ return TimeFrame.range(first, last)
814
+
815
+ def selection_ticks(self, taus: int) -> slice:
816
+ """
817
+ Convert this into a slice for which ticks are selected (by index).
818
+
819
+ Parameters
820
+ ----------
821
+ taus :
822
+ The total number of tau steps per day.
823
+
824
+ Returns
825
+ -------
826
+ :
827
+ The selection as an index slice.
828
+ """
829
+ day, tau_step = self.selection
830
+ if tau_step is not None and tau_step >= taus:
831
+ err = (
832
+ "Invalid time-axis tau step selection: this model has "
833
+ f"{taus} tau steps but you selected step index {tau_step} "
834
+ "which is out of range."
835
+ )
836
+ raise ValueError(err)
837
+ # There are two cases:
838
+ if tau_step is not None:
839
+ # If tau_step is specified, we want to select only the ticks
840
+ # in the date range which correspond to that tau step.
841
+ start = taus * (day.start or 0) + tau_step
842
+ stop = None if day.stop is None else taus * day.stop + tau_step
843
+ step = taus
844
+ return slice(start, stop, step)
845
+ else:
846
+ # If tau_step is None, then we will select every tau step
847
+ # in the date range.
848
+ # This implies it is not possible to "step" over days --
849
+ # the time series must be contiguous w.r.t. simulation days.
850
+ return slice(
851
+ None if day.start is None else day.start * taus,
852
+ None if day.stop is None else day.stop * taus,
853
+ # day.step is ignored if it is present
854
+ )
855
+
856
+
857
+ class _CanAggregate(TimeStrategy):
858
+ def agg(
859
+ self,
860
+ compartments: AggMethod = "last",
861
+ events: AggMethod = "sum",
862
+ ) -> "TimeAggregation":
863
+ """
864
+ Aggregate the time series using the specified methods.
865
+
866
+ Parameters
867
+ ----------
868
+ compartments :
869
+ The method to use to aggregate compartment values.
870
+ events :
871
+ The method to use to aggregate event values.
872
+
873
+ Returns
874
+ -------
875
+ :
876
+ The aggregation strategy object.
877
+ """
878
+ return TimeAggregation(
879
+ self.time_frame,
880
+ self.selection,
881
+ self.grouping,
882
+ TimeAggMethod(compartments, events),
883
+ )
884
+
885
+
886
+ @dataclass(frozen=True)
887
+ class TimeSelection(_CanAggregate, TimeStrategy):
888
+ """
889
+ A kind of `TimeStrategy` describing a sub-selection of a time frame.
890
+ A selection performs no grouping or aggregation.
891
+
892
+ Typically you will create one of these by calling methods on a
893
+ `TimeSelector` instance.
894
+
895
+ Parameters
896
+ ----------
897
+ time_frame :
898
+ The original simulation time frame.
899
+ selection :
900
+ The selected subset of the time frame: described as a date slice
901
+ and an optional tau step index.
902
+ """
903
+
904
+ time_frame: TimeFrame
905
+ """The original time frame."""
906
+ selection: tuple[slice, int | None]
907
+ """
908
+ The selected subset of the time frame: described as a date slice
909
+ and an optional tau step index.
910
+ """
911
+ grouping: None = field(init=False, default=None)
912
+ """A method for grouping the time series data."""
913
+ aggregation: None = field(init=False, default=None)
914
+ """
915
+ A method for aggregating the time series data
916
+ (if no grouping is specified, the time series is reduced to a scalar).
917
+ """
918
+
919
+ @property
920
+ @override
921
+ def group_format(self) -> Literal["tick"]:
922
+ return "tick"
923
+
924
+ def group(
925
+ self,
926
+ grouping: Literal["day", "week", "epiweek", "month"] | TimeGrouping,
927
+ ) -> "TimeGroup":
928
+ """
929
+ Group the time series using the specified grouping.
930
+
931
+ Parameters
932
+ ----------
933
+ grouping :
934
+ The grouping to use. You can specify a supported string value --
935
+ all of which act as shortcuts for common `TimeGrouping` instances --
936
+ or you can provide a `TimeGrouping` instance to perform custom grouping.
937
+
938
+ The shortcut values are:
939
+
940
+ - "day": equivalent to `ByDate`
941
+ - "week": equivalent to `ByWeek`
942
+ - "epiweek": equivalent to `ByEpiWeek`
943
+ - "month": equivalent to `ByMonth`
944
+
945
+ Returns
946
+ -------
947
+ :
948
+ The grouping strategy.
949
+ """
950
+ match grouping:
951
+ # String-based short-cuts:
952
+ case "day":
953
+ grouping = ByDate()
954
+ case "week":
955
+ grouping = ByWeek()
956
+ case "epiweek":
957
+ grouping = ByEpiWeek()
958
+ case "month":
959
+ grouping = ByMonth()
960
+ # Otherwise grouping is a TimeGrouping instance
961
+ case _:
962
+ pass
963
+ return TimeGroup(self.time_frame, self.selection, grouping)
964
+
965
+
966
+ @dataclass(frozen=True)
967
+ class TimeGroup(_CanAggregate, TimeStrategy):
968
+ """
969
+ A kind of `TimeStrategy` describing a group operation on a time frame,
970
+ with an optional sub-selection.
971
+
972
+ Typically you will create one of these by calling methods on a
973
+ `TimeSelection` instance.
974
+
975
+ Parameters
976
+ ----------
977
+ time_frame :
978
+ The original simulation time frame.
979
+ selection :
980
+ The selected subset of the time frame: described as a date slice
981
+ and an optional tau step index.
982
+ grouping :
983
+ A method for grouping the time series data.
984
+ """
985
+
986
+ time_frame: TimeFrame
987
+ """The original time frame."""
988
+ selection: tuple[slice, int | None]
989
+ """
990
+ The selected subset of the time frame: described as a date slice
991
+ and an optional tau step index.
992
+ """
993
+ grouping: TimeGrouping
994
+ """A method for grouping the time series data."""
995
+ aggregation: None = field(init=False, default=None)
996
+ """
997
+ A method for aggregating the time series data
998
+ (if no grouping is specified, the time series is reduced to a scalar).
999
+ """
1000
+
1001
+ @property
1002
+ @override
1003
+ def group_format(self):
1004
+ return self.grouping.group_format
1005
+
1006
+
1007
+ @dataclass(frozen=True)
1008
+ class TimeAggregation(TimeStrategy):
1009
+ """
1010
+ A kind of `TimeStrategy` describing a group-and-aggregate operation on a time frame,
1011
+ with an optional sub-selection.
1012
+
1013
+ Typically you will create one of these by calling methods on a
1014
+ `TimeSelection` or `TimeGroup` instance.
1015
+
1016
+ Parameters
1017
+ ----------
1018
+ time_frame: TimeFrame
1019
+ The original simulation time frame.
1020
+ selection: tuple[slice, int | None]
1021
+ The selected subset of the time frame: described as a date slice
1022
+ and an optional tau step index.
1023
+ grouping: TimeGrouping | None
1024
+ A method for grouping the time series data.
1025
+ aggregation: TimeAggMethod
1026
+ A method for aggregating the time series data
1027
+ (if no grouping is specified, the time series is reduced to a scalar).
1028
+ """
1029
+
1030
+ time_frame: TimeFrame
1031
+ """The original time frame."""
1032
+ selection: tuple[slice, int | None]
1033
+ """
1034
+ The selected subset of the time frame: described as a date slice
1035
+ and an optional tau step index.
1036
+ """
1037
+ grouping: TimeGrouping | None
1038
+ """A method for grouping the time series data."""
1039
+ aggregation: TimeAggMethod
1040
+ """
1041
+ A method for aggregating the time series data
1042
+ (if no grouping is specified, the time series is reduced to a scalar).
1043
+ """
1044
+
1045
+ @property
1046
+ @override
1047
+ def group_format(self):
1048
+ return "tick" if self.grouping is None else self.grouping.group_format
1049
+
1050
+
1051
+ @dataclass(frozen=True)
1052
+ class TimeSelector:
1053
+ """
1054
+ A utility class for selecting a subset of a time frame.
1055
+ Most of the time you obtain one of these using `TimeFrame`'s `select` property.
1056
+ """
1057
+
1058
+ time_frame: TimeFrame
1059
+ """The original time frame."""
1060
+
1061
+ def all(self, step: int | None = None) -> TimeSelection:
1062
+ """
1063
+ Select the entirety of the time frame.
1064
+
1065
+ Parameters
1066
+ ----------
1067
+ step :
1068
+ If given, narrow the selection to a specific tau step (by index) within
1069
+ the date range; by default include all steps.
1070
+
1071
+ Returns
1072
+ -------
1073
+ :
1074
+ The selection strategy object.
1075
+ """
1076
+ return TimeSelection(self.time_frame, (slice(None), step))
1077
+
1078
+ def _to_selection(
1079
+ self,
1080
+ other: TimeFrame,
1081
+ step: int | None = None,
1082
+ ) -> TimeSelection:
1083
+ """
1084
+ Use a `TimeFrame` object (which must be a subset of the base `TimeFrame`)
1085
+ to create a `TimeSelection`.
1086
+ """
1087
+ if not self.time_frame.is_subset(other):
1088
+ err = "When selecting part of a time frame you must specify a subset."
1089
+ raise ValueError(err)
1090
+ from_index = (other.start_date - self.time_frame.start_date).days
1091
+ to_index = (other.end_date - self.time_frame.start_date).days + 1
1092
+ return TimeSelection(self.time_frame, (slice(from_index, to_index), step))
1093
+
1094
+ def days(
1095
+ self,
1096
+ from_day: int,
1097
+ to_day: int,
1098
+ step: int | None = None,
1099
+ ) -> TimeSelection:
1100
+ """
1101
+ Subset the time frame by providing a start and end simulation day (inclusive).
1102
+
1103
+ Parameters
1104
+ ----------
1105
+ from_day :
1106
+ The starting simulation day of the range, as an index.
1107
+ to_day :
1108
+ The last included simulation day of the range, as an index.
1109
+ step :
1110
+ If given, narrow the selection to a specific tau step (by index) within
1111
+ the date range; by default include all steps.
1112
+
1113
+ Returns
1114
+ -------
1115
+ :
1116
+ The selection strategy object.
1117
+ """
1118
+ return TimeSelection(self.time_frame, (slice(from_day, to_day + 1), step))
1119
+
1120
+ def range(
1121
+ self,
1122
+ from_date: date | str,
1123
+ to_date: date | str,
1124
+ step: int | None = None,
1125
+ ) -> TimeSelection:
1126
+ """
1127
+ Subset the time frame by providing the start and end date (inclusive).
1128
+
1129
+ Parameters
1130
+ ----------
1131
+ from_date :
1132
+ The starting date of the range, as a date object or an ISO-8601 string.
1133
+ to_date :
1134
+ The last included date of the range, as a date object or an ISO-8601 string.
1135
+ step :
1136
+ If given, narrow the selection to a specific tau step (by index) within
1137
+ the date range; by default include all steps.
1138
+
1139
+ Returns
1140
+ -------
1141
+ :
1142
+ The selection strategy object.
1143
+ """
1144
+ other = TimeFrame.range(from_date, to_date)
1145
+ return self._to_selection(other, step)
1146
+
1147
+ def rangex(
1148
+ self,
1149
+ from_date: date | str,
1150
+ until_date: date | str,
1151
+ step: int | None = None,
1152
+ ) -> TimeSelection:
1153
+ """
1154
+ Subset the time frame by providing the start and end date (exclusive).
1155
+
1156
+ Parameters
1157
+ ----------
1158
+ from_date :
1159
+ The starting date of the range, as a date object or an ISO-8601 string.
1160
+ until_date :
1161
+ The stop date date of the range (the first date excluded)
1162
+ as a date object or an ISO-8601 string.
1163
+ step :
1164
+ If given, narrow the selection to a specific tau step (by index) within
1165
+ the date range; by default include all steps.
1166
+
1167
+ Returns
1168
+ -------
1169
+ :
1170
+ The selection strategy object.
1171
+ """
1172
+ other = TimeFrame.rangex(from_date, until_date)
1173
+ return self._to_selection(other, step)
1174
+
1175
+ def year(
1176
+ self,
1177
+ year: int,
1178
+ step: int | None = None,
1179
+ ) -> TimeSelection:
1180
+ """
1181
+ Subset the time frame to a specific year.
1182
+
1183
+ Parameters
1184
+ ----------
1185
+ year :
1186
+ The year to include, from January 1st through December 31st.
1187
+ step :
1188
+ If given, narrow the selection to a specific tau step (by index) within
1189
+ the date range; by default include all steps.
1190
+
1191
+ Returns
1192
+ -------
1193
+ :
1194
+ The selection strategy object.
1195
+ """
1196
+ other = TimeFrame.year(year)
1197
+ return self._to_selection(other, step)