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,33 @@
1
+ """The `pandas` source: a `DataFrame` passed through the Python API (`obj`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import pandas as pd
8
+ from pydantic import BaseModel
9
+
10
+ from hsmmkit.data.sources.base import Loaded, TabularOpts, frame_to_loaded
11
+ from hsmmkit.plugins import REGISTRY, provenance_of
12
+ from hsmmkit.utils.errors import ConfigError
13
+
14
+
15
+ class PandasSource:
16
+ """Observations and covariates from an in-memory `pandas.DataFrame` (Python API only)."""
17
+
18
+ name = "pandas"
19
+ options_model: type[BaseModel] = TabularOpts
20
+
21
+ def load(self, opts: BaseModel, *, obj: Any | None = None) -> Loaded: # noqa: ANN401
22
+ """Load from `obj`; a YAML `kind: pandas` without an object is a `ConfigError`."""
23
+ if not isinstance(obj, pd.DataFrame):
24
+ raise ConfigError(
25
+ "the `pandas` source needs a DataFrame passed through the Python API; "
26
+ "in YAML use `kind: csv` or `kind: parquet`",
27
+ path="data.source.kind",
28
+ )
29
+ assert isinstance(opts, TabularOpts)
30
+ return frame_to_loaded(obj, opts, source=self.name, snapshot_id=None)
31
+
32
+
33
+ REGISTRY.register("source", PandasSource.name, PandasSource(), provenance=provenance_of(__name__))
@@ -0,0 +1,37 @@
1
+ """The `parquet` source: a parquet file read with pyarrow."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import pandas as pd
8
+ import pyarrow as pa
9
+ from pydantic import BaseModel
10
+
11
+ from hsmmkit.data.sources.base import Loaded, TabularOpts, frame_to_loaded, sha256_file
12
+ from hsmmkit.plugins import REGISTRY, provenance_of
13
+ from hsmmkit.utils.errors import ConfigError, DataError
14
+
15
+
16
+ class ParquetSource:
17
+ """Observations and covariates from a parquet file (`path`)."""
18
+
19
+ name = "parquet"
20
+ options_model: type[BaseModel] = TabularOpts
21
+
22
+ def load(self, opts: BaseModel, *, obj: Any | None = None) -> Loaded: # noqa: ANN401
23
+ """Read `opts.path` and delegate to the tabular logic; the snapshot id hashes the file bytes."""
24
+ assert isinstance(opts, TabularOpts)
25
+ if opts.path is None:
26
+ raise ConfigError("the `parquet` source needs a path", path="data.source.path")
27
+ path = opts.path.expanduser()
28
+ if not path.is_file():
29
+ raise DataError(f"file not found: {path}", path="data.source.path")
30
+ try:
31
+ frame = pd.read_parquet(path)
32
+ except (OSError, ValueError, pa.ArrowException) as exc:
33
+ raise DataError(f"cannot read {path}: {exc}", path="data.source.path") from exc
34
+ return frame_to_loaded(frame, opts, source=self.name, snapshot_id=sha256_file(path))
35
+
36
+
37
+ REGISTRY.register("source", ParquetSource.name, ParquetSource(), provenance=provenance_of(__name__))
@@ -0,0 +1,62 @@
1
+ """The `xarray` source: an `xarray.Dataset` (`obj`) or a `.nc` / `.zarr` store (`path`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import pandas as pd
8
+ from pydantic import BaseModel
9
+
10
+ from hsmmkit.data.sources.base import Loaded, TabularOpts, frame_to_loaded, sha256_file
11
+ from hsmmkit.plugins import REGISTRY, provenance_of
12
+ from hsmmkit.utils.errors import ConfigError, DataError
13
+ from hsmmkit.utils.optional import optional_import
14
+
15
+
16
+ class XarraySource:
17
+ """Observations from data variables of a Dataset.
18
+
19
+ `observation_columns` are data variables, `time_column` a coordinate (or `None`), `sequence_column` a
20
+ coordinate or variable, `covariate_columns` further variables. The Dataset is flattened to a frame
21
+ (`to_dataframe().reset_index()`) and goes through the tabular logic.
22
+ """
23
+
24
+ name = "xarray"
25
+ options_model: type[BaseModel] = TabularOpts
26
+
27
+ def load(self, opts: BaseModel, *, obj: Any | None = None) -> Loaded: # noqa: ANN401
28
+ """Load from `obj` (a Dataset) or `opts.path` (`.nc` via `open_dataset`, `.zarr` via `open_zarr`)."""
29
+ assert isinstance(opts, TabularOpts)
30
+ xr = optional_import("xarray", extra="xarray")
31
+ digest: str | None = None
32
+ if obj is not None:
33
+ if not isinstance(obj, xr.Dataset):
34
+ raise ConfigError(
35
+ "the `xarray` source takes an xarray.Dataset as `obj`", path="data.source.kind"
36
+ )
37
+ dataset = obj
38
+ else:
39
+ if opts.path is None:
40
+ raise ConfigError("the `xarray` source needs a path or an object", path="data.source.path")
41
+ path = opts.path.expanduser()
42
+ if not path.exists():
43
+ raise DataError(f"file not found: {path}", path="data.source.path")
44
+ try:
45
+ dataset = xr.open_zarr(path) if path.suffix == ".zarr" else xr.open_dataset(path)
46
+ except (OSError, ValueError, ImportError) as exc:
47
+ raise DataError(f"cannot read {path}: {exc}", path="data.source.path") from exc
48
+ if path.is_file():
49
+ digest = sha256_file(path)
50
+ missing = [
51
+ c for c in (*opts.observation_columns, *opts.covariate_columns) if c not in dataset.variables
52
+ ]
53
+ if missing:
54
+ raise DataError(
55
+ f"variable {missing[0]!r} not found; available: {', '.join(map(str, dataset.variables))}",
56
+ path="data.source.observation_columns",
57
+ )
58
+ frame: pd.DataFrame = dataset.to_dataframe().reset_index()
59
+ return frame_to_loaded(frame, opts, source=self.name, snapshot_id=digest)
60
+
61
+
62
+ REGISTRY.register("source", XarraySource.name, XarraySource(), provenance=provenance_of(__name__))
@@ -0,0 +1,129 @@
1
+ """Observation transforms (registry kind `transform`) and covariate transforms of the `Preparer` (FR-D05).
2
+
3
+ The core registers `identity` and `diff`; an application registers more (the finance application: a
4
+ log-ratio transform). Covariate transforms act on a series' own prints, before alignment onto the grid
5
+ (E2-T06), in declared order.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Sequence
11
+ from typing import Protocol
12
+
13
+ import numpy as np
14
+
15
+ from hsmmkit.plugins import REGISTRY, provenance_of
16
+ from hsmmkit.utils.errors import ConfigError, DataError
17
+
18
+
19
+ class ObservationTransform(Protocol):
20
+ """A registered observation transform (registry kind `transform`).
21
+
22
+ Called with the `(T0, M)` values and their `(T0,)` times (`None` for time-less data); gives back the
23
+ transformed values and the matching times. A transform that shortens the series drops leading rows only
24
+ (the first row has no predecessor) and gives back the shortened times.
25
+ """
26
+
27
+ name: str
28
+
29
+ def __call__(self, values: np.ndarray, times: np.ndarray | None) -> tuple[np.ndarray, np.ndarray | None]:
30
+ """Transform `values`; the result has `T0 - k` rows and `times[k:]` for some `k >= 0`."""
31
+ ...
32
+
33
+
34
+ class IdentityTransform:
35
+ """`y_t = x_t`: the observations pass through unchanged (the default)."""
36
+
37
+ name = "identity"
38
+
39
+ def __call__(self, values: np.ndarray, times: np.ndarray | None) -> tuple[np.ndarray, np.ndarray | None]:
40
+ """Return `values` and `times` as they are."""
41
+ return values, times
42
+
43
+
44
+ class DiffTransform:
45
+ """`y_t = x_t - x_{t-1}`; the first row is dropped."""
46
+
47
+ name = "diff"
48
+
49
+ def __call__(self, values: np.ndarray, times: np.ndarray | None) -> tuple[np.ndarray, np.ndarray | None]:
50
+ """First differences per series, in float64."""
51
+ x = np.asarray(values, dtype=np.float64)
52
+ return x[1:] - x[:-1], None if times is None else times[1:]
53
+
54
+
55
+ REGISTRY.register(
56
+ "transform", IdentityTransform.name, IdentityTransform(), provenance=provenance_of(__name__)
57
+ )
58
+ REGISTRY.register("transform", DiffTransform.name, DiffTransform(), provenance=provenance_of(__name__))
59
+
60
+
61
+ def get_observation_transform(name: str | None) -> ObservationTransform:
62
+ """The registered transform `name` (`None` = `identity`).
63
+
64
+ Raises:
65
+ ConfigError: unknown name (`path="data.preparation.observation_transform"`).
66
+ """
67
+ chosen = name or "identity"
68
+ if not REGISTRY.has("transform", chosen):
69
+ listing = ", ".join(f"{e.name} ({e.provenance})" for e in REGISTRY.entries("transform"))
70
+ raise ConfigError(
71
+ f"unknown observation transform '{chosen}'; registered: {listing}",
72
+ path="data.preparation.observation_transform",
73
+ )
74
+ transform: ObservationTransform = REGISTRY.get("transform", chosen)
75
+ return transform
76
+
77
+
78
+ def _apply_one(x: np.ndarray, name: str, path: str | None) -> np.ndarray:
79
+ if name == "log":
80
+ if np.any(x <= 0):
81
+ raise DataError("transform 'log' needs strictly positive values", path=path)
82
+ return np.log(x)
83
+ if name == "diff":
84
+ out = np.full_like(x, np.nan)
85
+ out[1:] = x[1:] - x[:-1]
86
+ return out
87
+ if name == "pct":
88
+ if np.any(x[:-1] == 0):
89
+ raise DataError(
90
+ "transform 'pct' needs non-zero values (division by the previous print)", path=path
91
+ )
92
+ out = np.full_like(x, np.nan)
93
+ out[1:] = x[1:] / x[:-1] - 1.0
94
+ return out
95
+ if name == "zscore":
96
+ # Deprecated alias of standardization: handled by the Preparer with train-window stats.
97
+ return x
98
+ raise DataError(f"unknown transform {name!r}", path=path)
99
+
100
+
101
+ def apply_transforms(values: np.ndarray, transforms: Sequence[str], *, path: str | None = None) -> np.ndarray:
102
+ """Apply covariate transforms in declared order to a series' prints.
103
+
104
+ Non-finite prints (NaN such as FRED holidays, or ±inf) are skipped: `diff`/`pct` are taken
105
+ between consecutive finite prints, and the skipped positions become NaN. The first valid print
106
+ becomes NaN after `diff`/`pct` (no predecessor).
107
+
108
+ Args:
109
+ values: `(T1,)` raw values in time order.
110
+ transforms: any sequence of `log`, `diff`, `pct` (`x_t / x_{t-1} - 1`), `zscore` (no-op here).
111
+ path: config path for error messages (`data.covariates[i].transform`).
112
+
113
+ Returns:
114
+ `(T1,)` float64 transformed values.
115
+
116
+ Raises:
117
+ DataError: `log` of a non-positive value, `pct` after a zero print, or an unknown transform.
118
+ """
119
+ x = np.asarray(values, dtype=np.float64)
120
+ valid = np.isfinite(x)
121
+ compact = x[valid]
122
+ for name in transforms:
123
+ kept = ~np.isnan(compact)
124
+ step = np.full_like(compact, np.nan)
125
+ step[kept] = _apply_one(compact[kept], name, path)
126
+ compact = step
127
+ out = np.full_like(x, np.nan)
128
+ out[valid] = compact
129
+ return out
@@ -0,0 +1 @@
1
+ """Forward-backward, Viterbi and explicit-duration inference engines."""
@@ -0,0 +1,51 @@
1
+ """`ApproxInference`: the approximate-inference plug-in protocol for factorial models (E9-T02, ADR-0008).
2
+
3
+ Design only: no engine implements it in 0.1.x, and `InferenceEngine.approx()` of the exact engines still
4
+ gives `None`. A future factorial engine gives an `ApproxInference` from `approx()`; callers then run
5
+ `fit(...)` to obtain per-chain marginals instead of the exact joint `Posterior`. The accepted algorithm
6
+ (structured mean-field) and its complexity are recorded in `docs/adr/0008-approx-inference-plugin.md`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import TYPE_CHECKING, Protocol
13
+
14
+ if TYPE_CHECKING:
15
+ from hsmmkit.data.contracts import PreparedDataset
16
+ from hsmmkit.engine.base import Posterior
17
+ from hsmmkit.model.params import Params
18
+ from hsmmkit.statespace.factorial import FactorialSpace
19
+ from hsmmkit.utils.typing import Array
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class ApproxPosterior:
24
+ """Result of an approximate inference sweep.
25
+
26
+ Attributes:
27
+ marginals: per chain `c`, the approximate smoothed regime marginals `(T, N_c)` (rows sum to 1).
28
+ bound: a lower bound on `log p(y_1:T)` (the ELBO for structured mean-field), 0-d.
29
+ n_sweeps: coordinate-ascent sweeps (or Gibbs sweeps) actually run.
30
+ """
31
+
32
+ marginals: tuple[Array, ...]
33
+ bound: Array
34
+ n_sweeps: int
35
+
36
+
37
+ class ApproxInference(Protocol):
38
+ """Approximate posterior over a factorial model (several regime chains)."""
39
+
40
+ def fit(
41
+ self,
42
+ posterior_init: Posterior | None,
43
+ theta: Params,
44
+ factorial: FactorialSpace,
45
+ data: PreparedDataset,
46
+ ) -> ApproxPosterior:
47
+ """Run the approximation, optionally warm-started from an exact `Posterior` (e.g. of a smaller model).
48
+
49
+ Per-chain marginals are returned in chain order; the joint is never materialised.
50
+ """
51
+ ...
@@ -0,0 +1,93 @@
1
+ """Augmented-posterior utilities: phase/memory marginals, expected remaining/elapsed steps (E4-T04).
2
+
3
+ Concept refs: §4.7.1, §5.4. All functions are pure and jittable (`Posterior` is a pytree; `spec` is
4
+ closed over/static). Regime-conditional expectations return 0 (not NaN) where a regime has no
5
+ posterior mass.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING
11
+
12
+ import jax
13
+ import jax.numpy as jnp
14
+ import numpy as np
15
+
16
+ from hsmmkit.utils.typing import Array
17
+
18
+ if TYPE_CHECKING:
19
+ from hsmmkit.engine.base import Posterior
20
+ from hsmmkit.model.params import Params
21
+ from hsmmkit.model.spec import ModelSpec
22
+
23
+
24
+ def collapse_to_regimes(x: Array, collapse: Array) -> Array:
25
+ """`(T, S) @ C (S, N) -> (T, N)`: sum a per-state quantity over each regime's states."""
26
+ return x @ collapse
27
+
28
+
29
+ def phase_marginals(post: Posterior) -> Array:
30
+ """`(T, N, r_max)`: smoothed mass per `(regime, phase)`, summed over memory; zero for `phase > r_i`."""
31
+ index = post.index
32
+ n_regimes = index.collapse.shape[1]
33
+ max_phase = _max_phase(index.phase_of)
34
+ regime_one_hot = jax.nn.one_hot(index.regime_of, n_regimes) # (S, N)
35
+ phase_one_hot = jax.nn.one_hot(index.phase_of - 1, max_phase) # (S, r_max)
36
+ indicator = regime_one_hot[:, :, None] * phase_one_hot[:, None, :] # (S, N, r_max)
37
+ return jnp.einsum("ts,snp->tnp", post.smoothed, indicator)
38
+
39
+
40
+ def _max_phase(phase_of: Array) -> int:
41
+ """Static `r_max`; `Posterior.index` is pytree aux data, so `phase_of` is concrete even under jit."""
42
+ return int(np.max(np.asarray(phase_of)))
43
+
44
+
45
+ def memory_marginals(post: Posterior) -> Array:
46
+ """`(T, R)` smoothed mass per memory-tuple row (order >= 2), else `(T, 1)` (all mass)."""
47
+ index = post.index
48
+ if index.order < 2:
49
+ return jnp.sum(post.smoothed, axis=-1, keepdims=True)
50
+ n_rows = index.n_states * (index.n_states - 1) ** (index.order - 1)
51
+ row_one_hot = jax.nn.one_hot(index.row_of_state, n_rows) # (S, R)
52
+ return post.smoothed @ row_one_hot
53
+
54
+
55
+ def _phase_expectation(
56
+ post: Posterior, spec: ModelSpec, theta: Params, dt: Array, z_d: Array | None, elapsed: bool
57
+ ) -> Array:
58
+ phases = phase_marginals(post) # (T, N, r_max)
59
+ n_regimes, r_max = phases.shape[1], phases.shape[2]
60
+ r = jnp.asarray([spec.duration.n_phases(i) for i in range(n_regimes)]) # (N,)
61
+ c = jnp.arange(1, r_max + 1)[None, :] # (1, r_max)
62
+ steps = (c - 1) if elapsed else (r[:, None] - c + 1) # (N, r_max) phases still to go / already done
63
+ a = spec.duration.advance_prob(theta, dt, z_d) # (T, N)
64
+ a_safe = jnp.where(a > 0, a, 1.0) # double-where: a == 0 must not poison gradients
65
+ weighted = jnp.sum(phases * steps[None, :, :], axis=-1) / a_safe # (T, N)
66
+ regime_mass = jnp.sum(phases, axis=-1)
67
+ safe_mass = jnp.where(regime_mass > 0, regime_mass, 1.0)
68
+ return jnp.where(regime_mass > 0, weighted / safe_mass, 0.0)
69
+
70
+
71
+ def expected_remaining_steps(
72
+ post: Posterior, spec: ModelSpec, theta: Params, dt: Array, z_d: Array | None = None
73
+ ) -> Array:
74
+ """`(T, N)`: `E[remaining steps in the regime | regime i at t]` for the phase-type (NB) chain.
75
+
76
+ In phase `c` of `r_i`, `r_i - c + 1` phases remain, each lasting `1 / a_i(t)` steps in
77
+ expectation (constant-rate approximation at the step's own `a_i(t)`), weighted by the
78
+ smoothed phase marginals conditional on regime `i`.
79
+ """
80
+ return _phase_expectation(post, spec, theta, dt, z_d, elapsed=False)
81
+
82
+
83
+ def expected_elapsed_steps(
84
+ post: Posterior, spec: ModelSpec, theta: Params, dt: Array, z_d: Array | None = None
85
+ ) -> Array:
86
+ """`(T, N)`: phase-based **lower bound** on the elapsed steps in the current regime.
87
+
88
+ `(c - 1) / a_i(t)` for phase `c` (the time already spent in earlier phases; time spent inside
89
+ phase `c` itself is not counted), conditional on regime `i`. Exact elapsed-duration posteriors
90
+ come from the explicit-duration engine (`Posterior.elapsed_posterior`, E4-T06a): a run-length
91
+ recursion on regime marginals is not exact for an HSMM.
92
+ """
93
+ return _phase_expectation(post, spec, theta, dt, z_d, elapsed=True)
hsmmkit/engine/base.py ADDED
@@ -0,0 +1,134 @@
1
+ """`Posterior` (pytree-registered) and the `InferenceEngine` protocol stub (E1-T05).
2
+
3
+ `Posterior.engine` is a static `Literal["expanded", "explicit"]` tag (E4-T04); the utilities in
4
+ `engine/augmented.py` operate on `Posterior`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from typing import TYPE_CHECKING, Any, Literal, Protocol
11
+
12
+ import jax
13
+
14
+ from hsmmkit.statespace.index import StateIndex
15
+ from hsmmkit.utils.typing import Array
16
+
17
+ if TYPE_CHECKING:
18
+ from hsmmkit.data.contracts import PreparedDataset
19
+ from hsmmkit.model.params import Params
20
+ from hsmmkit.model.spec import ModelSpec
21
+ from hsmmkit.statespace.index import StateSpace
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class _StaticRef:
26
+ """Wraps an arbitrary object as identity-hashable pytree aux data.
27
+
28
+ `StateIndex` mixes JAX-array leaves with static ints (equinox's own default `__eq__`/`__hash__`
29
+ would try to compare/hash the array leaves too, hitting the same "numpy/JAX arrays are
30
+ unhashable" gotcha as CLAUDE.md §5 -- see `data/contracts.py`'s `_HashableArray` for the same
31
+ pattern). A `StateIndex` is built once per model and reused for the fit's lifetime, so
32
+ identity (not structural) equality is the right tradeoff here: cheap, and correct because
33
+ no two distinct-but-equal `StateIndex` instances are expected to coexist in practice.
34
+ """
35
+
36
+ value: Any
37
+
38
+ def __eq__(self, other: object) -> bool:
39
+ return isinstance(other, _StaticRef) and self.value is other.value
40
+
41
+ def __hash__(self) -> int:
42
+ return id(self.value)
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Posterior:
47
+ """Raw forward-backward output: log-alpha/beta, smoothed posterior, loglik, and the index."""
48
+
49
+ log_alpha: Array # (T, S)
50
+ log_beta: Array # (T, S)
51
+ smoothed: Array # (T, S)
52
+ loglik: Array # 0-d Array (a pytree leaf; PosteriorResult/FitResult.loglik are plain float)
53
+ index: StateIndex
54
+ engine: Literal["expanded", "explicit"] = "expanded" # static tag (E4-T04; explicit set by E4-T06a)
55
+
56
+ def regime_filtered(self) -> Array:
57
+ """`softmax(log_alpha) @ C`, shape `(T, N)`, computed row by row (`filtered_row`).
58
+
59
+ The row-wise `lax.map` makes the compiled arithmetic independent of `T`, so the online filter
60
+ (E15-T01), which evaluates one row per observation, reproduces it bitwise.
61
+ """
62
+ collapse = self.index.collapse
63
+ out: Array = jax.lax.map(lambda row: filtered_row(row, collapse), self.log_alpha)
64
+ return out
65
+
66
+ def regime_smoothed(self) -> Array:
67
+ """`smoothed @ C`, shape `(T, N)`."""
68
+ return self.smoothed @ self.index.collapse
69
+
70
+ def elapsed_posterior(self) -> Array:
71
+ """`(T, N, max_phase)`: smoothed mass bucketed by `(regime, phase)` (see `augmented.phase_marginals`).
72
+
73
+ `max_phase` is `max(r_i)` for the expanded engine's phase expansion and `D_max` for the
74
+ explicit engine (where `phase_of` holds the elapsed duration); both are "how many
75
+ phase/elapsed buckets a regime has", so one bucketing serves both `engine` tags.
76
+ """
77
+ from hsmmkit.engine.augmented import phase_marginals
78
+
79
+ return phase_marginals(self)
80
+
81
+
82
+ def filtered_row(log_alpha_row: Array, collapse: Array) -> Array:
83
+ """Filtered regime probabilities `softmax(log_alpha) @ C` of one step: `(S,)` -> `(N,)`."""
84
+ out: Array = jax.nn.softmax(log_alpha_row, axis=-1) @ collapse
85
+ return out
86
+
87
+
88
+ def _flatten_posterior(posterior: Posterior) -> tuple[tuple[Array, ...], tuple[_StaticRef, str]]:
89
+ children = (posterior.log_alpha, posterior.log_beta, posterior.smoothed, posterior.loglik)
90
+ return children, (_StaticRef(posterior.index), posterior.engine)
91
+
92
+
93
+ def _unflatten_posterior(aux: tuple[_StaticRef, str], children: tuple[Array, ...]) -> Posterior:
94
+ log_alpha, log_beta, smoothed, loglik = children
95
+ ref, engine = aux
96
+ return Posterior(
97
+ log_alpha=log_alpha,
98
+ log_beta=log_beta,
99
+ smoothed=smoothed,
100
+ loglik=loglik,
101
+ index=ref.value,
102
+ engine=engine, # type: ignore[arg-type]
103
+ )
104
+
105
+
106
+ jax.tree_util.register_pytree_node(Posterior, _flatten_posterior, _unflatten_posterior)
107
+
108
+
109
+ class InferenceEngine(Protocol):
110
+ """Structural type for the expanded/explicit-duration inference engines (E4-T03*/E4-T06*)."""
111
+
112
+ def loglik(self, theta: Params, spec: ModelSpec, space: StateSpace, data: PreparedDataset) -> Array:
113
+ """`log p(y_1:T)`, a 0-d `Array` (a pytree leaf)."""
114
+ ...
115
+
116
+ def forward(
117
+ self, theta: Params, spec: ModelSpec, space: StateSpace, data: PreparedDataset
118
+ ) -> tuple[Array, Array]:
119
+ """`(log_alpha (T, S), loglik)`."""
120
+ ...
121
+
122
+ def forward_backward(
123
+ self, theta: Params, spec: ModelSpec, space: StateSpace, data: PreparedDataset
124
+ ) -> Posterior:
125
+ """Full forward-backward, returning a `Posterior`."""
126
+ ...
127
+
128
+ def viterbi(self, theta: Params, spec: ModelSpec, space: StateSpace, data: PreparedDataset) -> Array:
129
+ """The most likely expanded-state path, shape `(T,)`."""
130
+ ...
131
+
132
+ def approx(self) -> object | None:
133
+ """Approximate-inference plug-in (FR-X01, ADR-0008); `None` for exact engines."""
134
+ ...