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,72 @@
1
+ """Pad a `PreparedDataset` to a multiple of 256 rows with masked dummy rows (E7-T02b).
2
+
3
+ A walk-forward run fits and filters windows of many different lengths. Every distinct `T` is a new
4
+ compilation of the jitted engine functions, so each window is padded at the *end* to the next multiple of
5
+ `PAD_MULTIPLE` rows. A padded row has `mask=False` (so it adds zero log-density), `observations=0`, the
6
+ last row's `dt` (positive, and exactly 1 under the `steps` clock), zero covariates and a time that
7
+ continues the grid's median step. The engines apply the transition kernel `A_t` to a masked row without an
8
+ emission term; every row of `A_t` sums to one, so the log-likelihood of the padded series equals the
9
+ unpadded one (tested to 1e-8), and the filter rows `0..T-1` are untouched (the filter is causal).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import dataclasses
15
+
16
+ import jax.numpy as jnp
17
+ import numpy as np
18
+ from jax.typing import DTypeLike
19
+
20
+ from hsmmkit.data.contracts import PreparedDataset
21
+ from hsmmkit.utils.errors import ConfigError
22
+ from hsmmkit.utils.typing import Array
23
+
24
+ PAD_MULTIPLE = 256
25
+
26
+ _FALLBACK_STEP = np.timedelta64(1, "D")
27
+
28
+
29
+ def padded_length(n_rows: int, multiple: int = PAD_MULTIPLE) -> int:
30
+ """The smallest multiple of `multiple` that is `>= n_rows` (and at least one multiple)."""
31
+ if multiple < 1:
32
+ raise ConfigError(f"padding multiple must be >= 1, got {multiple}", path="evaluation.padding")
33
+ return max(multiple, -(-n_rows // multiple) * multiple)
34
+
35
+
36
+ def pad_dataset(data: PreparedDataset, multiple: int = PAD_MULTIPLE) -> PreparedDataset:
37
+ """`data` with masked dummy rows appended so that `T` is a multiple of `multiple`.
38
+
39
+ Returns `data` itself when `T` already is one. Static fields (`prep_stats`, `snapshot_ids`,
40
+ `nominal_dt`, `boundaries`, ...) are kept; `labels` get `False` rows.
41
+ """
42
+ t = int(data.times.shape[0])
43
+ extra = padded_length(t, multiple) - t
44
+ if extra == 0:
45
+ return data
46
+
47
+ times = np.asarray(data.times).astype("datetime64[ns]")
48
+ step = np.median(np.diff(times)).astype("m8[ns]") if t > 1 else _FALLBACK_STEP.astype("m8[ns]")
49
+ new_times = np.concatenate([times, times[-1] + step * np.arange(1, extra + 1)])
50
+
51
+ def rows(block: Array, fill: float | bool, dtype: DTypeLike) -> Array:
52
+ arr = jnp.asarray(block)
53
+ pad = jnp.full((extra, *arr.shape[1:]), fill, dtype=dtype)
54
+ return jnp.concatenate([arr, pad], axis=0)
55
+
56
+ obs = jnp.asarray(data.observations)
57
+ dt = jnp.asarray(data.dt)
58
+
59
+ def cov(block: Array | None) -> Array | None:
60
+ return None if block is None else rows(block, 0.0, jnp.asarray(block).dtype)
61
+
62
+ return dataclasses.replace(
63
+ data,
64
+ times=new_times,
65
+ observations=rows(obs, 0, obs.dtype),
66
+ dt=jnp.concatenate([dt, jnp.full((extra,), dt[-1], dtype=dt.dtype)]),
67
+ mask=rows(data.mask, False, jnp.bool_),
68
+ cov_transition=cov(data.cov_transition),
69
+ cov_duration=cov(data.cov_duration),
70
+ cov_emission=cov(data.cov_emission),
71
+ labels=None if data.labels is None else rows(data.labels, False, jnp.bool_),
72
+ )
@@ -0,0 +1,170 @@
1
+ """`report.md` of a backtest run (E7-T04).
2
+
3
+ Concept refs: §5.9, §4.10. The report is deterministic for a given run (no timestamps): header (config,
4
+ snapshots, seed, versions, backend), model summary, per-fold fit summary, diagnostics of the last fold's fit
5
+ with their warnings (E5-T04), the backtest summary table, the sections contributed by the origin hooks
6
+ (`extra_sections`, E10-T07a) and timings.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import platform
12
+ from collections.abc import Callable, Sequence
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ import jax
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ if TYPE_CHECKING:
20
+ from hsmmkit.config.schema import ProjectConfig
21
+ from hsmmkit.evaluation.results import BacktestResult
22
+
23
+ SECTIONS = (
24
+ "Header",
25
+ "Model",
26
+ "Fit",
27
+ "Diagnostics",
28
+ "Backtest summary",
29
+ "Timings",
30
+ )
31
+
32
+
33
+ def md_table(frame: pd.DataFrame) -> str:
34
+ """A pipe table of `frame` (floats to 4 significant digits)."""
35
+
36
+ def cell(value: object) -> str:
37
+ if isinstance(value, float | np.floating):
38
+ return "n/a" if not np.isfinite(value) else f"{value:.4g}"
39
+ return str(value)
40
+
41
+ head = "| " + " | ".join(str(c) for c in frame.columns) + " |"
42
+ rule = "|" + "---|" * len(frame.columns)
43
+ body = ["| " + " | ".join(cell(v) for v in row) + " |" for row in frame.itertuples(index=False)]
44
+ return "\n".join([head, rule, *body])
45
+
46
+
47
+ def versions() -> dict[str, str]:
48
+ """Versions and backend of the running process (recorded in `backtest.json` and the header)."""
49
+ from importlib.metadata import PackageNotFoundError, version
50
+
51
+ try:
52
+ package = version("hsmmkit")
53
+ except PackageNotFoundError: # running from a source tree without an installed distribution
54
+ package = "unknown"
55
+ return {
56
+ "hsmmkit": package,
57
+ "python": platform.python_version(),
58
+ "jax": jax.__version__,
59
+ "backend": jax.default_backend(),
60
+ "x64": str(bool(jax.config.jax_enable_x64)),
61
+ }
62
+
63
+
64
+ def _model_lines(cfg: ProjectConfig, meta: dict[str, Any]) -> list[str]:
65
+ m = cfg.model
66
+ covs = [f"`{c.name}` ({', '.join(c.use_in)})" for c in cfg.data.covariates] or ["none"]
67
+ lines = [
68
+ f"- regimes N = {m.n_states}, engine `{m.engine}`, transition order {m.transition.order}, "
69
+ f"mode `{m.transition.mode}`, conditioning `{m.transition.duration_conditioning}`",
70
+ f"- emission `{m.emission.family}`, duration `{m.duration.family}`"
71
+ + (f" (r = {m.duration.r})" if m.duration.r else ""),
72
+ f"- covariates: {', '.join(covs)}",
73
+ f"- clock `{cfg.data.clock}`, free parameters: {meta.get('n_free', 'n/a')}",
74
+ ]
75
+ return lines
76
+
77
+
78
+ def _diagnostic_lines(diagnostics: dict[str, Any] | None) -> tuple[list[str], list[str]]:
79
+ """`(lines, warnings)` from the `{"value", "warning"}` entries of `estimation.report.diagnose`."""
80
+ if diagnostics is None:
81
+ return ["No diagnostics were computed."], []
82
+ lines: list[str] = []
83
+ warns: list[str] = []
84
+ for name, entry in diagnostics.items():
85
+ value = entry.get("value") if isinstance(entry, dict) else entry
86
+ warning = entry.get("warning") if isinstance(entry, dict) else None
87
+ arr = np.asarray(value) if value is not None and not isinstance(value, dict | str) else None
88
+ shown: object = value
89
+ if arr is not None and arr.ndim > 0 and arr.size > 6:
90
+ shown = f"array{tuple(arr.shape)}"
91
+ elif arr is not None and arr.ndim > 0:
92
+ shown = np.array2string(arr, precision=4)
93
+ lines.append(f"- `{name}`: {shown}" + (f" **warning:** {warning}" if warning else ""))
94
+ if warning:
95
+ warns.append(f"{name}: {warning}")
96
+ return lines, warns
97
+
98
+
99
+ def build_report(
100
+ name: str,
101
+ cfg: ProjectConfig,
102
+ result: BacktestResult,
103
+ meta: dict[str, Any],
104
+ diagnostics: dict[str, Any] | None,
105
+ extra_sections: Sequence[Callable[[dict[str, Any]], str]] = (),
106
+ ) -> str:
107
+ """The Markdown report of one backtest run (every heading of `SECTIONS`).
108
+
109
+ `extra_sections` are contributed by origin hooks (E10-T07a): each gets `{"cfg", "result", "meta"}` and
110
+ gives a Markdown section (with its `##` heading); they follow the backtest summary.
111
+ """
112
+ context = {"cfg": cfg, "result": result, "meta": meta}
113
+ snaps = meta.get("snapshot_ids", [])
114
+ ver = meta.get("versions", {})
115
+ folds = result.folds
116
+ fit_cols = ["fold", "train_end", "objective", "loglik", "converged", "n_iter", "restart_gap", "fit_time"]
117
+ fit_table = folds[[c for c in fit_cols if c in folds.columns]]
118
+ converged = int(folds["converged"].sum()) if "converged" in folds.columns else 0
119
+ diag_lines, warns = _diagnostic_lines(diagnostics)
120
+ summary = result.summary.rename(columns={"mean": "mean (over folds)", "sd": "sd (across folds)"})
121
+ fit_total = float(folds["fit_time"].sum())
122
+ best_fold = int(folds["fold"].iloc[int(np.argmin(folds["objective"].to_numpy()))])
123
+
124
+ out = [
125
+ f"# Backtest report: {name}",
126
+ "",
127
+ "## Header",
128
+ "",
129
+ f"- config: `{name}`, seed {meta.get('seed', 'n/a')}",
130
+ f"- data provenance (snapshot ids): {', '.join(f'`{s}`' for s in snaps) if snaps else 'n/a'}",
131
+ f"- versions: hsmmkit {ver.get('hsmmkit', 'n/a')}, python {ver.get('python', 'n/a')}, "
132
+ f"jax {ver.get('jax', 'n/a')}",
133
+ f"- backend: {ver.get('backend', 'n/a')}, x64 {ver.get('x64', 'n/a')}",
134
+ f"- scheme `{cfg.backtest_cfg().scheme}`, {len(folds)} folds, horizons {cfg.backtest_cfg().horizons}",
135
+ "",
136
+ "## Model",
137
+ "",
138
+ *_model_lines(cfg, meta),
139
+ "",
140
+ "## Fit",
141
+ "",
142
+ f"{converged} of {len(folds)} fold fits converged; best objective "
143
+ f"{float(folds['objective'].min()):.6g} (fold {best_fold}); "
144
+ "largest gap between the two best restarts "
145
+ f"{float(folds['restart_gap'].max()) if 'restart_gap' in folds.columns else float('nan'):.4g} "
146
+ "(0 with a single restart).",
147
+ "",
148
+ md_table(fit_table),
149
+ "",
150
+ "## Diagnostics",
151
+ "",
152
+ "Fit diagnostics (E5-T04) of the last fold's fit on its training window.",
153
+ "",
154
+ *diag_lines,
155
+ "",
156
+ *(["**Warnings**", "", *[f"- {w}" for w in warns]] if warns else ["No diagnostic warnings."]),
157
+ "",
158
+ "## Backtest summary",
159
+ "",
160
+ "Rows with horizon 0 are in-sample (per fold) or hook metrics; `pit_ks` rows pool all origins.",
161
+ "",
162
+ md_table(summary),
163
+ "",
164
+ *[block for section in extra_sections for block in (section(context).rstrip("\n"), "")],
165
+ "## Timings",
166
+ "",
167
+ f"- total fit time {fit_total:.1f} s, mean per fold {fit_total / max(len(folds), 1):.1f} s",
168
+ f"- total backtest wall time {meta.get('wall_s', float('nan')):.1f} s",
169
+ ]
170
+ return "\n".join(out) + "\n"
@@ -0,0 +1,28 @@
1
+ """`BacktestResult` (E1-T05): walk-forward evaluation output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ import pandas as pd
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class BacktestResult:
13
+ """Walk-forward folds, per-fold metrics, the aggregated summary and the frames of the origin hooks."""
14
+
15
+ folds: pd.DataFrame # fold, train_start, train_end, test_start, test_end, fit_time
16
+ metrics: pd.DataFrame # long format: fold, horizon, metric, value
17
+ summary: pd.DataFrame # aggregated per horizon/metric (mean, sd across folds)
18
+ extras: dict[str, pd.DataFrame] = field(default_factory=dict) # one frame per origin hook, by hook name
19
+
20
+ def to_pandas(self) -> pd.DataFrame:
21
+ """The long table of the result (`metrics`; E16-T02)."""
22
+ return self.metrics
23
+
24
+ def to_xarray(self) -> Any: # noqa: ANN401
25
+ """`metrics (fold, horizon, metric)` as a `Dataset` (extra `xarray`; E16-T02)."""
26
+ from hsmmkit.interop.xarray import backtest_to_dataset
27
+
28
+ return backtest_to_dataset(self)
@@ -0,0 +1 @@
1
+ """Decoding, simulation and forecasting."""
@@ -0,0 +1,344 @@
1
+ """Covariate forecasters (E6-T03): future covariate paths `(n_sim, h, K)` for multi-step forecasts.
2
+
3
+ Concept refs: §4.9, §5.5. `K` is the union of every covariate column across the three entry points
4
+ (transition/duration/emission), de-duplicated by name -- exactly `PreparedDataset.prep_stats.cov_names`
5
+ (E2-T07 already builds this de-duplicated tuple). `ColumnMap` maps that unified `(..., K)` array back
6
+ to each entry point's own column order (`PreparedDataset.cov_names[entry_point]`), since a name's
7
+ position can differ per block and a name may appear in more than one block.
8
+
9
+ Since covariates are lagged by >= 1 step (CLAUDE.md §3.7), `z_{t+1}` is already known at the forecast
10
+ origin `t` and is passed in as `last (K,)`; `h = 1` needs no generation (the caller would not invoke a
11
+ forecaster at all, but `sample_paths` handles it gracefully: `last` broadcast with nothing to generate).
12
+ `fit(data)` must only look at the training window (`data.prep_stats.train_window`), never the full
13
+ series -- the same look-ahead discipline `data.prepare.Preparer` already applies to its own stats.
14
+
15
+ File I/O (loading a `scenario` path from the `forecast.covariate_forecaster.path` config field) stays
16
+ out of this module (`inference/` is not an I/O layer, CLAUDE.md §4 invariant 1); `make_forecaster`
17
+ takes already-parsed `scenario_values` instead, leaving the actual file read to the CLI/`Project` layer
18
+ that eventually wires this up (E6-T04a/E6-T05).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import dataclasses
24
+ from dataclasses import dataclass
25
+ from typing import TYPE_CHECKING, Protocol, cast
26
+
27
+ import jax
28
+ import jax.numpy as jnp
29
+ import numpy as np
30
+
31
+ from hsmmkit.plugins import REGISTRY, register
32
+ from hsmmkit.utils.errors import ConfigError, DataError
33
+
34
+ if TYPE_CHECKING:
35
+ from hsmmkit.config.schema import CovariateForecasterCfg
36
+ from hsmmkit.data.contracts import PreparedDataset
37
+ from hsmmkit.utils.typing import Array
38
+
39
+ _ENTRY_POINTS = ("transition", "duration", "emission")
40
+
41
+
42
+ class CovariateForecaster(Protocol):
43
+ """Structural type for the four covariate-forecaster families."""
44
+
45
+ name: str
46
+
47
+ def fit(self, data: PreparedDataset) -> CovariateForecaster:
48
+ """Fit on `data`'s training window only; returns a new, fitted instance."""
49
+ ...
50
+
51
+ def sample_paths(self, key: Array, h: int, n_sim: int, last: Array) -> Array:
52
+ """`(n_sim, h, K)`, standardized units; row 0 is `last` (already known at the origin)."""
53
+ ...
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class ColumnMap:
58
+ """Unified `(K,)` covariate columns (`names`) <-> each entry point's own column order."""
59
+
60
+ names: tuple[str, ...]
61
+ transition: tuple[int, ...]
62
+ duration: tuple[int, ...]
63
+ emission: tuple[int, ...]
64
+
65
+ @classmethod
66
+ def from_dataset(cls, data: PreparedDataset) -> ColumnMap:
67
+ """Build from `data.prep_stats.cov_names` (the union) and `data.cov_names` (per block)."""
68
+ names = data.prep_stats.cov_names
69
+ position = {name: k for k, name in enumerate(names)}
70
+ try:
71
+ blocks = {ep: tuple(position[n] for n in data.cov_names.get(ep, ())) for ep in _ENTRY_POINTS}
72
+ except KeyError as exc:
73
+ raise DataError(
74
+ f"a covariate name in data.cov_names is missing from prep_stats.cov_names: {exc}",
75
+ path="cov_names",
76
+ ) from exc
77
+ return cls(
78
+ names=names,
79
+ transition=blocks["transition"],
80
+ duration=blocks["duration"],
81
+ emission=blocks["emission"],
82
+ )
83
+
84
+ def split(self, paths: Array) -> dict[str, Array | None]:
85
+ """`(..., K)` -> `{"transition": (..., K_pi) | None, "duration": ..., "emission": ...}`."""
86
+
87
+ def select(idx: tuple[int, ...]) -> Array | None:
88
+ return paths[..., list(idx)] if idx else None
89
+
90
+ return {ep: select(getattr(self, ep)) for ep in _ENTRY_POINTS}
91
+
92
+
93
+ def _unified_covariates(data: PreparedDataset) -> np.ndarray:
94
+ """`(T, K)` in `prep_stats.cov_names` order, reading each name from whichever block holds it."""
95
+ names = data.prep_stats.cov_names
96
+ t = int(data.observations.shape[0])
97
+ out = np.full((t, len(names)), np.nan)
98
+ for ep in _ENTRY_POINTS:
99
+ ep_names = data.cov_names.get(ep, ())
100
+ if not ep_names:
101
+ continue
102
+ block = np.asarray(getattr(data, f"cov_{ep}"))
103
+ for local_idx, name in enumerate(ep_names):
104
+ out[:, names.index(name)] = block[:, local_idx]
105
+ if names and np.any(np.isnan(out)):
106
+ raise DataError("a prep_stats.cov_names entry has no covariate block", path="cov_names")
107
+ return out
108
+
109
+
110
+ def _train_window_mask(data: PreparedDataset) -> np.ndarray:
111
+ """Boolean `(T,)`: rows within `prep_stats.train_window` (inclusive on both ends)."""
112
+ start, end = data.prep_stats.train_window
113
+ times = data.times.astype("datetime64[ns]")
114
+ return (times >= np.datetime64(start)) & (times <= np.datetime64(end))
115
+
116
+
117
+ def _seed_from_key(key: Array) -> int:
118
+ """A plain int NumPy seed from a JAX key (the ticket's own NumPy-RNG exception for bootstrap)."""
119
+ return int(jax.random.bits(key, (), dtype=jnp.uint32))
120
+
121
+
122
+ def _bootstrap_source_indices(
123
+ rng: np.random.Generator, t_diff: int, n_steps: int, mean_block_length: float
124
+ ) -> np.ndarray:
125
+ """`(n_steps,)` indices into a `t_diff`-long series: a stationary (circular) block bootstrap.
126
+
127
+ Block starts are uniform over `[0, t_diff)`; block lengths are `Geometric(1 / mean_block_length)`
128
+ (mean `mean_block_length`), truncated at the series' end (circular wrap via `% t_diff`).
129
+ """
130
+ p = 1.0 / mean_block_length
131
+ idx = np.empty(n_steps, dtype=np.int64)
132
+ pos = 0
133
+ while pos < n_steps:
134
+ start = int(rng.integers(0, t_diff))
135
+ block_len = min(int(rng.geometric(p)), n_steps - pos)
136
+ for j in range(block_len):
137
+ idx[pos] = (start + j) % t_diff
138
+ pos += 1
139
+ return idx
140
+
141
+
142
+ @dataclass(frozen=True)
143
+ class FreezeForecaster:
144
+ """`freeze`: every row (including row 0) equals `last`."""
145
+
146
+ name: str = "freeze"
147
+
148
+ def fit(self, data: PreparedDataset) -> FreezeForecaster:
149
+ """No parameters to fit."""
150
+ del data
151
+ return self
152
+
153
+ def sample_paths(self, key: Array, h: int, n_sim: int, last: Array) -> Array:
154
+ """`(n_sim, h, K)`, every row `= last`."""
155
+ del key
156
+ return jnp.broadcast_to(last, (n_sim, h, last.shape[-1]))
157
+
158
+
159
+ @dataclass(frozen=True)
160
+ class ScenarioForecaster:
161
+ """`scenario`: a user path (by column name) for a subset of columns; missing columns freeze.
162
+
163
+ `paths[name]` has length `h` (validated against the `h` passed to `sample_paths`, since `h` is not
164
+ known at construction time) and supplies every row (`0..h-1`) of that column, overriding `last`'s
165
+ own row 0 for the columns it names -- CLAUDE.md §10: the ticket's own AC1 ("row 0 equals last ...
166
+ for all types") is read here as describing the three *stochastic* types (`freeze`/`bootstrap`/`ar`,
167
+ where there is no user override); `scenario`'s own row-0 behaviour is AC4's, not AC1's.
168
+ """
169
+
170
+ paths: dict[str, np.ndarray]
171
+ name: str = "scenario"
172
+ column_map: ColumnMap | None = None
173
+
174
+ def fit(self, data: PreparedDataset) -> ScenarioForecaster:
175
+ """Resolve column names against `data`'s unified covariate layout."""
176
+ return dataclasses.replace(self, column_map=ColumnMap.from_dataset(data))
177
+
178
+ def sample_paths(self, key: Array, h: int, n_sim: int, last: Array) -> Array:
179
+ """`(n_sim, h, K)`: configured columns use the scenario path; others freeze at `last`."""
180
+ del key
181
+ if self.column_map is None:
182
+ raise ConfigError("ScenarioForecaster.fit(data) must be called before sample_paths")
183
+ k = last.shape[-1]
184
+ out = np.asarray(jnp.broadcast_to(last, (n_sim, h, k))).copy()
185
+ for raw_name, values in self.paths.items():
186
+ if raw_name not in self.column_map.names:
187
+ raise ConfigError(
188
+ f"scenario column {raw_name!r} is not a covariate",
189
+ path="forecast.covariate_forecaster.path",
190
+ )
191
+ values = np.asarray(values)
192
+ if values.shape[0] != h:
193
+ raise ConfigError(
194
+ f"scenario column {raw_name!r} has length {values.shape[0]}, expected h={h}",
195
+ path="forecast.covariate_forecaster.path",
196
+ )
197
+ col = self.column_map.names.index(raw_name)
198
+ out[:, :, col] = values[None, :]
199
+ return jnp.asarray(out)
200
+
201
+
202
+ @dataclass(frozen=True)
203
+ class BootstrapForecaster:
204
+ """`bootstrap`: stationary block bootstrap (Politis-Romano) of first differences, from `last`."""
205
+
206
+ mean_block_length: float
207
+ name: str = "bootstrap"
208
+ diffs: np.ndarray | None = None # (T_train - 1, K), training-window first differences
209
+
210
+ def fit(self, data: PreparedDataset) -> BootstrapForecaster:
211
+ """First differences of the unified covariates, training window only."""
212
+ z = _unified_covariates(data)[_train_window_mask(data)]
213
+ return dataclasses.replace(self, diffs=np.diff(z, axis=0))
214
+
215
+ def sample_paths(self, key: Array, h: int, n_sim: int, last: Array) -> Array:
216
+ """`(n_sim, h, K)`: row 0 is `last`; rows `1..h-1` cumulate bootstrapped differences."""
217
+ if self.diffs is None:
218
+ raise ConfigError("BootstrapForecaster.fit(data) must be called before sample_paths")
219
+ k = last.shape[-1]
220
+ last_np = np.asarray(last)
221
+ out = np.empty((n_sim, h, k))
222
+ out[:, 0, :] = last_np
223
+ if h <= 1:
224
+ return jnp.asarray(out)
225
+ t_diff = self.diffs.shape[0]
226
+ rng = np.random.default_rng(_seed_from_key(key))
227
+ for i in range(n_sim):
228
+ src = _bootstrap_source_indices(rng, t_diff, h - 1, self.mean_block_length)
229
+ out[i, 1:, :] = last_np + np.cumsum(self.diffs[src], axis=0)
230
+ return jnp.asarray(out)
231
+
232
+
233
+ @dataclass(frozen=True)
234
+ class ARForecaster:
235
+ """`ar`: VAR(1) `z_{k+1} = c + Phi z_k + eps`, OLS on the training window, Gaussian innovations.
236
+
237
+ `diagonal=True` fits each column independently (`Phi` forced diagonal).
238
+ """
239
+
240
+ diagonal: bool = False
241
+ name: str = "ar"
242
+ c: np.ndarray | None = None # (K,)
243
+ phi: np.ndarray | None = None # (K, K)
244
+ chol_cov: np.ndarray | None = None # (K, K), Cholesky of the residual covariance
245
+
246
+ def fit(self, data: PreparedDataset) -> ARForecaster:
247
+ """OLS VAR(1) (or per-column AR(1) if `diagonal`), training window only."""
248
+ z = _unified_covariates(data)[_train_window_mask(data)]
249
+ k = z.shape[1]
250
+ x = np.column_stack([np.ones(z.shape[0] - 1), z[:-1]])
251
+ y = z[1:]
252
+ if self.diagonal:
253
+ c = np.zeros(k)
254
+ phi = np.zeros((k, k))
255
+ resid = np.empty_like(y)
256
+ for j in range(k):
257
+ xj = np.column_stack([np.ones(z.shape[0] - 1), z[:-1, j]])
258
+ coef, *_ = np.linalg.lstsq(xj, y[:, j], rcond=None)
259
+ c[j], phi[j, j] = coef
260
+ resid[:, j] = y[:, j] - xj @ coef
261
+ else:
262
+ coef, *_ = np.linalg.lstsq(x, y, rcond=None)
263
+ c = coef[0]
264
+ phi = coef[1:].T
265
+ resid = y - x @ coef
266
+ dof = max(resid.shape[0] - x.shape[1], 1)
267
+ cov = (resid.T @ resid) / dof
268
+ chol = np.linalg.cholesky(cov + 1e-12 * np.eye(k))
269
+ return dataclasses.replace(self, c=c, phi=phi, chol_cov=chol)
270
+
271
+ def sample_paths(self, key: Array, h: int, n_sim: int, last: Array) -> Array:
272
+ """`(n_sim, h, K)`: row 0 is `last`; rows `1..h-1` from the fitted VAR(1) recursion."""
273
+ if self.c is None or self.phi is None or self.chol_cov is None:
274
+ raise ConfigError("ARForecaster.fit(data) must be called before sample_paths")
275
+ k = last.shape[-1]
276
+ n_steps = max(h - 1, 0)
277
+ eps = jax.random.normal(key, (n_sim, n_steps, k))
278
+ eps_corr = jnp.einsum("nhk,jk->nhj", eps, jnp.asarray(self.chol_cov))
279
+ c = jnp.asarray(self.c)
280
+ phi = jnp.asarray(self.phi)
281
+
282
+ def step(z_prev: Array, eps_t: Array) -> tuple[Array, Array]:
283
+ z_t = c + phi @ z_prev + eps_t
284
+ return z_t, z_t
285
+
286
+ def one_path(eps_path: Array) -> Array:
287
+ _, zs = jax.lax.scan(step, last, eps_path)
288
+ return jnp.concatenate([last[None], zs], axis=0)
289
+
290
+ return jax.vmap(one_path)(eps_corr)
291
+
292
+
293
+ @register("covariate_forecaster", "freeze")
294
+ def _make_freeze(
295
+ cfg: CovariateForecasterCfg, scenario_values: dict[str, np.ndarray] | None
296
+ ) -> CovariateForecaster:
297
+ return cast(CovariateForecaster, FreezeForecaster())
298
+
299
+
300
+ @register("covariate_forecaster", "scenario")
301
+ def _make_scenario(
302
+ cfg: CovariateForecasterCfg, scenario_values: dict[str, np.ndarray] | None
303
+ ) -> CovariateForecaster:
304
+ if scenario_values is None:
305
+ raise ConfigError(
306
+ "scenario forecaster needs scenario_values (read from forecast.covariate_forecaster.path)",
307
+ path="forecast.covariate_forecaster.path",
308
+ )
309
+ return cast(CovariateForecaster, ScenarioForecaster(paths=scenario_values))
310
+
311
+
312
+ @register("covariate_forecaster", "bootstrap")
313
+ def _make_bootstrap(
314
+ cfg: CovariateForecasterCfg, scenario_values: dict[str, np.ndarray] | None
315
+ ) -> CovariateForecaster:
316
+ if cfg.mean_block_length is None:
317
+ raise ConfigError(
318
+ "bootstrap forecaster requires mean_block_length",
319
+ path="forecast.covariate_forecaster.mean_block_length",
320
+ )
321
+ return cast(CovariateForecaster, BootstrapForecaster(mean_block_length=float(cfg.mean_block_length)))
322
+
323
+
324
+ @register("covariate_forecaster", "ar")
325
+ def _make_ar(
326
+ cfg: CovariateForecasterCfg, scenario_values: dict[str, np.ndarray] | None
327
+ ) -> CovariateForecaster:
328
+ return cast(CovariateForecaster, ARForecaster(diagonal=bool(cfg.diagonal)))
329
+
330
+
331
+ def make_forecaster(
332
+ cfg: CovariateForecasterCfg, scenario_values: dict[str, np.ndarray] | None = None
333
+ ) -> CovariateForecaster:
334
+ """`forecast.covariate_forecaster` config -> an (unfitted) `CovariateForecaster`.
335
+
336
+ `scenario_values` must already be parsed (the caller reads `cfg.path`, not this function --
337
+ `inference/` is not an I/O layer). The factory is looked up in `REGISTRY` kind `covariate_forecaster`.
338
+ """
339
+ if not REGISTRY.has("covariate_forecaster", cfg.type):
340
+ raise ConfigError(
341
+ f"unknown covariate forecaster type {cfg.type!r}", path="forecast.covariate_forecaster.type"
342
+ )
343
+ factory = REGISTRY.get("covariate_forecaster", cfg.type)
344
+ return cast(CovariateForecaster, factory(cfg, scenario_values))