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,185 @@
1
+ """`decode`: a fitted model + data -> `PosteriorResult` (E6-T02).
2
+
3
+ Concept refs: §5.4 (`PosteriorResult`), §5.9. Rebuilds `space`/`engine` from `fit.spec` the same way
4
+ `estimation.map.fit` does, runs forward-backward and Viterbi, and assembles the regime-level
5
+ filtered/smoothed marginals, the RLE segments and the information criteria.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING, overload
11
+
12
+ import numpy as np
13
+
14
+ from hsmmkit.data.batch import SequenceBatch
15
+ from hsmmkit.engine.batch import batched_forward_backward, batched_viterbi
16
+ from hsmmkit.engine.criteria import information_criteria
17
+ from hsmmkit.engine.expanded_hmm import ExpandedHMMEngine
18
+ from hsmmkit.engine.explicit_duration import ExplicitDurationEngine
19
+ from hsmmkit.engine.ffbs import ffbs_expanded, ffbs_explicit
20
+ from hsmmkit.engine.viterbi import segments
21
+ from hsmmkit.inference.results import PosteriorResult
22
+ from hsmmkit.model.params.manager import ParamManager
23
+ from hsmmkit.statespace.builders import build_expanded, build_explicit
24
+ from hsmmkit.utils.errors import ConfigError
25
+ from hsmmkit.utils.rng import PURPOSE_FFBS, key_for
26
+
27
+
28
+ def _regime_samples(
29
+ fit: FitResult, space: StateSpace, pb: PaddedBatch, samples: int, seed: int
30
+ ) -> np.ndarray:
31
+ """`(R, B, T_max)` posterior regime paths by FFBS (`-1` on padding)."""
32
+ spec = fit.spec
33
+ key = key_for(seed, PURPOSE_FFBS)
34
+ if spec.engine == "explicit":
35
+ return np.asarray(ffbs_explicit(key, fit.params, spec, space, pb, samples))
36
+ states = np.asarray(ffbs_expanded(key, fit.params, spec, space, pb, samples))
37
+ regimes = np.asarray(space.index.regime_of)[np.maximum(states, 0)]
38
+ return np.where(states >= 0, regimes, -1)
39
+
40
+
41
+ def boundary_probability(paths: np.ndarray) -> np.ndarray:
42
+ """`(T,)` probability that a new segment starts at step `t >= 1`, estimated from `(R, T)` path samples.
43
+
44
+ A new segment is a regime change from step `t - 1`; entry 0 is 0 (the first segment starts there).
45
+ """
46
+ out = np.zeros(paths.shape[1])
47
+ out[1:] = (paths[:, 1:] != paths[:, :-1]).mean(axis=0)
48
+ return out
49
+
50
+
51
+ def _decode_batch(
52
+ fit: FitResult, batch: SequenceBatch, space: StateSpace, samples: int = 0, seed: int = 0
53
+ ) -> list[PosteriorResult]:
54
+ """One batched forward-backward and Viterbi pass; per-sequence results cut to their own lengths."""
55
+ spec = fit.spec
56
+ eng = ExplicitDurationEngine() if spec.engine == "explicit" else ExpandedHMMEngine()
57
+ pb = batch.padded()
58
+ posterior = batched_forward_backward(eng, fit.params, spec, space, pb, batch.ids)
59
+ paths = np.asarray(batched_viterbi(eng, fit.params, spec, space, pb))
60
+ n_free = ParamManager(spec.param_specs).n_free
61
+ drawn = _regime_samples(fit, space, pb, samples, seed) if samples > 0 else None
62
+ out: list[PosteriorResult] = []
63
+ for b, (seq, post) in enumerate(zip(batch.sequences, posterior.unpad(), strict=True)):
64
+ regime_path = np.asarray(space.index.regime_of[paths[b, : seq.observations.shape[0]]])
65
+ ic = information_criteria(
66
+ float(post.loglik), n_free, np.asarray(post.smoothed), mask=np.asarray(seq.mask)
67
+ )
68
+ out.append(
69
+ PosteriorResult(
70
+ times=seq.times,
71
+ filtered=post.regime_filtered(),
72
+ smoothed=post.regime_smoothed(),
73
+ viterbi=regime_path,
74
+ segments=segments(regime_path),
75
+ augmented=post,
76
+ loglik=float(post.loglik),
77
+ aic=ic.aic,
78
+ bic=ic.bic,
79
+ icl=ic.icl,
80
+ pruned_states=fit.pruned_states,
81
+ path_samples=None if drawn is None else drawn[:, b, : seq.observations.shape[0]],
82
+ boundary_prob=None
83
+ if drawn is None
84
+ else boundary_probability(drawn[:, b, : seq.observations.shape[0]]),
85
+ )
86
+ )
87
+ return out
88
+
89
+
90
+ if TYPE_CHECKING:
91
+ from hsmmkit.data.batch import PaddedBatch
92
+ from hsmmkit.data.contracts import PreparedDataset
93
+ from hsmmkit.engine.base import InferenceEngine
94
+ from hsmmkit.estimation.results import FitResult
95
+ from hsmmkit.statespace.index import StateSpace
96
+
97
+
98
+ @overload
99
+ def decode(
100
+ fit: FitResult,
101
+ data: PreparedDataset,
102
+ engine: InferenceEngine | None = None,
103
+ *,
104
+ samples: int = 0,
105
+ seed: int = 0,
106
+ ) -> PosteriorResult: ...
107
+
108
+
109
+ @overload
110
+ def decode(
111
+ fit: FitResult,
112
+ data: SequenceBatch,
113
+ engine: InferenceEngine | None = None,
114
+ *,
115
+ samples: int = 0,
116
+ seed: int = 0,
117
+ ) -> list[PosteriorResult]: ...
118
+
119
+
120
+ def decode(
121
+ fit: FitResult,
122
+ data: PreparedDataset | SequenceBatch,
123
+ engine: InferenceEngine | None = None,
124
+ *,
125
+ samples: int = 0,
126
+ seed: int = 0,
127
+ ) -> PosteriorResult | list[PosteriorResult]:
128
+ """Decode `data` under `fit.spec`/`fit.params`: filtered/smoothed marginals, Viterbi, IC.
129
+
130
+ A `SequenceBatch` is decoded in one batched pass and gives one `PosteriorResult` per sequence.
131
+
132
+ `engine` defaults to the engine `fit.spec.engine` names (`ExpandedHMMEngine`/
133
+ `ExplicitDurationEngine`, default construction); pass one explicitly to reuse a configured
134
+ instance (e.g. a non-default `chunk_size`).
135
+
136
+ `samples=R > 0` also draws `R` exact posterior regime paths by forward-filtering backward-sampling
137
+ (`engine.ffbs`, key `key_for(seed, PURPOSE_FFBS)`): `path_samples (R, T)` and `boundary_prob (T,)`.
138
+
139
+ Raises:
140
+ NumericalError: the engine's log-likelihood is non-finite (`information_criteria`; CLI
141
+ exit code 4).
142
+ ConfigError: `samples < 0`, or samples of an explicit model with duration-dependent jumps.
143
+ """
144
+ spec = fit.spec
145
+ space = build_explicit(spec) if spec.engine == "explicit" else build_expanded(spec)
146
+ if samples < 0:
147
+ raise ConfigError(f"samples must be >= 0, got {samples}", path="--samples")
148
+ if isinstance(data, SequenceBatch):
149
+ return _decode_batch(fit, data, space, samples, seed)
150
+ eng = (
151
+ engine
152
+ if engine is not None
153
+ else (ExplicitDurationEngine() if spec.engine == "explicit" else ExpandedHMMEngine())
154
+ )
155
+
156
+ posterior = eng.forward_backward(fit.params, spec, space, data)
157
+ path = np.asarray(eng.viterbi(fit.params, spec, space, data))
158
+ regime_path = np.asarray(space.index.regime_of[path])
159
+ segs = segments(regime_path)
160
+
161
+ manager = ParamManager(spec.param_specs)
162
+ loglik = float(posterior.loglik)
163
+ smoothed = np.asarray(posterior.smoothed)
164
+ ic = information_criteria(loglik, manager.n_free, smoothed, mask=np.asarray(data.mask))
165
+
166
+ drawn = (
167
+ _regime_samples(fit, space, SequenceBatch.of(data).padded(), samples, seed)[:, 0, :]
168
+ if samples > 0
169
+ else None
170
+ )
171
+ return PosteriorResult(
172
+ times=data.times,
173
+ filtered=posterior.regime_filtered(),
174
+ smoothed=posterior.regime_smoothed(),
175
+ viterbi=regime_path,
176
+ segments=segs,
177
+ augmented=posterior,
178
+ loglik=loglik,
179
+ aic=ic.aic,
180
+ bic=ic.bic,
181
+ icl=ic.icl,
182
+ pruned_states=fit.pruned_states,
183
+ path_samples=drawn,
184
+ boundary_prob=None if drawn is None else boundary_probability(drawn),
185
+ )
@@ -0,0 +1,475 @@
1
+ """Monte-Carlo forecasting from the filtered augmented posterior (E6-T04a sampling, E6-T04b aggregation).
2
+
3
+ Concept refs: §4.9 algorithm steps 1-2, §5.5. The origin state of every path is drawn from
4
+ `softmax(log_alpha_T)`; step `k = 1..h` then applies `A_{T+k}` (built from covariate row `k-1` of the
5
+ covariate path and `dt_future[k-1]`, CLAUDE.md §3.7 -- `cov_paths[:, 0]` is the row already known at
6
+ the origin) and draws the return from the new regime's emission.
7
+
8
+ Expanded engine: the state-path scan of `simulate_paths` (E6-T01) is reused unchanged. A dummy row 0
9
+ (a copy of row 1) plays the role of the origin step, so the scan applies `A_{T+1}, ...` from the sampled
10
+ origin state; that row is dropped from the outputs. Covariates are per path (vmap over the path axis).
11
+
12
+ Explicit engine: state `(regime, elapsed)`. The origin's total sojourn `d` is drawn from the regime's
13
+ pmf restricted to `d >= elapsed` (the segment has already run `elapsed` steps, right-censored at `T`);
14
+ the segment ends after exactly `d` steps, then a new regime is drawn from the jump row and a fresh
15
+ duration from its pmf. That is the hazard simulation `h_j(e)` written as a duration draw (the two are the
16
+ same distribution). Durations use `nominal_dt` (regular-grid assumption, ADR-0007); emissions use the
17
+ real `dt_future`.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from collections.abc import Mapping
23
+ from functools import partial
24
+ from typing import TYPE_CHECKING, Any, NamedTuple
25
+
26
+ import jax
27
+ import jax.numpy as jnp
28
+ import numpy as np
29
+
30
+ from hsmmkit.inference.covariate_forecasters import ColumnMap, _unified_covariates
31
+ from hsmmkit.inference.results import ForecastResult
32
+ from hsmmkit.inference.simulate import _simulate_one_path
33
+ from hsmmkit.utils.clock import future_grid
34
+ from hsmmkit.utils.errors import ConfigError, NumericalError
35
+ from hsmmkit.utils.rng import FORECAST_COVARIATES, FORECAST_PATHS, PURPOSE_FORECAST, key_for
36
+
37
+ if TYPE_CHECKING:
38
+ from hsmmkit.config.schema import ForecastSection
39
+ from hsmmkit.data.contracts import PreparedDataset
40
+ from hsmmkit.engine.base import InferenceEngine, Posterior
41
+ from hsmmkit.estimation.results import FitResult
42
+ from hsmmkit.inference.covariate_forecasters import CovariateForecaster
43
+ from hsmmkit.model.params.manager import Params
44
+ from hsmmkit.model.spec import ModelSpec
45
+ from hsmmkit.statespace.index import StateSpace
46
+ from hsmmkit.utils.typing import Array
47
+
48
+ MAX_SAMPLE_FLOATS = 2e8
49
+
50
+
51
+ class ForecastPaths(NamedTuple):
52
+ """`n_sim` future paths of horizon `h`."""
53
+
54
+ states: Array # (n_sim, h) int, augmented state index at each future step
55
+ regimes: Array # (n_sim, h) int
56
+ values: Array # (n_sim, h, M)
57
+
58
+
59
+ def _blocks(
60
+ cov_paths: Array | None, colmap: ColumnMap | None, n_sim: int, h: int
61
+ ) -> tuple[Array, Array, Array]:
62
+ """Per-entry-point covariate blocks `(n_sim, h, K_*)`; absent blocks are zeros of width 0."""
63
+ empty = jnp.zeros((n_sim, h, 0))
64
+ if cov_paths is None:
65
+ return empty, empty, empty
66
+ if colmap is None:
67
+ raise ConfigError("cov_paths needs a ColumnMap to split it by entry point", path="forecast")
68
+ if cov_paths.shape[:2] != (n_sim, h):
69
+ raise ConfigError(
70
+ f"cov_paths must have shape (n_sim={n_sim}, h={h}, K), got {cov_paths.shape}",
71
+ path="forecast.covariate_forecaster",
72
+ )
73
+ parts = colmap.split(cov_paths)
74
+ z_pi, z_d, z_e = (parts[k] for k in ("transition", "duration", "emission"))
75
+ return (
76
+ empty if z_pi is None else z_pi,
77
+ empty if z_d is None else z_d,
78
+ empty if z_e is None else z_e,
79
+ )
80
+
81
+
82
+ def _reject_autoregressive(spec: ModelSpec) -> None:
83
+ """Forecasting an autoregressive emission (`msar`) or duration-dependent jumps is not supported yet."""
84
+ if spec.duration_dependent_jumps:
85
+ raise ConfigError(
86
+ "forecasting with duration-dependent jumps is not supported yet (the jump depends on the "
87
+ "elapsed duration of the origin segment)",
88
+ path="model.duration.duration_dependent_jumps",
89
+ )
90
+ if hasattr(spec.emission, "sample_path"):
91
+ raise ConfigError(
92
+ "forecasting with an autoregressive emission (msar) is not supported yet: its draws need the "
93
+ "last observed values as lags",
94
+ path="model.emission.family",
95
+ )
96
+
97
+
98
+ def _check_inputs(log_alpha_t: Array, dt_future: Array, n_sim: int) -> None:
99
+ if n_sim < 1:
100
+ raise ConfigError(f"n_sim must be >= 1, got {n_sim}", path="forecast.n_sim")
101
+ if dt_future.ndim != 1 or dt_future.shape[0] < 1:
102
+ raise ConfigError("dt_future must be a non-empty (h,) array", path="forecast.horizon")
103
+ if log_alpha_t.ndim != 1:
104
+ raise ConfigError("log_alpha_T must be the (S,) last row of log_alpha", path="log_alpha")
105
+
106
+
107
+ def _check_state_count(log_alpha_t: Array, space: StateSpace) -> None:
108
+ if log_alpha_t.shape[0] != space.n_expanded:
109
+ raise ConfigError(
110
+ f"log_alpha_T has {log_alpha_t.shape[0]} states, the state space has {space.n_expanded}",
111
+ path="log_alpha",
112
+ )
113
+
114
+
115
+ def _check_finite(values: Array) -> None:
116
+ """Public-boundary guard (CLAUDE.md §4): no NaN/Inf may leave the sampler."""
117
+ if not bool(jnp.all(jnp.isfinite(values))):
118
+ raise NumericalError("non-finite value in forecast values", path="values")
119
+
120
+
121
+ def _prepend(x: Array) -> Array:
122
+ """Copy of row 0 in front, so the simulate scan's untransitioned row 0 is the origin step."""
123
+ return jnp.concatenate([x[:1], x], axis=0)
124
+
125
+
126
+ def _expanded_path(
127
+ key: Array,
128
+ theta: Params,
129
+ spec: ModelSpec,
130
+ space: StateSpace,
131
+ dt: Array,
132
+ z_pi: Array,
133
+ z_d: Array,
134
+ z_e: Array,
135
+ s0: Array,
136
+ ) -> tuple[Array, Array, Array]:
137
+ _reject_autoregressive(spec)
138
+ states, regimes, values = _simulate_one_path(
139
+ key, theta, spec, space, _prepend(dt), _prepend(z_pi), _prepend(z_d), _prepend(z_e), s0
140
+ )
141
+ return states[1:], regimes[1:], values[1:]
142
+
143
+
144
+ @partial(jax.jit, static_argnames=("spec", "n_sim"))
145
+ def _expanded_core(
146
+ key: Array,
147
+ theta: Params,
148
+ spec: ModelSpec,
149
+ space: StateSpace,
150
+ log_alpha_t: Array,
151
+ dt: Array,
152
+ z_pi: Array,
153
+ z_d: Array,
154
+ z_e: Array,
155
+ n_sim: int,
156
+ ) -> tuple[Array, Array, Array]:
157
+ origin_key, path_key = jax.random.split(key)
158
+ logits = jnp.broadcast_to(log_alpha_t, (n_sim, log_alpha_t.shape[0]))
159
+ s0 = jax.random.categorical(origin_key, logits).astype(space.index.regime_of.dtype)
160
+ keys = jax.random.split(path_key, n_sim)
161
+ in_axes = (0, None, None, None, None, 0, 0, 0, 0)
162
+ return jax.vmap(_expanded_path, in_axes=in_axes)(keys, theta, spec, space, dt, z_pi, z_d, z_e, s0)
163
+
164
+
165
+ def forecast_paths(
166
+ key: Array,
167
+ theta: Params,
168
+ spec: ModelSpec,
169
+ space: StateSpace,
170
+ log_alpha_t: Array,
171
+ dt_future: Array,
172
+ n_sim: int,
173
+ cov_paths: Array | None = None,
174
+ colmap: ColumnMap | None = None,
175
+ ) -> ForecastPaths:
176
+ """Sample `n_sim` paths of `h = len(dt_future)` steps from `softmax(log_alpha_t)` (expanded engine).
177
+
178
+ Args:
179
+ key: PRNG key; the result is deterministic per key.
180
+ theta: parameters.
181
+ spec: model structure (static).
182
+ space: the expanded `StateSpace` the posterior lives in.
183
+ log_alpha_t: `(S,)` last row of the filtered `log_alpha` at the origin.
184
+ dt_future: `(h,)` `Δ` of the future steps (`utils.clock.future_grid`).
185
+ n_sim: number of paths.
186
+ cov_paths: `(n_sim, h, K)` future covariates in `colmap` order (row 0 = the row known at the
187
+ origin), or `None` for a model without covariates.
188
+ colmap: unified-column -> entry-point mapping of `cov_paths`.
189
+
190
+ Returns:
191
+ `ForecastPaths(states (n_sim, h), regimes (n_sim, h), values (n_sim, h, M))`.
192
+
193
+ Raises:
194
+ ConfigError: inconsistent shapes or a non-positive `n_sim`.
195
+ NumericalError: a non-finite simulated return.
196
+ """
197
+ _check_inputs(log_alpha_t, dt_future, n_sim)
198
+ _check_state_count(log_alpha_t, space)
199
+ h = int(dt_future.shape[0])
200
+ z_pi, z_d, z_e = _blocks(cov_paths, colmap, n_sim, h)
201
+ out = _expanded_core(key, theta, spec, space, log_alpha_t, dt_future, z_pi, z_d, z_e, n_sim)
202
+ _check_finite(out[2])
203
+ return ForecastPaths(*out)
204
+
205
+
206
+ def _explicit_path(
207
+ key: Array,
208
+ theta: Params,
209
+ spec: ModelSpec,
210
+ space: StateSpace,
211
+ dt: Array,
212
+ z_pi: Array,
213
+ z_d: Array,
214
+ z_e: Array,
215
+ j0: Array,
216
+ e0: Array,
217
+ z_d_origin: Array,
218
+ nominal_dt: float,
219
+ ) -> tuple[Array, Array, Array]:
220
+ d_max, family = spec.d_max, spec.duration
221
+ has_entry = bool(getattr(family, "cov_idx", ()))
222
+ const_lp = None if has_entry else family.log_pmf(theta, d_max, nominal_dt, None)
223
+
224
+ def pmf(z: Array) -> Array:
225
+ return family.log_pmf(theta, d_max, nominal_dt, z) if has_entry else const_lp # type: ignore[return-value]
226
+
227
+ h = dt.shape[0]
228
+ k_dur, k_steps, k_emit = jax.random.split(key, 3)
229
+ support = jnp.arange(1, d_max + 1)
230
+ masked = jnp.where(support >= e0, pmf(z_d_origin)[j0], -jnp.inf)
231
+ d0 = (jax.random.categorical(k_dur, masked) + 1).astype(jnp.int64)
232
+ d0 = jnp.where(jnp.any(jnp.isfinite(masked)), d0, e0.astype(jnp.int64)) # no mass left: exit now
233
+
234
+ def step(
235
+ carry: tuple[Array, Array, Array], xs: tuple[Array, Array, Array]
236
+ ) -> tuple[tuple[Array, Array, Array], tuple[Array, Array]]:
237
+ j, e, d = carry
238
+ z_pi_k, z_d_k, key_k = xs
239
+ key_j, key_d = jax.random.split(key_k)
240
+ ended = e >= d
241
+ pi = spec.transition.jump_probs_t(theta, z_pi_k, space.layout)[j]
242
+ log_pi = jnp.where(pi > 0, jnp.log(jnp.where(pi > 0, pi, 1.0)), -jnp.inf)
243
+ j_new = jax.random.categorical(key_j, log_pi).astype(jnp.int64)
244
+ d_new = (jax.random.categorical(key_d, pmf(z_d_k)[j_new]) + 1).astype(jnp.int64)
245
+ j2 = jnp.where(ended, j_new, j)
246
+ e2 = jnp.where(ended, jnp.int64(1), e + 1)
247
+ d2 = jnp.where(ended, d_new, d)
248
+ state = j2 * d_max + jnp.minimum(e2, d_max) - 1
249
+ return (j2, e2, d2), (state, j2)
250
+
251
+ carry0 = (j0.astype(jnp.int64), e0.astype(jnp.int64), d0)
252
+ _, (states, regimes) = jax.lax.scan(step, carry0, (z_pi, z_d, jax.random.split(k_steps, h)))
253
+ _reject_autoregressive(spec)
254
+ values = spec.emission.sample(k_emit, regimes, dt, theta, z_e)
255
+ return states, regimes, values
256
+
257
+
258
+ @partial(jax.jit, static_argnames=("spec", "n_sim", "nominal_dt"))
259
+ def _explicit_core(
260
+ key: Array,
261
+ theta: Params,
262
+ spec: ModelSpec,
263
+ space: StateSpace,
264
+ log_alpha_t: Array,
265
+ dt: Array,
266
+ z_pi: Array,
267
+ z_d: Array,
268
+ z_e: Array,
269
+ z_d_hist: Array,
270
+ n_sim: int,
271
+ nominal_dt: float,
272
+ ) -> tuple[Array, Array, Array]:
273
+ origin_key, path_key = jax.random.split(key)
274
+ logits = jnp.broadcast_to(log_alpha_t, (n_sim, log_alpha_t.shape[0]))
275
+ s0 = jax.random.categorical(origin_key, logits)
276
+ j0 = space.index.regime_of[s0]
277
+ e0 = space.index.phase_of[s0]
278
+ t_len = z_d_hist.shape[0]
279
+ z_d_origin = z_d_hist[jnp.clip(t_len - e0, 0, t_len - 1)] # (n_sim, K_d): row where the segment began
280
+ keys = jax.random.split(path_key, n_sim)
281
+ in_axes = (0, None, None, None, None, 0, 0, 0, 0, 0, 0, None)
282
+ return jax.vmap(_explicit_path, in_axes=in_axes)(
283
+ keys, theta, spec, space, dt, z_pi, z_d, z_e, j0, e0, z_d_origin, nominal_dt
284
+ )
285
+
286
+
287
+ def forecast_paths_explicit(
288
+ key: Array,
289
+ theta: Params,
290
+ spec: ModelSpec,
291
+ space: StateSpace,
292
+ log_alpha_t: Array,
293
+ dt_future: Array,
294
+ n_sim: int,
295
+ nominal_dt: float,
296
+ cov_paths: Array | None = None,
297
+ colmap: ColumnMap | None = None,
298
+ z_d_hist: Array | None = None,
299
+ ) -> ForecastPaths:
300
+ """`forecast_paths` for the explicit-duration engine: origin `(regime, elapsed)`, then duration draws.
301
+
302
+ `log_alpha_t` is the `(N * D_max,)` last row of the explicit engine's filtered `log_alpha` (state
303
+ `j * D_max + e - 1`). `z_d_hist (T, K_d)` is the observed duration-covariate block: with entry-time
304
+ duration covariates the origin segment's pmf uses the row at which that segment began
305
+ (`T - elapsed`). `states` are augmented indices `j * D_max + min(e, D_max) - 1`.
306
+
307
+ Raises:
308
+ ConfigError: inconsistent shapes, `spec.engine != "explicit"` or a non-positive `n_sim`.
309
+ NumericalError: a non-finite simulated return.
310
+ """
311
+ if spec.engine != "explicit":
312
+ raise ConfigError("forecast_paths_explicit needs an explicit-engine spec", path="model.engine")
313
+ _check_inputs(log_alpha_t, dt_future, n_sim)
314
+ _check_state_count(log_alpha_t, space)
315
+ h = int(dt_future.shape[0])
316
+ z_pi, z_d, z_e = _blocks(cov_paths, colmap, n_sim, h)
317
+ needs_entry = bool(getattr(spec.duration, "cov_idx", ()))
318
+ if needs_entry and (z_d.shape[-1] == 0 or z_d_hist is None or z_d_hist.shape[0] == 0):
319
+ raise ConfigError(
320
+ "the duration family has entry-time covariates: pass cov_paths and z_d_hist",
321
+ path="forecast.covariate_forecaster",
322
+ )
323
+ hist = jnp.zeros((1, 0)) if z_d_hist is None or z_d_hist.shape[0] == 0 else z_d_hist
324
+ out = _explicit_core(
325
+ key, theta, spec, space, log_alpha_t, dt_future, z_pi, z_d, z_e, hist, n_sim, float(nominal_dt)
326
+ )
327
+ _check_finite(out[2])
328
+ return ForecastPaths(*out)
329
+
330
+
331
+ class MonteCarloForecaster:
332
+ """`forecast(fit, data, horizon, n_sim, seed) -> ForecastResult` (E6-T04b).
333
+
334
+ Runs the engine's filter on `data`, draws `n_sim` paths from the filtered posterior at the origin
335
+ (`forecast_paths` / `forecast_paths_explicit`) and aggregates them: regime probabilities, per-step
336
+ samples, cumulative-return quantiles and moments. Deterministic per `(fit, data, horizon, n_sim, seed)`.
337
+
338
+ Covariates. The row for the first forecast step is not part of `data` (the dataset ends at the last
339
+ observed step), so the last *observed* covariate row stands in for `last` -- the value `freeze`
340
+ repeats and the other forecasters start from. Multi-step forecasts with covariates need a
341
+ `forecaster`; a one-step forecast does not.
342
+
343
+ Args:
344
+ spec: model structure.
345
+ space: the state space `spec.engine` calls for (`build_expanded` / `build_explicit`).
346
+ engine: the matching inference engine.
347
+ forecaster: covariate forecaster, or `None` for covariate-free models and `horizon == 1`.
348
+ cfg: `forecast` config section (quantile levels).
349
+ clock_options: the options of the dataset's clock (`data.clock_options`).
350
+ """
351
+
352
+ def __init__(
353
+ self,
354
+ spec: ModelSpec,
355
+ space: StateSpace,
356
+ engine: InferenceEngine,
357
+ forecaster: CovariateForecaster | None,
358
+ cfg: ForecastSection,
359
+ clock_options: Mapping[str, Any] | None = None,
360
+ ) -> None:
361
+ """Store the model structure, engine, covariate forecaster and forecast config."""
362
+ self.spec = spec
363
+ self.space = space
364
+ self.engine = engine
365
+ self.forecaster = forecaster
366
+ self.cfg = cfg
367
+ self.clock_options = dict(clock_options or {})
368
+
369
+ def _origin_log_alpha(self, fit: FitResult, data: PreparedDataset, posterior: Posterior | None) -> Array:
370
+ if posterior is None:
371
+ log_alpha, _ = self.engine.forward(fit.params, self.spec, self.space, data)
372
+ else:
373
+ log_alpha = posterior.log_alpha
374
+ if log_alpha.shape[-1] != self.space.n_expanded:
375
+ raise ConfigError(
376
+ "the posterior is not over the full state space (chunked explicit posterior?)",
377
+ path="posterior",
378
+ )
379
+ return log_alpha[-1]
380
+
381
+ def _cov_paths(
382
+ self, data: PreparedDataset, horizon: int, n_sim: int, seed: int
383
+ ) -> tuple[Array | None, ColumnMap | None, str]:
384
+ n_cov = len(data.prep_stats.cov_names)
385
+ if n_cov == 0:
386
+ return None, None, "none"
387
+ last = jnp.asarray(_unified_covariates(data)[-1])
388
+ colmap = ColumnMap.from_dataset(data)
389
+ if horizon == 1:
390
+ return jnp.broadcast_to(last, (n_sim, 1, n_cov)), colmap, "none"
391
+ if self.forecaster is None:
392
+ raise ConfigError(
393
+ "horizon > 1 with covariates requires a covariate forecaster",
394
+ path="forecast.covariate_forecaster",
395
+ )
396
+ fitted = self.forecaster.fit(data)
397
+ key = key_for(seed, PURPOSE_FORECAST, FORECAST_COVARIATES)
398
+ return fitted.sample_paths(key, horizon, n_sim, last), colmap, fitted.name
399
+
400
+ def forecast(
401
+ self,
402
+ fit: FitResult,
403
+ data: PreparedDataset,
404
+ horizon: int,
405
+ n_sim: int,
406
+ seed: int,
407
+ posterior: Posterior | None = None,
408
+ ) -> ForecastResult:
409
+ """Forecast `horizon` steps from the end of `data` (`posterior` reuses a supplied filter pass).
410
+
411
+ Raises:
412
+ ConfigError: `horizon < 1`, `n_sim < 1`, or covariates with `horizon > 1` and no forecaster.
413
+ NumericalError: `n_sim * horizon * M > 2e8` (use fewer simulations) or non-finite output.
414
+ """
415
+ _reject_autoregressive(self.spec)
416
+ if horizon < 1:
417
+ raise ConfigError(f"horizon must be >= 1, got {horizon}", path="forecast.horizon")
418
+ if n_sim < 1:
419
+ raise ConfigError(f"n_sim must be >= 1, got {n_sim}", path="forecast.n_sim")
420
+ m = self.spec.n_series
421
+ if n_sim * horizon * m > MAX_SAMPLE_FLOATS:
422
+ raise NumericalError(
423
+ f"n_sim * horizon * M = {n_sim * horizon * m:.3g} > {MAX_SAMPLE_FLOATS:.0e} floats: "
424
+ "use fewer simulations or a shorter horizon",
425
+ path="forecast.n_sim",
426
+ )
427
+
428
+ times = np.asarray(data.times).astype("datetime64[ns]")
429
+ horizon_times, dt_np = future_grid(times[-1], horizon, data.clock, self.clock_options, times)
430
+ dt_future = jnp.asarray(dt_np)
431
+
432
+ log_alpha_t = self._origin_log_alpha(fit, data, posterior)
433
+ cov_paths, colmap, forecaster_name = self._cov_paths(data, horizon, n_sim, seed)
434
+ key = key_for(seed, PURPOSE_FORECAST, FORECAST_PATHS)
435
+ if self.spec.engine == "explicit":
436
+ paths = forecast_paths_explicit(
437
+ key,
438
+ fit.params,
439
+ self.spec,
440
+ self.space,
441
+ log_alpha_t,
442
+ dt_future,
443
+ n_sim,
444
+ data.nominal_dt,
445
+ cov_paths,
446
+ colmap,
447
+ data.cov_duration,
448
+ )
449
+ else:
450
+ paths = forecast_paths(
451
+ key, fit.params, self.spec, self.space, log_alpha_t, dt_future, n_sim, cov_paths, colmap
452
+ )
453
+
454
+ samples = paths.values # (n_sim, h, M)
455
+ regime_probs = jax.nn.one_hot(paths.regimes, self.spec.n_states).mean(axis=0) # (h, N)
456
+ cum = jnp.cumsum(samples, axis=1)
457
+ levels = tuple(float(q) for q in self.cfg.quantiles)
458
+ cum_quantiles = jnp.transpose(jnp.quantile(cum, jnp.asarray(levels), axis=0), (1, 0, 2)) # (h, Q, M)
459
+ mean, var = cum.mean(axis=0), cum.var(axis=0)
460
+ for name, arr in (("regime_probs", regime_probs), ("cum_quantiles", cum_quantiles), ("var", var)):
461
+ if not bool(jnp.all(jnp.isfinite(arr))):
462
+ raise NumericalError(f"non-finite {name} in forecast", path=name)
463
+
464
+ return ForecastResult(
465
+ origin_time=times[-1],
466
+ horizon_times=horizon_times,
467
+ regime_probs=regime_probs,
468
+ samples=samples,
469
+ cum_quantiles=cum_quantiles,
470
+ mean=mean,
471
+ var=var,
472
+ quantile_levels=levels,
473
+ covariate_forecaster=forecaster_name,
474
+ seed=seed,
475
+ )