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,505 @@
1
+ # ruff: noqa: N803, ANN401
2
+ """scikit-learn `HSMM` estimator (E16-T01; Part II Appendix I): `fit` / `predict` on top of the full model.
3
+
4
+ `HSMM(BaseEstimator)` maps the familiar API onto a `ProjectConfig` with `clock: steps` and the core
5
+ pipeline (`estimation.fit`, `inference.decode`). The constructor stores its arguments only;
6
+ `fit(X, y=None, *, lengths=None)` takes `X (sum T_b, M)` with `lengths` as in `hmmlearn` (`None`: one
7
+ sequence), splits `covariate_columns` off `X` as covariates of the transitions (the rows are used as
8
+ given: they must already be the values known at the previous step), and turns integer labels `y`
9
+ (`-1` unknown) into allowed-state sets of the constraint layer.
10
+ `config_overrides` are dotted configuration paths (`"estimation.restarts": 4`).
11
+
12
+ Importing this module needs scikit-learn (`pip install 'hsmmkit[sklearn]'`); `import hsmmkit` does not.
13
+ Pipelines with transformers that change `lengths` are not supported.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import copy
19
+ from collections.abc import Sequence
20
+ from typing import TYPE_CHECKING, Any
21
+
22
+ import jax
23
+ import jax.numpy as jnp
24
+ import numpy as np
25
+
26
+ from hsmmkit.config.schema import ForecastSection, parse_project_config
27
+ from hsmmkit.data.batch import SequenceBatch
28
+ from hsmmkit.data.contracts import PreparedDataset, PrepStats
29
+ from hsmmkit.estimation import fit as run_fit
30
+ from hsmmkit.inference.decode import decode
31
+ from hsmmkit.inference.simulate import simulate_paths
32
+ from hsmmkit.model.build import BuildInputs, build_model_spec_from
33
+ from hsmmkit.utils.errors import ConfigError
34
+ from hsmmkit.utils.optional import optional_import
35
+ from hsmmkit.utils.rng import key_for
36
+
37
+ _sk_base = optional_import("sklearn.base", extra="sklearn")
38
+ _sk_validation = optional_import("sklearn.utils.validation", extra="sklearn")
39
+ BaseEstimator: Any = _sk_base.BaseEstimator
40
+
41
+ if TYPE_CHECKING:
42
+ from hsmmkit.estimation.results import FitResult
43
+ from hsmmkit.inference.results import ForecastResult, PosteriorResult
44
+ from hsmmkit.model.spec import ModelSpec
45
+
46
+ __all__ = ["HSMM"]
47
+
48
+ _DISCRETE = {"poisson", "bernoulli", "categorical"}
49
+ _SECTIONS = {"project", "data", "model", "estimation", "forecast", "evaluation", "output", "online"}
50
+ _EXPLICIT = {"gamma", "weibull", "lognormal", "poisson", "nonparametric"}
51
+ _DEFAULT_SOJOURN = 10.0
52
+
53
+
54
+ def _set_path(raw: dict[str, Any], path: str, value: Any) -> None:
55
+ """`raw["a"]["b"]["c"] = value` for the dotted `path`, creating dictionaries on the way."""
56
+ parts = path.split(".")
57
+ node = raw
58
+ for part in parts[:-1]:
59
+ nxt = node.get(part)
60
+ if not isinstance(nxt, dict):
61
+ nxt = {}
62
+ node[part] = nxt
63
+ node = nxt
64
+ node[parts[-1]] = copy.deepcopy(value)
65
+
66
+
67
+ def _seed_of(random_state: Any) -> int:
68
+ """`random_state` -> int seed: `None` is 0, a `RandomState` / `Generator` gives its next draw."""
69
+ if random_state is None:
70
+ return 0
71
+ if isinstance(random_state, (int, np.integer)):
72
+ return int(random_state)
73
+ if hasattr(random_state, "randint"):
74
+ return int(random_state.randint(2**31 - 1))
75
+ if hasattr(random_state, "integers"):
76
+ return int(random_state.integers(2**31 - 1))
77
+ raise ValueError(f"unsupported random_state {random_state!r}")
78
+
79
+
80
+ def _prepared(
81
+ y: np.ndarray, z: np.ndarray | None, names: tuple[str, ...], labels: np.ndarray | None
82
+ ) -> PreparedDataset:
83
+ """A `PreparedDataset` on the step grid (`dt = 1`) with optional transition covariates and labels."""
84
+ t_len = y.shape[0]
85
+ stats = PrepStats(
86
+ cov_mean=np.zeros(0), cov_std=np.ones(0), train_window=("", ""), cov_names=(), transforms={}, lags={}
87
+ )
88
+ return PreparedDataset(
89
+ times=np.arange(t_len).astype("datetime64[D]").astype("datetime64[ns]"),
90
+ observations=jnp.asarray(y),
91
+ dt=jnp.ones(t_len),
92
+ mask=jnp.ones(y.shape, dtype=bool),
93
+ cov_transition=None if z is None else jnp.asarray(z),
94
+ cov_duration=None,
95
+ cov_emission=None,
96
+ cov_names={"transition": names, "duration": (), "emission": ()},
97
+ clock="steps",
98
+ nominal_dt=1.0,
99
+ prep_stats=stats,
100
+ snapshot_ids=(),
101
+ labels=None if labels is None else jnp.asarray(labels),
102
+ )
103
+
104
+
105
+ class HSMM(BaseEstimator): # type: ignore[misc]
106
+ """A hidden semi-Markov model with a scikit-learn interface.
107
+
108
+ Args:
109
+ n_states: number of regimes.
110
+ emission: registered emission family (`gaussian`, `student_t`, `poisson`, ...).
111
+ duration: `geometric`, `negbin` (expanded engine) or an explicit family (`gamma`, `weibull`, ...).
112
+ r: phases of the `negbin` duration.
113
+ topology: `full` (other values are passed to `model.topology`).
114
+ estimator: `map`, `em`, `gem`, `vb` or `mcmc`.
115
+ engine: `expanded` or `explicit` (explicit durations force `explicit`).
116
+ covariance: `diag` or `full` Gaussian covariance.
117
+ covariate_columns: column indices of `X` that are covariates.
118
+ random_state: int (or `RandomState` / `Generator`; `None` means 0) -> `project.seed`.
119
+ **config_overrides: dotted configuration paths, e.g. `"estimation.restarts": 4`.
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ n_states: int = 3,
125
+ emission: str = "gaussian",
126
+ duration: str = "negbin",
127
+ r: int = 3,
128
+ topology: str = "full",
129
+ estimator: str = "map",
130
+ engine: str = "expanded",
131
+ covariance: str = "diag",
132
+ covariate_columns: Sequence[int] | None = None,
133
+ random_state: Any = None,
134
+ **config_overrides: Any,
135
+ ) -> None:
136
+ """Store the arguments (scikit-learn rule: no validation, no work)."""
137
+ self.n_states = n_states
138
+ self.emission = emission
139
+ self.duration = duration
140
+ self.r = r
141
+ self.topology = topology
142
+ self.estimator = estimator
143
+ self.engine = engine
144
+ self.covariance = covariance
145
+ self.covariate_columns = covariate_columns
146
+ self.random_state = random_state
147
+ self.config_overrides = dict(config_overrides)
148
+
149
+ # -- parameters -----------------------------------------------------------------------------
150
+
151
+ def get_params(self, deep: bool = True) -> dict[str, Any]:
152
+ """The constructor arguments plus the configuration overrides (flat)."""
153
+ params: dict[str, Any] = super().get_params(deep=deep)
154
+ params.update(self.config_overrides)
155
+ return params
156
+
157
+ def set_params(self, **params: Any) -> HSMM:
158
+ """Set constructor arguments; unknown keys are configuration overrides."""
159
+ own = set(super().get_params(deep=False))
160
+ for key, value in params.items():
161
+ if key in own:
162
+ setattr(self, key, value)
163
+ else:
164
+ self.config_overrides = {**self.config_overrides, key: value}
165
+ return self
166
+
167
+ # -- configuration --------------------------------------------------------------------------
168
+
169
+ def _raw(self, x: np.ndarray, n_cov: int) -> dict[str, Any]:
170
+ n, m = self.n_states, x.shape[1]
171
+ q = np.quantile(x[:, 0], np.linspace(0.15, 0.85, n)) if n > 1 else np.array([float(np.mean(x[:, 0]))])
172
+ scale0 = float(np.std(x[:, 0])) or 1.0
173
+ explicit = self.duration in _EXPLICIT
174
+ emission: dict[str, Any] = {"family": self.emission, "scale_by_dt": False}
175
+ if self.emission == "gaussian":
176
+ emission["ito_correction"] = False
177
+ emission["covariance"] = self.covariance
178
+ emission["params"] = {"mean": {"mode": "free", "init": [float(v) for v in q]}}
179
+ if self.covariance == "full":
180
+ emission["params"]["chol"] = {"mode": "free"}
181
+ else:
182
+ emission["params"]["scale"] = {"mode": "free", "init": [scale0] * n}
183
+ elif self.emission == "student_t":
184
+ emission["params"] = {
185
+ "m": {"mode": "free", "init": [float(v) for v in q]},
186
+ "s": {"mode": "free", "init": [scale0] * n},
187
+ "nu": {"mode": "free", "init": [8.0] * n},
188
+ }
189
+ elif self.emission == "poisson":
190
+ emission["params"] = {"rate": {"mode": "free", "init": [max(float(v), 0.5) for v in q]}}
191
+ else:
192
+ emission["params"] = {}
193
+ sojourn = {"init_mean_sojourn_steps": [_DEFAULT_SOJOURN] * n}
194
+ if explicit:
195
+ from hsmmkit.selection.grid import FAMILY_PARAMS
196
+
197
+ params = copy.deepcopy(FAMILY_PARAMS[self.duration])
198
+ first = next(iter(params))
199
+ params[first] = {**params[first], **sojourn}
200
+ duration: dict[str, Any] = {"family": self.duration, "params": params}
201
+ else:
202
+ duration = {"family": self.duration, "params": {"rate": {"mode": "free", **sojourn}}}
203
+ if self.duration == "negbin":
204
+ duration["r"] = [int(self.r)] * n
205
+ model: dict[str, Any] = {
206
+ "n_states": n,
207
+ "initial_state": "uniform",
208
+ "emission": emission,
209
+ "duration": {"covariates": [], **duration},
210
+ "transition": {"mode": "jump", "order": 1, "covariates": []},
211
+ }
212
+ if self.topology != "full":
213
+ model["topology"] = self.topology
214
+ if explicit or self.engine == "explicit":
215
+ model["engine"] = "explicit"
216
+ model["d_max"] = 60
217
+ raw: dict[str, Any] = {
218
+ "schema_version": 1,
219
+ "project": {"name": "sklearn", "seed": _seed_of(self.random_state), "output_dir": "runs"},
220
+ "data": {
221
+ "source": {
222
+ "kind": "csv",
223
+ "path": "unused.csv",
224
+ "observation_columns": [f"x{i}" for i in range(m)],
225
+ },
226
+ "clock": "steps",
227
+ },
228
+ "model": model,
229
+ "estimation": {
230
+ "method": self.estimator,
231
+ "restarts": 3,
232
+ "max_iter": 200,
233
+ "init": ["rolling_kmeans", "random"],
234
+ "device": "cpu",
235
+ },
236
+ "forecast": {
237
+ "horizon": 1,
238
+ "n_sim": 200,
239
+ "covariate_forecaster": {"type": "freeze"},
240
+ "quantiles": [0.05, 0.5, 0.95],
241
+ },
242
+ "evaluation": {
243
+ "metrics": ["log_score"],
244
+ "backtest": {
245
+ "scheme": "expanding",
246
+ "initial_train_steps": 100,
247
+ "refit_every_steps": 50,
248
+ "horizons": [1],
249
+ "embargo_steps": 0,
250
+ },
251
+ },
252
+ "output": {"write": ["backtest"]},
253
+ }
254
+ if n_cov:
255
+ names = [f"c{i}" for i in range(n_cov)]
256
+ raw["data"]["source"]["covariate_columns"] = names
257
+ raw["data"]["covariates"] = [{"name": c, "lag": 1, "use_in": ["transition"]} for c in names]
258
+ raw["model"]["transition"]["covariates"] = names
259
+ for key, value in self.config_overrides.items():
260
+ _set_path(raw, key, value)
261
+ return raw
262
+
263
+ # -- data -----------------------------------------------------------------------------------
264
+
265
+ def _check(
266
+ self, x: Any, *, reset: bool, lengths: Sequence[int] | None
267
+ ) -> tuple[np.ndarray, np.ndarray | None, list[int]]:
268
+ """`(observations, covariates, lengths)` from `X (sum T_b, M [+ K])`."""
269
+ arr = _sk_validation.validate_data(
270
+ self,
271
+ x,
272
+ reset=reset,
273
+ dtype=np.float64,
274
+ ensure_2d=True,
275
+ ensure_min_samples=2 if reset else 1,
276
+ )
277
+ cols = list(self.covariate_columns or [])
278
+ if any(not 0 <= c < arr.shape[1] for c in cols):
279
+ raise ValueError(f"covariate_columns {cols} out of range for X with {arr.shape[1]} columns")
280
+ keep = [i for i in range(arr.shape[1]) if i not in cols]
281
+ if not keep:
282
+ raise ValueError("every column of X is a covariate: no observation columns left")
283
+ obs, cov = arr[:, keep], (arr[:, cols] if cols else None)
284
+ if self.emission in _DISCRETE and not (np.all(obs == np.floor(obs)) and np.all(obs >= 0)):
285
+ raise ValueError(f"the {self.emission} emission needs non-negative integer-valued X")
286
+ sizes = [arr.shape[0]] if lengths is None else [int(n) for n in lengths]
287
+ if sum(sizes) != arr.shape[0] or any(n < 1 for n in sizes):
288
+ raise ValueError("lengths must be positive and sum to the number of rows of X")
289
+ return obs, cov, sizes
290
+
291
+ def _datasets(
292
+ self, obs: np.ndarray, cov: np.ndarray | None, sizes: list[int], labels: np.ndarray | None = None
293
+ ) -> list[PreparedDataset]:
294
+ out, start = [], 0
295
+ names = tuple(f"c{i}" for i in range(0 if cov is None else cov.shape[1]))
296
+ for n in sizes:
297
+ sl = slice(start, start + n)
298
+ allowed = None
299
+ if labels is not None:
300
+ lab = labels[sl]
301
+ allowed = np.ones((n, self.n_states), dtype=bool)
302
+ known = lab >= 0
303
+ allowed[known] = False
304
+ allowed[np.flatnonzero(known), lab[known]] = True
305
+ out.append(_prepared(obs[sl], None if cov is None else cov[sl], names, allowed))
306
+ start += n
307
+ return out
308
+
309
+ # -- API ------------------------------------------------------------------------------------
310
+
311
+ def fit(
312
+ self,
313
+ X: Any,
314
+ y: Any = None,
315
+ *,
316
+ lengths: Sequence[int] | None = None,
317
+ **fit_params: Any,
318
+ ) -> HSMM:
319
+ """Fit on `X (sum T_b, M)`; `lengths` splits the sequences; `y` (int, `-1` unknown) labels regimes.
320
+
321
+ `lengths` is keyword-only (scikit-learn passes `y` as the second positional argument; `hmmlearn`'s
322
+ `fit(X, lengths)` becomes `fit(X, lengths=lengths)`).
323
+
324
+ Raises:
325
+ ValueError: `sample_weight` is given (unsupported), `y` has the wrong length or out-of-range
326
+ labels (or looks like `lengths`), `lengths` do not sum to the rows of `X`.
327
+ """
328
+ if fit_params.get("sample_weight") is not None:
329
+ raise ValueError("sample_weight is not supported by HSMM")
330
+ if set(fit_params) - {"sample_weight"}:
331
+ raise TypeError(
332
+ f"fit() got unexpected keyword arguments {sorted(set(fit_params) - {'sample_weight'})}"
333
+ )
334
+ for stale in ("means_", "transmat_"):
335
+ if hasattr(self, stale):
336
+ delattr(self, stale)
337
+ obs, cov, sizes = self._check(X, reset=True, lengths=lengths)
338
+ self._lengths_trap(y, obs.shape[0])
339
+ labels = self._labels(y, obs.shape[0])
340
+ bad = [k for k in self.config_overrides if k.split(".")[0] not in _SECTIONS]
341
+ if bad:
342
+ raise ValueError(
343
+ f"unknown configuration override(s) {bad}; keys start with one of {sorted(_SECTIONS)}"
344
+ )
345
+ raw = self._raw(obs, 0 if cov is None else cov.shape[1])
346
+ if labels is not None:
347
+ raw.setdefault("data", {})["labels"] = {"source": "column", "column": "label"}
348
+ raw["estimation"]["init"] = ["labels", *raw["estimation"]["init"]]
349
+ try:
350
+ cfg = parse_project_config(raw)
351
+ except ConfigError as exc:
352
+ raise ValueError(str(exc)) from exc
353
+ names = tuple(f"c{i}" for i in range(0 if cov is None else cov.shape[1]))
354
+ cov_names = {"transition": names} if names else {}
355
+ spec: ModelSpec = build_model_spec_from(
356
+ cfg, BuildInputs(n_series=obs.shape[1], cov_names=cov_names, clock="steps", nominal_dt=1.0)
357
+ )
358
+ sets = self._datasets(obs, cov, sizes, labels)
359
+ data: PreparedDataset | SequenceBatch = (
360
+ sets[0]
361
+ if len(sets) == 1
362
+ else SequenceBatch(tuple(sets), (), tuple(str(i) for i in range(len(sets))))
363
+ )
364
+ self.config_ = cfg
365
+ self.spec_ = spec
366
+ self.result_: FitResult = run_fit(spec, data, cfg.estimation, cfg.project.seed)
367
+ self.n_states_ = self.n_states
368
+ params = self.result_.params
369
+ if "emission.mean" in params:
370
+ self.means_ = np.asarray(params["emission.mean"]).reshape(self.n_states, -1)
371
+ elif "emission.eta" in params and self.emission == "poisson":
372
+ self.means_ = np.exp(np.asarray(params["emission.eta"])).reshape(self.n_states, -1)
373
+ if "transition.pi_rows" in params:
374
+ rows = np.asarray(params["transition.pi_rows"])
375
+ if rows.shape == (self.n_states, self.n_states - 1): # a full topology
376
+ self.transmat_ = self._jump_matrix(rows)
377
+ return self
378
+
379
+ @staticmethod
380
+ def _jump_matrix(pi_rows: np.ndarray) -> np.ndarray:
381
+ n = pi_rows.shape[0]
382
+ out = np.zeros((n, n))
383
+ for i in range(n):
384
+ out[i, np.arange(n) != i] = pi_rows[i]
385
+ return out
386
+
387
+ @staticmethod
388
+ def _lengths_trap(y: Any, n_rows: int) -> None:
389
+ """A second positional argument that looks like `lengths` (hmmlearn order) is an error, not labels."""
390
+ if y is None:
391
+ return
392
+ arr = np.asarray(y)
393
+ if arr.ndim == 1 and arr.shape[0] != n_rows and int(arr.sum()) == n_rows:
394
+ raise ValueError("the second argument is `y` (labels); pass the sequence lengths as `lengths=`")
395
+
396
+ def _labels(self, y: Any, n_rows: int) -> np.ndarray | None:
397
+ """`y` as int labels (`-1` unknown), validated against the rows of `X` and `n_states`."""
398
+ if y is None:
399
+ return None
400
+ labels = np.asarray(y).reshape(-1).astype(np.int64)
401
+ if labels.shape[0] != n_rows:
402
+ raise ValueError("y must have one label per row of X (-1 = unknown)")
403
+ if labels.max() >= self.n_states or labels.min() < -1:
404
+ raise ValueError(f"labels must be -1 (unknown) or in 0..{self.n_states - 1}")
405
+ return labels
406
+
407
+ def _decoded(self, X: Any, lengths: Sequence[int] | None, y: Any = None) -> list[PosteriorResult]:
408
+ _sk_validation.check_is_fitted(self, "result_")
409
+ obs, cov, sizes = self._check(X, reset=False, lengths=lengths)
410
+ labels = self._labels(y, obs.shape[0])
411
+ return [decode(self.result_, ds) for ds in self._datasets(obs, cov, sizes, labels)]
412
+
413
+ def predict(self, X: Any, lengths: Sequence[int] | None = None, y: Any = None) -> np.ndarray:
414
+ """Viterbi regimes of every sequence, concatenated `(sum T_b,)`.
415
+
416
+ `y` (int, `-1` unknown) constrains the decoding as in `fit`: a fully labelled `y` is returned as is.
417
+ """
418
+ decoded = self._decoded(X, lengths, y)
419
+ return np.concatenate([np.asarray(p.viterbi) for p in decoded]).astype(np.int64)
420
+
421
+ def predict_proba(
422
+ self, X: Any, lengths: Sequence[int] | None = None, filtered: bool = False
423
+ ) -> np.ndarray:
424
+ """Smoothed (or `filtered`) regime probabilities `(sum T_b, N)`."""
425
+ rows = [np.asarray(p.filtered if filtered else p.smoothed) for p in self._decoded(X, lengths)]
426
+ return np.concatenate(rows, axis=0)
427
+
428
+ def score(self, X: Any, y: Any = None, *, lengths: Sequence[int] | None = None) -> float:
429
+ """Total log-likelihood of the sequences (`y` is ignored; `lengths` is keyword-only)."""
430
+ self._lengths_trap(y, np.shape(X)[0])
431
+ return float(sum(p.loglik for p in self._decoded(X, lengths)))
432
+
433
+ def score_samples(self, X: Any, lengths: Sequence[int] | None = None) -> np.ndarray:
434
+ """One-step predictive log-density `log p(y_t | y_1:t-1)` per row `(sum T_b,)`."""
435
+ from hsmmkit.engine.expanded_hmm import ExpandedHMMEngine
436
+ from hsmmkit.engine.explicit_duration import ExplicitDurationEngine
437
+ from hsmmkit.statespace.builders import build_expanded, build_explicit
438
+
439
+ _sk_validation.check_is_fitted(self, "result_")
440
+ obs, cov, sizes = self._check(X, reset=False, lengths=lengths)
441
+ spec = self.result_.spec
442
+ explicit = spec.engine == "explicit"
443
+ space = build_explicit(spec) if explicit else build_expanded(spec)
444
+ engine: Any = ExplicitDurationEngine() if explicit else ExpandedHMMEngine()
445
+ out = []
446
+ for ds in self._datasets(obs, cov, sizes):
447
+ log_alpha, _ = engine.forward(self.result_.params, spec, space, ds)
448
+ norm = np.asarray(jax.scipy.special.logsumexp(log_alpha, axis=1))
449
+ out.append(np.diff(np.concatenate([[0.0], norm])))
450
+ return np.concatenate(out)
451
+
452
+ def decode(self, X: Any, lengths: Sequence[int] | None = None) -> tuple[float, np.ndarray]:
453
+ """`(log-likelihood, Viterbi regimes)` as in `hmmlearn`."""
454
+ decoded = self._decoded(X, lengths)
455
+ return float(sum(p.loglik for p in decoded)), np.concatenate([np.asarray(p.viterbi) for p in decoded])
456
+
457
+ def sample(self, n_samples: int = 1, random_state: Any = None) -> tuple[np.ndarray, np.ndarray]:
458
+ """`(X, regimes)` of `n_samples` simulated steps (models without covariates)."""
459
+ from hsmmkit.statespace.builders import build_expanded
460
+
461
+ _sk_validation.check_is_fitted(self, "result_")
462
+ if self.covariate_columns:
463
+ raise ValueError("sample is not available for models with covariates")
464
+ spec = self.result_.spec
465
+ if spec.engine == "explicit":
466
+ raise ValueError("sample is not available for the explicit-duration engine")
467
+ space = build_expanded(spec)
468
+ seed = _seed_of(self.random_state if random_state is None else random_state)
469
+ res = simulate_paths(
470
+ key_for(seed), self.result_.params, spec, space, jnp.ones(int(n_samples)), None, None, None, 1
471
+ )
472
+ return np.asarray(res.values[0]), np.asarray(res.regimes[0])
473
+
474
+ def forecast(
475
+ self,
476
+ X: Any,
477
+ horizon: int,
478
+ lengths: Sequence[int] | None = None,
479
+ n_sim: int = 200,
480
+ ) -> ForecastResult:
481
+ """Monte-Carlo forecast from the end of the last sequence of `X` (an extension of the API)."""
482
+ from hsmmkit.inference.forecast import MonteCarloForecaster
483
+ from hsmmkit.statespace.builders import build_expanded, build_explicit
484
+
485
+ _sk_validation.check_is_fitted(self, "result_")
486
+ obs, cov, sizes = self._check(X, reset=False, lengths=lengths)
487
+ last = self._datasets(obs, cov, sizes)[-1]
488
+ if cov is not None:
489
+ raise ValueError("forecast is not available for models with covariates")
490
+ spec = self.result_.spec
491
+ space = build_explicit(spec) if spec.engine == "explicit" else build_expanded(spec)
492
+ from hsmmkit.engine.expanded_hmm import ExpandedHMMEngine
493
+ from hsmmkit.engine.explicit_duration import ExplicitDurationEngine
494
+
495
+ engine: Any = ExplicitDurationEngine() if spec.engine == "explicit" else ExpandedHMMEngine()
496
+ cfg = ForecastSection(horizon=int(horizon), n_sim=int(n_sim), quantiles=[0.05, 0.5, 0.95])
497
+ mc = MonteCarloForecaster(spec, space, engine, None, cfg, {})
498
+ return mc.forecast(self.result_, last, int(horizon), int(n_sim), self.config_.project.seed)
499
+
500
+ def __sklearn_tags__(self) -> Any:
501
+ """Tags: no sparse input, multi-output labels `y` are optional (`-1` unknown)."""
502
+ tags = super().__sklearn_tags__()
503
+ tags.input_tags.sparse = False
504
+ tags.requires_fit = True
505
+ return tags