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.
- hsmmkit/__init__.py +13 -0
- hsmmkit/cli/__init__.py +1 -0
- hsmmkit/cli/app.py +513 -0
- hsmmkit/cli/stream.py +194 -0
- hsmmkit/config/__init__.py +1 -0
- hsmmkit/config/defaults.py +13 -0
- hsmmkit/config/gates.py +39 -0
- hsmmkit/config/migrate.py +53 -0
- hsmmkit/config/schema.py +996 -0
- hsmmkit/config/yaml_io.py +67 -0
- hsmmkit/data/__init__.py +1 -0
- hsmmkit/data/batch.py +311 -0
- hsmmkit/data/calendar.py +314 -0
- hsmmkit/data/clocks.py +165 -0
- hsmmkit/data/contracts.py +543 -0
- hsmmkit/data/labels.py +150 -0
- hsmmkit/data/prepare.py +706 -0
- hsmmkit/data/provenance.py +34 -0
- hsmmkit/data/quality.py +112 -0
- hsmmkit/data/sources/__init__.py +92 -0
- hsmmkit/data/sources/base.py +247 -0
- hsmmkit/data/sources/csv.py +36 -0
- hsmmkit/data/sources/numpy.py +143 -0
- hsmmkit/data/sources/pandas.py +33 -0
- hsmmkit/data/sources/parquet.py +37 -0
- hsmmkit/data/sources/xarray.py +62 -0
- hsmmkit/data/transforms.py +129 -0
- hsmmkit/engine/__init__.py +1 -0
- hsmmkit/engine/approx.py +51 -0
- hsmmkit/engine/augmented.py +93 -0
- hsmmkit/engine/base.py +134 -0
- hsmmkit/engine/batch.py +414 -0
- hsmmkit/engine/constraints.py +173 -0
- hsmmkit/engine/criteria.py +67 -0
- hsmmkit/engine/estep.py +314 -0
- hsmmkit/engine/estep_explicit.py +260 -0
- hsmmkit/engine/expanded_hmm.py +336 -0
- hsmmkit/engine/explicit_dd.py +114 -0
- hsmmkit/engine/explicit_duration.py +721 -0
- hsmmkit/engine/ffbs.py +229 -0
- hsmmkit/engine/parallel.py +98 -0
- hsmmkit/engine/viterbi.py +85 -0
- hsmmkit/estimation/__init__.py +36 -0
- hsmmkit/estimation/compare.py +154 -0
- hsmmkit/estimation/ecm.py +106 -0
- hsmmkit/estimation/em.py +460 -0
- hsmmkit/estimation/gem.py +467 -0
- hsmmkit/estimation/gibbs.py +136 -0
- hsmmkit/estimation/init.py +578 -0
- hsmmkit/estimation/map.py +287 -0
- hsmmkit/estimation/mcmc.py +370 -0
- hsmmkit/estimation/mstep.py +304 -0
- hsmmkit/estimation/newton.py +104 -0
- hsmmkit/estimation/objective.py +232 -0
- hsmmkit/estimation/optimizers.py +195 -0
- hsmmkit/estimation/recovery.py +748 -0
- hsmmkit/estimation/recovery_ext.py +557 -0
- hsmmkit/estimation/relabel.py +85 -0
- hsmmkit/estimation/report.py +167 -0
- hsmmkit/estimation/results.py +53 -0
- hsmmkit/estimation/selftest.py +154 -0
- hsmmkit/estimation/vb.py +508 -0
- hsmmkit/evaluation/__init__.py +1 -0
- hsmmkit/evaluation/backtest.py +616 -0
- hsmmkit/evaluation/compare.py +172 -0
- hsmmkit/evaluation/metrics/__init__.py +1 -0
- hsmmkit/evaluation/metrics/clustering.py +111 -0
- hsmmkit/evaluation/metrics/labels.py +40 -0
- hsmmkit/evaluation/metrics/matching.py +103 -0
- hsmmkit/evaluation/metrics/model.py +53 -0
- hsmmkit/evaluation/metrics/predictive.py +337 -0
- hsmmkit/evaluation/metrics/registry.py +154 -0
- hsmmkit/evaluation/metrics/segmentation.py +182 -0
- hsmmkit/evaluation/padding.py +72 -0
- hsmmkit/evaluation/report.py +170 -0
- hsmmkit/evaluation/results.py +28 -0
- hsmmkit/inference/__init__.py +1 -0
- hsmmkit/inference/covariate_forecasters.py +344 -0
- hsmmkit/inference/decode.py +185 -0
- hsmmkit/inference/forecast.py +475 -0
- hsmmkit/inference/results.py +97 -0
- hsmmkit/inference/simulate.py +342 -0
- hsmmkit/interop/__init__.py +1 -0
- hsmmkit/interop/arviz.py +114 -0
- hsmmkit/interop/hmmlearn.py +163 -0
- hsmmkit/interop/pandas.py +116 -0
- hsmmkit/interop/sklearn.py +505 -0
- hsmmkit/interop/xarray.py +296 -0
- hsmmkit/model/__init__.py +1 -0
- hsmmkit/model/build.py +404 -0
- hsmmkit/model/conjugate.py +260 -0
- hsmmkit/model/dists.py +244 -0
- hsmmkit/model/duration/__init__.py +23 -0
- hsmmkit/model/duration/base.py +215 -0
- hsmmkit/model/duration/explicit.py +205 -0
- hsmmkit/model/duration/gamma.py +53 -0
- hsmmkit/model/duration/geometric.py +106 -0
- hsmmkit/model/duration/hazard.py +23 -0
- hsmmkit/model/duration/lognormal.py +56 -0
- hsmmkit/model/duration/negbin.py +115 -0
- hsmmkit/model/duration/nonparametric.py +120 -0
- hsmmkit/model/duration/per_state.py +107 -0
- hsmmkit/model/duration/poisson.py +56 -0
- hsmmkit/model/duration/weibull.py +61 -0
- hsmmkit/model/emission/__init__.py +24 -0
- hsmmkit/model/emission/_discrete.py +104 -0
- hsmmkit/model/emission/base.py +105 -0
- hsmmkit/model/emission/bernoulli.py +131 -0
- hsmmkit/model/emission/categorical.py +158 -0
- hsmmkit/model/emission/gaussian.py +754 -0
- hsmmkit/model/emission/mixture.py +387 -0
- hsmmkit/model/emission/msar.py +545 -0
- hsmmkit/model/emission/poisson.py +144 -0
- hsmmkit/model/emission/product.py +390 -0
- hsmmkit/model/emission/student_t.py +454 -0
- hsmmkit/model/lattice.py +246 -0
- hsmmkit/model/params/__init__.py +45 -0
- hsmmkit/model/params/bijectors.py +238 -0
- hsmmkit/model/params/manager.py +307 -0
- hsmmkit/model/params/priors.py +84 -0
- hsmmkit/model/params/spec.py +65 -0
- hsmmkit/model/spec.py +43 -0
- hsmmkit/model/topology.py +97 -0
- hsmmkit/model/transition.py +419 -0
- hsmmkit/online/__init__.py +24 -0
- hsmmkit/online/alerts.py +181 -0
- hsmmkit/online/buffer.py +203 -0
- hsmmkit/online/covariates.py +162 -0
- hsmmkit/online/em.py +304 -0
- hsmmkit/online/filter.py +682 -0
- hsmmkit/online/session.py +364 -0
- hsmmkit/online/state.py +240 -0
- hsmmkit/persistence/__init__.py +1 -0
- hsmmkit/persistence/results.py +495 -0
- hsmmkit/persistence/store.py +394 -0
- hsmmkit/plot/__init__.py +13 -0
- hsmmkit/plot/_common.py +56 -0
- hsmmkit/plot/diagnostics.py +176 -0
- hsmmkit/plot/durations.py +74 -0
- hsmmkit/plot/forecast.py +55 -0
- hsmmkit/plot/regimes.py +146 -0
- hsmmkit/plugins.py +311 -0
- hsmmkit/presets/__init__.py +116 -0
- hsmmkit/presets/core/counts_poisson_hazard.yaml +61 -0
- hsmmkit/presets/core/msar2_hamilton.yaml +59 -0
- hsmmkit/presets/core/segmentation_gaussian_ltr.yaml +82 -0
- hsmmkit/presets/core/two_regime_gaussian.yaml +60 -0
- hsmmkit/presets/fixtures.py +330 -0
- hsmmkit/project.py +1106 -0
- hsmmkit/py.typed +0 -0
- hsmmkit/scaffold.py +80 -0
- hsmmkit/selection/__init__.py +30 -0
- hsmmkit/selection/bootstrap.py +388 -0
- hsmmkit/selection/cv.py +301 -0
- hsmmkit/selection/grid.py +412 -0
- hsmmkit/selection/ppc.py +199 -0
- hsmmkit/selection/pseudo_residuals.py +265 -0
- hsmmkit/selection/replicate.py +57 -0
- hsmmkit/selection/splitters.py +213 -0
- hsmmkit/statespace/__init__.py +1 -0
- hsmmkit/statespace/builders.py +317 -0
- hsmmkit/statespace/factorial.py +249 -0
- hsmmkit/statespace/index.py +85 -0
- hsmmkit/statespace/transitions.py +143 -0
- hsmmkit/templates/family-plugin/common/README.md.tmpl +9 -0
- hsmmkit/templates/family-plugin/common/pyproject.toml.tmpl +19 -0
- hsmmkit/templates/family-plugin/common/src/__pkg__/__init__.py.tmpl +7 -0
- hsmmkit/templates/family-plugin/common/src/__pkg__/tests/__init__.py.tmpl +0 -0
- hsmmkit/templates/family-plugin/duration/family.py.tmpl +19 -0
- hsmmkit/templates/family-plugin/duration/test_contract.py.tmpl +14 -0
- hsmmkit/templates/family-plugin/emission/family.py.tmpl +95 -0
- hsmmkit/templates/family-plugin/emission/test_contract.py.tmpl +48 -0
- hsmmkit/testing/__init__.py +6 -0
- hsmmkit/testing/clock_contract.py +53 -0
- hsmmkit/testing/duration_contract.py +218 -0
- hsmmkit/testing/family_contract.py +339 -0
- hsmmkit/testing/metric_contract.py +157 -0
- hsmmkit/testing/source_contract.py +196 -0
- hsmmkit/utils/__init__.py +1 -0
- hsmmkit/utils/clock.py +109 -0
- hsmmkit/utils/deprecation.py +125 -0
- hsmmkit/utils/errors.py +56 -0
- hsmmkit/utils/jax_setup.py +48 -0
- hsmmkit/utils/logging.py +30 -0
- hsmmkit/utils/optional.py +25 -0
- hsmmkit/utils/rng.py +49 -0
- hsmmkit/utils/typing.py +32 -0
- hsmmkit-0.5.0.dist-info/METADATA +84 -0
- hsmmkit-0.5.0.dist-info/RECORD +192 -0
- hsmmkit-0.5.0.dist-info/WHEEL +4 -0
- hsmmkit-0.5.0.dist-info/entry_points.txt +2 -0
- hsmmkit-0.5.0.dist-info/licenses/LICENSE +190 -0
hsmmkit/online/buffer.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""`RingBuffer` and the fixed-lag smoother (E15-T02).
|
|
2
|
+
|
|
3
|
+
Concept refs: Part II §14.11 (fixed-lag), §16.3 item 12. The buffer keeps the last `L + 1` steps `t-L … t`
|
|
4
|
+
as fixed-size arrays with a write pointer (`jit`-friendly, never reallocated): the emission log-terms
|
|
5
|
+
`ell`, the transition/duration covariate rows and `dt` (the transition `log A_u` is rebuilt on demand,
|
|
6
|
+
`O(L (S + K))` memory instead of `O(L S^2)`), and the forward vectors `log_alpha`.
|
|
7
|
+
|
|
8
|
+
`smoothed_at` runs the backward recursion over the buffer from `beta_t = 0` for `L` steps and returns the
|
|
9
|
+
regime marginals of step `t - L`. These equal the offline smoother run on the *prefix* `y_{1:t}`
|
|
10
|
+
(`data.window(0, t + 1)`), not the full-data smoother `gamma_{t-L | T}` (which they approach for `T >> t`);
|
|
11
|
+
at the end of a stream (`t = T`) the two coincide.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import TYPE_CHECKING
|
|
18
|
+
|
|
19
|
+
import jax
|
|
20
|
+
import jax.numpy as jnp
|
|
21
|
+
|
|
22
|
+
from hsmmkit.engine.expanded_hmm import _safe_logsumexp, backward_step
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from hsmmkit.data.contracts import PreparedDataset
|
|
26
|
+
from hsmmkit.estimation.results import FitResult
|
|
27
|
+
from hsmmkit.model.params import Params
|
|
28
|
+
from hsmmkit.model.spec import ModelSpec
|
|
29
|
+
from hsmmkit.statespace.index import StateSpace
|
|
30
|
+
from hsmmkit.utils.typing import Array
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class RingBuffer:
|
|
35
|
+
"""The last `L + 1` steps for fixed-lag smoothing (a pytree of arrays).
|
|
36
|
+
|
|
37
|
+
Attributes:
|
|
38
|
+
ell: `(L+1, S)` emission log-terms `ell_u`.
|
|
39
|
+
z_pi: `(L+1, K_pi)` transition covariate rows.
|
|
40
|
+
z_d: `(L+1, K_d)` duration covariate rows.
|
|
41
|
+
dt: `(L+1,)` step lengths.
|
|
42
|
+
log_alpha: `(L+1, S)` unnormalized forward log-vectors.
|
|
43
|
+
head: `()` int32, the slot the next step is written to.
|
|
44
|
+
count: `()` int32, filled slots (`<= L + 1`).
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
ell: Array
|
|
48
|
+
z_pi: Array
|
|
49
|
+
z_d: Array
|
|
50
|
+
dt: Array
|
|
51
|
+
log_alpha: Array
|
|
52
|
+
head: Array
|
|
53
|
+
count: Array
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def lag(self) -> int:
|
|
57
|
+
"""`L`: the capacity is `L + 1` steps."""
|
|
58
|
+
return int(self.ell.shape[0]) - 1
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _flatten(b: RingBuffer) -> tuple[tuple[Array, ...], None]:
|
|
62
|
+
return (b.ell, b.z_pi, b.z_d, b.dt, b.log_alpha, b.head, b.count), None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _unflatten(_: None, children: tuple[Array, ...]) -> RingBuffer:
|
|
66
|
+
return RingBuffer(*children)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
jax.tree_util.register_pytree_node(RingBuffer, _flatten, _unflatten)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def empty_buffer(lag: int, n_expanded: int, k_pi: int, k_d: int) -> RingBuffer:
|
|
73
|
+
"""A buffer with no step written yet."""
|
|
74
|
+
n = lag + 1
|
|
75
|
+
return RingBuffer(
|
|
76
|
+
ell=jnp.zeros((n, n_expanded)),
|
|
77
|
+
z_pi=jnp.zeros((n, k_pi)),
|
|
78
|
+
z_d=jnp.zeros((n, k_d)),
|
|
79
|
+
dt=jnp.ones((n,)),
|
|
80
|
+
log_alpha=jnp.zeros((n, n_expanded)),
|
|
81
|
+
head=jnp.zeros((), dtype=jnp.int32),
|
|
82
|
+
count=jnp.zeros((), dtype=jnp.int32),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def push(
|
|
87
|
+
buf: RingBuffer, ell_t: Array, z_pi_t: Array, z_d_t: Array, dt_t: Array, alpha_t: Array
|
|
88
|
+
) -> RingBuffer:
|
|
89
|
+
"""Write one step at `head` and advance the pointer."""
|
|
90
|
+
n = buf.ell.shape[0]
|
|
91
|
+
h = buf.head
|
|
92
|
+
return RingBuffer(
|
|
93
|
+
ell=buf.ell.at[h].set(ell_t),
|
|
94
|
+
z_pi=buf.z_pi.at[h].set(z_pi_t),
|
|
95
|
+
z_d=buf.z_d.at[h].set(z_d_t),
|
|
96
|
+
dt=buf.dt.at[h].set(dt_t),
|
|
97
|
+
log_alpha=buf.log_alpha.at[h].set(alpha_t),
|
|
98
|
+
head=(h + 1) % n,
|
|
99
|
+
count=jnp.minimum(buf.count + 1, n),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def smooth_window(theta: Params, space: StateSpace, buf: RingBuffer, lag: int) -> Array:
|
|
104
|
+
"""Regime marginals `(N,)` of step `t - lag` given data up to `t`; `NaN` until `lag + 1` steps exist.
|
|
105
|
+
|
|
106
|
+
`lag <= buf.lag` (static). Cost `O(lag S^2)`.
|
|
107
|
+
"""
|
|
108
|
+
n = buf.ell.shape[0]
|
|
109
|
+
k = jnp.arange(lag)
|
|
110
|
+
idx = (buf.head - 1 - k) % n # entries t, t-1, ..., t-lag+1 (newest first)
|
|
111
|
+
xs = (
|
|
112
|
+
buf.ell[idx],
|
|
113
|
+
buf.z_pi[idx],
|
|
114
|
+
buf.z_d[idx],
|
|
115
|
+
buf.dt[idx],
|
|
116
|
+
jnp.zeros((lag,), dtype=jnp.int8),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def body(beta_next: Array, x: tuple[Array, ...]) -> tuple[Array, None]:
|
|
120
|
+
return backward_step(space, theta, False, beta_next, *x), None
|
|
121
|
+
|
|
122
|
+
beta, _ = jax.lax.scan(body, jnp.zeros((buf.ell.shape[1],)), xs)
|
|
123
|
+
alpha = buf.log_alpha[(buf.head - 1 - lag) % n]
|
|
124
|
+
log_gamma = alpha + beta
|
|
125
|
+
norm = _safe_logsumexp(log_gamma, axis=0)
|
|
126
|
+
finite = jnp.isfinite(log_gamma)
|
|
127
|
+
gamma = jnp.where(finite, jnp.exp(jnp.where(finite, log_gamma - norm, 0.0)), 0.0)
|
|
128
|
+
out = gamma @ space.index.collapse
|
|
129
|
+
return jnp.where(buf.count >= lag + 1, out, jnp.nan)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def buffer_from_prefix(
|
|
133
|
+
theta: Params,
|
|
134
|
+
spec: ModelSpec,
|
|
135
|
+
space: StateSpace,
|
|
136
|
+
data: PreparedDataset,
|
|
137
|
+
log_alpha: Array,
|
|
138
|
+
lag: int,
|
|
139
|
+
) -> RingBuffer:
|
|
140
|
+
"""The buffer after the steps of `data` (warm start); `log_alpha (T, S)` is its offline forward pass."""
|
|
141
|
+
from hsmmkit.engine.expanded_hmm import _block, _expanded_log_emis
|
|
142
|
+
|
|
143
|
+
t_len = int(data.observations.shape[0])
|
|
144
|
+
k_pi = int(theta["transition.b"].shape[-1]) if "transition.b" in theta else 0
|
|
145
|
+
k_d = int(theta["duration.c"].shape[-1]) if "duration.c" in theta else 0
|
|
146
|
+
buf = empty_buffer(lag, space.n_expanded, k_pi, k_d)
|
|
147
|
+
take = min(t_len, lag + 1)
|
|
148
|
+
if take == 0:
|
|
149
|
+
return buf
|
|
150
|
+
lo = t_len - take
|
|
151
|
+
ell = _expanded_log_emis(theta, spec, space, data)
|
|
152
|
+
z_pi, z_d = _block(data.cov_transition, t_len), _block(data.cov_duration, t_len)
|
|
153
|
+
n = lag + 1
|
|
154
|
+
slots = jnp.arange(take) # the first `take` steps of the window go to slots 0..take-1
|
|
155
|
+
return RingBuffer(
|
|
156
|
+
ell=buf.ell.at[slots].set(ell[lo:]),
|
|
157
|
+
z_pi=buf.z_pi.at[slots].set(z_pi[lo:]),
|
|
158
|
+
z_d=buf.z_d.at[slots].set(z_d[lo:]),
|
|
159
|
+
dt=buf.dt.at[slots].set(data.dt[lo:]),
|
|
160
|
+
log_alpha=buf.log_alpha.at[slots].set(log_alpha[lo:]),
|
|
161
|
+
head=jnp.asarray(take % n, dtype=jnp.int32),
|
|
162
|
+
count=jnp.asarray(take, dtype=jnp.int32),
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def smoothed_series(fit: FitResult, data: PreparedDataset, lag: int) -> Array:
|
|
167
|
+
"""`(T, N)` fixed-lag smoothed marginals of a replay: row `t` is `gamma_{t-lag | t}` (`NaN` if `t < lag`).
|
|
168
|
+
|
|
169
|
+
One offline forward pass, then a backward window of `lag` steps per `t` (vectorized over `t`); equals
|
|
170
|
+
what the streaming filter returns at each step.
|
|
171
|
+
"""
|
|
172
|
+
from hsmmkit.engine.expanded_hmm import ExpandedHMMEngine, _block, _expanded_log_emis
|
|
173
|
+
from hsmmkit.statespace.builders import build_expanded
|
|
174
|
+
|
|
175
|
+
spec = fit.spec
|
|
176
|
+
space = build_expanded(spec)
|
|
177
|
+
theta: Params = dict(fit.params)
|
|
178
|
+
log_alpha, _ = ExpandedHMMEngine().forward(theta, spec, space, data)
|
|
179
|
+
t_len = int(data.observations.shape[0])
|
|
180
|
+
ell = _expanded_log_emis(theta, spec, space, data)
|
|
181
|
+
z_pi, z_d = _block(data.cov_transition, t_len), _block(data.cov_duration, t_len)
|
|
182
|
+
s = space.n_expanded
|
|
183
|
+
|
|
184
|
+
def one(t: Array) -> Array:
|
|
185
|
+
steps = t - jnp.arange(lag) # t, t-1, ..., t-lag+1
|
|
186
|
+
safe = jnp.maximum(steps, 0)
|
|
187
|
+
xs = (ell[safe], z_pi[safe], z_d[safe], data.dt[safe], jnp.zeros((lag,), dtype=jnp.int8))
|
|
188
|
+
|
|
189
|
+
def body(beta_next: Array, x: tuple[Array, ...]) -> tuple[Array, None]:
|
|
190
|
+
return backward_step(space, theta, False, beta_next, *x), None
|
|
191
|
+
|
|
192
|
+
beta, _ = jax.lax.scan(body, jnp.zeros((s,)), xs)
|
|
193
|
+
log_gamma = log_alpha[jnp.maximum(t - lag, 0)] + beta
|
|
194
|
+
norm = _safe_logsumexp(log_gamma, axis=0)
|
|
195
|
+
finite = jnp.isfinite(log_gamma)
|
|
196
|
+
gamma = jnp.where(finite, jnp.exp(jnp.where(finite, log_gamma - norm, 0.0)), 0.0)
|
|
197
|
+
return jnp.where(t >= lag, gamma @ space.index.collapse, jnp.nan)
|
|
198
|
+
|
|
199
|
+
out: Array = jax.jit(jax.vmap(one))(jnp.arange(t_len))
|
|
200
|
+
return out
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
__all__ = ["RingBuffer", "buffer_from_prefix", "empty_buffer", "push", "smooth_window", "smoothed_series"]
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""`OnlineCovariatePreparer`: raw covariate prints -> the lagged, standardized rows of the filter (E15-T01).
|
|
2
|
+
|
|
3
|
+
Applies, print by print, what the offline `Preparer` does to a covariate: the stored transforms (`log`,
|
|
4
|
+
`diff`, `pct`; `zscore` is a no-op there), the as-of alignment with lag `>= 1` and the stale limit, and the
|
|
5
|
+
standardization with the fitted `prep_stats` (`(x - cov_mean) / cov_std`). Prints are dated by their grid
|
|
6
|
+
index `j` (time-less / step alignment, `data.calendar._align_by_row`): row `t` takes the last non-NaN print
|
|
7
|
+
with index `<= t + 1 - lag`, carried at most `max_staleness` steps. Only `O(lag)` history is kept.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections import deque
|
|
13
|
+
from collections.abc import Mapping, Sequence
|
|
14
|
+
from typing import TYPE_CHECKING, Any
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from hsmmkit.utils.errors import ConfigError, DataError
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from hsmmkit.data.contracts import PrepStats
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class OnlineCovariatePreparer:
|
|
25
|
+
"""Stateful per-print covariate preparation.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
prep_stats: the fitted `PrepStats` (names, transforms, lags, mean, std).
|
|
29
|
+
max_staleness: grid steps a print may be carried forward; one value for all covariates, a sequence
|
|
30
|
+
per covariate, or `None` for no limit.
|
|
31
|
+
entry_points: optional `{"transition" | "duration" | "emission": [covariate indices]}` (the
|
|
32
|
+
`use_in` of `data.covariates`); with it `z(t)` returns the dict the filter expects.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
prep_stats: PrepStats,
|
|
38
|
+
*,
|
|
39
|
+
max_staleness: int | Sequence[int] | None = None,
|
|
40
|
+
entry_points: Mapping[str, Sequence[int]] | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
"""Validate the stored lags and set up empty per-covariate histories."""
|
|
43
|
+
self.names = tuple(prep_stats.cov_names)
|
|
44
|
+
k = len(self.names)
|
|
45
|
+
self._transforms = [list(prep_stats.transforms.get(n, [])) for n in self.names]
|
|
46
|
+
self._lags = [int(prep_stats.lags.get(n, 1)) for n in self.names]
|
|
47
|
+
for n, lag in zip(self.names, self._lags, strict=True):
|
|
48
|
+
if lag < 1:
|
|
49
|
+
raise ConfigError(f"covariate {n!r}: lag must be >= 1, got {lag}", path="prep_stats.lags")
|
|
50
|
+
self._mean = np.asarray(prep_stats.cov_mean, dtype=np.float64)
|
|
51
|
+
self._std = np.asarray(prep_stats.cov_std, dtype=np.float64)
|
|
52
|
+
if isinstance(max_staleness, int) or max_staleness is None:
|
|
53
|
+
self._stale: list[int | None] = [max_staleness] * k
|
|
54
|
+
else:
|
|
55
|
+
self._stale = list(max_staleness)
|
|
56
|
+
if len(self._stale) != k:
|
|
57
|
+
raise ConfigError("max_staleness needs one value per covariate", path="max_staleness")
|
|
58
|
+
self._entry = None if entry_points is None else {e: tuple(i) for e, i in entry_points.items()}
|
|
59
|
+
self._prev: list[list[float | None]] = [[None] * len(tr) for tr in self._transforms]
|
|
60
|
+
# per covariate: states "as of print j" = (j, last valid transformed value, its index)
|
|
61
|
+
self._hist: list[deque[tuple[int, float, int]]] = [deque(maxlen=lag) for lag in self._lags]
|
|
62
|
+
self.n_pushed = 0
|
|
63
|
+
|
|
64
|
+
def _transform(self, k: int, x: float) -> float:
|
|
65
|
+
"""The covariate's transforms applied to one print (NaN in = NaN out, stage states untouched)."""
|
|
66
|
+
if not np.isfinite(x):
|
|
67
|
+
return float("nan")
|
|
68
|
+
for stage, name in enumerate(self._transforms[k]):
|
|
69
|
+
prev = self._prev[k][stage]
|
|
70
|
+
if name == "log":
|
|
71
|
+
if x <= 0:
|
|
72
|
+
raise DataError("transform 'log' needs strictly positive values", path=self.names[k])
|
|
73
|
+
out = float(np.log(x))
|
|
74
|
+
elif name in ("diff", "pct"):
|
|
75
|
+
if name == "pct" and prev == 0:
|
|
76
|
+
raise DataError("transform 'pct' needs non-zero values", path=self.names[k])
|
|
77
|
+
out = float("nan") if prev is None else (x - prev if name == "diff" else x / prev - 1.0)
|
|
78
|
+
self._prev[k][stage] = x
|
|
79
|
+
elif name == "zscore":
|
|
80
|
+
out = x
|
|
81
|
+
else:
|
|
82
|
+
raise DataError(f"unknown transform {name!r}", path=self.names[k])
|
|
83
|
+
if name == "log":
|
|
84
|
+
self._prev[k][stage] = x
|
|
85
|
+
x = out
|
|
86
|
+
if np.isnan(x):
|
|
87
|
+
return x
|
|
88
|
+
return x
|
|
89
|
+
|
|
90
|
+
def push(self, raw: Sequence[float] | np.ndarray) -> None:
|
|
91
|
+
"""Register the prints dated at the next grid index (`(K,)`, `NaN` = no print)."""
|
|
92
|
+
values = np.asarray(raw, dtype=np.float64).reshape(-1)
|
|
93
|
+
if values.shape[0] != len(self.names):
|
|
94
|
+
raise ConfigError(f"expected {len(self.names)} prints, got {values.shape[0]}", path="raw")
|
|
95
|
+
j = self.n_pushed
|
|
96
|
+
for k, x in enumerate(values):
|
|
97
|
+
value = self._transform(k, float(x))
|
|
98
|
+
hist = self._hist[k]
|
|
99
|
+
if np.isfinite(value):
|
|
100
|
+
hist.append((j, value, j))
|
|
101
|
+
elif hist:
|
|
102
|
+
_, last_value, last_idx = hist[-1]
|
|
103
|
+
hist.append((j, last_value, last_idx))
|
|
104
|
+
else:
|
|
105
|
+
hist.append((j, float("nan"), -1))
|
|
106
|
+
self.n_pushed += 1
|
|
107
|
+
|
|
108
|
+
def row(self, t: int) -> np.ndarray:
|
|
109
|
+
"""The standardized lagged row `(K,)` for step `t` (0-based); `NaN` where no usable print exists.
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
ConfigError: the prints up to index `t + 1 - lag` have not all been pushed, or have been dropped.
|
|
113
|
+
"""
|
|
114
|
+
out = np.full(len(self.names), np.nan)
|
|
115
|
+
for k, lag in enumerate(self._lags):
|
|
116
|
+
source = t + 1 - lag
|
|
117
|
+
if source < 0:
|
|
118
|
+
continue
|
|
119
|
+
if source >= self.n_pushed:
|
|
120
|
+
raise ConfigError(
|
|
121
|
+
f"covariate {self.names[k]!r}: step {t} needs the print with index {source}, "
|
|
122
|
+
f"only {self.n_pushed} pushed",
|
|
123
|
+
path="t",
|
|
124
|
+
)
|
|
125
|
+
state = next((s for s in self._hist[k] if s[0] == source), None)
|
|
126
|
+
if state is None:
|
|
127
|
+
raise ConfigError(f"the print state for step {t} was already dropped", path="t")
|
|
128
|
+
_, value, idx = state
|
|
129
|
+
stale = self._stale[k]
|
|
130
|
+
if idx < 0 or (stale is not None and source - idx > stale):
|
|
131
|
+
continue
|
|
132
|
+
out[k] = value
|
|
133
|
+
return (out - self._mean) / self._std
|
|
134
|
+
|
|
135
|
+
def state_dict(self) -> dict[str, Any]:
|
|
136
|
+
"""The preparer's state as JSON-serializable data (`NaN` as `None`); `load_state_dict` restores it."""
|
|
137
|
+
|
|
138
|
+
def num(x: float | None) -> float | None:
|
|
139
|
+
return None if x is None or np.isnan(x) else float(x)
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
"n_pushed": self.n_pushed,
|
|
143
|
+
"prev": [[num(v) for v in stages] for stages in self._prev],
|
|
144
|
+
"hist": [[[j, num(value), idx] for j, value, idx in h] for h in self._hist],
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
def load_state_dict(self, blob: Mapping[str, Any]) -> None:
|
|
148
|
+
"""Restore a state written by `state_dict` (same covariates, lags and transforms)."""
|
|
149
|
+
if len(blob["hist"]) != len(self.names) or len(blob["prev"]) != len(self.names):
|
|
150
|
+
raise ConfigError("the saved covariate state has another number of covariates", path="state")
|
|
151
|
+
self.n_pushed = int(blob["n_pushed"])
|
|
152
|
+
self._prev = [list(stages) for stages in blob["prev"]]
|
|
153
|
+
for h, saved in zip(self._hist, blob["hist"], strict=True):
|
|
154
|
+
h.clear()
|
|
155
|
+
h.extend((int(j), float("nan") if v is None else float(v), int(idx)) for j, v, idx in saved)
|
|
156
|
+
|
|
157
|
+
def z(self, t: int) -> dict[str, np.ndarray]:
|
|
158
|
+
"""`row(t)` split by entry point, as `ExpandedOnlineFilter.update` expects (needs `entry_points`)."""
|
|
159
|
+
if self._entry is None:
|
|
160
|
+
raise ConfigError("entry_points were not given", path="entry_points")
|
|
161
|
+
r = self.row(t)
|
|
162
|
+
return {e: r[list(idx)] for e, idx in self._entry.items()}
|
hsmmkit/online/em.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""Online EM (Cappe & Moulines 2009) for the expanded-engine `OnlineFilter` (E15-T05, ADR-0026).
|
|
2
|
+
|
|
3
|
+
The recursion keeps running expected complete-data statistics `rho_t(s) in R^K` conditional on the current
|
|
4
|
+
expanded state `s`:
|
|
5
|
+
|
|
6
|
+
phi_t(i | j) = alpha_{t-1}(i) A_ij / sum_i' alpha_{t-1}(i') A_i'j (backward kernel of the filter)
|
|
7
|
+
rho_t(j) = sum_i phi_t(i | j) [(1 - g_t) rho_{t-1}(i) + g_t s(i, j, y_t)]
|
|
8
|
+
S_t = sum_j alpha_t(j) rho_t(j), g_t = t^-kappa, g_1 = 1
|
|
9
|
+
|
|
10
|
+
`K = 3 R_rate + R N + K_f`: the statistics of `engine.estep.ExpandedEStats` (stay, advance, occupancy per
|
|
11
|
+
duration-rate row and the jump counts per jump row and target regime) and the flattened sufficient statistics
|
|
12
|
+
of the emission family (`sufficient_stats` with one-hot regime weights; they are linear in the weights).
|
|
13
|
+
With `kappa = 1`, fixed parameters and the totals `t S_t` the recursion reproduces the offline E-step exactly;
|
|
14
|
+
after the burn-in the parameters are re-estimated with the batch M-step functions (`estimation.mstep`) every
|
|
15
|
+
`update_every` observations. Components without a closed-form M-step (or not listed in `components`) keep
|
|
16
|
+
their fitted values.
|
|
17
|
+
|
|
18
|
+
The step is part of the filter's jitted body (`online.filter._step_fn`): the parameters live in
|
|
19
|
+
`EMState.theta` and replace the fit's parameters, so streaming one row at a time, `update_many` and a save /
|
|
20
|
+
load round trip give bitwise equal states.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import warnings
|
|
26
|
+
from collections.abc import Sequence
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
29
|
+
|
|
30
|
+
import jax
|
|
31
|
+
import jax.numpy as jnp
|
|
32
|
+
import numpy as np
|
|
33
|
+
from jax.flatten_util import ravel_pytree
|
|
34
|
+
|
|
35
|
+
from hsmmkit.engine.estep import ExpandedEStats
|
|
36
|
+
from hsmmkit.estimation.mstep import NoClosedFormError, apply_modes, phase_mstep, transition_mstep
|
|
37
|
+
from hsmmkit.utils.errors import ConfigError
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING:
|
|
40
|
+
from hsmmkit.model.params import Params
|
|
41
|
+
from hsmmkit.model.spec import ModelSpec
|
|
42
|
+
from hsmmkit.statespace.index import StateSpace
|
|
43
|
+
from hsmmkit.utils.typing import Array
|
|
44
|
+
|
|
45
|
+
__all__ = ["COMPONENTS", "EMState", "OnlineEM"]
|
|
46
|
+
|
|
47
|
+
COMPONENTS = ("emission", "duration", "transition")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class EMState:
|
|
52
|
+
"""The online-EM part of an `OnlineState` (a pytree).
|
|
53
|
+
|
|
54
|
+
Attributes:
|
|
55
|
+
theta: the current constrained parameters (the fit's, then updated).
|
|
56
|
+
rho: `(S, K)` running conditional statistics.
|
|
57
|
+
n_updates: `()` int64 number of M-steps taken.
|
|
58
|
+
nominal_dt: `()` the step the duration M-step converts rates with.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
theta: Params
|
|
62
|
+
rho: Array
|
|
63
|
+
n_updates: Array
|
|
64
|
+
nominal_dt: Array
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
jax.tree_util.register_pytree_node(
|
|
68
|
+
EMState,
|
|
69
|
+
lambda s: ((s.theta, s.rho, s.n_updates, s.nominal_dt), None),
|
|
70
|
+
lambda _, c: EMState(*c),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class OnlineEM:
|
|
75
|
+
"""Static structure and the jittable update of the online-EM recursion for one model.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
spec: the model structure (`engine: expanded`, segment memory).
|
|
79
|
+
space: `build_expanded(spec)`.
|
|
80
|
+
kappa: step-size exponent, `g_t = t^-kappa`, in `(0.5, 1]`.
|
|
81
|
+
burn_in: observations with the parameters held fixed before the first M-step.
|
|
82
|
+
update_every: M-step every this many observations after the burn-in.
|
|
83
|
+
components: which of `emission`, `duration`, `transition` are updated (the others stay fixed).
|
|
84
|
+
|
|
85
|
+
Components without a closed-form M-step are dropped with a warning that lists them.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
spec: ModelSpec,
|
|
91
|
+
space: StateSpace,
|
|
92
|
+
*,
|
|
93
|
+
kappa: float,
|
|
94
|
+
burn_in: int,
|
|
95
|
+
update_every: int,
|
|
96
|
+
components: Sequence[str] = COMPONENTS,
|
|
97
|
+
) -> None:
|
|
98
|
+
"""Build the static index arrays and probe which components can be updated."""
|
|
99
|
+
if not 0.5 < kappa <= 1.0:
|
|
100
|
+
raise ConfigError(f"kappa must be in (0.5, 1], got {kappa}", path="online.em.kappa")
|
|
101
|
+
if burn_in < 1 or update_every < 1:
|
|
102
|
+
raise ConfigError("burn_in and update_every must be >= 1", path="online.em")
|
|
103
|
+
unknown = [c for c in components if c not in COMPONENTS]
|
|
104
|
+
if unknown:
|
|
105
|
+
raise ConfigError(
|
|
106
|
+
f"unknown components {unknown}; available: {list(COMPONENTS)}", path="online.em.components"
|
|
107
|
+
)
|
|
108
|
+
self.spec, self.space = spec, space
|
|
109
|
+
self.kappa, self.burn_in, self.update_every = float(kappa), int(burn_in), int(update_every)
|
|
110
|
+
n, s_n = spec.n_states, space.n_expanded
|
|
111
|
+
self.n_regimes, self.n_expanded = n, s_n
|
|
112
|
+
n_rate = space.n_rates
|
|
113
|
+
n_row = int(space.entry_state_of.shape[0])
|
|
114
|
+
self._n_rate, self._n_row = n_rate, n_row
|
|
115
|
+
self.k_trans = 3 * n_rate + n_row * n
|
|
116
|
+
rate_of = np.asarray(space.rate_index_of)
|
|
117
|
+
row_of = np.asarray(space.index.row_of_state)
|
|
118
|
+
last = np.asarray(space.is_last_phase)
|
|
119
|
+
exits = np.asarray(space.exit_targets)
|
|
120
|
+
a = np.full((s_n, s_n), self.k_trans, dtype=np.int64) # stay / advance column (dummy = k_trans)
|
|
121
|
+
b = np.full((s_n, s_n), self.k_trans, dtype=np.int64) # occupancy column
|
|
122
|
+
c = np.full((s_n, s_n), self.k_trans, dtype=np.int64) # jump column
|
|
123
|
+
for i in range(s_n):
|
|
124
|
+
for j in range(s_n):
|
|
125
|
+
a[i, j] = rate_of[i] if i == j else n_rate + rate_of[i]
|
|
126
|
+
b[i, j] = 2 * n_rate + rate_of[i]
|
|
127
|
+
if last[i]:
|
|
128
|
+
for reg in range(n):
|
|
129
|
+
j = int(exits[i, reg])
|
|
130
|
+
if j >= 0:
|
|
131
|
+
c[i, j] = 3 * n_rate + int(row_of[i]) * n + reg
|
|
132
|
+
self._cols = tuple(jnp.asarray(x) for x in (a, b, c))
|
|
133
|
+
self._regime_of = jnp.asarray(np.asarray(space.index.regime_of))
|
|
134
|
+
self.active, dropped = self._probe(components)
|
|
135
|
+
if dropped:
|
|
136
|
+
warnings.warn(
|
|
137
|
+
"online EM keeps these components at their fitted values (no closed-form M-step): "
|
|
138
|
+
+ ", ".join(dropped),
|
|
139
|
+
UserWarning,
|
|
140
|
+
stacklevel=3,
|
|
141
|
+
)
|
|
142
|
+
# family statistics: flatten the pytree once to fix its layout
|
|
143
|
+
probe = self._family_pytree(jnp.zeros((1, spec.n_series)), jnp.ones(1), jnp.ones((1, n)), None)
|
|
144
|
+
flat, self._unravel = ravel_pytree(probe)
|
|
145
|
+
self.k_family = int(flat.shape[0]) if "emission" in self.active else 0
|
|
146
|
+
self.k_total = self.k_trans + self.k_family
|
|
147
|
+
|
|
148
|
+
# -- structure ---------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
def _family_pytree(self, y: Array, dt: Array, gamma: Array, z: Array | None) -> Any: # noqa: ANN401
|
|
151
|
+
suff = self.spec.emission.sufficient_stats(y, dt, gamma, z)
|
|
152
|
+
return suff if suff else {}
|
|
153
|
+
|
|
154
|
+
def _probe(self, components: Sequence[str]) -> tuple[tuple[str, ...], list[str]]:
|
|
155
|
+
spec = self.spec
|
|
156
|
+
active: list[str] = []
|
|
157
|
+
dropped: list[str] = []
|
|
158
|
+
n = spec.n_states
|
|
159
|
+
if "emission" in components:
|
|
160
|
+
suff = spec.emission.sufficient_stats(
|
|
161
|
+
jnp.zeros((1, spec.n_series)), jnp.ones(1), jnp.ones((1, n)), None
|
|
162
|
+
)
|
|
163
|
+
if suff and hasattr(spec.emission, "m_step"):
|
|
164
|
+
try:
|
|
165
|
+
ok = spec.emission.m_step(suff) is not None
|
|
166
|
+
except Exception: # a family that cannot even probe has no closed form
|
|
167
|
+
ok = False
|
|
168
|
+
else:
|
|
169
|
+
ok = False
|
|
170
|
+
(active if ok else dropped).append(
|
|
171
|
+
"emission" if ok else f"emission ({type(spec.emission).__name__})"
|
|
172
|
+
)
|
|
173
|
+
if "duration" in components:
|
|
174
|
+
fam = spec.duration
|
|
175
|
+
ok = getattr(fam, "from_advance_prob", None) is not None and not getattr(fam, "cov_idx", None)
|
|
176
|
+
(active if ok else dropped).append("duration" if ok else f"duration ({type(fam).__name__})")
|
|
177
|
+
if "transition" in components:
|
|
178
|
+
trans = spec.transition
|
|
179
|
+
ok = not getattr(trans, "cov_idx", ())
|
|
180
|
+
names = {s.name for s in spec.param_specs}
|
|
181
|
+
ok = ok and "transition.b" not in names
|
|
182
|
+
(active if ok else dropped).append("transition" if ok else f"transition ({type(trans).__name__})")
|
|
183
|
+
return tuple(active), dropped
|
|
184
|
+
|
|
185
|
+
# -- state ---------------------------------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
def init_state(self, theta: Params, nominal_dt: float) -> EMState:
|
|
188
|
+
"""The state before the first observation: the parameters, zero statistics."""
|
|
189
|
+
return EMState(
|
|
190
|
+
theta={k: jnp.asarray(v) for k, v in theta.items()},
|
|
191
|
+
rho=jnp.zeros((self.n_expanded, self.k_total)),
|
|
192
|
+
n_updates=jnp.zeros((), dtype=jnp.int64),
|
|
193
|
+
nominal_dt=jnp.asarray(nominal_dt, dtype=jnp.float64),
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
# -- the recursion ---------------------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
def _family_rows(self, y: Array, dt: Array, z_e: Array, observed: Array) -> Array:
|
|
199
|
+
"""`(N, K_f)`: the flattened family statistics of one observation for each one-hot regime weight."""
|
|
200
|
+
if self.k_family == 0:
|
|
201
|
+
return jnp.zeros((self.n_regimes, 0))
|
|
202
|
+
eye = jnp.eye(self.n_regimes)
|
|
203
|
+
z = z_e[None, :] if z_e.shape[0] > 0 else None
|
|
204
|
+
|
|
205
|
+
def one(g: Array) -> Array:
|
|
206
|
+
suff = self._family_pytree(y[None, :], dt[None], (g * observed)[None, :], z)
|
|
207
|
+
return ravel_pytree(suff)[0]
|
|
208
|
+
|
|
209
|
+
return jax.vmap(one)(eye)
|
|
210
|
+
|
|
211
|
+
def update(
|
|
212
|
+
self,
|
|
213
|
+
em: EMState,
|
|
214
|
+
theta: Params,
|
|
215
|
+
log_alpha_prev: Array,
|
|
216
|
+
log_alpha: Array,
|
|
217
|
+
t_prev: Array,
|
|
218
|
+
y: Array,
|
|
219
|
+
dt: Array,
|
|
220
|
+
z_pi: Array,
|
|
221
|
+
z_d: Array,
|
|
222
|
+
z_e: Array,
|
|
223
|
+
) -> EMState:
|
|
224
|
+
"""One observation: `rho` from the backward kernel of this step, then the M-step when due.
|
|
225
|
+
|
|
226
|
+
`theta` are the parameters the filter step just used (`em.theta`); `t_prev` the number of observations
|
|
227
|
+
before this one.
|
|
228
|
+
"""
|
|
229
|
+
mask = ~jnp.isnan(y)
|
|
230
|
+
y_safe = jnp.where(mask, y, 0.0)
|
|
231
|
+
observed = jnp.all(mask).astype(y.dtype)
|
|
232
|
+
fam = self._family_rows(y_safe, dt, z_e, observed) # (N, K_f)
|
|
233
|
+
fam_s = fam[self._regime_of] # (S, K_f)
|
|
234
|
+
first = t_prev == 0
|
|
235
|
+
a_t, _ = self.space.transition_fn(theta, z_pi, z_d, dt) # (S, S) probabilities
|
|
236
|
+
alpha_prev = jax.nn.softmax(log_alpha_prev)
|
|
237
|
+
joint = alpha_prev[:, None] * a_t
|
|
238
|
+
pred = jnp.sum(joint, axis=0)
|
|
239
|
+
phi = joint / jnp.where(pred > 0, pred, 1.0)[None, :] # phi[i, j] = phi(i | j)
|
|
240
|
+
t = (t_prev + 1).astype(y.dtype)
|
|
241
|
+
gamma = jnp.where(first, 1.0, t**-self.kappa)
|
|
242
|
+
cols_a, cols_b, cols_c = self._cols
|
|
243
|
+
jj = jnp.broadcast_to(jnp.arange(self.n_expanded)[None, :], phi.shape)
|
|
244
|
+
trans = jnp.zeros((self.n_expanded, self.k_trans + 1))
|
|
245
|
+
for cols in (cols_a, cols_b, cols_c):
|
|
246
|
+
trans = trans.at[jj, cols].add(phi)
|
|
247
|
+
new_stat = jnp.concatenate([trans[:, : self.k_trans], fam_s], axis=1)
|
|
248
|
+
mixed = (1.0 - gamma) * (phi.T @ em.rho) + gamma * new_stat
|
|
249
|
+
rho_first = jnp.concatenate([jnp.zeros((self.n_expanded, self.k_trans)), fam_s], axis=1)
|
|
250
|
+
rho = jnp.where(first, rho_first, mixed)
|
|
251
|
+
stats_t = self.totals(rho, log_alpha, t)
|
|
252
|
+
due = ((t_prev + 1) >= self.burn_in) & (((t_prev + 1) - self.burn_in) % self.update_every == 0)
|
|
253
|
+
new_theta = jax.lax.cond(due, lambda: self._mstep(theta, stats_t, em.nominal_dt), lambda: dict(theta))
|
|
254
|
+
n_upd = em.n_updates + due.astype(em.n_updates.dtype)
|
|
255
|
+
return EMState(new_theta, rho, n_upd, em.nominal_dt)
|
|
256
|
+
|
|
257
|
+
def totals(self, rho: Array, log_alpha: Array, t: Array) -> Array:
|
|
258
|
+
"""`(K,)` totals `t S_t = t sum_j alpha_t(j) rho_t(j)` (the offline E-step sums at `kappa = 1`)."""
|
|
259
|
+
return jax.nn.softmax(log_alpha) @ rho * t
|
|
260
|
+
|
|
261
|
+
def split(self, totals: Array) -> dict[str, Array]:
|
|
262
|
+
"""Named parts of `totals`: `stay`, `advance`, `occupancy` `(R_rate,)`, `jump (R, N)`, `family`."""
|
|
263
|
+
r, nr, n = self._n_rate, self._n_row, self.n_regimes
|
|
264
|
+
return {
|
|
265
|
+
"stay": totals[:r],
|
|
266
|
+
"advance": totals[r : 2 * r],
|
|
267
|
+
"occupancy": totals[2 * r : 3 * r],
|
|
268
|
+
"jump": totals[3 * r : 3 * r + nr * n].reshape(nr, n),
|
|
269
|
+
"family": totals[self.k_trans :],
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
def _mstep(self, theta: Params, totals: Array, nominal_dt: Array) -> Params:
|
|
273
|
+
"""The batch M-step functions applied to the running totals (components not `active` stay fixed)."""
|
|
274
|
+
spec, n = self.spec, self.n_regimes
|
|
275
|
+
r, nr = self._n_rate, self._n_row
|
|
276
|
+
stay, adv, occ = totals[:r], totals[r : 2 * r], totals[2 * r : 3 * r]
|
|
277
|
+
jump = totals[3 * r : 3 * r + nr * n].reshape(nr, n)
|
|
278
|
+
stats = ExpandedEStats(
|
|
279
|
+
loglik=jnp.zeros(1),
|
|
280
|
+
gamma_regime=jnp.zeros((1, 1, n)),
|
|
281
|
+
gamma1=jnp.zeros((1, self.n_expanded)),
|
|
282
|
+
stay=stay,
|
|
283
|
+
advance=adv,
|
|
284
|
+
occupancy=occ,
|
|
285
|
+
jump=jump,
|
|
286
|
+
)
|
|
287
|
+
new = dict(theta)
|
|
288
|
+
shapes = {s.name: tuple(s.shape) for s in spec.param_specs}
|
|
289
|
+
if "emission" in self.active:
|
|
290
|
+
update = spec.emission.m_step(self._unravel(totals[self.k_trans :]))
|
|
291
|
+
for name, value in (update or {}).items():
|
|
292
|
+
new[name] = (
|
|
293
|
+
jnp.reshape(value, shapes.get(name, jnp.shape(theta[name]))) if name in theta else value
|
|
294
|
+
)
|
|
295
|
+
try:
|
|
296
|
+
if "duration" in self.active:
|
|
297
|
+
new = phase_mstep(spec, new, stats, cast("float", nominal_dt))
|
|
298
|
+
if "transition" in self.active:
|
|
299
|
+
new = transition_mstep(spec, self.space, new, stats, False)
|
|
300
|
+
except NoClosedFormError: # probed away at construction; kept for safety
|
|
301
|
+
return dict(theta)
|
|
302
|
+
moved = apply_modes(new, theta, spec.param_specs)
|
|
303
|
+
# a regime whose weight underflowed gives 0/0: such entries keep their previous value
|
|
304
|
+
return {k: jnp.where(jnp.isfinite(v), v, theta[k]) if k in theta else v for k, v in moved.items()}
|