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,996 @@
1
+ """Configuration schema: pydantic v2 models with `extra="forbid"` and cross-field validation.
2
+
3
+ Rules (concept §5.7, overview §4.1, CLAUDE.md §3.4): see `_validate_cross_fields` for the
4
+ numbered rules. `parse_project_config` is the entry point that converts pydantic's own
5
+ `ValidationError` (unknown keys, wrong types, ...) into `ConfigError(path=...)`, matching the
6
+ "all raise ConfigError" contract; custom cross-field rules raise `ConfigError` directly from
7
+ inside `@model_validator` methods (pydantic does not intercept non-`ValueError` exceptions, so
8
+ they propagate unwrapped).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import importlib
15
+ import itertools
16
+ import warnings as warnings_module
17
+ from pathlib import Path
18
+ from typing import Any, ClassVar, Literal, cast
19
+
20
+ import pydantic
21
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
22
+
23
+ from hsmmkit.config.defaults import (
24
+ D_MAX_CAP,
25
+ D_MAX_SOJOURN_MULTIPLIER,
26
+ D_MAX_WARN_SOJOURN_MULTIPLIER,
27
+ MAX_ORDER_WARN,
28
+ )
29
+ from hsmmkit.plugins import REGISTRY, Kind
30
+ from hsmmkit.utils.clock import get_clock, parse_clock_options
31
+ from hsmmkit.utils.errors import ConfigError
32
+
33
+ CURRENT_SCHEMA_VERSION = 1
34
+
35
+ Transform = Literal["log", "diff", "pct", "zscore"]
36
+ MissingPolicy = Literal["ffill", "drop", "error"]
37
+ EntryPoint = Literal["transition", "duration", "emission"]
38
+ ParamMode = Literal["free", "fixed", "tied", "bounded", "prior"]
39
+ CORE_OUTPUTS = ("posterior", "forecast", "backtest", "cv", "report")
40
+
41
+
42
+ class _Base(BaseModel):
43
+ model_config = ConfigDict(extra="forbid", validate_assignment=True)
44
+
45
+
46
+ def _registered_names(kind: Kind, *, needs: str | None = None) -> list[str]:
47
+ """Registered names of `kind` (optionally only objects with attribute `needs`); loads the components."""
48
+ importlib.import_module("hsmmkit.model.emission") # the families register on import
49
+ importlib.import_module("hsmmkit.model.duration")
50
+ importlib.import_module("hsmmkit.inference.covariate_forecasters")
51
+ importlib.import_module("hsmmkit.estimation.init")
52
+ if kind == "metric":
53
+ from hsmmkit.evaluation.metrics.registry import available
54
+
55
+ return list(available())
56
+ return [e.name for e in REGISTRY.entries(kind) if needs is None or hasattr(e.obj, needs)]
57
+
58
+
59
+ def _check_name(kind: Kind, name: str, path: str, *, needs: str | None = None) -> str:
60
+ """`name` if it is registered for `kind`, else a `ConfigError(path)` listing the registered names."""
61
+ names = _registered_names(kind, needs=needs)
62
+ if name not in names:
63
+ listing = (
64
+ ", ".join(f"{e.name} ({e.provenance})" for e in REGISTRY.entries(kind) if e.name in names)
65
+ or "<none>"
66
+ )
67
+ raise ConfigError(f"unknown {kind} '{name}'; registered: {listing}", path=path)
68
+ return name
69
+
70
+
71
+ def _register_core_sources() -> None:
72
+ """Import the core sources (lazy: they import this module) so that their kinds are registered."""
73
+ importlib.import_module("hsmmkit.data.sources")
74
+
75
+
76
+ def _validate_source_options(
77
+ kind: str, options: dict[str, Any], path: str, *, covariate: bool = False
78
+ ) -> None:
79
+ """Validate a core source's options with its `options_model` (lazy: the sources import this module)."""
80
+ from hsmmkit.data.sources.base import validate_options
81
+
82
+ validate_options(kind, options, path, covariate=covariate)
83
+
84
+
85
+ # --- project / data -------------------------------------------------------------------------
86
+
87
+
88
+ class ProjectSection(_Base):
89
+ """`project:` — run identity, seed, output location, logging."""
90
+
91
+ name: str
92
+ seed: int
93
+ output_dir: Path
94
+ log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
95
+
96
+
97
+ class SourceCfg(_Base):
98
+ """`data.source:` — where the observations come from.
99
+
100
+ `kind` names a registered source (`REGISTRY` kind `source`); the other keys are the options of that
101
+ source and are validated by the options model it registers.
102
+ """
103
+
104
+ model_config = ConfigDict(extra="allow", validate_assignment=True)
105
+
106
+ kind: str
107
+
108
+ def option(self, name: str, default: Any = None) -> Any: # noqa: ANN401
109
+ """The source option `name` (extra keys), or `default`."""
110
+ extra = self.model_extra or {}
111
+ return extra.get(name, default)
112
+
113
+ def options(self) -> dict[str, Any]:
114
+ """All options of the source (the extra keys)."""
115
+ return dict(self.model_extra or {})
116
+
117
+
118
+ class CovariateCfg(_Base):
119
+ """`data.covariates[]:` — one covariate series and how it enters the model."""
120
+
121
+ name: str
122
+ source: SourceCfg | None = None
123
+ column: str | None = None
124
+ transform: list[Transform] = Field(default_factory=list)
125
+ lag: int = Field(ge=1)
126
+ missing: MissingPolicy = "ffill"
127
+ max_staleness: int = 5
128
+ use_in: list[EntryPoint]
129
+
130
+
131
+ class PrepCfg(_Base):
132
+ """`data.preparation:` — observation and covariate preparation settings."""
133
+
134
+ observation_transform: str | None = None
135
+ standardize_observations: bool = False
136
+ standardize_covariates: bool = True
137
+ missing_observations: Literal["mask", "drop", "error"] = "mask"
138
+
139
+ @field_validator("observation_transform")
140
+ @classmethod
141
+ def _known_transform(cls, value: str | None) -> str | None:
142
+ if value is not None and REGISTRY.names("transform"): # the registry fills in E10-T05
143
+ _check_name("transform", value, "data.preparation.observation_transform")
144
+ return value
145
+
146
+
147
+ class SequencesCfg(_Base):
148
+ """`data.sequences:` — how a multi-sequence data set is grouped and padded (E12-T01a on)."""
149
+
150
+ group_by: str | None = None
151
+ bucket_edges: list[int] = Field(default_factory=lambda: [256, 512, 1024, 2048, 4096])
152
+
153
+ @field_validator("bucket_edges")
154
+ @classmethod
155
+ def _increasing(cls, value: list[int]) -> list[int]:
156
+ if any(e < 1 for e in value) or any(b <= a for a, b in itertools.pairwise(value)):
157
+ raise ConfigError(
158
+ "bucket_edges must be strictly increasing and >= 1", path="data.sequences.bucket_edges"
159
+ )
160
+ return value
161
+
162
+
163
+ class BoundariesCfg(_Base):
164
+ """`data.labels.boundaries:` — steps where a regime switch is required / forbidden."""
165
+
166
+ must_switch_at: list[int] = Field(default_factory=list)
167
+ must_not_switch_at: list[int] = Field(default_factory=list)
168
+
169
+
170
+ class LabelsCfg(_Base):
171
+ """`data.labels:` — partial supervision (E12-T06 on)."""
172
+
173
+ source: Literal["column", "file"]
174
+ column: str | None = None
175
+ path: Path | None = None
176
+ allowed_sets: bool = False
177
+ boundaries: BoundariesCfg | None = None
178
+
179
+ @model_validator(mode="after")
180
+ def _source_keys(self) -> LabelsCfg:
181
+ if self.source == "column" and self.column is None:
182
+ raise ConfigError("source='column' requires column", path="data.labels.column")
183
+ if self.source == "file" and self.path is None:
184
+ raise ConfigError("source='file' requires path", path="data.labels.path")
185
+ return self
186
+
187
+
188
+ class DataSection(_Base):
189
+ """`data:` — source, clock, covariates, preparation, sequences, labels."""
190
+
191
+ source: SourceCfg
192
+ clock: str = "steps"
193
+ clock_options: dict[str, Any] = Field(default_factory=dict)
194
+ covariates: list[CovariateCfg] = Field(default_factory=list)
195
+ preparation: PrepCfg = Field(default_factory=PrepCfg)
196
+ sequences: SequencesCfg | None = None
197
+ labels: LabelsCfg | None = None
198
+
199
+ def clock_option(self, name: str, default: Any = None) -> Any: # noqa: ANN401
200
+ """The clock option `name` (`clock_options`), or `default`."""
201
+ return self.clock_options.get(name, default)
202
+
203
+ @field_validator("source")
204
+ @classmethod
205
+ def _known_source(cls, value: SourceCfg) -> SourceCfg:
206
+ _register_core_sources()
207
+ _check_name("source", value.kind, "data.source.kind")
208
+ _validate_source_options(
209
+ value.kind, value.options(), "data.source"
210
+ ) # core sources: ConfigError per key
211
+ return value
212
+
213
+ @model_validator(mode="after")
214
+ def _valid_covariate_sources(self) -> DataSection:
215
+ for i, cov in enumerate(self.covariates):
216
+ if cov.source is not None:
217
+ _register_core_sources()
218
+ _check_name("source", cov.source.kind, f"data.covariates[{i}].source.kind")
219
+ _validate_source_options(
220
+ cov.source.kind, cov.source.options(), f"data.covariates[{i}].source", covariate=True
221
+ )
222
+ return self
223
+
224
+ @field_validator("clock")
225
+ @classmethod
226
+ def _known_clock(cls, value: str) -> str:
227
+ get_clock(value) # ConfigError(path="data.clock") listing the registered clocks
228
+ return value
229
+
230
+ @model_validator(mode="after")
231
+ def _valid_clock_options(self) -> DataSection:
232
+ parse_clock_options(self.clock, self.clock_options) # ConfigError(path="data.clock_options.<field>")
233
+ return self
234
+
235
+
236
+ # --- model: params, priors, emission/duration/transition/lattice -----------------------------
237
+
238
+
239
+ class PriorCfg(_Base):
240
+ """`prior:` — a named prior distribution and its parameters."""
241
+
242
+ type: Literal["normal", "lognormal", "dirichlet", "lkj"]
243
+ sd: float | None = None
244
+ alpha: float | None = None
245
+ eta: float | None = Field(default=None, gt=0.0)
246
+
247
+
248
+ class ParamCfg(_Base):
249
+ """A single (possibly per-state) parameter's estimation mode and initialization."""
250
+
251
+ mode: ParamMode
252
+ values: list[float] | None = None
253
+ init: list[float] | float | Literal["labels"] | None = None
254
+ """Initial values per state, or `"labels"` (the `labels` init method fills it from `data.labels`)."""
255
+ init_mean_sojourn_steps: list[float] | float | None = None
256
+ bounds: tuple[float, float] | None = None
257
+ constraint: Literal["none", "increasing"] = "none"
258
+ prior: PriorCfg | None = None
259
+ tie: str | None = None
260
+
261
+
262
+ class EmissionCovariates(_Base):
263
+ """`model.emission.covariates:` — which covariates drive the location and the log-scale.
264
+
265
+ `mean` / `log_scale` are the keys of the `gaussian` family; `drift` / `log_vol` those of an application's
266
+ `gbm` family and of `student_t`.
267
+ """
268
+
269
+ mean: list[str] = Field(default_factory=list)
270
+ log_scale: list[str] = Field(default_factory=list)
271
+ drift: list[str] = Field(default_factory=list)
272
+ log_vol: list[str] = Field(default_factory=list)
273
+
274
+
275
+ class MixtureCfg(_Base):
276
+ """`model.emission.mixture:` — `components` copies of the family `base`."""
277
+
278
+ components: int = Field(ge=1)
279
+ base: str
280
+
281
+
282
+ class ArCfg(_Base):
283
+ """`model.emission.ar:` — order and form of an `msar` (Markov-switching autoregression) emission."""
284
+
285
+ p: int = Field(default=1, ge=1)
286
+ """Autoregressive order (number of own lags)."""
287
+ form: Literal["coefficients", "mean_adjusted"] = "coefficients"
288
+ """`coefficients`: regime-dependent intercept and AR coefficients; `mean_adjusted`: Hamilton, `p <= 2`."""
289
+
290
+
291
+ class EmissionCfg(_Base):
292
+ """`model.emission:` — emission family, per-parameter configs, covariate links."""
293
+
294
+ family: str
295
+ params: dict[str, ParamCfg]
296
+ covariates: EmissionCovariates = Field(default_factory=EmissionCovariates)
297
+ scale_by_dt: bool | None = None
298
+ """Declared time scaling of the family (`None`: the family's own); a different value is rejected."""
299
+ ito_correction: bool | None = None
300
+ """`gaussian`: subtract `scale**2 / 2` from the location (`None`: the family's own, `False`)."""
301
+ covariance: Literal["diag", "full"] = "diag"
302
+ """`gaussian` / `student_t` (joint path): covariance structure `diag` or `full`."""
303
+ mixture: MixtureCfg | None = None
304
+ """Per-state finite mixture of `base` components (not available before E11-T06)."""
305
+ per_series: bool = True
306
+ """`True`: own location/scale per series, `(N, M)`; `False`: one per regime, shared."""
307
+ ar: ArCfg | None = None
308
+ """`msar`: autoregressive order and form (required by that family, rejected by every other)."""
309
+ columns: list[int | str] | None = None
310
+ """A `product` block: the observation columns (indices or names) the block's family emits."""
311
+ blocks: list[EmissionCfg] | None = None
312
+ """`product`: independent blocks of series, each any registered family (each names its `columns`)."""
313
+
314
+ @field_validator("family")
315
+ @classmethod
316
+ def _known_family(cls, value: str) -> str:
317
+ return _check_name("emission", value, "model.emission.family", needs="from_config")
318
+
319
+
320
+ class PerStateDurationCfg(_Base):
321
+ """`model.duration.per_state[]:` — the duration family of one regime."""
322
+
323
+ family: str
324
+ params: dict[str, ParamCfg] = Field(default_factory=dict)
325
+ r: int | None = None
326
+ """`negbin`: the number of phases of this regime."""
327
+
328
+ @field_validator("family")
329
+ @classmethod
330
+ def _known_family(cls, value: str) -> str:
331
+ return _check_name("duration", value, "model.duration.per_state.family", needs="from_config")
332
+
333
+
334
+ class DurationCfg(_Base):
335
+ """`model.duration:` — duration family (or one per state), minimum sojourns, per-parameter configs."""
336
+
337
+ family: str | None = None
338
+ r: list[int] | None = None
339
+ params: dict[str, ParamCfg] = Field(default_factory=dict)
340
+ covariates: list[str] = Field(default_factory=list)
341
+ duration_covariates_at_entry: bool = False
342
+ per_state: list[PerStateDurationCfg] | None = None
343
+ """One family per regime (`engine: explicit`; not available before E12-T05)."""
344
+ duration_dependent_jumps: bool = False
345
+ """Jump probabilities depend on the sojourn length (`engine: explicit`; not before E12-T05)."""
346
+
347
+ @field_validator("family")
348
+ @classmethod
349
+ def _known_family(cls, value: str | None) -> str | None:
350
+ if value is None:
351
+ return None
352
+ return _check_name("duration", value, "model.duration.family", needs="from_config")
353
+
354
+ @model_validator(mode="after")
355
+ def _family_or_per_state(self) -> DurationCfg:
356
+ if (self.family is None) == (self.per_state is None):
357
+ raise ConfigError("exactly one of family / per_state", path="model.duration.family")
358
+ if self.per_state is not None and not self.per_state:
359
+ raise ConfigError("per_state must not be empty", path="model.duration.per_state")
360
+ return self
361
+
362
+
363
+ class TransitionCfg(_Base):
364
+ """`model.transition:` — jump/generator mode, order, covariates, priors."""
365
+
366
+ mode: Literal["jump", "generator"] = "jump"
367
+ order: int = Field(default=1, ge=1)
368
+ duration_conditioning: Literal["current", "pair"] = "current"
369
+ covariates: list[str] = Field(default_factory=list)
370
+ prior: PriorCfg | None = None
371
+ coef_prior_sd: float = 1.0
372
+
373
+
374
+ class LatticeCfg(_Base):
375
+ """`model.lattice:` — multi-start initialization grids."""
376
+
377
+ grids: dict[str, list[float]]
378
+
379
+
380
+ class BandedCfg(_Base):
381
+ """`model.topology: {banded: k}` — jumps only to regimes within `k` positions (`0 < |j - i| <= k`)."""
382
+
383
+ banded: int = Field(ge=1)
384
+
385
+
386
+ class MatrixCfg(_Base):
387
+ """`model.topology: {matrix: [[...]]}` — the allowed jumps as an `N x N` 0/1 matrix (zero diagonal)."""
388
+
389
+ matrix: list[list[int]]
390
+
391
+
392
+ Topology = Literal["full", "left_to_right", "cyclic"] | BandedCfg | MatrixCfg
393
+
394
+
395
+ class ModelSection(_Base):
396
+ """`model:` — state count, engine, initial-distribution mode, families, lattice."""
397
+
398
+ n_states: int = Field(ge=2)
399
+ engine: Literal["expanded", "explicit"] = "expanded"
400
+ d_max: int | None = None
401
+ initial_state: Literal["uniform", "stationary", "free"] = "uniform"
402
+ initial_groups: Literal["shared", "per_group"] = "shared"
403
+ topology: Topology = "full"
404
+ left_censored: bool = False
405
+ emission: EmissionCfg
406
+ duration: DurationCfg
407
+ transition: TransitionCfg
408
+ lattice: LatticeCfg | None = None
409
+
410
+
411
+ # --- estimation / forecast / evaluation / output ----------------------------------------------
412
+
413
+
414
+ class TemperingCfg(_Base):
415
+ """`tempering:` — deterministic annealing of the E-step (`beta0` rising to 1 in `steps`)."""
416
+
417
+ enabled: bool = False
418
+ beta0: float = Field(default=0.3, gt=0.0, le=1.0)
419
+ steps: int = Field(default=10, ge=1)
420
+
421
+
422
+ class EcmCfg(_Base):
423
+ """`estimation.em.ecm:` — conditional maximization of blocks without a closed form."""
424
+
425
+ inner_iter: int = Field(default=5, ge=1)
426
+
427
+
428
+ class EmCfg(_Base):
429
+ """`estimation.em:` / `estimation.gem:` — EM options."""
430
+
431
+ tempering: TemperingCfg = Field(default_factory=TemperingCfg)
432
+ ecm: EcmCfg = Field(default_factory=EcmCfg)
433
+ warm_start_from: Literal["map", "none"] = "none"
434
+ """`map`: run EM from the MAP optimum (the parity suite); `none`: the configured initializations."""
435
+
436
+
437
+ class VbCfg(_Base):
438
+ """`estimation.vb:` — variational Bayes options."""
439
+
440
+ prune_below: float = Field(default=0.01, ge=0.0, lt=1.0)
441
+ max_iter: int = Field(default=500, ge=1)
442
+
443
+
444
+ class McmcCfg(_Base):
445
+ """`estimation.mcmc:` — MCMC options."""
446
+
447
+ sampler: Literal["nuts", "gibbs"] = "nuts"
448
+ chains: int = Field(default=4, ge=1)
449
+ warmup: int = Field(default=1000, ge=0)
450
+ draws: int = Field(default=1000, ge=1)
451
+ target_accept: float = Field(default=0.8, gt=0.0, lt=1.0)
452
+ max_tree_depth: int = Field(default=10, ge=1)
453
+ chain_method: Literal["sequential", "vectorized"] = "sequential"
454
+ default_priors: bool = True
455
+ """Add weakly informative priors to the free parameters that have none (else they are an error)."""
456
+ jitter: float = Field(default=0.05, ge=0.0)
457
+ """Standard deviation of the Gaussian jitter added to the MAP start of each chain (unconstrained)."""
458
+ log_likelihood: bool = True
459
+ """Store the per-sequence log-likelihood of every draw in the `log_likelihood` group."""
460
+ keep_paths_every: int = Field(default=0, ge=0)
461
+ """Gibbs only: keep the sampled regime paths of every k-th draw in a `path_samples` group (0: none)."""
462
+
463
+
464
+ class EstimationSection(_Base):
465
+ """`estimation:` — method, optimizer, convergence, multi-start, device."""
466
+
467
+ method: Literal["map", "em", "gem", "vb", "mcmc"] = "map"
468
+ em: EmCfg | None = None
469
+ gem: EmCfg | None = None
470
+ vb: VbCfg | None = None
471
+ mcmc: McmcCfg | None = None
472
+ optimizer: Literal["lbfgs", "adam"] = "lbfgs"
473
+ max_iter: int = 1000
474
+ tol_f: float = 1.0e-9
475
+ tol_g: float = 1.0e-6
476
+ restarts: int = 8
477
+ init: list[str] = Field(default_factory=list)
478
+ use_priors: bool = True
479
+ std_errors: bool = False
480
+ device: Literal["cpu", "gpu", "auto"] = "auto"
481
+ chunk_size: int | None = Field(default=None, ge=1) # explicit engine: steps per chunk (None = auto)
482
+ parallel_scan: bool = False # expanded engine: associative-scan smoothing (memory T*S^2)
483
+ diagnostics: list[Literal["pseudo_residuals", "ppc"]] = Field(
484
+ default_factory=lambda: cast("list[Literal['pseudo_residuals', 'ppc']]", ["pseudo_residuals"])
485
+ )
486
+ """Model-adequacy sections of `fit_report.json` (E14-T05): normal pseudo-residuals and / or the PPC."""
487
+ ppc_replicates: int = Field(default=200, ge=2)
488
+
489
+ @field_validator("init")
490
+ @classmethod
491
+ def _known_inits(cls, value: list[str]) -> list[str]:
492
+ for i, name in enumerate(value):
493
+ _check_name("init", name, f"estimation.init[{i}]")
494
+ return value
495
+
496
+
497
+ class CovariateForecasterCfg(_Base):
498
+ """`forecast.covariate_forecaster:` — a discriminated-union-ish free-form config.
499
+
500
+ Type-specific keys (`mean_block_length` for `bootstrap`, `diagonal` for `ar`, `path` for
501
+ `scenario`) are validated loosely as extra fields are forbidden per type; unrecognized keys
502
+ for the chosen `type` are still rejected by `extra='forbid'` on the concrete subclass chosen
503
+ by `type`, resolved in `_validate_cross_fields`.
504
+ """
505
+
506
+ type: str
507
+ mean_block_length: int | None = None
508
+ diagonal: bool | None = None
509
+ path: str | None = None
510
+
511
+ @field_validator("type")
512
+ @classmethod
513
+ def _known_type(cls, value: str) -> str:
514
+ return _check_name("covariate_forecaster", value, "forecast.covariate_forecaster.type")
515
+
516
+
517
+ class ForecastSection(_Base):
518
+ """`forecast:` — horizon, simulation count, covariate forecaster, quantile levels."""
519
+
520
+ horizon: int
521
+ n_sim: int
522
+ covariate_forecaster: CovariateForecasterCfg = Field(
523
+ default_factory=lambda: CovariateForecasterCfg(type="freeze")
524
+ )
525
+ quantiles: list[float]
526
+
527
+ @model_validator(mode="after")
528
+ def _check_quantiles(self) -> ForecastSection:
529
+ qs = self.quantiles
530
+ if any(not (0.0 < q < 1.0) for q in qs):
531
+ raise ConfigError("quantiles must be strictly between 0 and 1", path="quantiles")
532
+ if list(qs) != sorted(qs) or len(set(qs)) != len(qs):
533
+ raise ConfigError("quantiles must be strictly increasing", path="quantiles")
534
+ return self
535
+
536
+
537
+ class BacktestCfg(_Base):
538
+ """`evaluation.backtest:` — walk-forward scheme, horizons, embargo.
539
+
540
+ `initial_train` and `rolling_window` are lengths in clock units (years under the calendar-based clocks,
541
+ steps under `steps`); `initial_train_steps` and `rolling_window_steps` give the same lengths in rows.
542
+ Exactly one of `initial_train` / `initial_train_steps`; at most one of the rolling pair.
543
+ """
544
+
545
+ scheme: Literal["expanding", "rolling"]
546
+ initial_train: float | None = None
547
+ initial_train_steps: int | None = Field(default=None, ge=1)
548
+ rolling_window: float | None = None
549
+ rolling_window_steps: int | None = Field(default=None, ge=1)
550
+ refit_every_steps: int
551
+ horizons: list[int]
552
+ embargo_steps: int = 0
553
+ n_sim: int | None = Field(default=None, ge=1) # simulated paths per origin (None = forecast.n_sim)
554
+
555
+ @model_validator(mode="after")
556
+ def _one_of_each_pair(self) -> BacktestCfg:
557
+ if (self.initial_train is None) == (self.initial_train_steps is None):
558
+ raise ConfigError(
559
+ "exactly one of initial_train / initial_train_steps", path="evaluation.backtest.initial_train"
560
+ )
561
+ if self.rolling_window is not None and self.rolling_window_steps is not None:
562
+ raise ConfigError(
563
+ "at most one of rolling_window / rolling_window_steps",
564
+ path="evaluation.backtest.rolling_window",
565
+ )
566
+ return self
567
+
568
+
569
+ class LabelSource(_Base):
570
+ """`evaluation.labels:` — an optional external ground-truth regime label source."""
571
+
572
+ path: str
573
+
574
+
575
+ class CvCfg(_Base):
576
+ """`evaluation.cv:` — cross-validation over sequences (E14-T01 on)."""
577
+
578
+ splitter: Literal["sequence_kfold", "walk_forward"]
579
+ folds: int = Field(default=5, ge=2)
580
+ seed: int = 0
581
+
582
+
583
+ class ParallelCfg(_Base):
584
+ """`evaluation.grid.parallel:` — process-pool execution of the grid cells."""
585
+
586
+ backend: Literal["process"] = "process"
587
+ workers: int = Field(default=2, ge=1)
588
+
589
+
590
+ class GridCfg(_Base):
591
+ """`evaluation.grid:` — model-selection grid (E14-T02).
592
+
593
+ Every axis is optional (an absent axis keeps the base configuration's value). `r` lists explicit
594
+ per-regime phase counts (negative binomial), `r_same_for_all` lists values used for every regime.
595
+ `duration` and `emission` name families, `estimator` the `estimation.method`.
596
+ """
597
+
598
+ n_states: list[int] = Field(default_factory=list)
599
+ r: list[list[int]] = Field(default_factory=list)
600
+ r_same_for_all: list[int] = Field(default_factory=list)
601
+ emission: list[str] = Field(default_factory=list)
602
+ duration: list[str] = Field(default_factory=list)
603
+ estimator: list[str] = Field(default_factory=list)
604
+ parallel: ParallelCfg | None = None
605
+
606
+ @field_validator("n_states")
607
+ @classmethod
608
+ def _states(cls, value: list[int]) -> list[int]:
609
+ if any(n < 2 for n in value):
610
+ raise ConfigError("n_states entries must be >= 2", path="evaluation.grid.n_states")
611
+ return value
612
+
613
+
614
+ class EvaluationSection(_Base):
615
+ """`evaluation:` — metrics, backtest scheme, cross-validation, grid, optional labels."""
616
+
617
+ metrics: list[str]
618
+ backtest: BacktestCfg | None = None
619
+ labels: LabelSource | None = None
620
+ cv: CvCfg | None = None
621
+ grid: GridCfg | None = None
622
+ boundary_tolerance: int = Field(default=5, ge=0)
623
+
624
+ @field_validator("metrics")
625
+ @classmethod
626
+ def _known_metrics(cls, value: list[str]) -> list[str]:
627
+ for i, name in enumerate(value):
628
+ _check_name("metric", name, f"evaluation.metrics[{i}]")
629
+ return value
630
+
631
+
632
+ class AlertCfg(_Base):
633
+ """`online.alerts[]:` — hysteresis on a regime probability, or on the remaining duration.
634
+
635
+ `name` labels the events (default `alert<i>`), `use` picks the probability source (`smoothed` is the
636
+ fixed-lag smoothed marginal and needs `online.lag > 0`), `p_min` is the probability a regime needs for a
637
+ remaining-duration rule to apply.
638
+ """
639
+
640
+ name: str | None = None
641
+ regime: int = Field(ge=0)
642
+ p_on: float | None = Field(default=None, gt=0.0, le=1.0)
643
+ p_off: float | None = Field(default=None, ge=0.0, lt=1.0)
644
+ remaining_duration_below: float | None = Field(default=None, gt=0.0)
645
+ p_min: float = Field(default=0.5, gt=0.0, le=1.0)
646
+ use: Literal["filtered", "smoothed"] = "filtered"
647
+
648
+ @model_validator(mode="after")
649
+ def _one_kind(self) -> AlertCfg:
650
+ prob = self.p_on is not None or self.p_off is not None
651
+ if prob == (self.remaining_duration_below is not None):
652
+ raise ConfigError(
653
+ "an alert is {regime, p_on, p_off} or {regime, remaining_duration_below}",
654
+ path="online.alerts",
655
+ )
656
+ if prob:
657
+ if self.p_on is None or self.p_off is None:
658
+ raise ConfigError("p_on and p_off are both required", path="online.alerts.p_off")
659
+ if not self.p_off < self.p_on:
660
+ raise ConfigError("p_off must be < p_on", path="online.alerts.p_off")
661
+ return self
662
+
663
+
664
+ class OnlineEmCfg(_Base):
665
+ """`online.em:` — online parameter updates by the Cappe-Moulines recursion (E15-T05, ADR-0026).
666
+
667
+ `kappa` is the step-size exponent (`g_t = t^-kappa`); `burn_in` the observations before the first update
668
+ (`None`: `max(500, 25 n_free)`); `components` the parts of the model that are re-estimated (the others,
669
+ and components without a closed-form M-step, keep the fitted values).
670
+ """
671
+
672
+ enabled: bool = False
673
+ kappa: float = Field(default=0.6, gt=0.5, le=1.0)
674
+ burn_in: int | None = Field(default=None, ge=1)
675
+ update_every: int = Field(default=1, ge=1)
676
+ components: list[Literal["emission", "duration", "transition"]] = Field(
677
+ default_factory=lambda: cast(
678
+ "list[Literal['emission', 'duration', 'transition']]", ["emission", "duration", "transition"]
679
+ )
680
+ )
681
+
682
+
683
+ class OnlineCfg(_Base):
684
+ """`online:` — streaming filter, fixed-lag smoothing and alerts (E15 on)."""
685
+
686
+ lag: int = Field(default=0, ge=0)
687
+ em: OnlineEmCfg | None = None
688
+ alerts: list[AlertCfg] = Field(default_factory=list)
689
+ checkpoint_every: int = Field(default=1000, ge=1)
690
+ """Rows between state checkpoints of `hsmmkit stream --state`."""
691
+
692
+ @model_validator(mode="after")
693
+ def _alert_names_and_sources(self) -> OnlineCfg:
694
+ names = [a.name for a in self.alerts if a.name is not None]
695
+ if len(set(names)) != len(names):
696
+ raise ConfigError("alert names must be unique", path="online.alerts.name")
697
+ for i, alert in enumerate(self.alerts):
698
+ if alert.use == "smoothed" and self.lag == 0:
699
+ raise ConfigError("use: smoothed needs online.lag > 0", path=f"online.alerts[{i}].use")
700
+ return self
701
+
702
+
703
+ class OutputSection(_Base):
704
+ """`output:` — which artifacts to write."""
705
+
706
+ write: list[str]
707
+
708
+ extra_outputs: ClassVar[tuple[str, ...]] = ()
709
+ """Output names an extension adds (set by the subclass of the extension)."""
710
+
711
+ @field_validator("write")
712
+ @classmethod
713
+ def _known_outputs(cls, value: list[str]) -> list[str]:
714
+ allowed = (*CORE_OUTPUTS, *cls.extra_outputs)
715
+ for i, name in enumerate(value):
716
+ if name not in allowed:
717
+ raise ConfigError(
718
+ f"unknown output '{name}'; allowed: {', '.join(allowed)}", path=f"output.write[{i}]"
719
+ )
720
+ return value
721
+
722
+
723
+ # --- top level ---------------------------------------------------------------------------------
724
+
725
+
726
+ class ProjectConfig(_Base):
727
+ """The whole resolved configuration of the domain-neutral core.
728
+
729
+ Applications extend it by subclassing (D24): they replace sections by subclasses, set `SCHEMA_ID` and
730
+ `SCHEMA_VERSION`, and register their own migrations (`hsmmkit.config.migrate`).
731
+ """
732
+
733
+ SCHEMA_ID: ClassVar[str] = "core"
734
+ SCHEMA_VERSION: ClassVar[int] = CURRENT_SCHEMA_VERSION
735
+
736
+ schema_version: int = CURRENT_SCHEMA_VERSION
737
+ project: ProjectSection
738
+ data: DataSection
739
+ model: ModelSection
740
+ estimation: EstimationSection
741
+ forecast: ForecastSection
742
+ evaluation: EvaluationSection
743
+ output: OutputSection
744
+ online: OnlineCfg | None = None
745
+ warnings: list[str] = Field(default_factory=list)
746
+
747
+ @model_validator(mode="after")
748
+ def _validate_cross_fields(self) -> ProjectConfig:
749
+ _check_param_cfg_consistency(self)
750
+ _check_per_state_lengths(self)
751
+ _check_covariate_cross_references(self)
752
+ _check_transition_order(self)
753
+ _check_generator_mode(self)
754
+ _check_engine_duration_covariates_warning(self)
755
+ _check_part2_keys(self)
756
+ _resolve_d_max(self)
757
+ return self
758
+
759
+ def backtest_cfg(self) -> BacktestCfg:
760
+ """`evaluation.backtest`, required by the walk-forward commands.
761
+
762
+ Raises:
763
+ ConfigError: the section is absent (`path="evaluation.backtest"`).
764
+ """
765
+ if self.evaluation.backtest is None:
766
+ raise ConfigError("evaluation.backtest is required for a backtest", path="evaluation.backtest")
767
+ return self.evaluation.backtest
768
+
769
+ def expected_sojourn_steps(self) -> float | None:
770
+ """Largest initial mean sojourn in steps that the config states (`None` when it states none)."""
771
+ values: list[float] = []
772
+ for pc in self.model.duration.params.values():
773
+ if pc.init_mean_sojourn_steps is not None:
774
+ values.extend(_as_list(pc.init_mean_sojourn_steps))
775
+ elif isinstance(pc.init, list) and self.data.clock == "steps":
776
+ values.extend(pc.init)
777
+ for ps in (
778
+ self.model.duration.per_state or []
779
+ ): # only the stated mean sojourns (`init` is a shape etc.)
780
+ for pc in ps.params.values():
781
+ if pc.init_mean_sojourn_steps is not None:
782
+ values.extend(_as_list(pc.init_mean_sojourn_steps))
783
+ return max(values) if values else None
784
+
785
+
786
+ def _as_list(value: float | list[float]) -> list[float]:
787
+ return list(value) if isinstance(value, list) else [value]
788
+
789
+
790
+ # --- cross-field rule implementations (kept out of the class body for readability) -----------
791
+
792
+
793
+ def _warn(config: ProjectConfig, message: str) -> None:
794
+ config.warnings.append(message)
795
+ warnings_module.warn(message, stacklevel=3)
796
+
797
+
798
+ def _named_param_cfgs(config: ProjectConfig) -> list[tuple[str, ParamCfg]]:
799
+ """`(dotted path, ParamCfg)` for every `ParamCfg` in `model.emission.params`/`model.duration.params`."""
800
+ out = [(f"model.emission.params.{key}", pc) for key, pc in config.model.emission.params.items()]
801
+ out += [(f"model.duration.params.{key}", pc) for key, pc in config.model.duration.params.items()]
802
+ for i, ps in enumerate(config.model.duration.per_state or []):
803
+ out += [(f"model.duration.per_state[{i}].params.{key}", pc) for key, pc in ps.params.items()]
804
+ return out
805
+
806
+
807
+ def _check_param_cfg_consistency(config: ProjectConfig) -> None:
808
+ for path, pc in _named_param_cfgs(config):
809
+ if pc.mode == "fixed" and pc.values is None:
810
+ raise ConfigError("mode='fixed' requires values", path=f"{path}.values")
811
+ if pc.mode == "bounded" and pc.bounds is None:
812
+ raise ConfigError("mode='bounded' requires bounds", path=f"{path}.bounds")
813
+ if pc.mode == "tied" and pc.tie is None:
814
+ raise ConfigError("mode='tied' requires tie", path=f"{path}.tie")
815
+ if pc.mode == "prior" and pc.prior is None:
816
+ raise ConfigError("mode='prior' requires prior", path=f"{path}.prior")
817
+
818
+
819
+ def _check_per_state_lengths(config: ProjectConfig) -> None:
820
+ n = config.model.n_states
821
+ duration = config.model.duration
822
+ if duration.r is not None and len(duration.r) != n:
823
+ raise ConfigError(f"r must have length n_states={n}", path="model.duration.r")
824
+
825
+ def _check(section_path: str, params: dict[str, ParamCfg], allowed: tuple[int, ...] = (n,)) -> None:
826
+ for key, pc in params.items():
827
+ if key in (
828
+ "chol",
829
+ "probs",
830
+ "weights",
831
+ ): # packed / categorical / mixture vectors: the family checks
832
+ continue
833
+ for field_name in ("values", "init", "init_mean_sojourn_steps"):
834
+ value = getattr(pc, field_name)
835
+ if isinstance(value, list) and len(value) not in allowed:
836
+ raise ConfigError(
837
+ f"{field_name} must have length n_states={n}"
838
+ + (
839
+ ""
840
+ if allowed == (n,)
841
+ else f" (or {' or '.join(str(a) for a in allowed[1:])} for a mixture)"
842
+ ),
843
+ path=f"{section_path}.params.{key}.{field_name}",
844
+ )
845
+
846
+ mixture = config.model.emission.mixture
847
+ allowed = (n,) if mixture is None else (n, n * mixture.components, mixture.components)
848
+ _check("model.emission", config.model.emission.params, tuple(dict.fromkeys(allowed)))
849
+ _check("model.duration", config.model.duration.params)
850
+
851
+
852
+ def _check_covariate_cross_references(config: ProjectConfig) -> None:
853
+ by_name = {c.name: c for c in config.data.covariates}
854
+
855
+ def _require(name: str, entry_point: EntryPoint, path: str) -> None:
856
+ cov = by_name.get(name)
857
+ if cov is None:
858
+ raise ConfigError(f"covariate {name!r} not found in data.covariates", path=path)
859
+ if entry_point not in cov.use_in:
860
+ raise ConfigError(f"covariate {name!r} does not list {entry_point!r} in its use_in", path=path)
861
+
862
+ for name in config.model.transition.covariates:
863
+ _require(name, "transition", "model.transition.covariates")
864
+ for name in config.model.duration.covariates:
865
+ _require(name, "duration", "model.duration.covariates")
866
+ for key in ("mean", "log_scale", "drift", "log_vol"):
867
+ for name in getattr(config.model.emission.covariates, key):
868
+ _require(name, "emission", f"model.emission.covariates.{key}")
869
+
870
+
871
+ def _check_transition_order(config: ProjectConfig) -> None:
872
+ order = config.model.transition.order
873
+ if order > MAX_ORDER_WARN:
874
+ _warn(
875
+ config, f"transition.order={order} > {MAX_ORDER_WARN}; higher orders expand the state space fast"
876
+ )
877
+
878
+
879
+ def _check_generator_mode(config: ProjectConfig) -> None:
880
+ transition = config.model.transition
881
+ if transition.mode != "generator":
882
+ return
883
+ duration = config.model.duration
884
+ if duration.family != "geometric":
885
+ raise ConfigError(
886
+ "mode='generator' is only valid with duration.family='geometric'", path="model.transition.mode"
887
+ )
888
+ if duration.r is not None and any(r != 1 for r in duration.r):
889
+ raise ConfigError("mode='generator' requires all r == 1", path="model.transition.mode")
890
+
891
+
892
+ def _check_engine_duration_covariates_warning(config: ProjectConfig) -> None:
893
+ duration = config.model.duration
894
+ if config.model.engine == "explicit" and duration.family == "negbin" and duration.covariates:
895
+ duration.duration_covariates_at_entry = True
896
+ _warn(config, "explicit engine + negbin duration covariates: switching to entry-time evaluation")
897
+
898
+
899
+ def _check_part2_keys(config: ProjectConfig) -> None:
900
+ """Validation rules of the Part II keys (Part II §15.4)."""
901
+ m = config.model
902
+ n = m.n_states
903
+ if (m.duration.per_state is not None) and m.engine != "explicit":
904
+ raise ConfigError("per_state requires engine: explicit", path="model.duration.per_state")
905
+ if m.duration.duration_dependent_jumps and m.engine != "explicit":
906
+ raise ConfigError(
907
+ "only the explicit engine can express duration-dependent jumps",
908
+ path="model.duration.duration_dependent_jumps",
909
+ )
910
+ if m.duration.per_state is not None and len(m.duration.per_state) != n:
911
+ raise ConfigError(f"per_state must have length n_states={n}", path="model.duration.per_state")
912
+ topo = m.topology
913
+ if isinstance(topo, BandedCfg) and topo.banded >= n:
914
+ raise ConfigError(f"banded must be < n_states={n}", path="model.topology.banded")
915
+ if isinstance(topo, MatrixCfg):
916
+ mat = topo.matrix
917
+ if len(mat) != n or any(len(row) != n for row in mat):
918
+ raise ConfigError(f"matrix must be {n} x {n}", path="model.topology.matrix")
919
+ if any(v not in (0, 1) for row in mat for v in row):
920
+ raise ConfigError("matrix entries must be 0 or 1", path="model.topology.matrix")
921
+ if any(mat[i][i] != 0 for i in range(n)):
922
+ raise ConfigError("matrix must have a zero diagonal", path="model.topology.matrix")
923
+ absorbing = [i for i, row in enumerate(mat) if not any(row)]
924
+ if absorbing:
925
+ _warn(config, f"topology.matrix: states {absorbing} have no outgoing jump (absorbing)")
926
+ label_inits = [p for p, pc in _named_param_cfgs(config) if pc.init == "labels"]
927
+ if label_inits and config.data.labels is None:
928
+ raise ConfigError("init: labels requires data.labels", path=f"{label_inits[0]}.init")
929
+ if "labels" in config.estimation.init and config.data.labels is None:
930
+ raise ConfigError("the 'labels' init requires data.labels", path="estimation.init")
931
+ if config.online is not None:
932
+ for i, alert in enumerate(config.online.alerts):
933
+ if alert.regime >= n:
934
+ raise ConfigError(f"regime must be < n_states={n}", path=f"online.alerts[{i}].regime")
935
+ if config.estimation.method in ("vb", "mcmc"):
936
+ names = _non_conjugate_components(config)
937
+ if names:
938
+ _warn(
939
+ config,
940
+ f"estimation.method={config.estimation.method!r}: no conjugate prior known for "
941
+ + ", ".join(names),
942
+ )
943
+
944
+
945
+ def _non_conjugate_components(config: ProjectConfig) -> list[str]:
946
+ """Components whose family does not override `conjugate_prior()` (VB and MCMC fall back)."""
947
+ from hsmmkit.model.emission.base import BaseEmission
948
+
949
+ _registered_names("emission")
950
+ out: list[str] = []
951
+ families = [("emission", config.model.emission.family)]
952
+ if config.model.duration.family is not None:
953
+ families.append(("duration", config.model.duration.family))
954
+ for ps in config.model.duration.per_state or []:
955
+ families.append(("duration", ps.family))
956
+ for kind, name in families:
957
+ entry = next((e for e in REGISTRY.entries(kind) if e.name == name), None) # type: ignore[arg-type]
958
+ fn = getattr(entry.obj, "conjugate_prior", None) if entry is not None else None
959
+ conjugate = fn is not None and fn is not BaseEmission.conjugate_prior
960
+ if conjugate and kind == "emission": # the answer may depend on the options (e.g. `covariance`)
961
+ emission = config.model.emission
962
+ with contextlib.suppress(TypeError): # a family without these options keeps the class answer
963
+ family = entry.obj( # type: ignore[union-attr]
964
+ covariance=emission.covariance, scale_by_dt=bool(emission.scale_by_dt)
965
+ )
966
+ conjugate = family.conjugate_prior() is not None
967
+ if not conjugate and f"{kind}.{name}" not in out:
968
+ out.append(f"{kind}.{name}")
969
+ return out
970
+
971
+
972
+ def _resolve_d_max(config: ProjectConfig) -> None:
973
+ expected = config.expected_sojourn_steps()
974
+ if config.model.d_max is None:
975
+ if expected is None:
976
+ config.model.d_max = D_MAX_CAP
977
+ else:
978
+ config.model.d_max = min(D_MAX_CAP, round(D_MAX_SOJOURN_MULTIPLIER * expected))
979
+ elif expected is not None and config.model.d_max < D_MAX_WARN_SOJOURN_MULTIPLIER * expected:
980
+ _warn(
981
+ config,
982
+ f"model.d_max={config.model.d_max} is small relative to the expected sojourn "
983
+ f"({expected:.1f} steps); consider raising it",
984
+ )
985
+
986
+
987
+ def parse_project_config(
988
+ data: dict[str, Any], config_cls: type[ProjectConfig] = ProjectConfig
989
+ ) -> ProjectConfig:
990
+ """Validate `data` into a `config_cls`, converting pydantic errors into `ConfigError`."""
991
+ try:
992
+ return config_cls.model_validate(data)
993
+ except pydantic.ValidationError as exc:
994
+ first = exc.errors()[0]
995
+ path = ".".join(str(part) for part in first["loc"])
996
+ raise ConfigError(first["msg"], path=path or None) from exc