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,419 @@
1
+ """`TransitionModel`: jump matrix, multinomial-logit covariate link, generator mode (E3-T05).
2
+
3
+ `MemoryLayout` lives here per CLAUDE.md §3.1 ("E3-T05 left `covariates.py` open" -- no such module
4
+ is created in 0.1.0). Concept refs: §4.3 Geometric/Generator, §4.4 Transitions, §4.5, Appendix E.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from functools import lru_cache
11
+ from typing import TYPE_CHECKING, Literal, Protocol
12
+
13
+ import jax
14
+ import jax.numpy as jnp
15
+ import numpy as np
16
+
17
+ from hsmmkit.model.params import DirichletPrior, NormalPrior, Params
18
+ from hsmmkit.model.params.spec import Mode, ParamSpec
19
+ from hsmmkit.utils.errors import ConfigError
20
+ from hsmmkit.utils.typing import Array
21
+
22
+ if TYPE_CHECKING:
23
+ from hsmmkit.config.schema import TransitionCfg
24
+ from hsmmkit.model.topology import Topology
25
+
26
+
27
+ @dataclass(frozen=True, eq=False)
28
+ class MemoryLayout:
29
+ """Maps each admissible memory tuple (row `r`) to the regime whose exit it models.
30
+
31
+ `tuples (R, order)`: admissible memory tuples (order 1: `R = N`, tuple `(i,)`; order 2:
32
+ `R = N(N-1)`, tuples `(i, j)` with `i != j`; adjacent entries always differ). `current_of (R,)`
33
+ is each tuple's last element (the regime whose exit is being modelled). `target_mask (R, N)`
34
+ is `True` where `target != current` (`bool`).
35
+ """
36
+
37
+ n_states: int
38
+ order: int
39
+ tuples: np.ndarray
40
+ current_of: np.ndarray
41
+ target_mask: np.ndarray
42
+
43
+ def __eq__(self, other: object) -> bool:
44
+ """Structural equality, safe for numpy array fields.
45
+
46
+ Needed once `StateSpace` (E4-T02a) stores a `MemoryLayout` as `eqx.field(static=True)`
47
+ (CLAUDE.md §5's numpy-unhashable gotcha).
48
+ """
49
+ if not isinstance(other, MemoryLayout):
50
+ return NotImplemented
51
+ return (
52
+ self.n_states == other.n_states
53
+ and self.order == other.order
54
+ and np.array_equal(self.tuples, other.tuples)
55
+ and np.array_equal(self.current_of, other.current_of)
56
+ and np.array_equal(self.target_mask, other.target_mask)
57
+ )
58
+
59
+ def __hash__(self) -> int:
60
+ """Content-based hash, consistent with `__eq__`."""
61
+ return hash((self.n_states, self.order, self.tuples.tobytes(), self.current_of.tobytes()))
62
+
63
+
64
+ def build_memory_layout(n_states: int, order: int, topology: Topology | None = None) -> MemoryLayout:
65
+ """Enumerate every length-`order` sequence of regimes with no two adjacent entries equal.
66
+
67
+ With a non-full `topology` (E12-T03) a tuple `(..., i, j)` exists only if the jump `i -> j` is allowed,
68
+ and `target_mask` marks the allowed targets of each tuple's current regime.
69
+ """
70
+ if order < 1:
71
+ raise ConfigError(f"transition.order must be >= 1, got {order}", path="model.transition.order")
72
+ allowed = None if topology is None else topology.allowed
73
+ tuples: list[tuple[int, ...]] = [(i,) for i in range(n_states)]
74
+ for _ in range(order - 1):
75
+ tuples = [
76
+ (*t, j)
77
+ for t in tuples
78
+ for j in range(n_states)
79
+ if (j != t[-1] if allowed is None else bool(allowed[t[-1], j]))
80
+ ]
81
+ if not tuples:
82
+ raise ConfigError("the topology allows no jump at all", path="model.topology")
83
+ arr = np.asarray(tuples, dtype=np.int64)
84
+ current_of = arr[:, -1]
85
+ target_mask = (
86
+ current_of[:, None] != np.arange(n_states)[None, :] if allowed is None else allowed[current_of]
87
+ )
88
+ return MemoryLayout(
89
+ n_states=n_states, order=order, tuples=arr, current_of=current_of, target_mask=target_mask
90
+ )
91
+
92
+
93
+ def _target_order(current_of: np.ndarray, n_states: int) -> np.ndarray:
94
+ """`(R, N-1)`: for each row, the targets `j != current`, ascending (`[:, 0]` is the reference)."""
95
+ return np.stack([np.array([j for j in range(n_states) if j != c], dtype=np.int64) for c in current_of])
96
+
97
+
98
+ def _target_onehot(target_idx: np.ndarray, n_states: int) -> np.ndarray:
99
+ """`(R, N-1, N)`: one-hot scatter matrix from target-order position to the full state axis."""
100
+ return np.asarray(np.eye(n_states, dtype=np.float64)[target_idx])
101
+
102
+
103
+ class TransitionModel(Protocol):
104
+ """Structural type for the jump/generator transition model."""
105
+
106
+ mode: Literal["jump", "generator"]
107
+
108
+ def param_specs(self, n_states: int, order: int, cov_names: tuple[str, ...]) -> tuple[ParamSpec, ...]:
109
+ """The `ParamSpec`s this model contributes for a model of `n_states` regimes/`order` memory."""
110
+ ...
111
+
112
+ def jump_probs(self, theta: Params, z_pi: Array | None, memory: MemoryLayout) -> Array:
113
+ """`(T, R, N)`: row `r` sums to 1 with exactly zero on `memory.current_of[r]`."""
114
+ ...
115
+
116
+ def jump_probs_t(self, theta: Params, z_pi_t: Array | None, memory: MemoryLayout) -> Array:
117
+ """Per-step wrapper of `jump_probs` (`(R, N)`), for use inside a `jax.lax.scan` body."""
118
+ ...
119
+
120
+
121
+ def _cov_idx_from_names(names: list[str], cov_names: tuple[str, ...], path: str) -> tuple[int, ...]:
122
+ try:
123
+ return tuple(cov_names.index(c) for c in names)
124
+ except ValueError as exc:
125
+ raise ConfigError(str(exc), path=path) from exc
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class JumpTransition:
130
+ """Multinomial-logit jump matrix: rows are memory tuples, reference target is the smallest `j != i`.
131
+
132
+ No covariates: `transition.pi_rows (R, N-1)` is a `simplex_ref`-domain spec (the row itself,
133
+ reference-dropped bijector -- `N-2` free entries per row, matching Appendix B). With
134
+ covariates: `transition.a (R, N-2)` / `transition.b (R, N-2, K_pi)` are logits for the
135
+ non-reference targets, softmax-combined with an implicit zero logit at the reference.
136
+ """
137
+
138
+ mode: Literal["jump", "generator"] = "jump"
139
+ cov_idx: tuple[int, ...] = ()
140
+ dirichlet_alpha: float | None = None
141
+ duration_dependent: bool = False
142
+ """`pi_ij(d)` depends on the duration `d` of the segment being left (`transition.c`; explicit engine)."""
143
+ topology: Topology | None = None
144
+ """A non-full topology (E12-T03): the free logits are one flat vector `transition.a (F,)` (and
145
+ `transition.b (F, K_pi)`), `F = sum over rows of max(0, |A| - 1)`; `None` is the Part I layout."""
146
+ """Set by `from_config` when covariates are configured with a Dirichlet prior: `ParamManager`'s
147
+ per-spec prior (`prior.log_prob(theta[name])`) can't express "Dirichlet on `pi` at `z = 0`" since
148
+ `pi` isn't `theta["transition.a"/"transition.b"]` directly; `log_prior_extra` computes it instead
149
+ (a hook for `estimation/objective.py`, E5-T01, to add to the objective's `log_prior` term)."""
150
+
151
+ def param_specs(self, n_states: int, order: int, cov_names: tuple[str, ...]) -> tuple[ParamSpec, ...]:
152
+ """Default (config-free) spec: `transition.pi_rows`, free/`simplex_ref`."""
153
+ del cov_names
154
+ if self.topology is not None:
155
+ return tuple(_flat_specs(build_memory_layout(n_states, order, self.topology), 0, None))
156
+ layout = build_memory_layout(n_states, order)
157
+ r = layout.tuples.shape[0]
158
+ shape = (r, n_states - 1)
159
+ return (
160
+ ParamSpec(
161
+ name="transition.pi_rows",
162
+ shape=shape,
163
+ domain="simplex_ref",
164
+ mode="free",
165
+ init=np.full(shape, 1.0 / (n_states - 1)),
166
+ ),
167
+ )
168
+
169
+ @classmethod
170
+ def from_config(
171
+ cls,
172
+ cfg: TransitionCfg,
173
+ n_states: int,
174
+ order: int,
175
+ cov_names: tuple[str, ...],
176
+ topology: Topology | None = None,
177
+ duration_dependent: bool = False,
178
+ ) -> tuple[JumpTransition, tuple[ParamSpec, ...]]:
179
+ """Map `model.transition` config to a configured `JumpTransition` and its `ParamSpec`s.
180
+
181
+ `topology` is a non-full `Topology` (`None`/full: the Part I layout, bitwise unchanged).
182
+ """
183
+ cov_idx = _cov_idx_from_names(cfg.covariates, cov_names, "model.transition.covariates")
184
+ if topology is not None and topology.is_full:
185
+ topology = None
186
+ if duration_dependent and topology is None:
187
+ from hsmmkit.model.topology import from_config as topology_from_name
188
+
189
+ topology = topology_from_name("full", n_states) # the flat layout carries `transition.c`
190
+ if topology is not None:
191
+ if cfg.mode == "generator":
192
+ raise ConfigError(
193
+ "a non-full topology needs transition.mode: jump", path="model.transition.mode"
194
+ )
195
+ layout = build_memory_layout(n_states, order, topology)
196
+ prior_flat = cfg.prior if (cfg.prior is not None and cfg.prior.type == "dirichlet") else None
197
+ family = cls(
198
+ mode=cfg.mode,
199
+ cov_idx=cov_idx,
200
+ dirichlet_alpha=None if prior_flat is None else (prior_flat.alpha or 1.0),
201
+ topology=topology,
202
+ duration_dependent=duration_dependent,
203
+ )
204
+ return family, tuple(
205
+ _flat_specs(layout, len(cov_idx), cfg.coef_prior_sd, with_c=duration_dependent)
206
+ )
207
+ layout = build_memory_layout(n_states, order)
208
+ r = layout.tuples.shape[0]
209
+ k_pi = len(cov_idx)
210
+ prior_cfg = cfg.prior if (cfg.prior is not None and cfg.prior.type == "dirichlet") else None
211
+ if k_pi == 0:
212
+ family = cls(mode=cfg.mode, cov_idx=cov_idx)
213
+ shape = (r, n_states - 1)
214
+ prior = DirichletPrior(alpha=prior_cfg.alpha or 1.0) if prior_cfg is not None else None
215
+ mode: Mode = "prior" if prior is not None else "free"
216
+ spec = ParamSpec(
217
+ name="transition.pi_rows",
218
+ shape=shape,
219
+ domain="simplex_ref",
220
+ mode=mode,
221
+ init=np.full(shape, 1.0 / (n_states - 1)),
222
+ prior=prior,
223
+ )
224
+ return family, (spec,)
225
+ dirichlet_alpha = (prior_cfg.alpha or 1.0) if prior_cfg is not None else None
226
+ family = cls(mode=cfg.mode, cov_idx=cov_idx, dirichlet_alpha=dirichlet_alpha)
227
+ coef_prior = NormalPrior(sd=cfg.coef_prior_sd)
228
+ a_shape = (r, n_states - 2)
229
+ b_shape = (r, n_states - 2, k_pi)
230
+ a_spec = ParamSpec(
231
+ name="transition.a", shape=a_shape, domain="real", mode="free", init=np.zeros(a_shape)
232
+ )
233
+ b_spec = ParamSpec(
234
+ name="transition.b",
235
+ shape=b_shape,
236
+ domain="real",
237
+ mode="free",
238
+ init=np.zeros(b_shape),
239
+ prior=coef_prior,
240
+ )
241
+ return family, (a_spec, b_spec)
242
+
243
+ def log_prior_extra(self, theta: Params, memory: MemoryLayout) -> Array:
244
+ """`DirichletPrior(dirichlet_alpha).log_prob(pi at z=0)`, or `0.` when not configured.
245
+
246
+ Not wired into `ParamManager.log_prior` (which only evaluates a spec's prior on its own
247
+ `theta[name]`); callers building the full objective (`estimation/objective.py`, E5-T01) add
248
+ this term explicitly when `dirichlet_alpha is not None`.
249
+ """
250
+ if self.dirichlet_alpha is None:
251
+ return jnp.zeros(())
252
+ if self.topology is not None:
253
+ pi = self.jump_probs_t(theta, jnp.zeros((len(self.cov_idx),)), memory) # (R, N)
254
+ n_allowed = memory.target_mask.sum(axis=1)
255
+ rows = np.flatnonzero(n_allowed >= 2)
256
+ a = self.dirichlet_alpha
257
+ if rows.size == 0:
258
+ return jnp.zeros(())
259
+ logp = jnp.log(jnp.where(memory.target_mask[rows], pi[rows], 1.0))
260
+ gammaln = jax.scipy.special.gammaln
261
+ const = gammaln(n_allowed[rows] * a) - n_allowed[rows] * gammaln(a)
262
+ return jnp.sum((a - 1.0) * jnp.sum(logp, axis=1) + const)
263
+ n_states = memory.n_states
264
+ z0 = jnp.zeros((len(self.cov_idx),))
265
+ pi_full = self.jump_probs_t(theta, z0, memory) # (R, N)
266
+ target_idx = jnp.asarray(_target_order(memory.current_of, n_states)) # (R, N-1)
267
+ pi_targets = jnp.take_along_axis(pi_full, target_idx, axis=1) # (R, N-1)
268
+ return DirichletPrior(alpha=self.dirichlet_alpha).log_prob(pi_targets)
269
+
270
+ def jump_probs(self, theta: Params, z_pi: Array | None, memory: MemoryLayout) -> Array:
271
+ """`(T, R, N)` jump probabilities."""
272
+ if self.topology is not None:
273
+ if z_pi is None:
274
+ return self.jump_probs_t(theta, None, memory)[None]
275
+ return jax.vmap(lambda z: self.jump_probs_t(theta, z, memory))(z_pi)
276
+ n_states = memory.n_states
277
+ r = memory.current_of.shape[0]
278
+ target_idx = _target_order(memory.current_of, n_states)
279
+ onehot = jnp.asarray(_target_onehot(target_idx, n_states)) # (R, N-1, N)
280
+
281
+ if "transition.pi_rows" in theta:
282
+ t = z_pi.shape[0] if z_pi is not None else 1
283
+ pi = jnp.broadcast_to(theta["transition.pi_rows"][None, :, :], (t, r, n_states - 1))
284
+ else:
285
+ a, b = theta["transition.a"], theta["transition.b"]
286
+ t = z_pi.shape[0] if z_pi is not None else 1
287
+ z = (
288
+ z_pi[:, jnp.asarray(self.cov_idx)]
289
+ if (z_pi is not None and self.cov_idx)
290
+ else jnp.zeros((t, 0))
291
+ )
292
+ logits_nonref = a[None, :, :] + jnp.einsum("rok,tk->tro", b, z) # (T, R, N-2)
293
+ logits = jnp.concatenate([jnp.zeros((t, r, 1)), logits_nonref], axis=-1) # (T, R, N-1)
294
+ pi = jax.nn.softmax(logits, axis=-1)
295
+
296
+ return jnp.einsum("tro,ron->trn", pi, onehot)
297
+
298
+ def jump_probs_dur(
299
+ self, theta: Params, z_pi_t: Array | None, memory: MemoryLayout, durations: Array
300
+ ) -> Array:
301
+ """`(D, R, N)` jump probabilities `pi_ij(d)` for the durations `d` of the segment being left.
302
+
303
+ `logit_ij(d) = a_ij + b_ij . z + c_ij log d` on the free cells (`c = 0` without `transition.c`).
304
+ """
305
+ return jax.vmap(lambda d: self._masked_probs(theta, z_pi_t, memory, jnp.log(d)))(durations)
306
+
307
+ def _masked_probs(
308
+ self, theta: Params, z_pi_t: Array | None, memory: MemoryLayout, log_d: Array | None = None
309
+ ) -> Array:
310
+ """Masked multinomial logit: the smallest allowed target has logit 0, structural zeros stay 0."""
311
+ free_row, free_col = _flat_structure(memory)
312
+ allowed = jnp.asarray(memory.target_mask)
313
+ r, n = allowed.shape
314
+ logits = jnp.zeros((r, n))
315
+ if free_row.size:
316
+ a = theta["transition.a"]
317
+ if "transition.b" in theta:
318
+ z = (
319
+ z_pi_t[jnp.asarray(self.cov_idx)]
320
+ if (z_pi_t is not None and self.cov_idx)
321
+ else jnp.zeros((0,))
322
+ )
323
+ a = a + theta["transition.b"] @ z
324
+ if log_d is not None and "transition.c" in theta:
325
+ a = a + theta["transition.c"] * log_d
326
+ logits = logits.at[free_row, free_col].set(a)
327
+ shifted = jnp.where(allowed, logits, -jnp.inf)
328
+ top = jnp.max(shifted, axis=1, keepdims=True)
329
+ top_safe = jnp.where(jnp.isfinite(top), top, 0.0)
330
+ e = jnp.where(allowed, jnp.exp(jnp.where(allowed, logits, 0.0) - top_safe), 0.0)
331
+ total = jnp.sum(e, axis=1, keepdims=True)
332
+ return jnp.where(total > 0, e / jnp.where(total > 0, total, 1.0), 0.0)
333
+
334
+ def jump_probs_t(self, theta: Params, z_pi_t: Array | None, memory: MemoryLayout) -> Array:
335
+ """`(R, N)` jump probabilities at a single step."""
336
+ if self.topology is not None:
337
+ return self._masked_probs(theta, z_pi_t, memory)
338
+ n_states = memory.n_states
339
+ r = memory.current_of.shape[0]
340
+ target_idx = _target_order(memory.current_of, n_states)
341
+ onehot = jnp.asarray(_target_onehot(target_idx, n_states)) # (R, N-1, N)
342
+
343
+ if "transition.pi_rows" in theta:
344
+ pi = theta["transition.pi_rows"] # (R, N-1)
345
+ else:
346
+ a, b = theta["transition.a"], theta["transition.b"]
347
+ z = (
348
+ z_pi_t[jnp.asarray(self.cov_idx)]
349
+ if (z_pi_t is not None and self.cov_idx)
350
+ else jnp.zeros((0,))
351
+ )
352
+ logits_nonref = a + b @ z # (R, N-2)
353
+ logits = jnp.concatenate([jnp.zeros((r, 1)), logits_nonref], axis=-1)
354
+ pi = jax.nn.softmax(logits, axis=-1)
355
+
356
+ return jnp.einsum("ro,ron->rn", pi, onehot)
357
+
358
+
359
+ @lru_cache(maxsize=64)
360
+ def _flat_structure(memory: MemoryLayout) -> tuple[np.ndarray, np.ndarray]:
361
+ """`(free_row, free_col)`: the cells with a free logit (all allowed targets but the smallest, logit 0)."""
362
+ free_row: list[int] = []
363
+ free_col: list[int] = []
364
+ for r in range(memory.target_mask.shape[0]):
365
+ targets = np.flatnonzero(memory.target_mask[r])
366
+ for j in targets[1:]:
367
+ free_row.append(r)
368
+ free_col.append(int(j))
369
+ return np.asarray(free_row, dtype=np.int64), np.asarray(free_col, dtype=np.int64)
370
+
371
+
372
+ def _flat_specs(
373
+ memory: MemoryLayout, k_pi: int, coef_prior_sd: float | None, *, with_c: bool = False
374
+ ) -> list[ParamSpec]:
375
+ """`transition.a (F,)` (and `transition.b (F, K)`) for a topology layout; no spec when `F == 0`."""
376
+ free_row, _ = _flat_structure(memory)
377
+ f = int(free_row.size)
378
+ if f == 0:
379
+ return []
380
+ specs = [ParamSpec(name="transition.a", shape=(f,), domain="real", mode="free", init=np.zeros(f))]
381
+ if with_c:
382
+ specs.append(
383
+ ParamSpec(
384
+ name="transition.c",
385
+ shape=(f,),
386
+ domain="real",
387
+ mode="free",
388
+ init=np.zeros(f),
389
+ prior=NormalPrior(sd=1.0 if coef_prior_sd is None else coef_prior_sd),
390
+ )
391
+ )
392
+ if k_pi:
393
+ shape = (f, k_pi)
394
+ specs.append(
395
+ ParamSpec(
396
+ name="transition.b",
397
+ shape=shape,
398
+ domain="real",
399
+ mode="free",
400
+ init=np.zeros(shape),
401
+ prior=NormalPrior(sd=1.0 if coef_prior_sd is None else coef_prior_sd),
402
+ )
403
+ )
404
+ return specs
405
+
406
+
407
+ def transition_matrix_generator(theta: Params, lam: Array, dt: Array) -> Array:
408
+ """`(T, N, N)`: the CTMC transition matrix `expm(Q * dt_t)` for the geometric/HMM special case.
409
+
410
+ `Q_ij = lambda_i * pi_ij` (`i != j`), `Q_ii = -lambda_i`; `pi` is `JumpTransition.jump_probs`
411
+ at `order = 1` (each memory row is a single current regime), with no covariates in scope here
412
+ (HMM-only generator mode, per the ticket).
413
+ """
414
+ n_states = lam.shape[0]
415
+ memory = build_memory_layout(n_states, order=1)
416
+ pi = JumpTransition().jump_probs(theta, None, memory)[0] # (N, N)
417
+ q_off = pi * lam[:, None]
418
+ q = q_off - jnp.diag(jnp.sum(q_off, axis=1))
419
+ return jnp.asarray(jax.vmap(lambda dt_t: jax.scipy.linalg.expm(q * dt_t))(dt))
@@ -0,0 +1,24 @@
1
+ """Online (streaming) filtering of fitted models (E15)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from hsmmkit.online.alerts import AlertEvent, AlertRule
6
+ from hsmmkit.online.covariates import OnlineCovariatePreparer
7
+ from hsmmkit.online.filter import ExpandedOnlineFilter
8
+ from hsmmkit.online.session import OnlineSession
9
+ from hsmmkit.online.state import OnlineState, load_state, save_state, spec_hash
10
+
11
+ OnlineFilter = ExpandedOnlineFilter
12
+
13
+ __all__ = [
14
+ "AlertEvent",
15
+ "AlertRule",
16
+ "ExpandedOnlineFilter",
17
+ "OnlineCovariatePreparer",
18
+ "OnlineFilter",
19
+ "OnlineSession",
20
+ "OnlineState",
21
+ "load_state",
22
+ "save_state",
23
+ "spec_hash",
24
+ ]
@@ -0,0 +1,181 @@
1
+ """Alert rules with hysteresis and structured events (E15-T03).
2
+
3
+ Concept refs: Part II §14.11 (alerts), §15.4 (`online.alerts`). Rules are evaluated in plain Python on the
4
+ `(N,)` vectors a streaming step returns (negligible cost); the active flags live in `OnlineState.alerts`.
5
+
6
+ * probability rule `{regime, p_on, p_off}`: `on` when `P(regime) >= p_on` while inactive, `off` when
7
+ `P(regime) < p_off` while active (`p_off < p_on`: a path hovering around `p_on` does not flap);
8
+ * `use: smoothed` (probability rules) reads the fixed-lag marginal of step `t - lag`; duration rules use
9
+ the filtered probability of the current step;
10
+ * remaining-duration rule `{regime, remaining_duration_below: d, p_min}`: `on` when `P(regime) >= p_min` and
11
+ the expected remaining duration of the current segment (clock units) is `< d`; `off` when it rises above
12
+ `HYSTERESIS * d` or the regime's probability falls below `p_min`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import math
19
+ from collections.abc import Mapping, Sequence
20
+ from dataclasses import dataclass
21
+ from typing import Any, Literal
22
+
23
+ import numpy as np
24
+
25
+ from hsmmkit.utils.errors import ConfigError
26
+
27
+ HYSTERESIS = 1.2
28
+ """A remaining-duration alert switches off when the remaining duration exceeds `HYSTERESIS * d`."""
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class AlertRule:
33
+ """One resolved alert rule (`online.alerts[i]`)."""
34
+
35
+ name: str
36
+ regime: int
37
+ p_on: float | None = None
38
+ p_off: float | None = None
39
+ remaining_below: float | None = None
40
+ p_min: float = 0.5
41
+ use: Literal["filtered", "smoothed"] = "filtered"
42
+
43
+ @property
44
+ def kind(self) -> Literal["probability", "duration"]:
45
+ """The rule family."""
46
+ return "duration" if self.remaining_below is not None else "probability"
47
+
48
+ @classmethod
49
+ def from_config(cls, cfg: Mapping[str, Any] | Any, index: int) -> AlertRule: # noqa: ANN401
50
+ """From an `AlertCfg` (or its dict); the default name is `alert<index>`."""
51
+ get = cfg.get if isinstance(cfg, Mapping) else lambda k, d=None: getattr(cfg, k, d)
52
+ return cls(
53
+ name=get("name") or f"alert{index}",
54
+ regime=int(get("regime") or 0),
55
+ p_on=get("p_on"),
56
+ p_off=get("p_off"),
57
+ remaining_below=get("remaining_duration_below"),
58
+ p_min=float(get("p_min", 0.5) or 0.5),
59
+ use=get("use", "filtered") or "filtered",
60
+ )
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class AlertEvent:
65
+ """A regime alert turning `on` or `off` at step `t`.
66
+
67
+ `value` is the quantity that crossed `threshold` (a probability, or a remaining duration in clock units).
68
+ """
69
+
70
+ time: Any
71
+ t: int
72
+ rule: str
73
+ kind: Literal["on", "off"]
74
+ regime: int
75
+ value: float
76
+ threshold: float
77
+
78
+ def to_dict(self) -> dict[str, Any]:
79
+ """JSON-serializable form (`time` as ISO text or a number)."""
80
+ time = self.time
81
+ if isinstance(time, np.datetime64):
82
+ time = str(np.datetime_as_string(time, unit="ns"))
83
+ elif isinstance(time, np.integer):
84
+ time = int(time)
85
+ elif isinstance(time, np.floating):
86
+ time = float(time)
87
+ return {
88
+ "time": time,
89
+ "t": int(self.t),
90
+ "rule": self.rule,
91
+ "kind": self.kind,
92
+ "regime": int(self.regime),
93
+ "value": float(self.value),
94
+ "threshold": float(self.threshold),
95
+ }
96
+
97
+ @classmethod
98
+ def from_dict(cls, blob: Mapping[str, Any]) -> AlertEvent:
99
+ """Inverse of `to_dict` (a string `time` that parses as a date comes back as `datetime64[ns]`)."""
100
+ time = blob["time"]
101
+ if isinstance(time, str):
102
+ with contextlib.suppress(ValueError):
103
+ time = np.datetime64(time, "ns")
104
+ return cls(
105
+ time,
106
+ int(blob["t"]),
107
+ blob["rule"],
108
+ blob["kind"],
109
+ int(blob["regime"]),
110
+ float(blob["value"]),
111
+ float(blob["threshold"]),
112
+ )
113
+
114
+
115
+ def rules_from_config(alerts: Sequence[Mapping[str, Any] | Any]) -> tuple[AlertRule, ...]:
116
+ """Resolve and validate the rules (`regime` is checked against `n_states` by the filter)."""
117
+ rules = tuple(AlertRule.from_config(a, i) for i, a in enumerate(alerts))
118
+ names = [r.name for r in rules]
119
+ if len(set(names)) != len(names):
120
+ raise ConfigError("alert names must be unique", path="online.alerts.name")
121
+ return rules
122
+
123
+
124
+ def evaluate(
125
+ rules: Sequence[AlertRule],
126
+ active: np.ndarray,
127
+ t: int,
128
+ time: Any, # noqa: ANN401
129
+ filtered: np.ndarray,
130
+ smoothed: np.ndarray | None,
131
+ remaining: np.ndarray | None,
132
+ ) -> tuple[np.ndarray, list[AlertEvent]]:
133
+ """Advance the active flags by one step.
134
+
135
+ Args:
136
+ rules: the resolved rules.
137
+ active: `(n_rules,)` bool flags before the step.
138
+ t: the step index (number of observations processed, `1`-based after this step).
139
+ time: the step's timestamp (or `None`).
140
+ filtered: `(N,)` filtered regime probabilities.
141
+ smoothed: `(N,)` fixed-lag smoothed marginals (`NaN` while the buffer fills) or `None`.
142
+ remaining: `(N,)` expected remaining duration per regime in clock units, or `None`.
143
+
144
+ Returns:
145
+ `(active', events)`; events are ordered by rule.
146
+ """
147
+ out = np.array(active, dtype=bool, copy=True)
148
+ events: list[AlertEvent] = []
149
+ for i, rule in enumerate(rules):
150
+ # `use: smoothed` applies to probability rules; a duration rule is about the current step
151
+ source = filtered
152
+ if rule.use == "smoothed" and smoothed is not None and rule.kind == "probability":
153
+ source = smoothed
154
+ p = float(source[rule.regime])
155
+ if math.isnan(p):
156
+ continue # the smoothed source is still filling
157
+ if rule.kind == "probability":
158
+ assert rule.p_on is not None
159
+ assert rule.p_off is not None
160
+ if not out[i] and p >= rule.p_on:
161
+ out[i] = True
162
+ events.append(AlertEvent(time, t, rule.name, "on", rule.regime, p, rule.p_on))
163
+ elif out[i] and p < rule.p_off:
164
+ out[i] = False
165
+ events.append(AlertEvent(time, t, rule.name, "off", rule.regime, p, rule.p_off))
166
+ continue
167
+ assert rule.remaining_below is not None
168
+ rem = float("nan") if remaining is None else float(remaining[rule.regime])
169
+ if not out[i] and p >= rule.p_min and rem < rule.remaining_below:
170
+ out[i] = True
171
+ events.append(AlertEvent(time, t, rule.name, "on", rule.regime, rem, rule.remaining_below))
172
+ elif out[i]:
173
+ if p < rule.p_min:
174
+ out[i] = False
175
+ events.append(AlertEvent(time, t, rule.name, "off", rule.regime, p, rule.p_min))
176
+ elif rem > HYSTERESIS * rule.remaining_below:
177
+ out[i] = False
178
+ events.append(
179
+ AlertEvent(time, t, rule.name, "off", rule.regime, rem, HYSTERESIS * rule.remaining_below)
180
+ )
181
+ return out, events