hsmmkit 0.5.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 (192) hide show
  1. hsmmkit/__init__.py +13 -0
  2. hsmmkit/cli/__init__.py +1 -0
  3. hsmmkit/cli/app.py +513 -0
  4. hsmmkit/cli/stream.py +194 -0
  5. hsmmkit/config/__init__.py +1 -0
  6. hsmmkit/config/defaults.py +13 -0
  7. hsmmkit/config/gates.py +39 -0
  8. hsmmkit/config/migrate.py +53 -0
  9. hsmmkit/config/schema.py +996 -0
  10. hsmmkit/config/yaml_io.py +67 -0
  11. hsmmkit/data/__init__.py +1 -0
  12. hsmmkit/data/batch.py +311 -0
  13. hsmmkit/data/calendar.py +314 -0
  14. hsmmkit/data/clocks.py +165 -0
  15. hsmmkit/data/contracts.py +543 -0
  16. hsmmkit/data/labels.py +150 -0
  17. hsmmkit/data/prepare.py +706 -0
  18. hsmmkit/data/provenance.py +34 -0
  19. hsmmkit/data/quality.py +112 -0
  20. hsmmkit/data/sources/__init__.py +92 -0
  21. hsmmkit/data/sources/base.py +247 -0
  22. hsmmkit/data/sources/csv.py +36 -0
  23. hsmmkit/data/sources/numpy.py +143 -0
  24. hsmmkit/data/sources/pandas.py +33 -0
  25. hsmmkit/data/sources/parquet.py +37 -0
  26. hsmmkit/data/sources/xarray.py +62 -0
  27. hsmmkit/data/transforms.py +129 -0
  28. hsmmkit/engine/__init__.py +1 -0
  29. hsmmkit/engine/approx.py +51 -0
  30. hsmmkit/engine/augmented.py +93 -0
  31. hsmmkit/engine/base.py +134 -0
  32. hsmmkit/engine/batch.py +414 -0
  33. hsmmkit/engine/constraints.py +173 -0
  34. hsmmkit/engine/criteria.py +67 -0
  35. hsmmkit/engine/estep.py +314 -0
  36. hsmmkit/engine/estep_explicit.py +260 -0
  37. hsmmkit/engine/expanded_hmm.py +336 -0
  38. hsmmkit/engine/explicit_dd.py +114 -0
  39. hsmmkit/engine/explicit_duration.py +721 -0
  40. hsmmkit/engine/ffbs.py +229 -0
  41. hsmmkit/engine/parallel.py +98 -0
  42. hsmmkit/engine/viterbi.py +85 -0
  43. hsmmkit/estimation/__init__.py +36 -0
  44. hsmmkit/estimation/compare.py +154 -0
  45. hsmmkit/estimation/ecm.py +106 -0
  46. hsmmkit/estimation/em.py +460 -0
  47. hsmmkit/estimation/gem.py +467 -0
  48. hsmmkit/estimation/gibbs.py +136 -0
  49. hsmmkit/estimation/init.py +578 -0
  50. hsmmkit/estimation/map.py +287 -0
  51. hsmmkit/estimation/mcmc.py +370 -0
  52. hsmmkit/estimation/mstep.py +304 -0
  53. hsmmkit/estimation/newton.py +104 -0
  54. hsmmkit/estimation/objective.py +232 -0
  55. hsmmkit/estimation/optimizers.py +195 -0
  56. hsmmkit/estimation/recovery.py +748 -0
  57. hsmmkit/estimation/recovery_ext.py +557 -0
  58. hsmmkit/estimation/relabel.py +85 -0
  59. hsmmkit/estimation/report.py +167 -0
  60. hsmmkit/estimation/results.py +53 -0
  61. hsmmkit/estimation/selftest.py +154 -0
  62. hsmmkit/estimation/vb.py +508 -0
  63. hsmmkit/evaluation/__init__.py +1 -0
  64. hsmmkit/evaluation/backtest.py +616 -0
  65. hsmmkit/evaluation/compare.py +172 -0
  66. hsmmkit/evaluation/metrics/__init__.py +1 -0
  67. hsmmkit/evaluation/metrics/clustering.py +111 -0
  68. hsmmkit/evaluation/metrics/labels.py +40 -0
  69. hsmmkit/evaluation/metrics/matching.py +103 -0
  70. hsmmkit/evaluation/metrics/model.py +53 -0
  71. hsmmkit/evaluation/metrics/predictive.py +337 -0
  72. hsmmkit/evaluation/metrics/registry.py +154 -0
  73. hsmmkit/evaluation/metrics/segmentation.py +182 -0
  74. hsmmkit/evaluation/padding.py +72 -0
  75. hsmmkit/evaluation/report.py +170 -0
  76. hsmmkit/evaluation/results.py +28 -0
  77. hsmmkit/inference/__init__.py +1 -0
  78. hsmmkit/inference/covariate_forecasters.py +344 -0
  79. hsmmkit/inference/decode.py +185 -0
  80. hsmmkit/inference/forecast.py +475 -0
  81. hsmmkit/inference/results.py +97 -0
  82. hsmmkit/inference/simulate.py +342 -0
  83. hsmmkit/interop/__init__.py +1 -0
  84. hsmmkit/interop/arviz.py +114 -0
  85. hsmmkit/interop/hmmlearn.py +163 -0
  86. hsmmkit/interop/pandas.py +116 -0
  87. hsmmkit/interop/sklearn.py +505 -0
  88. hsmmkit/interop/xarray.py +296 -0
  89. hsmmkit/model/__init__.py +1 -0
  90. hsmmkit/model/build.py +404 -0
  91. hsmmkit/model/conjugate.py +260 -0
  92. hsmmkit/model/dists.py +244 -0
  93. hsmmkit/model/duration/__init__.py +23 -0
  94. hsmmkit/model/duration/base.py +215 -0
  95. hsmmkit/model/duration/explicit.py +205 -0
  96. hsmmkit/model/duration/gamma.py +53 -0
  97. hsmmkit/model/duration/geometric.py +106 -0
  98. hsmmkit/model/duration/hazard.py +23 -0
  99. hsmmkit/model/duration/lognormal.py +56 -0
  100. hsmmkit/model/duration/negbin.py +115 -0
  101. hsmmkit/model/duration/nonparametric.py +120 -0
  102. hsmmkit/model/duration/per_state.py +107 -0
  103. hsmmkit/model/duration/poisson.py +56 -0
  104. hsmmkit/model/duration/weibull.py +61 -0
  105. hsmmkit/model/emission/__init__.py +24 -0
  106. hsmmkit/model/emission/_discrete.py +104 -0
  107. hsmmkit/model/emission/base.py +105 -0
  108. hsmmkit/model/emission/bernoulli.py +131 -0
  109. hsmmkit/model/emission/categorical.py +158 -0
  110. hsmmkit/model/emission/gaussian.py +754 -0
  111. hsmmkit/model/emission/mixture.py +387 -0
  112. hsmmkit/model/emission/msar.py +545 -0
  113. hsmmkit/model/emission/poisson.py +144 -0
  114. hsmmkit/model/emission/product.py +390 -0
  115. hsmmkit/model/emission/student_t.py +454 -0
  116. hsmmkit/model/lattice.py +246 -0
  117. hsmmkit/model/params/__init__.py +45 -0
  118. hsmmkit/model/params/bijectors.py +238 -0
  119. hsmmkit/model/params/manager.py +307 -0
  120. hsmmkit/model/params/priors.py +84 -0
  121. hsmmkit/model/params/spec.py +65 -0
  122. hsmmkit/model/spec.py +43 -0
  123. hsmmkit/model/topology.py +97 -0
  124. hsmmkit/model/transition.py +419 -0
  125. hsmmkit/online/__init__.py +24 -0
  126. hsmmkit/online/alerts.py +181 -0
  127. hsmmkit/online/buffer.py +203 -0
  128. hsmmkit/online/covariates.py +162 -0
  129. hsmmkit/online/em.py +304 -0
  130. hsmmkit/online/filter.py +682 -0
  131. hsmmkit/online/session.py +364 -0
  132. hsmmkit/online/state.py +240 -0
  133. hsmmkit/persistence/__init__.py +1 -0
  134. hsmmkit/persistence/results.py +495 -0
  135. hsmmkit/persistence/store.py +394 -0
  136. hsmmkit/plot/__init__.py +13 -0
  137. hsmmkit/plot/_common.py +56 -0
  138. hsmmkit/plot/diagnostics.py +176 -0
  139. hsmmkit/plot/durations.py +74 -0
  140. hsmmkit/plot/forecast.py +55 -0
  141. hsmmkit/plot/regimes.py +146 -0
  142. hsmmkit/plugins.py +311 -0
  143. hsmmkit/presets/__init__.py +116 -0
  144. hsmmkit/presets/core/counts_poisson_hazard.yaml +61 -0
  145. hsmmkit/presets/core/msar2_hamilton.yaml +59 -0
  146. hsmmkit/presets/core/segmentation_gaussian_ltr.yaml +82 -0
  147. hsmmkit/presets/core/two_regime_gaussian.yaml +60 -0
  148. hsmmkit/presets/fixtures.py +330 -0
  149. hsmmkit/project.py +1106 -0
  150. hsmmkit/py.typed +0 -0
  151. hsmmkit/scaffold.py +80 -0
  152. hsmmkit/selection/__init__.py +30 -0
  153. hsmmkit/selection/bootstrap.py +388 -0
  154. hsmmkit/selection/cv.py +301 -0
  155. hsmmkit/selection/grid.py +412 -0
  156. hsmmkit/selection/ppc.py +199 -0
  157. hsmmkit/selection/pseudo_residuals.py +265 -0
  158. hsmmkit/selection/replicate.py +57 -0
  159. hsmmkit/selection/splitters.py +213 -0
  160. hsmmkit/statespace/__init__.py +1 -0
  161. hsmmkit/statespace/builders.py +317 -0
  162. hsmmkit/statespace/factorial.py +249 -0
  163. hsmmkit/statespace/index.py +85 -0
  164. hsmmkit/statespace/transitions.py +143 -0
  165. hsmmkit/templates/family-plugin/common/README.md.tmpl +9 -0
  166. hsmmkit/templates/family-plugin/common/pyproject.toml.tmpl +19 -0
  167. hsmmkit/templates/family-plugin/common/src/__pkg__/__init__.py.tmpl +7 -0
  168. hsmmkit/templates/family-plugin/common/src/__pkg__/tests/__init__.py.tmpl +0 -0
  169. hsmmkit/templates/family-plugin/duration/family.py.tmpl +19 -0
  170. hsmmkit/templates/family-plugin/duration/test_contract.py.tmpl +14 -0
  171. hsmmkit/templates/family-plugin/emission/family.py.tmpl +95 -0
  172. hsmmkit/templates/family-plugin/emission/test_contract.py.tmpl +48 -0
  173. hsmmkit/testing/__init__.py +6 -0
  174. hsmmkit/testing/clock_contract.py +53 -0
  175. hsmmkit/testing/duration_contract.py +218 -0
  176. hsmmkit/testing/family_contract.py +339 -0
  177. hsmmkit/testing/metric_contract.py +157 -0
  178. hsmmkit/testing/source_contract.py +196 -0
  179. hsmmkit/utils/__init__.py +1 -0
  180. hsmmkit/utils/clock.py +109 -0
  181. hsmmkit/utils/deprecation.py +125 -0
  182. hsmmkit/utils/errors.py +56 -0
  183. hsmmkit/utils/jax_setup.py +48 -0
  184. hsmmkit/utils/logging.py +30 -0
  185. hsmmkit/utils/optional.py +25 -0
  186. hsmmkit/utils/rng.py +49 -0
  187. hsmmkit/utils/typing.py +32 -0
  188. hsmmkit-0.5.0.dist-info/METADATA +84 -0
  189. hsmmkit-0.5.0.dist-info/RECORD +192 -0
  190. hsmmkit-0.5.0.dist-info/WHEEL +4 -0
  191. hsmmkit-0.5.0.dist-info/entry_points.txt +2 -0
  192. hsmmkit-0.5.0.dist-info/licenses/LICENSE +190 -0
@@ -0,0 +1,314 @@
1
+ """Master calendar: observation grid, `Δ_t` per clock, covariate alignment and lagging (FR-D04, FR-D05).
2
+
3
+ Grid convention (concept §4.1, §5.6). The master grid is the primary series' timestamps after
4
+ missing-value handling, `τ_0 < … < τ_T`. Observation `t` (math, 1-based) covers `(τ_{t-1}, τ_t]`,
5
+ so there are `T = len(times) - 1` observations and `Δ_t` has shape `(T,)`. In code, row `t`
6
+ (0-based) is math step `t + 1`, i.e. the interval `(τ_t, τ_{t+1}]` (CLAUDE.md §3.7).
7
+
8
+ Covariate alignment (no look-ahead). Each series is aligned "as of" every grid time (the last
9
+ non-NaN print dated at or before `τ_j`, as `pd.merge_asof(direction="backward")` would), then
10
+ shifted by `lag ≥ 1` grid steps: code row `t` holds the value as of `τ_{t+1-lag}`, which is never
11
+ later than `τ_t`, the start of observation `t`. Values are carried forward at most `max_staleness`
12
+ grid steps after the print first became visible; beyond that they are NaN (the missing policy of
13
+ E2-T07 decides what happens next).
14
+
15
+ This module and `utils/clock.py` are the only places that branch on the clock *name*
16
+ (CLAUDE.md §3.2); everything downstream uses `dt`/`nominal_dt`.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Mapping, Sequence
22
+ from dataclasses import dataclass
23
+ from typing import Any, Literal
24
+
25
+ import numpy as np
26
+
27
+ from hsmmkit.data.contracts import Clock, CovariateSeries, ObservationSet
28
+ from hsmmkit.utils.clock import future_grid as future_grid # re-export (E6-T04a)
29
+ from hsmmkit.utils.clock import get_clock, is_irregular, parse_clock_options
30
+ from hsmmkit.utils.errors import ConfigError, DataError
31
+
32
+ MissingObservations = Literal["mask", "drop", "error"]
33
+
34
+ _NS_PER_DAY = 86_400 * 10**9
35
+ _NEVER = -1 # staleness of a row with no usable print (before the first one, or lost to the lag)
36
+
37
+
38
+ @dataclass(frozen=True, eq=False)
39
+ class Grid:
40
+ """The master observation grid.
41
+
42
+ Attributes:
43
+ times: `(T+1,)` `datetime64[ns]` grid end times `τ_0 … τ_T` (`int64` step index if time-less).
44
+ values: `(T+1, M)` float64 values on the grid; column 0 (the primary) has no NaN, the other
45
+ series may (a missing value masks that series' observation, E9-T01).
46
+ dt: `(T,)` float64 `Δ_t` in clock units (years for a year clock such as `calendar`, 1 for `steps`).
47
+ nominal_dt: `median(Δ_t)`.
48
+ irregular: `max Δ_t / min Δ_t > 1.5` (always `False` under `steps`).
49
+ clock: the clock `dt` was computed under.
50
+ """
51
+
52
+ times: np.ndarray
53
+ values: np.ndarray
54
+ dt: np.ndarray
55
+ nominal_dt: float
56
+ irregular: bool
57
+ clock: Clock
58
+
59
+ @property
60
+ def n_steps(self) -> int:
61
+ """Number of observations `T` (one fewer than grid times)."""
62
+ return int(self.dt.shape[0])
63
+
64
+ @property
65
+ def end_times(self) -> np.ndarray:
66
+ """`(T,)` observation end times `τ_1 … τ_T` (what `PreparedDataset.times` holds)."""
67
+ return self.times[1:]
68
+
69
+
70
+ @dataclass(frozen=True, eq=False)
71
+ class AlignedCovariates:
72
+ """Covariates aligned and lagged onto a grid, in declared order.
73
+
74
+ Attributes:
75
+ names: `(K,)` covariate names.
76
+ values: `(T, K)` float64; NaN where no print is usable or the last one is too stale.
77
+ staleness: `(T, K)` int64 grid steps since the print in use became visible (0 = fresh);
78
+ `-1` where no print is usable at all. Reported even where `values` is NaN. A print
79
+ dated before `τ_0` is aged in median grid spacings (rounded up).
80
+ """
81
+
82
+ names: tuple[str, ...]
83
+ values: np.ndarray
84
+ staleness: np.ndarray
85
+
86
+
87
+ def _as_ns(times: np.ndarray) -> np.ndarray:
88
+ return np.asarray(times).astype("datetime64[ns]")
89
+
90
+
91
+ def build_grid(
92
+ obs: ObservationSet,
93
+ missing_observations: MissingObservations,
94
+ *,
95
+ clock: str,
96
+ clock_options: Mapping[str, Any] | None = None,
97
+ ) -> Grid:
98
+ """Build the master grid from the primary instrument's observations.
99
+
100
+ Args:
101
+ obs: values `(T0, M)` on strictly increasing `times`; series 0 is the primary and defines the grid.
102
+ missing_observations: `"mask"` keeps every row (non-finite values are masked later); `"drop"`
103
+ removes every row where the primary has a missing (NaN) value (the other
104
+ series keep their NaN and are masked by `Preparer`); `"error"` raises on the first row where
105
+ any series is missing.
106
+ clock: name of a registered clock (`steps`, `calendar`, or an application's, e.g. the finance
107
+ application's own clock): it defines `Δ_t` (ADR-0013, ADR-0015).
108
+ clock_options: the clock's options (`data.clock_options`), validated by its options model.
109
+
110
+ Returns:
111
+ The grid with `T + 1` times and `T` values of `Δ_t`.
112
+
113
+ Raises:
114
+ ConfigError: unknown `missing_observations` policy or clock, invalid clock options.
115
+ DataError: non-increasing times, a missing value under `"error"`, fewer than two rows left.
116
+ """
117
+ if missing_observations not in ("mask", "drop", "error"):
118
+ raise ConfigError(
119
+ f"missing_observations must be 'mask', 'drop' or 'error', got {missing_observations!r}",
120
+ path="data.preparation.missing_observations",
121
+ )
122
+ clk = get_clock(clock)
123
+ opts = parse_clock_options(clock, clock_options)
124
+
125
+ values = np.asarray(obs.values, dtype=np.float64)
126
+ times: np.ndarray
127
+ if obs.times is None:
128
+ if clk.unit != "step":
129
+ raise ConfigError(
130
+ f"observations without a time column need a step clock (data.clock: steps), not {clock!r}",
131
+ path="data.clock",
132
+ )
133
+ times = np.arange(values.shape[0], dtype=np.int64) # the step index is the time axis
134
+ else:
135
+ times = _as_ns(obs.times)
136
+ if times.shape[0] > 1 and not bool(np.all(np.diff(times) > np.timedelta64(0, "ns"))):
137
+ raise DataError("primary times must be strictly increasing", path="times")
138
+
139
+ if missing_observations == "error":
140
+ gaps = np.argwhere(np.isnan(values))
141
+ if gaps.size:
142
+ row, col = gaps[np.argmin(gaps[:, 0])]
143
+ first = str(times[row]) if obs.times is None else np.datetime_as_string(times[row], unit="s")
144
+ name = obs.series_names[col] if col < len(obs.series_names) else str(col)
145
+ what = "primary value" if col == 0 and len(obs.series_names) == 1 else f"value of {name!r}"
146
+ raise DataError(
147
+ f"missing {what} at {first} (missing_observations='error')",
148
+ path="data.preparation.missing_observations",
149
+ )
150
+ missing = (
151
+ np.isnan(values[:, 0]) if missing_observations != "mask" else np.zeros(values.shape[0], dtype=bool)
152
+ )
153
+ if missing.any():
154
+ times, values = times[~missing], values[~missing]
155
+ if times.shape[0] < 2:
156
+ raise DataError("the master grid needs at least two rows with a value", path="values")
157
+
158
+ dt = clk.dt(times, times.shape[0] - 1, opts)
159
+ return Grid(
160
+ times=times,
161
+ values=values,
162
+ dt=dt,
163
+ nominal_dt=float(np.median(dt)),
164
+ irregular=False if clk.unit == "step" else is_irregular(dt),
165
+ clock=clock,
166
+ )
167
+
168
+
169
+ def _visible_at(grid_times: np.ndarray, pub_times: np.ndarray) -> np.ndarray:
170
+ """Grid index at which each print first becomes visible (first `τ_j >= print time`).
171
+
172
+ Prints dated before `τ_0` get a negative index: their age is extrapolated backwards in units of
173
+ the median grid spacing (rounded up), so an old print is not mistaken for a fresh one at `τ_0`.
174
+ """
175
+ visible = np.searchsorted(grid_times, pub_times, side="left").astype(np.int64)
176
+ before = pub_times < grid_times[0]
177
+ if before.any():
178
+ spacing = int(np.median(np.diff(grid_times).astype(np.int64)))
179
+ age_ns = (grid_times[0] - pub_times[before]).astype(np.int64)
180
+ visible[before] = (-age_ns) // spacing # = -ceil(age / spacing)
181
+ return visible
182
+
183
+
184
+ def _align_by_row(
185
+ grid: Grid, series: CovariateSeries, raw_values: np.ndarray, lag: int, max_staleness: int
186
+ ) -> tuple[np.ndarray, np.ndarray]:
187
+ """Row-index alignment for time-less grids: print `j` is dated at grid row `j`.
188
+
189
+ Same semantics as the timestamp path with `τ_j = j`: row `t` takes the last non-NaN print at index
190
+ `<= t + 1 - lag`, carried at most `max_staleness` steps.
191
+ """
192
+ n_grid = grid.times.shape[0]
193
+ if raw_values.shape[0] == n_grid - 1: # one print per observation; the grid has a virtual start time
194
+ raw_values = np.concatenate([[np.nan], raw_values])
195
+ if raw_values.shape[0] != n_grid:
196
+ raise DataError(
197
+ f"covariate {series.name!r}: a series without timestamps needs {n_grid} values "
198
+ f"(the grid length, or one fewer with a virtual start time), got {raw_values.shape[0]}",
199
+ path="data.covariates",
200
+ )
201
+ j = np.arange(n_grid)
202
+ last_pub = np.maximum.accumulate(np.where(np.isnan(raw_values), -1, j)) # last non-NaN print <= j
203
+ has_pub = last_pub >= 0
204
+ pick = np.maximum(last_pub, 0)
205
+ asof_values = np.where(has_pub, raw_values[pick], np.nan)
206
+ asof_stale = np.where(has_pub, j - last_pub, _NEVER)
207
+ source = np.arange(grid.n_steps) + 1 - lag
208
+ in_range = source >= 0
209
+ safe = np.maximum(source, 0)
210
+ values = np.where(in_range, asof_values[safe], np.nan)
211
+ staleness = np.where(in_range, asof_stale[safe], _NEVER).astype(np.int64)
212
+ values = np.where(staleness > max_staleness, np.nan, values)
213
+ return values.astype(np.float64), staleness
214
+
215
+
216
+ def align_covariate(
217
+ grid: Grid,
218
+ series: CovariateSeries,
219
+ lag: int,
220
+ max_staleness: int,
221
+ *,
222
+ index: int = 0,
223
+ ) -> tuple[np.ndarray, np.ndarray]:
224
+ """Align one covariate onto the grid: as-of backward, shift by `lag`, stale-limit.
225
+
226
+ Code row `t` (observation `(τ_t, τ_{t+1}]`) receives the last non-NaN print dated at or before
227
+ `τ_{t+1-lag}`; rows with `t + 1 - lag < 0` have none. NaN values in `series` count as "no print";
228
+ of several prints with the same timestamp the last one in input order wins (as `merge_asof`).
229
+
230
+ Args:
231
+ grid: the master grid.
232
+ series: the raw covariate (any frequency; monthly series become step functions).
233
+ lag: grid steps of lag, `≥ 1` (`lag = 1`: the value known at the end of the previous step).
234
+ max_staleness: grid steps a print may be carried forward after it became visible.
235
+ index: position in `data.covariates`, used in error paths.
236
+
237
+ Returns:
238
+ `values (T,)` float64 and `staleness (T,)` int64 (see `AlignedCovariates`).
239
+
240
+ Raises:
241
+ ConfigError: `lag < 1` (`data.covariates[i].lag`) or `max_staleness < 0`.
242
+ """
243
+ if lag < 1:
244
+ raise ConfigError(
245
+ f"covariate {series.name!r}: lag must be >= 1 (no look-ahead), got {lag}",
246
+ path=f"data.covariates[{index}].lag",
247
+ )
248
+ if max_staleness < 0:
249
+ raise ConfigError(
250
+ f"covariate {series.name!r}: max_staleness must be >= 0, got {max_staleness}",
251
+ path=f"data.covariates[{index}].max_staleness",
252
+ )
253
+
254
+ raw_values = np.asarray(series.values, dtype=np.float64)
255
+ grid_by_row = np.issubdtype(np.asarray(grid.times).dtype, np.integer)
256
+ if (
257
+ grid_by_row
258
+ and series.times is not None
259
+ and not np.issubdtype(np.asarray(series.times).dtype, np.integer)
260
+ ):
261
+ raise DataError(
262
+ f"covariate {series.name!r} has timestamps but the grid is a step index", path="data.covariates"
263
+ )
264
+ if series.times is None or grid_by_row:
265
+ return _align_by_row(grid, series, raw_values, lag, max_staleness)
266
+ if np.issubdtype(np.asarray(series.times).dtype, np.integer):
267
+ raise DataError(
268
+ f"covariate {series.name!r} has a step index but the grid has timestamps", path="data.covariates"
269
+ )
270
+ keep = ~np.isnan(raw_values)
271
+ pub_times = _as_ns(series.times)[keep]
272
+ pub_values = raw_values[keep]
273
+ order = np.argsort(pub_times, kind="stable")
274
+ pub_times, pub_values = pub_times[order], pub_values[order]
275
+
276
+ # As-of at every grid time τ_j: index of the last print with time <= τ_j (-1: none yet).
277
+ last_pub = np.searchsorted(pub_times, grid.times, side="right") - 1
278
+ has_pub = last_pub >= 0
279
+ pick = np.maximum(last_pub, 0)
280
+ visible_at = _visible_at(grid.times, pub_times)
281
+ asof_values = np.where(has_pub, pub_values[pick] if pub_values.size else np.nan, np.nan)
282
+ asof_stale = np.where(
283
+ has_pub, np.arange(grid.times.shape[0]) - (visible_at[pick] if visible_at.size else 0), _NEVER
284
+ )
285
+
286
+ # Row t takes grid time j = t + 1 - lag.
287
+ source = np.arange(grid.n_steps) + 1 - lag
288
+ in_range = source >= 0
289
+ safe = np.maximum(source, 0)
290
+ values = np.where(in_range, asof_values[safe], np.nan)
291
+ staleness = np.where(in_range, asof_stale[safe], _NEVER).astype(np.int64)
292
+ values = np.where(staleness > max_staleness, np.nan, values)
293
+ return values.astype(np.float64), staleness
294
+
295
+
296
+ def align_covariates(
297
+ grid: Grid,
298
+ series: Sequence[CovariateSeries],
299
+ lags: Sequence[int],
300
+ max_staleness: Sequence[int],
301
+ ) -> AlignedCovariates:
302
+ """Align several covariates in declared order (`data.covariates[i]` ↔ position `i`).
303
+
304
+ Returns:
305
+ `AlignedCovariates` with `values`/`staleness` of shape `(T, K)`; `K = 0` gives `(T, 0)`.
306
+ """
307
+ if not (len(series) == len(lags) == len(max_staleness)):
308
+ raise ValueError("series, lags and max_staleness must have the same length")
309
+ n_steps, n_cov = grid.n_steps, len(series)
310
+ values = np.empty((n_steps, n_cov), dtype=np.float64)
311
+ staleness = np.empty((n_steps, n_cov), dtype=np.int64)
312
+ for i, (s, lag, stale) in enumerate(zip(series, lags, max_staleness, strict=True)):
313
+ values[:, i], staleness[:, i] = align_covariate(grid, s, lag, stale, index=i)
314
+ return AlignedCovariates(names=tuple(s.name for s in series), values=values, staleness=staleness)
hsmmkit/data/clocks.py ADDED
@@ -0,0 +1,165 @@
1
+ """Clocks (E10-T03, FR-G02, D13): how the grid spacing `Δ_t` is defined, registered as kind `clock`.
2
+
3
+ The core knows two clocks: `steps` (`Δ_t ≡ 1`, the default) and `calendar` (`Δ_t` in years from the
4
+ timestamps). Applications register more. A clock gives the
5
+ spacing of an observed grid (`dt`) and of the future grid of a forecast (`future_grid`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Literal, Protocol, cast
11
+
12
+ import numpy as np
13
+ from pydantic import BaseModel, ConfigDict
14
+
15
+ from hsmmkit.plugins import REGISTRY, provenance_of
16
+ from hsmmkit.utils.clock import CALENDAR_DAYS_PER_YEAR
17
+ from hsmmkit.utils.errors import ConfigError
18
+
19
+ LastTime = np.datetime64 | int | np.integer
20
+
21
+ NS_PER_DAY = 86_400 * 10**9
22
+
23
+
24
+ class Clock(Protocol):
25
+ """A grid-spacing definition (see the module docstring)."""
26
+
27
+ name: str
28
+ unit: Literal["year", "step"]
29
+ options_model: type[BaseModel]
30
+ days_per_year: float | None
31
+
32
+ def dt(self, times: np.ndarray | None, n: int, opts: BaseModel) -> np.ndarray:
33
+ """`(n,)` spacing `Δ_t > 0` of an observed grid (`times` are the `n + 1` timestamps, if any)."""
34
+ ...
35
+
36
+ def future_grid(
37
+ self,
38
+ last_time: LastTime,
39
+ h: int,
40
+ opts: BaseModel,
41
+ times: np.ndarray | None,
42
+ ) -> tuple[np.ndarray, np.ndarray]:
43
+ """`(horizon_times (h,), dt (h,))` of the `h` steps after `last_time`."""
44
+ ...
45
+
46
+ def steps_per_day(self, opts: BaseModel) -> int:
47
+ """Grid steps per calendar day, for the config-time days-to-steps heuristic."""
48
+ ...
49
+
50
+
51
+ class NoOptions(BaseModel):
52
+ """Options model of clocks without options."""
53
+
54
+ model_config = ConfigDict(extra="forbid")
55
+
56
+
57
+ def is_weekend(t: np.datetime64) -> bool:
58
+ """Saturday or Sunday (1970-01-01 was a Thursday)."""
59
+ days = int(t.astype("datetime64[D]").astype(np.int64))
60
+ return (days + 3) % 7 >= 5
61
+
62
+
63
+ def median_step(times: np.ndarray | None, default: np.timedelta64) -> np.timedelta64:
64
+ """Median spacing of `times` (nanoseconds), or `default` when fewer than two timestamps are given."""
65
+ if times is None or np.asarray(times).shape[0] < 2:
66
+ return default
67
+ stamps = np.asarray(times).astype("datetime64[ns]")
68
+ return np.median(np.diff(stamps)).astype("m8[ns]") # type: ignore[no-any-return]
69
+
70
+
71
+ def check_horizon(h: int) -> None:
72
+ """Reject a non-positive horizon."""
73
+ if h < 1:
74
+ raise ConfigError(f"horizon must be >= 1, got {h}", path="forecast.horizon")
75
+
76
+
77
+ def check_step(step_ns: np.timedelta64) -> None:
78
+ """Reject a non-positive step."""
79
+ if step_ns <= np.timedelta64(0, "ns"):
80
+ raise ConfigError("step must be positive", path="forecast.step")
81
+
82
+
83
+ def continue_times(last: LastTime, h: int, step_ns: np.timedelta64, *, skip_weekends: bool) -> np.ndarray:
84
+ """`h` timestamps after `last`, `step_ns` apart, optionally skipping Saturdays and Sundays."""
85
+ times = np.empty(h, dtype="datetime64[ns]")
86
+ cur = np.datetime64(cast(Any, last), "ns")
87
+ for k in range(h):
88
+ cur = cur + step_ns
89
+ if skip_weekends:
90
+ while is_weekend(cur):
91
+ cur = cur + step_ns
92
+ times[k] = cur
93
+ return times
94
+
95
+
96
+ class StepsClock:
97
+ """`Δ_t ≡ 1` (parameters per step, no conversion to years)."""
98
+
99
+ name = "steps"
100
+ unit: Literal["year", "step"] = "step"
101
+ options_model = NoOptions
102
+ days_per_year: float | None = None
103
+
104
+ def dt(self, times: np.ndarray | None, n: int, opts: BaseModel) -> np.ndarray:
105
+ """Ones."""
106
+ return np.ones(n, dtype=np.float64)
107
+
108
+ def future_grid(
109
+ self,
110
+ last_time: LastTime,
111
+ h: int,
112
+ opts: BaseModel,
113
+ times: np.ndarray | None,
114
+ ) -> tuple[np.ndarray, np.ndarray]:
115
+ """Integer steps for integer `last_time`, else timestamps continued with the median spacing."""
116
+ check_horizon(h)
117
+ if isinstance(last_time, int | np.integer):
118
+ return np.arange(int(last_time) + 1, int(last_time) + 1 + h), np.ones(h)
119
+ step_ns = median_step(times, np.timedelta64(NS_PER_DAY, "ns"))
120
+ check_step(step_ns)
121
+ return continue_times(last_time, h, step_ns, skip_weekends=False), np.ones(h)
122
+
123
+ def steps_per_day(self, opts: BaseModel) -> int:
124
+ """One."""
125
+ return 1
126
+
127
+
128
+ class CalendarClock:
129
+ """`Δ_t` = elapsed calendar days / 365.25 (years)."""
130
+
131
+ name = "calendar"
132
+ unit: Literal["year", "step"] = "year"
133
+ options_model = NoOptions
134
+ days_per_year: float | None = CALENDAR_DAYS_PER_YEAR
135
+
136
+ def dt(self, times: np.ndarray | None, n: int, opts: BaseModel) -> np.ndarray:
137
+ """Gaps between the timestamps in years (needs `times`)."""
138
+ if times is None:
139
+ raise ConfigError("the calendar clock needs timestamps", path="data.clock")
140
+ days = np.diff(np.asarray(times).astype("datetime64[ns]")).astype(np.int64).astype(np.float64)
141
+ return days / NS_PER_DAY / CALENDAR_DAYS_PER_YEAR
142
+
143
+ def future_grid(
144
+ self,
145
+ last_time: LastTime,
146
+ h: int,
147
+ opts: BaseModel,
148
+ times: np.ndarray | None,
149
+ ) -> tuple[np.ndarray, np.ndarray]:
150
+ """Weekday timestamps continuing with the median spacing; `Δ` from the calendar gaps."""
151
+ check_horizon(h)
152
+ step_ns = median_step(times, np.timedelta64(NS_PER_DAY, "ns"))
153
+ check_step(step_ns)
154
+ last = np.datetime64(cast(Any, last_time), "ns")
155
+ out = continue_times(last, h, step_ns, skip_weekends=True)
156
+ gaps = np.diff(np.concatenate([[last], out])).astype(np.int64).astype(np.float64)
157
+ return out, gaps / NS_PER_DAY / CALENDAR_DAYS_PER_YEAR
158
+
159
+ def steps_per_day(self, opts: BaseModel) -> int:
160
+ """One."""
161
+ return 1
162
+
163
+
164
+ for _clock in (StepsClock(), CalendarClock()):
165
+ REGISTRY.register("clock", _clock.name, _clock, provenance=provenance_of(__name__))