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,706 @@
1
+ """`Preparer`: raw observations + covariates -> `PreparedDataset`, sklearn-style (FR-D05).
2
+
3
+ Pipeline (same for `fit` and `transform`):
4
+
5
+ 1. Master grid from the observations' times, or the step index (`data.calendar.build_grid`,
6
+ `missing_observations` policy: `mask` keeps every row, `drop` removes rows where the primary series is
7
+ missing, `error` raises).
8
+ 2. Observations `y = transform(values)` with the registered observation transform (`identity` by default;
9
+ an application registers more, e.g. a transform that drops the first row). `mask = isfinite(y)`, masked
10
+ values are set to 0. A transform that keeps every row gets one virtual grid time before the first row,
11
+ so that every observation has a spacing `dt`.
12
+ 3. Support check (`real`, `count`, `binary`, `categorical`) against the emission family's support; counts,
13
+ binary and categorical observations become `int64`.
14
+ 4. Per covariate, in declared order: transforms on the series' own prints (`log`, `diff`, `pct`; `zscore`
15
+ is a deprecated alias of standardization), then alignment + lag + `max_staleness` forward-fill
16
+ (`data.calendar.align_covariate`). Prints are sorted by time first; of duplicated timestamps the last
17
+ (a revision) is kept.
18
+ 5. Warm-up: leading rows before every covariate has its first usable value are trimmed. The lag
19
+ shift and each `diff`/`pct` cost rows by construction; that is history that does not exist yet,
20
+ not missing data, and is trimmed for every policy. A covariate that starts later than that
21
+ (e.g. a series beginning after the primary) raises under `missing: error` and is trimmed with a
22
+ warning otherwise.
23
+ 6. Missing policy on the remaining NaN, per covariate: `error` -> `DataError` naming the first
24
+ offending timestamp; `drop` -> drop those grid rows; `ffill` -> the fill up to `max_staleness`
25
+ already happened in step 4, rows still NaN are dropped like `drop`. Drops are joint: observations,
26
+ `dt`, `mask`, `times` and every covariate are re-sliced together.
27
+ 7. Standardization of the covariates (`standardize_covariates`, or `zscore` in a covariate's transforms)
28
+ and, for real observations, of the observations (`standardize_observations`), with mean/std (ddof 0)
29
+ fitted by `fit` on rows whose end time is `<= train_end` only, applied by `transform`.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import dataclasses
35
+ import json
36
+ import warnings
37
+ from collections.abc import Sequence
38
+ from dataclasses import dataclass, replace
39
+ from typing import Any, get_args
40
+
41
+ import jax.numpy as jnp
42
+ import numpy as np
43
+ import pandas as pd
44
+
45
+ from hsmmkit.config.schema import CovariateCfg, DataSection, EntryPoint
46
+ from hsmmkit.data.batch import SequenceBatch, split_sequences
47
+ from hsmmkit.data.calendar import Grid, align_covariate, build_grid
48
+ from hsmmkit.data.contracts import (
49
+ BoundaryConstraints,
50
+ Clock,
51
+ CovariateSeries,
52
+ ObservationSet,
53
+ PreparedDataset,
54
+ PrepStats,
55
+ Support,
56
+ lag_names,
57
+ own_lag_columns,
58
+ )
59
+ from hsmmkit.data.labels import allowed_from_values, boundaries_of
60
+ from hsmmkit.data.transforms import apply_transforms, get_observation_transform
61
+ from hsmmkit.utils.clock import get_clock, parse_clock_options
62
+ from hsmmkit.utils.errors import ConfigError, DataError
63
+ from hsmmkit.utils.logging import get_logger
64
+
65
+ MIN_STD = 1e-12
66
+ ENTRY_POINTS: tuple[EntryPoint, ...] = get_args(EntryPoint)
67
+
68
+ _log = get_logger(__name__)
69
+
70
+
71
+ def _step(t: Any) -> int: # noqa: ANN401
72
+ """A step index from `t`; time-less data takes integer train bounds."""
73
+ try:
74
+ return int(t)
75
+ except (TypeError, ValueError):
76
+ raise DataError(
77
+ f"time-less data needs an integer train bound (a step index), got {t!r}", path="train_end"
78
+ ) from None
79
+
80
+
81
+ def _at_or_before(times: np.ndarray, t: Any) -> np.ndarray: # noqa: ANN401
82
+ """`times <= t` for timestamps or a step index."""
83
+ if np.issubdtype(times.dtype, np.integer):
84
+ return np.asarray(times <= _step(t))
85
+ return np.asarray(times <= _utc_ns(t))
86
+
87
+
88
+ def _at_or_after(times: np.ndarray, t: Any) -> np.ndarray: # noqa: ANN401
89
+ """`times >= t` for timestamps or a step index."""
90
+ if np.issubdtype(times.dtype, np.integer):
91
+ return np.asarray(times >= _step(t))
92
+ return np.asarray(times >= _utc_ns(t))
93
+
94
+
95
+ def _utc_ns(t: str | np.datetime64 | pd.Timestamp) -> np.datetime64:
96
+ """Parse a timestamp; naive means UTC, aware ones are converted to UTC."""
97
+ ts = pd.Timestamp(t)
98
+ if ts.tzinfo is not None:
99
+ ts = ts.tz_convert("UTC").tz_localize(None)
100
+ return np.datetime64(ts.as_unit("ns").to_datetime64(), "ns")
101
+
102
+
103
+ def _canonical(series: CovariateSeries) -> CovariateSeries:
104
+ """Sort prints by time (stable) and keep the last of duplicated timestamps (a revised print)."""
105
+ if series.times is None or np.issubdtype(np.asarray(series.times).dtype, np.integer):
106
+ return series # time-less: one print per grid row, already in order
107
+ times = np.asarray(series.times).astype("datetime64[ns]")
108
+ order = np.argsort(times, kind="stable")
109
+ times, values = times[order], np.asarray(series.values, dtype=np.float64)[order]
110
+ last = np.ones(times.shape[0], dtype=bool)
111
+ last[:-1] = times[1:] != times[:-1]
112
+ return replace(series, times=times[last], values=values[last])
113
+
114
+
115
+ def _structural_warmup(c: CovariateCfg) -> int:
116
+ """Leading rows a covariate cannot fill by construction: lag shift plus one per `diff`/`pct`."""
117
+ return c.lag - 1 + sum(t in ("diff", "pct") for t in c.transform)
118
+
119
+
120
+ def _iso(t: np.datetime64 | np.integer) -> str:
121
+ if isinstance(t, np.integer):
122
+ return str(int(t))
123
+ ts = pd.Timestamp(t)
124
+ return str(ts.date()) if ts == ts.normalize() else ts.isoformat()
125
+
126
+
127
+ @dataclass(frozen=True, eq=False)
128
+ class _Frame:
129
+ """Rows of the prepared grid before standardization."""
130
+
131
+ times: np.ndarray # (T,) observation end times
132
+ observations: np.ndarray # (T, M)
133
+ mask: np.ndarray # (T, M)
134
+ dt: np.ndarray # (T,)
135
+ covariates: np.ndarray # (T, K), raw (transformed, aligned) covariate values
136
+ nominal_dt: float
137
+ clock: Clock
138
+ n_categories: int | None = None
139
+
140
+
141
+ @dataclass(frozen=True, eq=False)
142
+ class PrepDiagnostics:
143
+ """What the last `fit`/`transform` pipeline run removed or carried forward (for the quality report).
144
+
145
+ Attributes:
146
+ missing_rows: primary rows dropped for a missing value (`missing_observations: drop`).
147
+ warmup_rows: leading grid rows trimmed before every covariate had a usable value.
148
+ dropped: per covariate name, grid rows its `missing` policy dropped (rows can overlap).
149
+ staleness: per covariate name, `(T_grid,)` staleness on the full grid (-1 = no usable print).
150
+ """
151
+
152
+ missing_rows: int
153
+ warmup_rows: int
154
+ dropped: dict[str, int]
155
+ staleness: dict[str, np.ndarray]
156
+
157
+
158
+ def _with_virtual_start(grid: Grid, clock: str, clock_options: Any) -> Grid: # noqa: ANN401
159
+ """The grid with one extra time before the first row, so that every observation has a spacing.
160
+
161
+ Used when the observation transform keeps every row: observation `t` then covers `(τ_{t-1}, τ_t]`
162
+ with `τ_{-1}` one median spacing before the first time (for a step index: one step).
163
+ """
164
+ clk = get_clock(clock)
165
+ opts = parse_clock_options(clock, clock_options)
166
+ times = grid.times
167
+ if np.issubdtype(times.dtype, np.integer):
168
+ first = times[:1] - 1
169
+ else:
170
+ spacing = np.median(np.diff(times)) if times.shape[0] > 1 else np.timedelta64(1, "D")
171
+ first = times[:1] - spacing
172
+ extended = np.concatenate([first, times])
173
+ dt = clk.dt(extended, extended.shape[0] - 1, opts)
174
+ values = np.vstack([np.full((1, grid.values.shape[1]), np.nan), grid.values])
175
+ return Grid(
176
+ times=extended,
177
+ values=values,
178
+ dt=dt,
179
+ nominal_dt=float(np.median(dt)),
180
+ irregular=False if clk.unit == "step" else grid.irregular,
181
+ clock=grid.clock,
182
+ )
183
+
184
+
185
+ class Preparer:
186
+ """Fit/transform preparation of a `PreparedDataset` (statistics from the training window only).
187
+
188
+ Covariate series pair with `cfg.covariates[i]` by position; each `CovariateSeries.series_id` must
189
+ equal `cfg.covariates[i].series`. Output covariate names are the config names.
190
+ """
191
+
192
+ def __init__(
193
+ self,
194
+ cfg: DataSection,
195
+ *,
196
+ support: Support = "real",
197
+ n_categories: int | None = None,
198
+ own_lags: int = 0,
199
+ series_support: Sequence[Support] | None = None,
200
+ n_regimes: int | None = None,
201
+ ) -> None:
202
+ """Store the `data:` config section and the observation support; nothing is fitted yet.
203
+
204
+ Args:
205
+ cfg: the `data:` section.
206
+ support: the emission family's support (`real`, `count`, `binary`, `categorical`).
207
+ n_categories: number of categories for `categorical` (`None`: `max + 1` with a warning).
208
+ series_support: per-series supports of a mixed-family (`product` blocks) model; each column is
209
+ validated against its own support and the observations stay float (`support` is then the first
210
+ non-real entry). `None`: every series has `support`.
211
+ n_regimes: the number of regimes `N`, needed to encode `data.labels` as the `(T, N)`
212
+ allowed-regime matrix of `PreparedDataset.labels` (E12-T06).
213
+ own_lags: `p > 0` appends the own lags `y_{t-1..t-p}` (after the observation transform and
214
+ standardization) to the emission covariates as `__lag{l}_{series}`, and masks the first `p`
215
+ steps and every step with an unobserved lag (autoregressive emissions, `requires_own_lags`).
216
+
217
+ Raises:
218
+ ConfigError: `standardize_observations` with a non-real support.
219
+ """
220
+ if cfg.preparation.standardize_observations and support != "real":
221
+ raise ConfigError(
222
+ f"standardize_observations needs real observations, not support {support!r}",
223
+ path="data.preparation.standardize_observations",
224
+ )
225
+ self.series_support = None if series_support is None else tuple(series_support)
226
+ if self.series_support is not None and support == "real":
227
+ support = next((s for s in self.series_support if s != "real"), "real")
228
+ self.support = support
229
+ self.n_categories = n_categories
230
+ if own_lags < 0:
231
+ raise ConfigError("own_lags must be >= 0", path="model.emission.ar.p")
232
+ self.own_lags = own_lags
233
+ self.n_regimes = n_regimes
234
+ self.cfg = cfg
235
+ self._stats: PrepStats | None = None
236
+ self.diagnostics: PrepDiagnostics | None = None
237
+
238
+ @property
239
+ def prep_stats(self) -> PrepStats:
240
+ """The fitted statistics (raises `DataError` before `fit`)."""
241
+ if self._stats is None:
242
+ raise DataError("Preparer is not fitted: call fit() first", path="prep_stats")
243
+ return self._stats
244
+
245
+ def fit(
246
+ self,
247
+ obs: ObservationSet,
248
+ covs: Sequence[CovariateSeries],
249
+ train_end: str | np.datetime64 | pd.Timestamp,
250
+ train_start: str | np.datetime64 | pd.Timestamp | None = None,
251
+ ) -> Preparer:
252
+ """Fit standardization statistics on rows whose end time is `<= train_end` (and `>= train_start`).
253
+
254
+ Args:
255
+ obs: the observations.
256
+ covs: raw covariate series in `data.covariates` order.
257
+ train_end: last training timestamp (inclusive), any `pd.Timestamp`-parsable value;
258
+ naive means UTC, timezone-aware values are converted to UTC.
259
+ train_start: optional first training timestamp (inclusive; a rolling walk-forward window).
260
+ `None` = from the first prepared row.
261
+
262
+ Returns:
263
+ `self`, fitted.
264
+
265
+ Raises:
266
+ DataError: no training rows, a train-window std `< 1e-12`, or any pipeline error.
267
+ """
268
+ frame, train = self._train_frame(obs, covs, train_end, train_start)
269
+ if not train.any():
270
+ raise DataError(
271
+ f"train_end {train_end!r} is before the first prepared observation {_iso(frame.times.min())}",
272
+ path="train_end",
273
+ )
274
+ covariates = self.cfg.covariates
275
+ mean = np.zeros(len(covariates))
276
+ std = np.ones(len(covariates))
277
+ for i, c in enumerate(covariates):
278
+ if "zscore" in c.transform:
279
+ warnings.warn(
280
+ f"data.covariates[{i}].transform: 'zscore' is deprecated; it is applied as "
281
+ "train-window standardization (use preparation.standardize_covariates)",
282
+ FutureWarning,
283
+ stacklevel=2,
284
+ )
285
+ if not (self.cfg.preparation.standardize_covariates or "zscore" in c.transform):
286
+ continue
287
+ x = frame.covariates[train, i]
288
+ mean[i], std[i] = x.mean(), x.std()
289
+ if not std[i] >= MIN_STD:
290
+ raise DataError(
291
+ f"covariate {c.name!r} has train-window std {std[i]:.3g} < {MIN_STD} (constant?)",
292
+ path=f"data.covariates[{i}]",
293
+ )
294
+ obs_mean: np.ndarray | None = None
295
+ obs_std: np.ndarray | None = None
296
+ if self.cfg.preparation.standardize_observations:
297
+ y, ok = frame.observations[train], frame.mask[train]
298
+ counts = ok.sum(axis=0)
299
+ if bool(np.any(counts < 2)):
300
+ raise DataError(
301
+ "standardize_observations needs two observed train rows per series",
302
+ path="data.preparation.standardize_observations",
303
+ )
304
+ obs_mean = (np.where(ok, y, 0.0).sum(axis=0) / counts).astype(np.float64)
305
+ centered = np.where(ok, y - obs_mean, 0.0)
306
+ obs_std = np.sqrt((centered**2).sum(axis=0) / counts)
307
+ if not bool(np.all(obs_std >= MIN_STD)):
308
+ raise DataError(
309
+ f"an observation series has train-window std < {MIN_STD} (constant?)",
310
+ path="data.preparation.standardize_observations",
311
+ )
312
+ self._stats = PrepStats(
313
+ cov_mean=mean,
314
+ cov_std=std,
315
+ train_window=(_iso(frame.times[train].min()), _iso(frame.times[train].max())),
316
+ cov_names=tuple(c.name for c in covariates),
317
+ transforms={c.name: list(c.transform) for c in covariates},
318
+ lags={c.name: c.lag for c in covariates},
319
+ obs_mean=obs_mean,
320
+ obs_std=obs_std,
321
+ )
322
+ return self
323
+
324
+ def _train_frame(
325
+ self,
326
+ obs: ObservationSet,
327
+ covs: Sequence[CovariateSeries],
328
+ train_end: str | np.datetime64 | pd.Timestamp,
329
+ train_start: str | np.datetime64 | pd.Timestamp | None,
330
+ ) -> tuple[_Frame, np.ndarray]:
331
+ """The (pooled) prepared rows and the mask of the training rows.
332
+
333
+ With `obs.sequence_ids` every sequence is prepared on its own and the rows of all sequences are
334
+ concatenated, so the standardization statistics are those of the pooled training rows.
335
+ """
336
+ parts = split_sequences(obs, covs)
337
+ frames = [self._frame(o, c) for _, o, c in parts]
338
+ trains = []
339
+ for f in frames:
340
+ tr = _at_or_before(f.times, train_end)
341
+ if train_start is not None:
342
+ tr &= _at_or_after(f.times, train_start)
343
+ trains.append(tr)
344
+ if len(frames) == 1:
345
+ return frames[0], trains[0]
346
+ first = frames[0]
347
+ pooled = _Frame(
348
+ times=np.concatenate([f.times for f in frames]),
349
+ observations=np.concatenate([f.observations for f in frames]),
350
+ mask=np.concatenate([f.mask for f in frames]),
351
+ dt=np.concatenate([f.dt for f in frames]),
352
+ covariates=np.concatenate([f.covariates for f in frames]),
353
+ nominal_dt=first.nominal_dt,
354
+ clock=first.clock,
355
+ n_categories=first.n_categories,
356
+ )
357
+ return pooled, np.concatenate(trains)
358
+
359
+ def transform_batch(self, obs: ObservationSet, covs: Sequence[CovariateSeries]) -> SequenceBatch:
360
+ """Prepare every sequence of `obs` (rows grouped by `sequence_ids`) with the fitted pooled statistics.
361
+
362
+ Own lags, lagged covariates and first-step masks are generated **within** each sequence, so nothing
363
+ crosses a sequence boundary. `data.sequences.group_by` (a column constant within a sequence) becomes
364
+ `PreparedDataset.group`; `data.sequences.bucket_edges` are the batch's bucket edges.
365
+
366
+ Returns:
367
+ A `SequenceBatch` in first-appearance order of the sequence ids (`B = 1` without ids).
368
+
369
+ Raises:
370
+ ConfigError: a group column that varies within a sequence (`data.sequences.group_by`).
371
+ """
372
+ parts = split_sequences(obs, covs)
373
+ datasets = [dataclasses.replace(self.transform(o, c), group=o.meta.get("group")) for _, o, c in parts]
374
+ edges = () if self.cfg.sequences is None else tuple(self.cfg.sequences.bucket_edges)
375
+ return SequenceBatch(tuple(datasets), edges, tuple(sid for sid, _, _ in parts))
376
+
377
+ def transform(self, obs: ObservationSet, covs: Sequence[CovariateSeries]) -> PreparedDataset:
378
+ """Prepare any window with the fitted statistics.
379
+
380
+ Returns:
381
+ A validated `PreparedDataset`; covariate blocks are `None` for unused entry points.
382
+ """
383
+ if obs.sequence_ids is not None and np.unique(np.asarray(obs.sequence_ids)).shape[0] > 1:
384
+ raise ConfigError(
385
+ "the observations hold several sequences: use transform_batch",
386
+ path="data.source.sequence_column",
387
+ )
388
+ stats = self.prep_stats
389
+ names = tuple(c.name for c in self.cfg.covariates)
390
+ if stats.cov_names != names:
391
+ raise DataError(
392
+ f"fitted covariates {stats.cov_names} differ from the config {names}", path="prep_stats"
393
+ )
394
+ frame = self._frame(obs, covs)
395
+ standardized = (frame.covariates - stats.cov_mean) / stats.cov_std
396
+ observations = frame.observations
397
+ if stats.obs_mean is not None and stats.obs_std is not None:
398
+ observations = np.where(frame.mask, (observations - stats.obs_mean) / stats.obs_std, 0.0)
399
+
400
+ blocks: dict[EntryPoint, Any] = {}
401
+ cov_names: dict[str, tuple[str, ...]] = {}
402
+ for ep in ENTRY_POINTS:
403
+ idx = [i for i, c in enumerate(self.cfg.covariates) if ep in c.use_in]
404
+ if idx:
405
+ blocks[ep] = jnp.asarray(standardized[:, idx])
406
+ cov_names[ep] = tuple(names[i] for i in idx)
407
+
408
+ mask = frame.mask
409
+ if self.own_lags:
410
+ lags, ok = own_lag_columns(observations, mask, self.own_lags)
411
+ lag_block = jnp.asarray(lags)
412
+ block = blocks.get("emission")
413
+ blocks["emission"] = lag_block if block is None else jnp.concatenate([block, lag_block], axis=1)
414
+ cov_names["emission"] = (
415
+ *cov_names.get("emission", ()),
416
+ *lag_names(obs.series_names, self.own_lags),
417
+ )
418
+ mask = mask & ok[:, None]
419
+
420
+ labels, boundaries = self._supervision(obs, frame)
421
+ dataset = PreparedDataset(
422
+ times=frame.times,
423
+ observations=jnp.asarray(observations),
424
+ dt=jnp.asarray(frame.dt),
425
+ mask=jnp.asarray(mask),
426
+ cov_transition=blocks.get("transition"),
427
+ cov_duration=blocks.get("duration"),
428
+ cov_emission=blocks.get("emission"),
429
+ cov_names=cov_names,
430
+ clock=frame.clock,
431
+ nominal_dt=frame.nominal_dt,
432
+ prep_stats=stats,
433
+ snapshot_ids=(obs.snapshot_id, *(s.snapshot_id for s in covs)),
434
+ support=self.support,
435
+ series_support=self.series_support,
436
+ n_categories=frame.n_categories,
437
+ labels=labels,
438
+ boundaries=boundaries,
439
+ group=None,
440
+ )
441
+ dataset.validate()
442
+ return dataset
443
+
444
+ def _supervision(self, obs: ObservationSet, frame: _Frame) -> tuple[Any, BoundaryConstraints | None]:
445
+ """`(labels (T, N) bool or None, boundaries)` of the prepared rows (`data.labels`, E12-T06)."""
446
+ cfg = self.cfg.labels
447
+ if cfg is None:
448
+ return None, None
449
+ if self.n_regimes is None:
450
+ raise ConfigError(
451
+ "data.labels needs the number of regimes: Preparer(..., n_regimes=N)", path="data.labels"
452
+ )
453
+ raw = obs.meta.get("label_values")
454
+ if raw is None:
455
+ raise DataError(
456
+ "data.labels is configured but the source delivered no labels", path="data.labels"
457
+ )
458
+ allowed = allowed_from_values(raw, self.n_regimes, allowed_sets=cfg.allowed_sets)
459
+ keys = (
460
+ np.arange(len(raw), dtype=np.int64)
461
+ if obs.times is None
462
+ else np.asarray(obs.times).astype("datetime64[ns]")
463
+ )
464
+ times = np.asarray(frame.times)
465
+ times = times.astype(np.int64) if obs.times is None else times.astype("datetime64[ns]")
466
+ pos = np.minimum(np.searchsorted(keys, times), len(keys) - 1)
467
+ matched = keys[pos] == times # grid rows without a source row are unlabelled
468
+ labels = jnp.asarray(np.where(matched[:, None], allowed[pos], True))
469
+ bounds = cfg.boundaries
470
+ boundaries = (
471
+ None
472
+ if bounds is None
473
+ else boundaries_of(bounds.must_switch_at, bounds.must_not_switch_at, int(times.shape[0]))
474
+ )
475
+ return labels, boundaries
476
+
477
+ # --- pipeline ------------------------------------------------------------------------------
478
+
479
+ def _frame(self, obs: ObservationSet, covs: Sequence[CovariateSeries]) -> _Frame:
480
+ cfg = self.cfg
481
+ self._check_covariates(covs)
482
+ grid = build_grid(
483
+ obs,
484
+ cfg.preparation.missing_observations,
485
+ clock=cfg.clock,
486
+ clock_options=cfg.clock_options,
487
+ )
488
+
489
+ transform = get_observation_transform(cfg.preparation.observation_transform)
490
+ y, _ = transform(grid.values, grid.times)
491
+ y = np.asarray(y)
492
+ removed = grid.times.shape[0] - y.shape[0]
493
+ if removed not in (0, 1):
494
+ raise DataError(
495
+ f"observation transform '{transform.name}' removed {removed} rows; only 0 or 1 are supported",
496
+ path="data.preparation.observation_transform",
497
+ )
498
+ if removed == 0:
499
+ grid = _with_virtual_start(grid, cfg.clock, cfg.clock_options)
500
+ mask = np.isfinite(y)
501
+ y = np.where(mask, y, 0.0)
502
+ y, n_categories = self._apply_support(y, mask, obs.series_names)
503
+
504
+ n_cov = len(cfg.covariates)
505
+ x = np.empty((grid.n_steps, n_cov), dtype=np.float64)
506
+ staleness: dict[str, np.ndarray] = {}
507
+ for i, (c, s) in enumerate(zip(cfg.covariates, covs, strict=True)):
508
+ s = _canonical(s)
509
+ values = apply_transforms(s.values, c.transform, path=f"data.covariates[{i}].transform")
510
+ x[:, i], staleness[c.name] = align_covariate(
511
+ grid, replace(s, values=values), c.lag, c.max_staleness, index=i
512
+ )
513
+ x[~np.isfinite(x)] = np.nan # defensive: nothing non-finite may reach the dataset
514
+ missing_rows = int(obs.values.shape[0] - (grid.times.shape[0] - (1 - removed)))
515
+ # Recorded before the policies run, so a report can still show staleness if `error` raises.
516
+ self.diagnostics = PrepDiagnostics(missing_rows, 0, {}, staleness)
517
+
518
+ start = self._warmup(x, cfg.covariates, grid.end_times)
519
+ keep, dropped = self._policy_keep(x[start:], cfg.covariates, grid.end_times[start:])
520
+ rows = start + np.flatnonzero(keep)
521
+ self.diagnostics = PrepDiagnostics(
522
+ missing_rows=missing_rows,
523
+ warmup_rows=start,
524
+ dropped=dropped,
525
+ staleness=staleness,
526
+ )
527
+ return _Frame(
528
+ times=grid.end_times[rows],
529
+ observations=y[rows],
530
+ mask=mask[rows],
531
+ dt=grid.dt[rows],
532
+ covariates=x[rows],
533
+ nominal_dt=grid.nominal_dt,
534
+ clock=grid.clock,
535
+ n_categories=n_categories,
536
+ )
537
+
538
+ def _apply_support(
539
+ self, y: np.ndarray, mask: np.ndarray, names: Sequence[str]
540
+ ) -> tuple[np.ndarray, int | None]:
541
+ """Check the observations against the support; counts, binary and categorical become `int64`."""
542
+ if self.series_support is not None:
543
+ return self._apply_series_support(y, mask, names), None
544
+ support = self.support
545
+ if support == "real":
546
+ return y, None
547
+ observed = np.where(mask, y, 0.0)
548
+ path = "data.source.observation_columns"
549
+
550
+ def violated(bad: np.ndarray) -> DataError:
551
+ r, m = (int(v) for v in np.argwhere(bad)[0])
552
+ return DataError(f"{support} support violated at row {r}, series {names[m]}", path=path)
553
+
554
+ integral = np.abs(observed - np.rint(observed)) < 1e-12
555
+ if not bool(np.all(integral | ~mask)):
556
+ raise violated(~integral & mask)
557
+ ints = np.rint(observed).astype(np.int64)
558
+ if support == "count":
559
+ if bool(np.any((ints < 0) & mask)):
560
+ raise violated((ints < 0) & mask)
561
+ return ints, None
562
+ if support == "binary":
563
+ bad = ~np.isin(ints, (0, 1)) & mask
564
+ if bool(bad.any()):
565
+ raise violated(bad)
566
+ return ints, None
567
+ if y.shape[1] != 1:
568
+ raise DataError("categorical support needs a single series", path=path)
569
+ if bool(np.any((ints < 0) & mask)):
570
+ raise violated((ints < 0) & mask)
571
+ n_cat = self.n_categories
572
+ if n_cat is None:
573
+ n_cat = int(ints[mask].max()) + 1 if bool(mask.any()) else 1
574
+ warnings.warn(f"n_categories not given; using max + 1 = {n_cat}", UserWarning, stacklevel=3)
575
+ if bool(np.any((ints >= n_cat) & mask)):
576
+ raise violated((ints >= n_cat) & mask)
577
+ return ints, n_cat
578
+
579
+ def _apply_series_support(self, y: np.ndarray, mask: np.ndarray, names: Sequence[str]) -> np.ndarray:
580
+ """Mixed supports: check each column against its own support; the array stays float."""
581
+ assert self.series_support is not None
582
+ if len(self.series_support) != y.shape[1]:
583
+ raise ConfigError(
584
+ f"{len(self.series_support)} block supports for {y.shape[1]} observation series",
585
+ path="model.emission.blocks",
586
+ )
587
+ for m, support in enumerate(self.series_support):
588
+ col = y[mask[:, m], m]
589
+ if support == "real":
590
+ continue
591
+ if support == "categorical":
592
+ raise ConfigError(
593
+ "a categorical series cannot be part of a product", path="model.emission.blocks"
594
+ )
595
+ bad = np.abs(col - np.rint(col)) >= 1e-12
596
+ bad |= col < 0 if support == "count" else ~np.isin(np.rint(col), (0, 1))
597
+ if bool(bad.any()):
598
+ row = int(np.flatnonzero(mask[:, m])[int(np.argmax(bad))])
599
+ raise DataError(
600
+ f"{support} support violated at row {row}, series {names[m]}",
601
+ path="data.source.observation_columns",
602
+ )
603
+ return y
604
+
605
+ def _check_covariates(self, covs: Sequence[CovariateSeries]) -> None:
606
+ expected = self.cfg.covariates
607
+ if len(covs) != len(expected):
608
+ raise DataError(
609
+ f"expected {len(expected)} covariate series (data.covariates), got {len(covs)}",
610
+ path="data.covariates",
611
+ )
612
+ for i, (c, s) in enumerate(zip(expected, covs, strict=True)):
613
+ if c.source is None:
614
+ series: Any = c.column or c.name
615
+ else:
616
+ series = c.source.option("series")
617
+ if series is not None and s.series_id != series:
618
+ raise DataError(
619
+ f"covariate {i} ({c.name!r}) expects series {series!r}, got {s.series_id!r}",
620
+ path=f"data.covariates[{i}].series",
621
+ )
622
+
623
+ @staticmethod
624
+ def _warmup(x: np.ndarray, covariates: Sequence[CovariateCfg], end_times: np.ndarray) -> int:
625
+ start = 0
626
+ for i, c in enumerate(covariates):
627
+ valid = np.flatnonzero(~np.isnan(x[:, i]))
628
+ if valid.size == 0:
629
+ raise DataError(
630
+ f"covariate {c.name!r} has no usable value on the grid "
631
+ f"({_iso(end_times[0])} .. {_iso(end_times[-1])})",
632
+ path=f"data.covariates[{i}]",
633
+ )
634
+ first = int(valid[0])
635
+ if first > _structural_warmup(c):
636
+ where = f"{_iso(end_times[0])} .. {_iso(end_times[first])}"
637
+ if c.missing == "error":
638
+ raise DataError(
639
+ f"covariate {c.name!r} has no value for the observations {where} (missing='error')",
640
+ path=f"data.covariates[{i}].missing",
641
+ )
642
+ _log.warning("covariate_starts_late", covariate=c.name, rows=first, span=where)
643
+ start = max(start, first)
644
+ if start:
645
+ _log.info("warmup_rows_trimmed", count=start, first_time=_iso(end_times[start]))
646
+ return start
647
+
648
+ @staticmethod
649
+ def _policy_keep(
650
+ x: np.ndarray, covariates: Sequence[CovariateCfg], end_times: np.ndarray
651
+ ) -> tuple[np.ndarray, dict[str, int]]:
652
+ keep = np.ones(x.shape[0], dtype=bool)
653
+ dropped = {c.name: 0 for c in covariates}
654
+ for i, c in enumerate(covariates):
655
+ missing = np.isnan(x[:, i])
656
+ if not missing.any():
657
+ continue
658
+ if c.missing == "error":
659
+ first = _iso(end_times[np.flatnonzero(missing)[0]])
660
+ raise DataError(
661
+ f"covariate {c.name!r} has no value within max_staleness={c.max_staleness} "
662
+ f"for the observation ending {first} (missing='error')",
663
+ path=f"data.covariates[{i}].missing",
664
+ )
665
+ _log.info("covariate_rows_dropped", covariate=c.name, policy=c.missing, count=int(missing.sum()))
666
+ dropped[c.name] = int(missing.sum())
667
+ keep &= ~missing
668
+ return keep, dropped
669
+
670
+
671
+ def prep_stats_to_json(stats: PrepStats) -> str:
672
+ """Serialize `PrepStats` to JSON (floats round-trip exactly via `repr`)."""
673
+ return json.dumps(
674
+ {
675
+ "cov_mean": [float(v) for v in stats.cov_mean],
676
+ "cov_std": [float(v) for v in stats.cov_std],
677
+ "train_window": list(stats.train_window),
678
+ "cov_names": list(stats.cov_names),
679
+ "transforms": {k: list(v) for k, v in stats.transforms.items()},
680
+ "lags": dict(stats.lags),
681
+ **(
682
+ {}
683
+ if stats.obs_mean is None or stats.obs_std is None
684
+ else {
685
+ "obs_mean": [float(v) for v in stats.obs_mean],
686
+ "obs_std": [float(v) for v in stats.obs_std],
687
+ }
688
+ ),
689
+ },
690
+ indent=2,
691
+ )
692
+
693
+
694
+ def prep_stats_from_json(text: str) -> PrepStats:
695
+ """Inverse of `prep_stats_to_json`."""
696
+ d = json.loads(text)
697
+ return PrepStats(
698
+ cov_mean=np.asarray(d["cov_mean"], dtype=np.float64),
699
+ cov_std=np.asarray(d["cov_std"], dtype=np.float64),
700
+ train_window=(d["train_window"][0], d["train_window"][1]),
701
+ cov_names=tuple(d["cov_names"]),
702
+ transforms={k: list(v) for k, v in d["transforms"].items()},
703
+ lags={k: int(v) for k, v in d["lags"].items()},
704
+ obs_mean=None if "obs_mean" not in d else np.asarray(d["obs_mean"], dtype=np.float64),
705
+ obs_std=None if "obs_std" not in d else np.asarray(d["obs_std"], dtype=np.float64),
706
+ )