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,557 @@
1
+ """Extended parameter-recovery scenarios R7-R11 (E14-T06; Part II §16.4, Appendix G).
2
+
3
+ Pure functions (no pytest, no file I/O). Every scenario simulates with the deterministic generators of
4
+ `hsmmkit.presets.fixtures`, fits with the estimators named in the table and compares with the truth under the
5
+ tolerances of Appendix D / G (covariance entries 15 % relative, AR coefficients and regime means 2 standard
6
+ errors, mean sojourn 25 %, jump probabilities 0.15 absolute). A scenario passes when every *gating* category
7
+ holds in at least 4 of 5 seeds (`run_ext_suite`).
8
+
9
+ | id | data | model | estimators |
10
+ |---|---|---|---|
11
+ | R7 | `M = 3`, 50 x `T = 300` | full-covariance Gaussian, 3 regimes, NB `r = 2` | MAP, EM |
12
+ | R8 | counts, daily calendar `dt` | Poisson, 2 regimes, gamma durations (explicit) | GEM |
13
+ | R9 | `M = 1`, `T = 5000` | MS-AR(2), mean-adjusted (Hamilton) | MAP |
14
+ | R10 | `M = 2`, 60 sessions, 30 % labels | left-to-right, per-state durations | GEM, `init: labels` |
15
+ | R11 | `M = 1`, `T = 5000` | Gaussian diagonal, 4 configured / 3 true regimes | VB (exactly one pruned) |
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import dataclasses
21
+ import warnings
22
+ from collections.abc import Callable, Sequence
23
+ from dataclasses import dataclass
24
+ from typing import TYPE_CHECKING, Any
25
+
26
+ import jax.numpy as jnp
27
+ import numpy as np
28
+
29
+ from hsmmkit.config.schema import EstimationSection, parse_project_config
30
+ from hsmmkit.data.batch import SequenceBatch
31
+ from hsmmkit.estimation import fit as run_fit
32
+ from hsmmkit.model.build import BuildInputs, build_model_spec_from
33
+ from hsmmkit.model.dists import unpack_lower
34
+ from hsmmkit.model.params.manager import ParamManager
35
+ from hsmmkit.presets import fixtures as fx
36
+
37
+ if TYPE_CHECKING:
38
+ from hsmmkit.config.schema import ProjectConfig
39
+ from hsmmkit.estimation.results import FitResult
40
+ from hsmmkit.model.spec import ModelSpec
41
+
42
+ __all__ = ["EXT_SCENARIOS", "ExtCheck", "ExtReport", "ExtScenario", "ExtSuite", "run_ext", "run_ext_suite"]
43
+
44
+ SEEDS = (0, 1, 2, 3, 4)
45
+ COV_TOL = 0.15
46
+ SOJOURN_TOL = 0.25
47
+ JUMP_TOL = 0.15
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class ExtCheck:
52
+ """One truth / estimate / tolerance comparison."""
53
+
54
+ category: str
55
+ name: str
56
+ truth: float
57
+ estimate: float
58
+ rule: str
59
+ passed: bool
60
+ gating: bool = True
61
+
62
+ def line(self) -> str:
63
+ """`name: truth=.. estimate=.. (rule)`."""
64
+ return f"{self.name}: truth={self.truth:.4g} estimate={self.estimate:.4g} ({self.rule})"
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class ExtReport:
69
+ """One scenario, estimator and seed: the checks and the fit's health."""
70
+
71
+ scenario: str
72
+ estimator: str
73
+ seed: int
74
+ checks: tuple[ExtCheck, ...]
75
+ finite: bool
76
+ fit: FitResult | None = None
77
+
78
+ @property
79
+ def categories(self) -> dict[str, bool]:
80
+ """`{category: all its checks pass}` over the gating checks."""
81
+ out: dict[str, bool] = {}
82
+ for c in self.checks:
83
+ if c.gating:
84
+ out[c.category] = out.get(c.category, True) and c.passed
85
+ return out
86
+
87
+ def failures(self) -> str:
88
+ """The failing check lines."""
89
+ lines = [c.line() for c in self.checks if c.gating and not c.passed]
90
+ return "; ".join(lines) if lines else "no failing checks"
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class ExtScenario:
95
+ """A scenario: its id, title, estimators and runner `(seed, estimator, quick) -> ExtReport`."""
96
+
97
+ name: str
98
+ title: str
99
+ estimators: tuple[str, ...]
100
+ run: Callable[[int, str, bool], ExtReport]
101
+ seeds: tuple[int, ...] = SEEDS
102
+ """The five seeds (R9 uses 100-104, the seeds E11-T05 fixed after its calibration run)."""
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class ExtSuite:
107
+ """`run_ext_suite` output: the reports of one estimator and the per-category pass counts."""
108
+
109
+ scenario: str
110
+ estimator: str
111
+ reports: tuple[ExtReport, ...]
112
+
113
+ @property
114
+ def category_counts(self) -> dict[str, tuple[int, int]]:
115
+ """`{category: (seeds passing, seeds)}`."""
116
+ cats = sorted({c for r in self.reports for c in r.categories})
117
+ return {c: (sum(r.categories.get(c, False) for r in self.reports), len(self.reports)) for c in cats}
118
+
119
+ @property
120
+ def passed(self) -> bool:
121
+ """Every gating category holds in at least 4 of 5 seeds (fewer seeds: in all but one)."""
122
+ need = max(len(self.reports) - 1, 1)
123
+ return all(k >= need for k, _ in self.category_counts.values())
124
+
125
+ def summary(self) -> str:
126
+ """One line per category plus the failures of the seeds that missed."""
127
+ lines = [
128
+ f"{self.scenario}/{self.estimator}: "
129
+ + ", ".join(f"{c} {k}/{n}" for c, (k, n) in self.category_counts.items())
130
+ ]
131
+ lines += [f" seed {r.seed}: {r.failures()}" for r in self.reports if not all(r.categories.values())]
132
+ return "\n".join(lines)
133
+
134
+
135
+ # --- helpers ---------------------------------------------------------------------------------
136
+
137
+
138
+ def _raw(
139
+ n: int,
140
+ series: list[str],
141
+ emission: dict[str, Any],
142
+ duration: dict[str, Any],
143
+ **model: Any, # noqa: ANN401
144
+ ) -> dict[str, Any]:
145
+ """A minimal configuration: `n` regimes, the emission and duration sections, extra `model` keys."""
146
+ return {
147
+ "schema_version": 1,
148
+ "project": {"name": "recovery", "seed": 0, "output_dir": "runs"},
149
+ "data": {
150
+ "source": {"kind": "csv", "path": "unused.csv", "observation_columns": series},
151
+ "clock": model.pop("clock", "steps"),
152
+ },
153
+ "model": {
154
+ "n_states": n,
155
+ "initial_state": "uniform",
156
+ "emission": emission,
157
+ "duration": {"covariates": [], **duration},
158
+ "transition": {"mode": "jump", "order": 1, "covariates": []},
159
+ **model,
160
+ },
161
+ "estimation": {"restarts": 1, "max_iter": 100, "init": ["rolling_kmeans"], "device": "cpu"},
162
+ "forecast": {
163
+ "horizon": 1,
164
+ "n_sim": 50,
165
+ "covariate_forecaster": {"type": "freeze"},
166
+ "quantiles": [0.05, 0.5, 0.95],
167
+ },
168
+ "evaluation": {
169
+ "metrics": ["log_score"],
170
+ "backtest": {
171
+ "scheme": "expanding",
172
+ "initial_train_steps": 160,
173
+ "refit_every_steps": 60,
174
+ "horizons": [1],
175
+ "embargo_steps": 0,
176
+ },
177
+ },
178
+ "output": {"write": ["backtest"]},
179
+ }
180
+
181
+
182
+ def _spec(
183
+ raw: dict[str, Any], n_series: int, clock: str = "steps", nominal_dt: float = 1.0
184
+ ) -> tuple[ProjectConfig, ModelSpec]:
185
+ cfg = parse_project_config(raw)
186
+ return cfg, build_model_spec_from(
187
+ cfg, BuildInputs(n_series=n_series, cov_names={}, clock=clock, nominal_dt=nominal_dt)
188
+ )
189
+
190
+
191
+ def _dataset(y: np.ndarray, dt: np.ndarray, clock: str = "steps", nominal_dt: float = 1.0) -> Any: # noqa: ANN401
192
+ from hsmmkit.estimation import recovery
193
+
194
+ data = recovery._empty_prepared(y.shape[0], y, jnp.asarray(dt))
195
+ return dataclasses.replace(data, clock=clock, nominal_dt=nominal_dt)
196
+
197
+
198
+ def _fit(spec: ModelSpec, data: Any, cfg: EstimationSection, seed: int, warm: Any = None) -> FitResult: # noqa: ANN401
199
+ with warnings.catch_warnings():
200
+ warnings.simplefilter("ignore", UserWarning)
201
+ return run_fit(spec, data, cfg, seed, warm)
202
+
203
+
204
+ def _finite(res: FitResult) -> bool:
205
+ return bool(np.isfinite(res.loglik) and np.all(np.isfinite(np.asarray(res.uparams))))
206
+
207
+
208
+ def _rel_check(
209
+ category: str, name: str, truth: float, est: float, tol: float, *, gating: bool = True
210
+ ) -> ExtCheck:
211
+ ok = bool(np.isfinite(est) and abs(est - truth) <= tol * abs(truth))
212
+ return ExtCheck(category, name, float(truth), float(est), f"|rel err| <= {tol:.0%}", ok, gating)
213
+
214
+
215
+ def _abs_check(
216
+ category: str, name: str, truth: float, est: float, tol: float, *, gating: bool = True
217
+ ) -> ExtCheck:
218
+ ok = bool(np.isfinite(est) and abs(est - truth) <= tol)
219
+ return ExtCheck(category, name, float(truth), float(est), f"|err| <= {tol:g}", ok, gating)
220
+
221
+
222
+ def _jump_matrix(pi_rows: np.ndarray) -> np.ndarray:
223
+ n = pi_rows.shape[0]
224
+ out = np.zeros((n, n))
225
+ for i in range(n):
226
+ out[i, np.arange(n) != i] = pi_rows[i]
227
+ return out
228
+
229
+
230
+ # --- R7: full-covariance Gaussian, batch, NB ---------------------------------------------------
231
+
232
+
233
+ def _r7(seed: int, estimator: str, quick: bool) -> ExtReport:
234
+ tr = fx.R7_TRUTH
235
+ n_seq, t_len = (10, 200) if quick else (50, 300)
236
+ frame = fx.simulate_r7(seed, n_seq=n_seq, t_len=t_len)
237
+ seqs = [
238
+ _dataset(g[["y0", "y1", "y2"]].to_numpy(), np.ones(len(g)))
239
+ for _, g in frame.groupby("sequence_id", sort=True)
240
+ ]
241
+ batch = SequenceBatch(tuple(seqs), (), tuple(str(i) for i in range(len(seqs))))
242
+ emission = {
243
+ "family": "gaussian",
244
+ "covariance": "full",
245
+ "scale_by_dt": False,
246
+ "ito_correction": False,
247
+ "params": {"mean": {"mode": "free", "init": [0.0, 0.0, 0.0]}, "chol": {"mode": "free"}},
248
+ }
249
+ duration = {
250
+ "family": "negbin",
251
+ "r": [2, 2, 2],
252
+ "params": {"rate": {"mode": "free", "init_mean_sojourn_steps": [12.0, 12.0, 12.0]}},
253
+ }
254
+ _, spec = _spec(_raw(3, ["y0", "y1", "y2"], emission, duration), 3)
255
+ est = EstimationSection.model_validate(
256
+ {
257
+ "method": estimator,
258
+ "restarts": 3,
259
+ "max_iter": 300,
260
+ "init": ["rolling_kmeans", "random"],
261
+ "device": "cpu",
262
+ }
263
+ )
264
+ res = _fit(spec, batch, est, seed)
265
+ th = {k: np.asarray(v) for k, v in res.params.items()}
266
+ order = np.argsort(th["emission.mean"][:, 0]) # the truth is ordered by the first series' mean
267
+ mean_hat = th["emission.mean"][order]
268
+ chol_hat = np.asarray(unpack_lower(jnp.asarray(th["emission.chol"]), 3))[order]
269
+ cov_hat = chol_hat @ np.swapaxes(chol_hat, -1, -2)
270
+ cov_true = tr["chol"] @ np.swapaxes(tr["chol"], -1, -2)
271
+ checks: list[ExtCheck] = []
272
+ for i in range(3):
273
+ for a in range(3):
274
+ for b in range(a + 1):
275
+ checks.append(
276
+ _rel_check(
277
+ "covariance", f"cov[{i}][{a},{b}]", cov_true[i, a, b], cov_hat[i, a, b], COV_TOL
278
+ )
279
+ )
280
+ for i in range(3):
281
+ for a in range(3):
282
+ checks.append(_abs_check("mean", f"mean[{i},{a}]", tr["mean"][i, a], mean_hat[i, a], 0.1))
283
+ soj_hat = np.asarray(spec.duration.mean_sojourn(res.params, 1.0))[order]
284
+ for i in range(3):
285
+ checks.append(
286
+ _rel_check("mean_sojourn", f"mean_sojourn[{i}]", tr["sojourn"][i], soj_hat[i], SOJOURN_TOL)
287
+ )
288
+ jump_hat = _jump_matrix(th["transition.pi_rows"])[np.ix_(order, order)]
289
+ jump_true = _jump_matrix(tr["pi_rows"])
290
+ for i in range(3):
291
+ for j in range(3):
292
+ if i != j:
293
+ checks.append(_abs_check("jump", f"pi[{i},{j}]", jump_true[i, j], jump_hat[i, j], JUMP_TOL))
294
+ return ExtReport("R7", estimator, seed, tuple(checks), _finite(res), res)
295
+
296
+
297
+ # --- R9: MS-AR(2), Hamilton mean-adjusted ------------------------------------------------------
298
+
299
+
300
+ def _r9(seed: int, estimator: str, quick: bool) -> ExtReport:
301
+ from hsmmkit.data.contracts import lag_names, own_lag_columns
302
+ from hsmmkit.engine.expanded_hmm import ExpandedHMMEngine
303
+ from hsmmkit.estimation.objective import make_objective
304
+ from hsmmkit.estimation.report import std_errors
305
+ from hsmmkit.model.build import build_model_spec
306
+ from hsmmkit.statespace.builders import build_expanded
307
+
308
+ tr = fx.R9_TRUTH
309
+ frame = fx.simulate_r9(seed, 2000 if quick else 5000)
310
+ p = 2
311
+ emission = {
312
+ "family": "msar",
313
+ "ar": {"p": p, "form": "mean_adjusted"},
314
+ "params": {
315
+ "mean": {"mode": "free", "init": [-0.3, 0.8], "constraint": "increasing"},
316
+ "scale": {"mode": "free", "init": [1.0, 1.0]},
317
+ },
318
+ }
319
+ duration = {
320
+ "family": "geometric",
321
+ "params": {"rate": {"mode": "free", "init_mean_sojourn_steps": [12.0, 15.0]}},
322
+ }
323
+ cfg = parse_project_config(_raw(2, ["x"], emission, duration))
324
+ y = frame[["y"]].to_numpy()
325
+ lags, ok = own_lag_columns(y, np.ones(y.shape, dtype=bool), p) # the own lags are emission covariates
326
+ data = _dataset(y, np.ones(len(frame)))
327
+ data = dataclasses.replace(
328
+ data,
329
+ cov_emission=jnp.asarray(lags),
330
+ mask=jnp.asarray(np.broadcast_to(ok[:, None], y.shape)),
331
+ cov_names={"transition": (), "duration": (), "emission": lag_names(("y0",), p)},
332
+ )
333
+ spec = build_model_spec(cfg, data)
334
+ est = EstimationSection.model_validate(
335
+ {"method": estimator, "restarts": 3, "max_iter": 300, "init": ["rolling_kmeans"], "device": "cpu"}
336
+ )
337
+ res = _fit(spec, data, est, seed)
338
+ manager = ParamManager(spec.param_specs)
339
+ objective = make_objective(
340
+ spec, build_expanded(spec), ExpandedHMMEngine(), manager, data, use_priors=False
341
+ )
342
+ se = std_errors(objective, res.uparams, manager)
343
+ th = {k: np.asarray(v) for k, v in res.params.items()}
344
+ checks: list[ExtCheck] = []
345
+ for key, truth, cat in (("emission.ar", tr["phi"], "ar"), ("emission.mean", tr["mean"], "mean")):
346
+ est_v = th[key].ravel()
347
+ sd = np.asarray(se[key]).ravel() if se is not None else np.full(truth.shape, np.nan)
348
+ for i, (t, e, s_) in enumerate(zip(truth, est_v, sd, strict=True)):
349
+ ok_i = bool(np.isfinite(s_) and abs(e - t) <= 2.0 * s_)
350
+ checks.append(ExtCheck(cat, f"{key}[{i}]", float(t), float(e), f"|err| <= 2 SE ({s_:.3g})", ok_i))
351
+ soj = 1.0 / np.asarray(spec.duration.advance_prob_t(res.params, jnp.asarray(1.0), None))
352
+ for i in range(2):
353
+ checks.append(
354
+ _rel_check("mean_sojourn", f"mean_sojourn[{i}]", tr["sojourn"][i], float(soj[i]), SOJOURN_TOL)
355
+ )
356
+ return ExtReport("R9", estimator, seed, tuple(checks), _finite(res), res)
357
+
358
+
359
+ # --- R11: VB with one superfluous regime ------------------------------------------------------
360
+
361
+
362
+ def _r11(seed: int, estimator: str, quick: bool) -> ExtReport:
363
+ tr = fx.R11_TRUTH
364
+ frame = fx.simulate_r11(seed, 2500 if quick else 5000)
365
+ data = _dataset(frame[["y"]].to_numpy(), np.ones(len(frame)))
366
+ emission = {
367
+ "family": "gaussian",
368
+ "scale_by_dt": False,
369
+ "ito_correction": False,
370
+ "params": {
371
+ "mean": {"mode": "free", "init": [-2.5, -0.5, 0.5, 2.5]},
372
+ "scale": {"mode": "free", "init": [0.8] * 4},
373
+ },
374
+ }
375
+ duration = {
376
+ "family": "geometric",
377
+ "params": {"rate": {"mode": "free", "init_mean_sojourn_steps": [20.0] * 4}},
378
+ }
379
+ _, spec = _spec(_raw(4, ["y"], emission, duration), 1)
380
+ est = EstimationSection.model_validate(
381
+ {"method": "vb", "restarts": 0, "max_iter": 300, "tol_f": 1e-10, "device": "cpu"}
382
+ )
383
+ res = _fit(spec, data, est, 0, ParamManager(spec.param_specs).init_u())
384
+ keep = [i for i in range(4) if i not in res.pruned_states]
385
+ mean_hat = np.sort(np.asarray(res.params["emission.mean"]).ravel()[keep])
386
+ checks = [
387
+ ExtCheck(
388
+ "pruned",
389
+ "n_pruned",
390
+ 1.0,
391
+ float(len(res.pruned_states)),
392
+ "exactly one regime pruned",
393
+ len(res.pruned_states) == 1,
394
+ )
395
+ ]
396
+ if len(keep) == 3:
397
+ for i in range(3):
398
+ checks.append(_abs_check("mean", f"mean[{i}]", tr["mean"][i], float(mean_hat[i]), 0.15))
399
+ return ExtReport("R11", "vb", seed, tuple(checks), _finite(res), res)
400
+
401
+
402
+ # --- R8: Poisson counts, gamma durations, irregular calendar grid -----------------------------
403
+
404
+
405
+ def _r8(seed: int, estimator: str, quick: bool) -> ExtReport:
406
+ tr = fx.R8_TRUTH
407
+ frame = fx.simulate_r8(seed, 3000 if quick else 8000)
408
+ dt = frame["dt"].to_numpy()
409
+ nominal = float(np.median(dt))
410
+ data = _dataset(frame[["y"]].to_numpy(), dt, clock="calendar", nominal_dt=nominal)
411
+ emission = {
412
+ "family": "poisson",
413
+ "scale_by_dt": True,
414
+ "params": {"rate": {"mode": "free", "init": [1500.0, 3500.0]}}, # per year
415
+ }
416
+ duration = {
417
+ "family": "gamma",
418
+ "params": {
419
+ "shape": {"mode": "free", "init": [2.0, 2.0]},
420
+ "scale": {"mode": "free", "init": [5.0 * nominal, 5.0 * nominal]},
421
+ },
422
+ }
423
+ _, spec = _spec(
424
+ _raw(2, ["y"], emission, duration, engine="explicit", d_max=fx.R8_D_MAX, clock="calendar"),
425
+ 1,
426
+ "calendar",
427
+ nominal,
428
+ )
429
+ est = EstimationSection.model_validate(
430
+ {
431
+ "method": estimator,
432
+ "restarts": 0,
433
+ "max_iter": 300,
434
+ "tol_f": 1e-9,
435
+ "use_priors": False,
436
+ "device": "cpu",
437
+ }
438
+ )
439
+ res = _fit(spec, data, est, seed, ParamManager(spec.param_specs).init_u())
440
+ rate_hat = np.exp(np.asarray(res.params["emission.eta"]).ravel())
441
+ order = np.argsort(rate_hat)
442
+ per_day = rate_hat[order] * nominal
443
+ soj = np.asarray(spec.duration.mean_sojourn(res.params, nominal))[order] / nominal
444
+ soj_true = tr["shape"] * tr["scale_steps"]
445
+ checks: list[ExtCheck] = []
446
+ for i in range(2):
447
+ checks.append(_rel_check("rate", f"rate[{i}]", tr["rate_per_step"][i], float(per_day[i]), 0.1))
448
+ checks.append(
449
+ _rel_check("mean_sojourn", f"mean_sojourn[{i}]", soj_true[i], float(soj[i]), SOJOURN_TOL)
450
+ )
451
+ return ExtReport("R8", estimator, seed, tuple(checks), _finite(res), res)
452
+
453
+
454
+ # --- R10: left-to-right topology, per-state durations, labels -------------------------------
455
+
456
+
457
+ def _r10(seed: int, estimator: str, quick: bool) -> ExtReport:
458
+ tr = fx.R10_TRUTH
459
+ frame = fx.simulate_r10(seed, 30 if quick else 60)
460
+ seqs = []
461
+ for _, g in frame.groupby("sequence_id", sort=True):
462
+ data = _dataset(g[["y0", "y1"]].to_numpy(), np.ones(len(g)))
463
+ lab = g["label"].to_numpy()
464
+ allowed = np.ones((len(g), 4), dtype=bool)
465
+ known = np.isfinite(lab)
466
+ allowed[known] = False
467
+ allowed[np.flatnonzero(known), lab[known].astype(int)] = True
468
+ seqs.append(dataclasses.replace(data, labels=jnp.asarray(allowed)))
469
+ batch = SequenceBatch(tuple(seqs), (), tuple(str(i) for i in range(len(seqs))))
470
+ emission = {
471
+ "family": "gaussian",
472
+ "scale_by_dt": False,
473
+ "ito_correction": False,
474
+ "params": {
475
+ "mean": {"mode": "free", "init": [0.0, 0.0, 0.0, 0.0]},
476
+ "scale": {"mode": "free", "init": [1.0, 1.0, 1.0, 1.0]},
477
+ },
478
+ }
479
+ duration = {
480
+ "per_state": [
481
+ {
482
+ "family": "gamma",
483
+ "params": {"shape": {"mode": "free", "init": 2.0}, "scale": {"mode": "free", "init": 4.0}},
484
+ },
485
+ {
486
+ "family": "gamma",
487
+ "params": {"shape": {"mode": "free", "init": 2.0}, "scale": {"mode": "free", "init": 4.0}},
488
+ },
489
+ {"family": "geometric", "params": {"rate": {"mode": "free", "init_mean_sojourn_steps": 10.0}}},
490
+ {"family": "geometric", "params": {"rate": {"mode": "free", "init_mean_sojourn_steps": 10.0}}},
491
+ ]
492
+ }
493
+ topology = {"matrix": [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]]}
494
+ raw = _raw(4, ["y0", "y1"], emission, duration, engine="explicit", d_max=fx.R10_D_MAX, topology=topology)
495
+ raw["model"]["initial_state"] = "free"
496
+ _, spec = _spec(raw, 2)
497
+ est = EstimationSection.model_validate(
498
+ {
499
+ "method": estimator,
500
+ "restarts": 1,
501
+ "max_iter": 300,
502
+ "tol_f": 1e-9,
503
+ "init": ["labels"],
504
+ "use_priors": False,
505
+ "device": "cpu",
506
+ }
507
+ )
508
+ res = _fit(spec, batch, est, seed)
509
+ mean_hat = np.asarray(res.params["emission.mean"]).reshape(4, 2)
510
+ sd_hat = np.asarray(res.params["emission.scale"]).reshape(4, -1)[:, 0]
511
+ soj = np.asarray(spec.duration.mean_sojourn(res.params, 1.0))
512
+ soj_true = [tr["shape"][0] * tr["scale"][0], tr["shape"][1] * tr["scale"][1], tr["geometric_mean"]]
513
+ checks: list[ExtCheck] = []
514
+ for k in range(4):
515
+ for a in range(2):
516
+ checks.append(_abs_check("mean", f"mean[{k},{a}]", tr["mean"][k, a], float(mean_hat[k, a]), 0.15))
517
+ checks.append(_rel_check("sigma", f"sigma[{k}]", tr["sd"], float(sd_hat[k]), 0.1))
518
+ for k in range(3):
519
+ checks.append(
520
+ _rel_check("mean_sojourn", f"mean_sojourn[{k}]", soj_true[k], float(soj[k]), SOJOURN_TOL)
521
+ )
522
+ return ExtReport("R10", estimator, seed, tuple(checks), _finite(res), res)
523
+
524
+
525
+ EXT_SCENARIOS: dict[str, ExtScenario] = {
526
+ "R7": ExtScenario("R7", "full-covariance Gaussian, batch 50 x 300, NB r = 2", ("map", "em"), _r7),
527
+ "R8": ExtScenario("R8", "Poisson, gamma durations, daily calendar grid", ("gem",), _r8),
528
+ "R9": ExtScenario(
529
+ "R9", "MS-AR(2), Hamilton mean-adjusted", ("map",), _r9, seeds=(100, 101, 102, 103, 104)
530
+ ),
531
+ "R10": ExtScenario("R10", "left-to-right 4 regimes, per-state durations, 30 % labels", ("gem",), _r10),
532
+ "R11": ExtScenario("R11", "VB, 4 configured / 3 true regimes, one pruned", ("vb",), _r11),
533
+ }
534
+
535
+
536
+ def run_ext(scenario: str, seed: int, estimator: str | None = None, *, quick: bool = False) -> ExtReport:
537
+ """One report of `scenario` (R7-R11) at `seed` with `estimator` (default: the scenario's first)."""
538
+ from hsmmkit.utils.errors import ConfigError
539
+
540
+ if scenario not in EXT_SCENARIOS:
541
+ raise ConfigError(
542
+ f"unknown scenario {scenario!r}; available: {sorted(EXT_SCENARIOS)}", path="scenario"
543
+ )
544
+ sc = EXT_SCENARIOS[scenario]
545
+ est = estimator or sc.estimators[0]
546
+ if est not in sc.estimators:
547
+ raise ConfigError(f"{scenario} runs with {list(sc.estimators)}, not {est!r}", path="estimator")
548
+ return sc.run(seed, est, quick)
549
+
550
+
551
+ def run_ext_suite(
552
+ scenario: str, estimator: str | None = None, seeds: Sequence[int] | None = None, *, quick: bool = False
553
+ ) -> ExtSuite:
554
+ """`run_ext` over `seeds`; the suite passes when every gating category holds in >= 4 of 5 seeds."""
555
+ est = estimator or EXT_SCENARIOS[scenario].estimators[0]
556
+ chosen = EXT_SCENARIOS[scenario].seeds if seeds is None else seeds
557
+ return ExtSuite(scenario, est, tuple(run_ext(scenario, s, est, quick=quick) for s in chosen))
@@ -0,0 +1,85 @@
1
+ """Post-hoc relabelling of posterior draws (E13-T06b; Stephens 2000).
2
+
3
+ Without an identifiability guard (an ordering constraint or fixed location / scale parameters) the
4
+ posterior of
5
+ a hidden-state model is invariant under the permutations of the state labels and a sampler can switch between
6
+ the `N!` modes. `relabel_draws` maps every draw to the labelling closest to a *pivot* (the MAP optimum): the
7
+ permutation `sigma` minimizes `sum_i || f_{sigma(i)}(draw) - f_i(pivot) ||^2` over the emission location
8
+ parameters standardized by the pivot's spread across states (an assignment problem, solved exactly by the
9
+ vendored Hungarian algorithm of E14-T03), and is applied to every state-indexed block (emission, duration
10
+ rows, jump rows and columns, initial distribution) by `model.lattice.permute_states`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ import numpy as np
18
+
19
+ from hsmmkit.evaluation.metrics.matching import hungarian
20
+ from hsmmkit.model.lattice import permute_states
21
+
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Mapping
24
+
25
+ from hsmmkit.model.params import Params
26
+ from hsmmkit.model.spec import ModelSpec
27
+
28
+ __all__ = ["location_features", "relabel_draws", "relabel_permutation"]
29
+
30
+ _LOCATION_NAMES = ("emission.mean", "emission.m", "emission.mu", "emission.eta")
31
+ _SCALE_NAMES = ("emission.scale", "emission.s", "emission.sigma")
32
+
33
+
34
+ def location_features(theta: Mapping[str, np.ndarray], n_states: int) -> np.ndarray:
35
+ """`(N, K)` state features: emission locations and log scales (all emission parameters as a fallback)."""
36
+ names = [n for n in (*_LOCATION_NAMES, *_SCALE_NAMES) if n in theta]
37
+ if not names:
38
+ names = [n for n in theta if n.startswith("emission.")]
39
+ cols = []
40
+ for name in names:
41
+ arr = np.asarray(theta[name], dtype=np.float64)
42
+ if name in _SCALE_NAMES:
43
+ arr = np.log(np.maximum(arr, 1e-300)) # regimes that differ by volatility only
44
+ if arr.ndim >= 1 and arr.shape[0] == n_states:
45
+ cols.append(arr.reshape(n_states, -1))
46
+ if not cols:
47
+ return np.zeros((n_states, 1))
48
+ return np.concatenate(cols, axis=1)
49
+
50
+
51
+ def relabel_permutation(features: np.ndarray, pivot: np.ndarray, scale: np.ndarray) -> np.ndarray:
52
+ """`perm` (`perm[new] = old`) minimizing the standardized squared distance to the pivot states."""
53
+ diff = (pivot[:, None, :] - features[None, :, :]) / scale # (pivot i, draw j, K)
54
+ cost = np.sum(diff**2, axis=-1)
55
+ rows, cols = hungarian(cost)
56
+ perm = np.empty(pivot.shape[0], dtype=np.int64)
57
+ perm[rows] = cols
58
+ return perm
59
+
60
+
61
+ def relabel_draws(
62
+ draws: Mapping[str, np.ndarray], spec: ModelSpec, pivot: Params
63
+ ) -> tuple[dict[str, np.ndarray], float]:
64
+ """Relabel draws `(chain, draw, *shape)` towards `pivot`; returns `(draws, fraction relabelled)`."""
65
+ n = spec.n_states
66
+ first = next(iter(draws.values()))
67
+ n_chain, n_draw = first.shape[:2]
68
+ pivot_np = {k: np.asarray(v) for k, v in pivot.items()}
69
+ f_pivot = location_features(pivot_np, n)
70
+ spread = np.std(f_pivot, axis=0)
71
+ scale = np.where(spread > 1e-12, spread, np.maximum(np.abs(f_pivot).mean(axis=0), 1.0))
72
+ out = {k: np.array(v, copy=True) for k, v in draws.items()}
73
+ changed = 0
74
+ identity = np.arange(n)
75
+ for c in range(n_chain):
76
+ for d in range(n_draw):
77
+ theta = {k: v[c, d] for k, v in out.items()}
78
+ perm = relabel_permutation(location_features(theta, n), f_pivot, scale)
79
+ if np.array_equal(perm, identity):
80
+ continue
81
+ changed += 1
82
+ permuted = permute_states(theta, spec, perm)
83
+ for k, v in permuted.items():
84
+ out[k][c, d] = np.asarray(v)
85
+ return out, changed / max(n_chain * n_draw, 1)