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,543 @@
1
+ """Data contracts: the only shared types between the data layer and the model layer (FR-D07).
2
+
3
+ `PreparedDataset` is the sole contract the model layer (`model`, `statespace`, `engine`,
4
+ `estimation`, `inference`) may import from `hsmmkit.data` (the layer rule, overview §4.3).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import dataclasses
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Literal
12
+
13
+ import jax
14
+ import numpy as np
15
+
16
+ from hsmmkit.utils.clock import get_clock
17
+ from hsmmkit.utils.errors import DataError
18
+ from hsmmkit.utils.typing import Array
19
+
20
+ Clock = str # the name of a registered clock (`hsmmkit.data.clocks`, `PreparedDataset.clock`)
21
+ Support = Literal["real", "count", "binary", "categorical"]
22
+
23
+
24
+ LAG_PREFIX = "__lag"
25
+ """Prefix of the own-lag emission covariates generated for autoregressive emissions (`msar`)."""
26
+
27
+
28
+ def lag_names(series_names: tuple[str, ...], p: int) -> tuple[str, ...]:
29
+ """Names of the own-lag covariate columns: `__lag{l}_{series}` for `l = 1..p`, lag-major order."""
30
+ return tuple(f"{LAG_PREFIX}{lag}_{name}" for lag in range(1, p + 1) for name in series_names)
31
+
32
+
33
+ def own_lag_columns(observations: np.ndarray, mask: np.ndarray, p: int) -> tuple[np.ndarray, np.ndarray]:
34
+ """`(lags (T, p M), ok (T,))`: row `t` holds `y_{t-1}, ..., y_{t-p}` (lag-major, then series).
35
+
36
+ `ok[t]` is true when `t >= p` and every series was observed at the `p` previous steps; a row that is not
37
+ `ok` has zeros where a lag is unavailable and must be masked by the caller. Lags are `>= 1` by
38
+ construction: row `t` never reads `observations[t:]`.
39
+ """
40
+ t, m = observations.shape
41
+ y = np.where(mask, observations, 0.0)
42
+ lags = np.zeros((t, p * m))
43
+ ok = np.arange(t) >= p
44
+ observed = mask.all(axis=1)
45
+ for lag in range(1, p + 1):
46
+ lags[lag:, (lag - 1) * m : lag * m] = y[: t - lag]
47
+ ok[lag:] &= observed[: t - lag]
48
+ return lags, ok
49
+
50
+
51
+ def times_increase(times: np.ndarray, sequence_ids: np.ndarray | None = None) -> bool:
52
+ """Whether `times` strictly increase (within each sequence when `sequence_ids` are given)."""
53
+ if times.shape[0] < 2:
54
+ return True
55
+ if sequence_ids is None:
56
+ return bool(np.all(np.diff(times) > np.timedelta64(0, "ns")))
57
+ _, codes = np.unique(np.asarray(sequence_ids), return_inverse=True)
58
+ order = np.argsort(codes, kind="stable")
59
+ t, c = times[order], codes[order]
60
+ same = c[1:] == c[:-1]
61
+ return bool(np.all(np.diff(t)[same] > np.timedelta64(0, "ns")))
62
+
63
+
64
+ def _is_float_dtype(dtype: np.dtype[Any]) -> bool:
65
+ return np.issubdtype(dtype, np.floating)
66
+
67
+
68
+ def _array_equal(a: np.ndarray | jax.Array | None, b: np.ndarray | jax.Array | None) -> bool:
69
+ if a is None or b is None:
70
+ return a is b
71
+ return bool(np.array_equal(np.asarray(a), np.asarray(b)))
72
+
73
+
74
+ @dataclass(frozen=True, eq=False)
75
+ class ObservationSet:
76
+ """Raw observations of a source before alignment (data layer only).
77
+
78
+ Attributes:
79
+ series_names: `(M,)` names of the observed series (columns of `values`).
80
+ times: `(T0,)` `datetime64[ns]` UTC, strictly increasing; `None` only for time-less data, which
81
+ is valid under a `step` clock (`PreparedDataset.times` is then an `int64` step index).
82
+ values: `(T0, M)` `float64` or `int64`.
83
+ source: name of the source that produced the data.
84
+ snapshot_id: sha256 of the source bytes / array buffers; `""` if not computed.
85
+ meta: source-specific extras (an application puts its own descriptors here).
86
+ sequence_ids: `(T0,)` group ids when present; consumed from E12-T01a on, ignored before.
87
+ """
88
+
89
+ series_names: tuple[str, ...]
90
+ times: np.ndarray | None
91
+ values: np.ndarray
92
+ source: str
93
+ snapshot_id: str
94
+ meta: dict[str, Any] = field(default_factory=dict)
95
+ sequence_ids: np.ndarray | None = None
96
+
97
+ __hash__ = None # type: ignore[assignment]
98
+
99
+ def __eq__(self, other: object) -> bool:
100
+ """Structural equality, safe for numpy array fields."""
101
+ if not isinstance(other, ObservationSet):
102
+ return NotImplemented
103
+ return (
104
+ self.series_names == other.series_names
105
+ and _array_equal(self.times, other.times)
106
+ and _array_equal(self.values, other.values)
107
+ and self.source == other.source
108
+ and self.snapshot_id == other.snapshot_id
109
+ and self.meta == other.meta
110
+ and _array_equal(self.sequence_ids, other.sequence_ids)
111
+ )
112
+
113
+ def require_times(self) -> np.ndarray:
114
+ """The timestamps; `DataError` for time-less data (callers that cannot work without them)."""
115
+ if self.times is None:
116
+ raise DataError("this operation needs observations with timestamps", path="times")
117
+ return self.times
118
+
119
+ def validate(self) -> None:
120
+ """Raise `DataError(path=<field>)` on any contract violation."""
121
+ values = np.asarray(self.values)
122
+ if values.ndim != 2:
123
+ raise DataError("values must be 2-D (T0, M)", path="values")
124
+ t0, m = values.shape
125
+ if len(self.series_names) != m:
126
+ raise DataError(
127
+ f"series_names has {len(self.series_names)} entries but values has {m} columns",
128
+ path="series_names",
129
+ )
130
+ if not (np.issubdtype(values.dtype, np.floating) or np.issubdtype(values.dtype, np.integer)):
131
+ raise DataError(f"values must be float64 or int64, got {values.dtype}", path="values")
132
+ if self.times is not None:
133
+ times = np.asarray(self.times)
134
+ if times.ndim != 1 or times.shape[0] != t0:
135
+ raise DataError(f"times must have shape (T0={t0},)", path="times")
136
+ seq = None if self.sequence_ids is None else np.asarray(self.sequence_ids)
137
+ if seq is not None and seq.shape != (t0,):
138
+ raise DataError(f"sequence_ids must have shape (T0={t0},)", path="sequence_ids")
139
+ if not times_increase(times, seq):
140
+ raise DataError("times must be strictly increasing (within each sequence)", path="times")
141
+ if self.sequence_ids is not None and np.asarray(self.sequence_ids).shape != (t0,):
142
+ raise DataError(f"sequence_ids must have shape (T0={t0},)", path="sequence_ids")
143
+
144
+
145
+ @dataclass(frozen=True, eq=False)
146
+ class CovariateSeries:
147
+ """A single raw covariate series before alignment (data layer only)."""
148
+
149
+ name: str
150
+ times: np.ndarray | None # (T1,); None = one value per grid row (aligned by row index)
151
+ values: np.ndarray # (T1,), NaN allowed
152
+ source: str
153
+ series_id: str
154
+ snapshot_id: str
155
+ frequency: str
156
+
157
+ __hash__ = None # type: ignore[assignment]
158
+
159
+ def __eq__(self, other: object) -> bool:
160
+ """Structural equality, safe for numpy array fields."""
161
+ if not isinstance(other, CovariateSeries):
162
+ return NotImplemented
163
+ return (
164
+ self.name == other.name
165
+ and _array_equal(self.times, other.times)
166
+ and _array_equal(self.values, other.values)
167
+ and self.source == other.source
168
+ and self.series_id == other.series_id
169
+ and self.snapshot_id == other.snapshot_id
170
+ and self.frequency == other.frequency
171
+ )
172
+
173
+
174
+ @dataclass(frozen=True, eq=False)
175
+ class PrepStats:
176
+ """Preparation statistics fitted on the training window only."""
177
+
178
+ cov_mean: np.ndarray # (K,)
179
+ cov_std: np.ndarray # (K,)
180
+ train_window: tuple[str, str]
181
+ cov_names: tuple[str, ...]
182
+ transforms: dict[str, list[str]]
183
+ lags: dict[str, int]
184
+ obs_mean: np.ndarray | None = None # (M,) train-window mean when `standardize_observations`
185
+ obs_std: np.ndarray | None = None # (M,)
186
+
187
+ def __eq__(self, other: object) -> bool:
188
+ """Structural equality, safe for numpy array fields."""
189
+ if not isinstance(other, PrepStats):
190
+ return NotImplemented
191
+ return (
192
+ _array_equal(self.cov_mean, other.cov_mean)
193
+ and _array_equal(self.cov_std, other.cov_std)
194
+ and self.train_window == other.train_window
195
+ and self.cov_names == other.cov_names
196
+ and self.transforms == other.transforms
197
+ and self.lags == other.lags
198
+ and _array_equal(self.obs_mean, other.obs_mean)
199
+ and _array_equal(self.obs_std, other.obs_std)
200
+ )
201
+
202
+ def __hash__(self) -> int:
203
+ """Content-based hash, consistent with `__eq__` (required: `PrepStats` sits in pytree aux data)."""
204
+ return hash(
205
+ (
206
+ self.cov_mean.shape,
207
+ self.cov_mean.dtype.str,
208
+ self.cov_mean.tobytes(),
209
+ self.cov_std.shape,
210
+ self.cov_std.dtype.str,
211
+ self.cov_std.tobytes(),
212
+ self.train_window,
213
+ self.cov_names,
214
+ tuple(sorted((k, tuple(v)) for k, v in self.transforms.items())),
215
+ tuple(sorted(self.lags.items())),
216
+ None if self.obs_mean is None else self.obs_mean.tobytes(),
217
+ None if self.obs_std is None else self.obs_std.tobytes(),
218
+ )
219
+ )
220
+
221
+
222
+ @dataclass(frozen=True)
223
+ class BoundaryConstraints:
224
+ """Part II supervision hook; always `None` on `PreparedDataset` in 0.1.0."""
225
+
226
+ must_switch_at: tuple[int, ...] = ()
227
+ must_not_switch_at: tuple[int, ...] = ()
228
+
229
+ def __hash__(self) -> int:
230
+ """Value-based hash over the two index tuples."""
231
+ return hash((self.must_switch_at, self.must_not_switch_at))
232
+
233
+
234
+ @dataclass(frozen=True, eq=False)
235
+ class PreparedDataset:
236
+ """The only object the model layer consumes."""
237
+
238
+ times: np.ndarray # (T,) grid end times (datetime64[ns]) or an int64 step index; never a jit leaf
239
+ observations: Array # (T, M) float64
240
+ dt: Array # (T,) clock units, > 0
241
+ mask: Array # (T, M) bool, True = observed
242
+ cov_transition: Array | None # (T, K_pi)
243
+ cov_duration: Array | None # (T, K_d)
244
+ cov_emission: Array | None # (T, K_e)
245
+ cov_names: dict[str, tuple[str, ...]]
246
+ clock: Clock
247
+ nominal_dt: float
248
+ prep_stats: PrepStats
249
+ snapshot_ids: tuple[str, ...]
250
+ support: Support = "real"
251
+ n_categories: int | None = None
252
+ labels: Array | None = None # (T, N) bool
253
+ boundaries: BoundaryConstraints | None = None
254
+ group: str | None = None
255
+ series_support: tuple[Support, ...] | None = None
256
+ """Per-series supports of a mixed-family model (`None`: every series has `support`). With mixed blocks
257
+ `support` holds the first non-real support and `series_support` is authoritative; `observations` stay
258
+ float and each column is validated against its own support."""
259
+
260
+ def __hash__(self) -> int:
261
+ """Identity-based hash; equality below is value-based (fine: only used for `is`-safety)."""
262
+ return object.__hash__(self)
263
+
264
+ def __eq__(self, other: object) -> bool:
265
+ """Structural equality, safe for array-valued fields (used by round-trip tests)."""
266
+ if not isinstance(other, PreparedDataset):
267
+ return NotImplemented
268
+ return (
269
+ _array_equal(self.times, other.times)
270
+ and _array_equal(self.observations, other.observations)
271
+ and _array_equal(self.dt, other.dt)
272
+ and _array_equal(self.mask, other.mask)
273
+ and _array_equal(self.cov_transition, other.cov_transition)
274
+ and _array_equal(self.cov_duration, other.cov_duration)
275
+ and _array_equal(self.cov_emission, other.cov_emission)
276
+ and self.cov_names == other.cov_names
277
+ and self.clock == other.clock
278
+ and self.nominal_dt == other.nominal_dt
279
+ and self.prep_stats == other.prep_stats
280
+ and self.snapshot_ids == other.snapshot_ids
281
+ and self.support == other.support
282
+ and self.n_categories == other.n_categories
283
+ and _array_equal(self.labels, other.labels)
284
+ and self.boundaries == other.boundaries
285
+ and self.group == other.group
286
+ and self.series_support == other.series_support
287
+ )
288
+
289
+ def window(self, start: int, end: int) -> PreparedDataset:
290
+ """Slice `[start, end)` along `T`.
291
+
292
+ Keeps `dt`, masks, covariates, `cov_names`, `prep_stats`, `snapshot_ids`, `support`,
293
+ `group`, and `nominal_dt` (a property of the grid, not the slice).
294
+ """
295
+
296
+ def _slice(arr: Array | None) -> Array | None:
297
+ return None if arr is None else arr[start:end]
298
+
299
+ def _slice_required(arr: Array) -> Array:
300
+ return arr[start:end]
301
+
302
+ boundaries = None
303
+ if self.boundaries is not None:
304
+ boundaries = BoundaryConstraints(
305
+ must_switch_at=tuple(i - start for i in self.boundaries.must_switch_at if start < i < end),
306
+ must_not_switch_at=tuple(
307
+ i - start for i in self.boundaries.must_not_switch_at if start < i < end
308
+ ),
309
+ )
310
+
311
+ return dataclasses.replace(
312
+ self,
313
+ times=self.times[start:end],
314
+ observations=_slice_required(self.observations),
315
+ dt=_slice_required(self.dt),
316
+ mask=_slice_required(self.mask),
317
+ cov_transition=_slice(self.cov_transition),
318
+ cov_duration=_slice(self.cov_duration),
319
+ cov_emission=_slice(self.cov_emission),
320
+ labels=_slice(self.labels),
321
+ boundaries=boundaries,
322
+ )
323
+
324
+ def validate(self) -> None:
325
+ """Raise `DataError(path=<field>)` on any contract violation."""
326
+ times, observations, dt, mask = self.times, self.observations, self.dt, self.mask
327
+
328
+ if times.ndim != 1:
329
+ raise DataError("times must be 1-D", path="times")
330
+ t = times.shape[0]
331
+ step_index = np.issubdtype(times.dtype, np.integer)
332
+ if step_index and get_clock(self.clock).unit != "step":
333
+ raise DataError(
334
+ f"an integer step index is only valid under a step clock, not {self.clock!r}", path="times"
335
+ )
336
+ if t > 1 and not np.all(np.diff(times) > (0 if step_index else np.timedelta64(0, "ns"))):
337
+ raise DataError("times must be strictly increasing", path="times")
338
+
339
+ if observations.ndim != 2 or observations.shape[0] != t:
340
+ raise DataError(f"observations must have shape (T={t}, M)", path="observations")
341
+ m = observations.shape[1]
342
+
343
+ if dt.ndim != 1 or dt.shape[0] != t:
344
+ raise DataError(f"dt must have shape (T={t},)", path="dt")
345
+ if not bool(np.all(np.asarray(dt) > 0)):
346
+ raise DataError("dt must be > 0 everywhere", path="dt")
347
+ clock = get_clock(self.clock) # unknown name: ConfigError listing the registered clocks
348
+ if clock.unit == "step" and not bool(np.all(np.asarray(dt) == 1)):
349
+ raise DataError(f"dt must be exactly 1 under the step clock {self.clock!r}", path="dt")
350
+
351
+ if mask.shape != (t, m) or np.asarray(mask).dtype != np.bool_:
352
+ raise DataError(f"mask must be a bool array of shape (T={t}, M={m})", path="mask")
353
+
354
+ obs_np = np.asarray(observations)
355
+ mask_np = np.asarray(mask)
356
+ if not np.all(np.isfinite(obs_np[mask_np])):
357
+ raise DataError("observations must be finite where mask is True", path="observations")
358
+
359
+ self._validate_support(obs_np, mask_np)
360
+ self._validate_covariates(t)
361
+ self._validate_labels(t)
362
+ self._validate_boundaries(t)
363
+
364
+ def _validate_support(self, obs_np: np.ndarray, mask_np: np.ndarray) -> None:
365
+ if self.series_support is not None:
366
+ self._validate_series_support(obs_np, mask_np)
367
+ return
368
+ observed = obs_np[mask_np]
369
+ if self.support == "real":
370
+ if not _is_float_dtype(obs_np.dtype):
371
+ raise DataError("support='real' requires float observations", path="observations")
372
+ elif self.support == "count":
373
+ if not (np.issubdtype(obs_np.dtype, np.integer) and bool(np.all(observed >= 0))):
374
+ raise DataError(
375
+ "support='count' requires non-negative integer observations", path="observations"
376
+ )
377
+ elif self.support == "binary":
378
+ if not bool(np.all(np.isin(observed, [0, 1]))):
379
+ raise DataError("support='binary' requires observations in {0, 1}", path="observations")
380
+ elif self.support == "categorical":
381
+ if self.n_categories is None:
382
+ raise DataError("support='categorical' requires n_categories", path="n_categories")
383
+ if not (
384
+ np.issubdtype(obs_np.dtype, np.integer)
385
+ and bool(np.all((observed >= 0) & (observed < self.n_categories)))
386
+ ):
387
+ raise DataError(
388
+ f"support='categorical' requires integers in [0, {self.n_categories})",
389
+ path="observations",
390
+ )
391
+
392
+ def _validate_series_support(self, obs_np: np.ndarray, mask_np: np.ndarray) -> None:
393
+ """Mixed supports: every column against its own support (`categorical` is not allowed in a mix)."""
394
+ assert self.series_support is not None
395
+ if len(self.series_support) != obs_np.shape[1]:
396
+ raise DataError(
397
+ f"series_support has {len(self.series_support)} entries for {obs_np.shape[1]} series",
398
+ path="series_support",
399
+ )
400
+ for m, support in enumerate(self.series_support):
401
+ col = obs_np[mask_np[:, m], m]
402
+ if support == "count":
403
+ ok = bool(np.all((col >= 0) & (col == np.rint(col))))
404
+ elif support == "binary":
405
+ ok = bool(np.all(np.isin(col, [0, 1])))
406
+ elif support == "real":
407
+ ok = bool(np.all(np.isfinite(col)))
408
+ else:
409
+ raise DataError(f"series {m}: support {support!r} cannot be mixed", path="series_support")
410
+ if not ok:
411
+ raise DataError(
412
+ f"series {m}: observations violate support {support!r}", path=f"observations[:, {m}]"
413
+ )
414
+
415
+ def _validate_covariates(self, t: int) -> None:
416
+ blocks = {
417
+ "transition": self.cov_transition,
418
+ "duration": self.cov_duration,
419
+ "emission": self.cov_emission,
420
+ }
421
+ for entry_point, block in blocks.items():
422
+ path = f"cov_{entry_point}"
423
+ names = self.cov_names.get(entry_point, ())
424
+ if block is None:
425
+ if names:
426
+ raise DataError(f"cov_names['{entry_point}'] set but {path} is None", path="cov_names")
427
+ continue
428
+ if block.ndim != 2 or block.shape[0] != t:
429
+ raise DataError(f"{path} must have shape (T={t}, K)", path=path)
430
+ if len(names) != block.shape[1]:
431
+ raise DataError(
432
+ f"cov_names['{entry_point}'] length must match {path}.shape[1]", path="cov_names"
433
+ )
434
+
435
+ def _validate_labels(self, t: int) -> None:
436
+ if self.labels is None:
437
+ return
438
+ if self.labels.ndim != 2 or self.labels.shape[0] != t or np.asarray(self.labels).dtype != np.bool_:
439
+ raise DataError("labels must be a bool array of shape (T, N)", path="labels")
440
+
441
+ def _validate_boundaries(self, t: int) -> None:
442
+ if self.boundaries is None:
443
+ return
444
+ for indices in (self.boundaries.must_switch_at, self.boundaries.must_not_switch_at):
445
+ for i in indices:
446
+ if not (1 <= i <= t - 1):
447
+ raise DataError(f"boundary index {i} outside [1, {t - 1}]", path="boundaries")
448
+
449
+
450
+ @dataclass(frozen=True)
451
+ class _HashableArray:
452
+ """Wraps a numpy array so it can sit in a pytree's static aux data.
453
+
454
+ `times` is metadata (grid end times, dtype `datetime64[ns]`): not a valid JAX array dtype, so
455
+ it cannot be a pytree leaf (`jax.jit` would reject it), yet a raw `np.ndarray` is also not
456
+ safely hashable/comparable as plain aux data (`array == array` returns an array, not a bool,
457
+ breaking JAX's aux-equality check whenever `times` has more than one element — see CLAUDE.md
458
+ §5's "NumPy arrays are unhashable" gotcha). This wrapper is used only inside flatten/unflatten
459
+ below; `PreparedDataset.times` itself stays a plain `np.ndarray`.
460
+ """
461
+
462
+ array: np.ndarray
463
+
464
+ def __eq__(self, other: object) -> bool:
465
+ """Value equality via `np.array_equal`, always returning a plain `bool`."""
466
+ if not isinstance(other, _HashableArray):
467
+ return NotImplemented
468
+ return bool(np.array_equal(self.array, other.array))
469
+
470
+ def __hash__(self) -> int:
471
+ """Hash the array's shape, dtype, and bytes."""
472
+ return hash((self.array.shape, self.array.dtype.str, self.array.tobytes()))
473
+
474
+
475
+ def _flatten_prepared_dataset(
476
+ dataset: PreparedDataset,
477
+ ) -> tuple[tuple[Array | None, ...], tuple[Any, ...]]:
478
+ children = (
479
+ dataset.observations,
480
+ dataset.dt,
481
+ dataset.mask,
482
+ dataset.cov_transition,
483
+ dataset.cov_duration,
484
+ dataset.cov_emission,
485
+ dataset.labels,
486
+ )
487
+ aux = (
488
+ _HashableArray(dataset.times),
489
+ tuple(sorted(dataset.cov_names.items())),
490
+ dataset.clock,
491
+ dataset.nominal_dt,
492
+ dataset.prep_stats,
493
+ dataset.snapshot_ids,
494
+ dataset.support,
495
+ dataset.n_categories,
496
+ dataset.boundaries,
497
+ dataset.group,
498
+ dataset.series_support,
499
+ )
500
+ return children, aux
501
+
502
+
503
+ def _unflatten_prepared_dataset(aux: tuple[Any, ...], children: tuple[Array | None, ...]) -> PreparedDataset:
504
+ (
505
+ times,
506
+ cov_names_items,
507
+ clock,
508
+ nominal_dt,
509
+ prep_stats,
510
+ snapshot_ids,
511
+ support,
512
+ n_categories,
513
+ boundaries,
514
+ group,
515
+ series_support,
516
+ ) = aux
517
+ observations, dt, mask, cov_transition, cov_duration, cov_emission, labels = children
518
+ assert observations is not None
519
+ assert dt is not None
520
+ assert mask is not None
521
+ return PreparedDataset(
522
+ times=times.array,
523
+ observations=observations,
524
+ dt=dt,
525
+ mask=mask,
526
+ cov_transition=cov_transition,
527
+ cov_duration=cov_duration,
528
+ cov_emission=cov_emission,
529
+ cov_names=dict(cov_names_items),
530
+ clock=clock,
531
+ nominal_dt=nominal_dt,
532
+ prep_stats=prep_stats,
533
+ snapshot_ids=snapshot_ids,
534
+ support=support,
535
+ n_categories=n_categories,
536
+ labels=labels,
537
+ boundaries=boundaries,
538
+ group=group,
539
+ series_support=series_support,
540
+ )
541
+
542
+
543
+ jax.tree_util.register_pytree_node(PreparedDataset, _flatten_prepared_dataset, _unflatten_prepared_dataset)
hsmmkit/data/labels.py ADDED
@@ -0,0 +1,150 @@
1
+ """Regime labels and boundary constraints as data (E12-T06, FR-SV01, FR-SV02).
2
+
3
+ `data.labels` gives full or partial supervision. Three encodings reach the `Preparer` as one raw value per
4
+ observation row (`ObservationSet.meta["label_values"]`): a column of regime ids (`NaN` / `-1` = unlabelled), a
5
+ column of allowed sets (`allowed_sets: true`: a bitmask int, or a list-valued column), or a label file
6
+ (`sequence_id`, `t`, then `regime` or `allowed`; `t` is the 0-based row within the sequence). `Preparer` turns
7
+ them into `PreparedDataset.labels (T, N)` bool: one `True` per labelled row, all `True` where unlabelled.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import dataclasses
13
+ import math
14
+ from collections.abc import Sequence
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+ from hsmmkit.data.contracts import BoundaryConstraints, ObservationSet
22
+ from hsmmkit.utils.errors import DataError
23
+
24
+ __all__ = ["allowed_from_values", "attach_label_file", "boundaries_of"]
25
+
26
+ _PATH = "data.labels"
27
+
28
+
29
+ def _is_missing(v: Any) -> bool: # noqa: ANN401
30
+ if v is None:
31
+ return True
32
+ if isinstance(v, float | np.floating):
33
+ return math.isnan(float(v))
34
+ return bool(v is pd.NA)
35
+
36
+
37
+ def _as_int(v: Any, what: str) -> int: # noqa: ANN401
38
+ f = float(v)
39
+ if not f.is_integer():
40
+ raise DataError(f"{what} must be an integer, got {v!r}", path=_PATH)
41
+ return int(f)
42
+
43
+
44
+ def allowed_from_values(
45
+ values: Sequence[Any], n_regimes: int, *, allowed_sets: bool = False, path: str = _PATH
46
+ ) -> np.ndarray:
47
+ """`(T, N)` bool allowed regimes from raw label values (an unlabelled row allows every regime).
48
+
49
+ Raises:
50
+ DataError: an id outside `[0, N)`, a set with a regime outside `[0, N)`, or an empty set.
51
+ """
52
+ out = np.ones((len(values), n_regimes), dtype=bool)
53
+ for i, v in enumerate(values):
54
+ if isinstance(v, str | bytes):
55
+ raise DataError(f"label of row {i} is a string ({v!r}); expected regime ids", path=path)
56
+ if not isinstance(v, list | tuple | set | np.ndarray) and _is_missing(v):
57
+ continue
58
+ if allowed_sets:
59
+ if isinstance(v, list | tuple | set | np.ndarray):
60
+ ids = {_as_int(x, f"label set of row {i}") for x in v}
61
+ else:
62
+ mask = _as_int(v, f"label set of row {i}")
63
+ if mask == -1:
64
+ continue
65
+ if mask < 0:
66
+ raise DataError(f"label set of row {i} is a negative bitmask ({mask})", path=path)
67
+ ids = {k for k in range(max(mask.bit_length(), 1)) if (mask >> k) & 1}
68
+ if not ids:
69
+ raise DataError(f"label set of row {i} is empty", path=path)
70
+ if min(ids) < 0 or max(ids) >= n_regimes:
71
+ raise DataError(
72
+ f"label set of row {i} names regimes {sorted(ids)} outside [0, {n_regimes})", path=path
73
+ )
74
+ out[i] = False
75
+ out[i, sorted(ids)] = True
76
+ else:
77
+ k = _as_int(v, f"label of row {i}")
78
+ if k == -1:
79
+ continue
80
+ if not 0 <= k < n_regimes:
81
+ raise DataError(f"label {k} of row {i} is outside [0, {n_regimes})", path=path)
82
+ out[i] = False
83
+ out[i, k] = True
84
+ return out
85
+
86
+
87
+ def attach_label_file(obs: ObservationSet, path: Path | str) -> ObservationSet:
88
+ """`obs` with `meta["label_values"]` read from a label file (parquet or CSV).
89
+
90
+ The file has the columns `t` (0-based row within the sequence), `regime` or `allowed`, and `sequence_id`
91
+ (optional for a single-sequence data set). Rows of `obs` without an entry are unlabelled.
92
+
93
+ Raises:
94
+ DataError: an unreadable file, missing columns, or an entry that matches no row of `obs`.
95
+ """
96
+ p = Path(path)
97
+ try:
98
+ frame = pd.read_parquet(p) if p.suffix == ".parquet" else pd.read_csv(p)
99
+ except (OSError, ValueError) as exc:
100
+ raise DataError(f"cannot read the label file {p}: {exc}", path="data.labels.path") from exc
101
+ value_col = "regime" if "regime" in frame.columns else "allowed" if "allowed" in frame.columns else None
102
+ if "t" not in frame.columns or value_col is None:
103
+ raise DataError(
104
+ f"the label file {p} needs the columns 't' and 'regime' (or 'allowed'), "
105
+ f"has {list(frame.columns)}",
106
+ path="data.labels.path",
107
+ )
108
+ n_rows = obs.values.shape[0]
109
+ ids = np.asarray(obs.sequence_ids).astype(str) if obs.sequence_ids is not None else np.full(n_rows, "0")
110
+ position = np.zeros(n_rows, dtype=np.int64)
111
+ seen: dict[str, int] = {}
112
+ for i, sid in enumerate(ids):
113
+ position[i] = seen.get(sid, 0)
114
+ seen[sid] = position[i] + 1
115
+ file_ids = (
116
+ frame["sequence_id"].astype(str)
117
+ if "sequence_id" in frame.columns
118
+ else pd.Series("0", index=frame.index)
119
+ )
120
+ entries = {
121
+ (str(s), int(t)): v for s, t, v in zip(file_ids, frame["t"], frame[value_col].tolist(), strict=True)
122
+ }
123
+ values: list[Any] = [entries.pop((ids[i], int(position[i])), None) for i in range(n_rows)]
124
+ if entries:
125
+ key = next(iter(entries))
126
+ raise DataError(
127
+ f"{len(entries)} label entries match no observation row (first: sequence {key[0]!r}, t={key[1]})",
128
+ path="data.labels.path",
129
+ )
130
+ return dataclasses.replace(obs, meta={**obs.meta, "label_values": values})
131
+
132
+
133
+ def boundaries_of(
134
+ must_switch_at: Sequence[int], must_not_switch_at: Sequence[int], t_len: int
135
+ ) -> BoundaryConstraints | None:
136
+ """The boundary indices that fall inside a sequence of `t_len` steps (`1 <= t <= t_len - 1`), else `None`.
137
+
138
+ Indices outside the sequence are dropped (a configured list applies to every sequence of a batch).
139
+
140
+ Raises:
141
+ DataError: an index in both lists, or an index below 1.
142
+ """
143
+ if any(i < 1 for i in (*must_switch_at, *must_not_switch_at)):
144
+ raise DataError("boundary steps must be >= 1 (a switch is between steps t-1 and t)", path=_PATH)
145
+ both = set(must_switch_at) & set(must_not_switch_at)
146
+ if both:
147
+ raise DataError(f"step(s) {sorted(both)} are both must_switch_at and must_not_switch_at", path=_PATH)
148
+ sw = tuple(sorted(i for i in set(must_switch_at) if i < t_len))
149
+ ns = tuple(sorted(i for i in set(must_not_switch_at) if i < t_len))
150
+ return BoundaryConstraints(sw, ns) if sw or ns else None