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
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""`OnlineSession`: rows in, regime probabilities and alert events out (E15-T04).
|
|
2
|
+
|
|
3
|
+
Concept refs: Part II §14.11. The session turns raw rows (a mapping / `pandas.Series` with the observation
|
|
4
|
+
columns, an optional time column and the covariate columns of the configuration) into the arguments of
|
|
5
|
+
`ExpandedOnlineFilter.update_from_time`: observations (standardized with the fitted `prep_stats` if the model
|
|
6
|
+
was fitted on standardized observations), the lagged covariate rows (`OnlineCovariatePreparer`) and the
|
|
7
|
+
clock's `dt`. It backs `Project.online()` and the `stream` command.
|
|
8
|
+
|
|
9
|
+
Supported: the identity observation transform and no own-lag emissions (otherwise `ConfigError`). Covariates
|
|
10
|
+
are dated by row (`t + 1 - lag`, as a time-less offline alignment); leading rows for which a covariate has no
|
|
11
|
+
print yet are skipped (the offline `Preparer` trims them too) when the session starts cold.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import TYPE_CHECKING, Any
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
import pandas as pd
|
|
23
|
+
|
|
24
|
+
from hsmmkit.online.covariates import OnlineCovariatePreparer
|
|
25
|
+
from hsmmkit.online.filter import ExpandedOnlineFilter
|
|
26
|
+
from hsmmkit.online.state import load_state, save_state
|
|
27
|
+
from hsmmkit.utils.clock import get_clock
|
|
28
|
+
from hsmmkit.utils.errors import ConfigError, DataError
|
|
29
|
+
|
|
30
|
+
if TYPE_CHECKING:
|
|
31
|
+
from hsmmkit.config.schema import ProjectConfig
|
|
32
|
+
from hsmmkit.data.contracts import PreparedDataset
|
|
33
|
+
from hsmmkit.estimation.results import FitResult
|
|
34
|
+
from hsmmkit.inference.results import ForecastResult
|
|
35
|
+
from hsmmkit.online.alerts import AlertEvent
|
|
36
|
+
|
|
37
|
+
SESSION_FILE = "session.json"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _parse_time(value: Any, column: str) -> np.datetime64: # noqa: ANN401
|
|
41
|
+
"""A timestamp as naive-UTC `datetime64[ns]` (as the tabular sources parse the time column)."""
|
|
42
|
+
try:
|
|
43
|
+
stamp = pd.to_datetime(value, utc=True)
|
|
44
|
+
except (ValueError, TypeError) as exc:
|
|
45
|
+
raise DataError(f"cannot parse the time {value!r}: {exc}", path=column) from exc
|
|
46
|
+
if pd.isna(stamp):
|
|
47
|
+
raise DataError("the time column holds a missing value", path=column)
|
|
48
|
+
return np.datetime64(stamp.tz_localize(None).to_datetime64(), "ns")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _time_json(value: Any) -> Any: # noqa: ANN401
|
|
52
|
+
if isinstance(value, np.datetime64):
|
|
53
|
+
return str(np.datetime_as_string(value, unit="ns"))
|
|
54
|
+
if isinstance(value, np.integer):
|
|
55
|
+
return int(value)
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class OnlineSession:
|
|
60
|
+
"""Stateful streaming facade over an `ExpandedOnlineFilter` and a configuration.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
fit: the fitted model (expanded engine).
|
|
64
|
+
config: the project configuration (`data.source` column names, `data.covariates`, `data.clock`,
|
|
65
|
+
`online`).
|
|
66
|
+
initial: a prepared history for a warm start (the offline forward pass runs on it).
|
|
67
|
+
lag: fixed-lag smoothing delay (default `online.lag`).
|
|
68
|
+
nominal_dt: grid step in clock units for a cold start (`1` under a step clock; required otherwise
|
|
69
|
+
unless `initial` is given).
|
|
70
|
+
group: initial-distribution group of the stream (per-group fits).
|
|
71
|
+
|
|
72
|
+
Raises:
|
|
73
|
+
ConfigError: unsupported model or configuration (see the module docstring), a clock that needs a time
|
|
74
|
+
column, or a missing `nominal_dt`.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
fit: FitResult,
|
|
80
|
+
config: ProjectConfig,
|
|
81
|
+
*,
|
|
82
|
+
initial: PreparedDataset | None = None,
|
|
83
|
+
lag: int | None = None,
|
|
84
|
+
nominal_dt: float | None = None,
|
|
85
|
+
group: str | None = None,
|
|
86
|
+
) -> None:
|
|
87
|
+
"""Validate the configuration against the model and start the filter."""
|
|
88
|
+
from hsmmkit.model.build import required_own_lags
|
|
89
|
+
|
|
90
|
+
data_cfg = config.data
|
|
91
|
+
if data_cfg.preparation.observation_transform not in (None, "identity"):
|
|
92
|
+
raise ConfigError(
|
|
93
|
+
"online streaming supports only the identity observation transform",
|
|
94
|
+
path="data.preparation.observation_transform",
|
|
95
|
+
)
|
|
96
|
+
if required_own_lags(config) > 0:
|
|
97
|
+
raise ConfigError(
|
|
98
|
+
"online streaming does not support own-lag (autoregressive) emissions", path="model"
|
|
99
|
+
)
|
|
100
|
+
self.fit = fit
|
|
101
|
+
self.config = config
|
|
102
|
+
self.obs_columns: list[str] = list(data_cfg.source.option("observation_columns", []) or [])
|
|
103
|
+
if not self.obs_columns:
|
|
104
|
+
raise ConfigError(
|
|
105
|
+
"data.source.observation_columns is required", path="data.source.observation_columns"
|
|
106
|
+
)
|
|
107
|
+
self.time_column: str | None = data_cfg.source.option("time_column")
|
|
108
|
+
unit = get_clock(data_cfg.clock).unit
|
|
109
|
+
if self.time_column is None and unit != "step":
|
|
110
|
+
raise ConfigError(
|
|
111
|
+
"a clock in calendar units needs data.source.time_column", path="data.source.time_column"
|
|
112
|
+
)
|
|
113
|
+
if nominal_dt is None:
|
|
114
|
+
nominal_dt = 1.0 if unit == "step" else None
|
|
115
|
+
online_cfg = config.online
|
|
116
|
+
alerts = [a.model_dump() for a in online_cfg.alerts] if online_cfg else []
|
|
117
|
+
self.filter = ExpandedOnlineFilter(
|
|
118
|
+
fit,
|
|
119
|
+
group=group,
|
|
120
|
+
nominal_dt=nominal_dt,
|
|
121
|
+
lag=(online_cfg.lag if online_cfg else 0) if lag is None else lag,
|
|
122
|
+
alerts=alerts,
|
|
123
|
+
em=online_cfg.em.model_dump() if online_cfg is not None and online_cfg.em is not None else None,
|
|
124
|
+
)
|
|
125
|
+
self.emit_params = False
|
|
126
|
+
"""Include the current parameters (`params`) in every `push` result (online EM only)."""
|
|
127
|
+
self.state = self.filter.start(initial)
|
|
128
|
+
self.events: list[AlertEvent] = []
|
|
129
|
+
self.n_rows = int(self.state.t)
|
|
130
|
+
self._cold = initial is None
|
|
131
|
+
self._last_obs: np.ndarray | None = None
|
|
132
|
+
self.cov_columns = [c.column or c.name for c in data_cfg.covariates]
|
|
133
|
+
self._cov: OnlineCovariatePreparer | None = None
|
|
134
|
+
if data_cfg.covariates:
|
|
135
|
+
names = tuple(c.name for c in data_cfg.covariates)
|
|
136
|
+
if tuple(fit.prep_stats.cov_names) != names:
|
|
137
|
+
raise ConfigError(
|
|
138
|
+
f"the model was fitted with covariates {tuple(fit.prep_stats.cov_names)}, "
|
|
139
|
+
f"the configuration has {names}",
|
|
140
|
+
path="data.covariates",
|
|
141
|
+
)
|
|
142
|
+
entry: dict[str, list[int]] = {}
|
|
143
|
+
for i, c in enumerate(data_cfg.covariates):
|
|
144
|
+
for ep in c.use_in:
|
|
145
|
+
entry.setdefault(ep, []).append(i)
|
|
146
|
+
self._cov = OnlineCovariatePreparer(
|
|
147
|
+
fit.prep_stats,
|
|
148
|
+
max_staleness=[c.max_staleness for c in data_cfg.covariates],
|
|
149
|
+
entry_points=entry,
|
|
150
|
+
)
|
|
151
|
+
self._cov.push([np.nan] * len(names)) # the virtual start of the grid has no print
|
|
152
|
+
self._obs_mean = fit.prep_stats.obs_mean
|
|
153
|
+
self._obs_std = fit.prep_stats.obs_std
|
|
154
|
+
|
|
155
|
+
# -- required columns ----------------------------------------------------------------------
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def required_columns(self) -> list[str]:
|
|
159
|
+
"""Every column a row must have: time (if configured), observations, covariates."""
|
|
160
|
+
cols = [self.time_column] if self.time_column else []
|
|
161
|
+
return [*cols, *self.obs_columns, *self.cov_columns]
|
|
162
|
+
|
|
163
|
+
# -- pushing -------------------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _number(row: Mapping[str, Any], column: str) -> float:
|
|
167
|
+
if column not in row:
|
|
168
|
+
raise DataError(f"missing column {column!r}", path=column)
|
|
169
|
+
value = row[column]
|
|
170
|
+
if value is None or (isinstance(value, str) and not value.strip()):
|
|
171
|
+
return float("nan")
|
|
172
|
+
try:
|
|
173
|
+
return float(value)
|
|
174
|
+
except (TypeError, ValueError) as exc:
|
|
175
|
+
raise DataError(f"column {column!r}: cannot read {value!r} as a number", path=column) from exc
|
|
176
|
+
|
|
177
|
+
def push(self, row: Mapping[str, Any] | pd.Series) -> dict[str, Any]:
|
|
178
|
+
"""Absorb one row.
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
`{"t", "time", "filtered", "smoothed_lag", "events"}` (`filtered` is a list of `N` floats;
|
|
182
|
+
`smoothed_lag` a list or `None` without a lag; `events` a list of `AlertEvent.to_dict()`); a
|
|
183
|
+
warm-up row without a usable covariate gives `filtered: None` and no state change.
|
|
184
|
+
|
|
185
|
+
Raises:
|
|
186
|
+
DataError: a missing or unreadable column, a covariate without a print after the warm-up.
|
|
187
|
+
"""
|
|
188
|
+
mapping: Mapping[str, Any] = (
|
|
189
|
+
{str(k): v for k, v in row.items()} if isinstance(row, pd.Series) else row
|
|
190
|
+
)
|
|
191
|
+
# transactional: a row that fails (or is interrupted) leaves the covariate history and the row counter
|
|
192
|
+
# as they were, so that the next row is aligned as if it had never been pushed
|
|
193
|
+
snapshot = None if self._cov is None else self._cov.state_dict()
|
|
194
|
+
rows_before = self.n_rows
|
|
195
|
+
try:
|
|
196
|
+
return self._push(mapping)
|
|
197
|
+
except BaseException:
|
|
198
|
+
self.n_rows = rows_before
|
|
199
|
+
if snapshot is not None and self._cov is not None:
|
|
200
|
+
self._cov.load_state_dict(snapshot)
|
|
201
|
+
raise
|
|
202
|
+
|
|
203
|
+
def _push(self, mapping: Mapping[str, Any]) -> dict[str, Any]:
|
|
204
|
+
y = np.array([self._number(mapping, c) for c in self.obs_columns])
|
|
205
|
+
if self._obs_mean is not None and self._obs_std is not None:
|
|
206
|
+
y = (y - self._obs_mean) / self._obs_std
|
|
207
|
+
if self.time_column is not None:
|
|
208
|
+
if self.time_column not in mapping:
|
|
209
|
+
raise DataError(f"missing column {self.time_column!r}", path=self.time_column)
|
|
210
|
+
time: Any = _parse_time(mapping[self.time_column], self.time_column)
|
|
211
|
+
else:
|
|
212
|
+
time = self.n_rows
|
|
213
|
+
z: dict[str, np.ndarray] | None = None
|
|
214
|
+
warmup = False
|
|
215
|
+
if self._cov is not None:
|
|
216
|
+
prints = [self._number(mapping, c) for c in self.cov_columns]
|
|
217
|
+
z = self._cov.z(self.n_rows)
|
|
218
|
+
self._cov.push(prints)
|
|
219
|
+
if any(np.isnan(v).any() for v in z.values()):
|
|
220
|
+
if self._cold and int(self.state.t) == 0:
|
|
221
|
+
warmup = True
|
|
222
|
+
else:
|
|
223
|
+
raise DataError("a covariate has no usable print for this row", path="data.covariates")
|
|
224
|
+
self.n_rows += 1
|
|
225
|
+
if warmup:
|
|
226
|
+
return {
|
|
227
|
+
"t": int(self.state.t),
|
|
228
|
+
"time": _time_json(time),
|
|
229
|
+
"filtered": None,
|
|
230
|
+
"smoothed_lag": None,
|
|
231
|
+
"events": [],
|
|
232
|
+
}
|
|
233
|
+
step = self.filter.update_from_time(self.state, time, y, z)
|
|
234
|
+
self.state = step[0]
|
|
235
|
+
filtered = np.asarray(step[1])
|
|
236
|
+
smoothed = np.asarray(step[2]) if self.filter.lag > 0 else None
|
|
237
|
+
events: list[AlertEvent] = step[-1] if self.filter.rules else []
|
|
238
|
+
self.events.extend(events)
|
|
239
|
+
self._last_obs = y
|
|
240
|
+
out: dict[str, Any] = {
|
|
241
|
+
"t": int(self.state.t),
|
|
242
|
+
"time": _time_json(time),
|
|
243
|
+
"filtered": filtered.tolist(),
|
|
244
|
+
"smoothed_lag": None if smoothed is None else smoothed.tolist(),
|
|
245
|
+
"events": [e.to_dict() for e in events],
|
|
246
|
+
}
|
|
247
|
+
if self.emit_params and self.state.em is not None:
|
|
248
|
+
out["params"] = {k: np.asarray(v).tolist() for k, v in self.state.em.theta.items()}
|
|
249
|
+
return out
|
|
250
|
+
|
|
251
|
+
def push_many(self, rows: pd.DataFrame) -> pd.DataFrame:
|
|
252
|
+
"""`push` every row of `rows`; one output row per processed step.
|
|
253
|
+
|
|
254
|
+
Returns:
|
|
255
|
+
A frame with `t`, `time`, `filtered_<i>` (and `smoothed_<i>` with a lag) and `n_events`.
|
|
256
|
+
"""
|
|
257
|
+
out: list[dict[str, Any]] = []
|
|
258
|
+
for _, row in rows.iterrows():
|
|
259
|
+
result = self.push(row)
|
|
260
|
+
if result["filtered"] is None:
|
|
261
|
+
continue
|
|
262
|
+
rec: dict[str, Any] = {"t": result["t"], "time": result["time"]}
|
|
263
|
+
rec.update({f"filtered_{i}": v for i, v in enumerate(result["filtered"])})
|
|
264
|
+
if result["smoothed_lag"] is not None:
|
|
265
|
+
rec.update({f"smoothed_{i}": v for i, v in enumerate(result["smoothed_lag"])})
|
|
266
|
+
rec["n_events"] = len(result["events"])
|
|
267
|
+
out.append(rec)
|
|
268
|
+
return pd.DataFrame(out)
|
|
269
|
+
|
|
270
|
+
# -- persistence ---------------------------------------------------------------------------
|
|
271
|
+
|
|
272
|
+
def snapshot_fit(self) -> FitResult:
|
|
273
|
+
"""The fit with the current online-EM parameters (a `FitResult` that `ModelStore.save` can write).
|
|
274
|
+
|
|
275
|
+
Raises:
|
|
276
|
+
ConfigError: the session does not run online EM (`online.em.enabled`).
|
|
277
|
+
"""
|
|
278
|
+
import dataclasses
|
|
279
|
+
|
|
280
|
+
from hsmmkit.model.params.manager import ParamManager
|
|
281
|
+
|
|
282
|
+
if self.state.em is None:
|
|
283
|
+
raise ConfigError("the session does not run online EM (online.em.enabled)", path="online.em")
|
|
284
|
+
snap = self.filter.fit_of(self.state)
|
|
285
|
+
manager = ParamManager(self.fit.spec.param_specs)
|
|
286
|
+
return dataclasses.replace(snap, uparams=manager.flatten(snap.params))
|
|
287
|
+
|
|
288
|
+
def save(self, path: Path | str) -> Path:
|
|
289
|
+
"""Write the filter state, the alert flags and the covariate history into the directory `path`."""
|
|
290
|
+
out = save_state(self.state, path)
|
|
291
|
+
blob = {
|
|
292
|
+
"n_rows": self.n_rows,
|
|
293
|
+
"cold": self._cold,
|
|
294
|
+
"covariates": None if self._cov is None else self._cov.state_dict(),
|
|
295
|
+
}
|
|
296
|
+
(Path(out) / SESSION_FILE).write_text(json.dumps(blob), encoding="utf-8")
|
|
297
|
+
return out
|
|
298
|
+
|
|
299
|
+
def load(self, path: Path | str) -> None:
|
|
300
|
+
"""Restore a state written by `save` (resume); it must belong to the session's model."""
|
|
301
|
+
src = Path(path)
|
|
302
|
+
self.state = load_state(src, self.fit)
|
|
303
|
+
try:
|
|
304
|
+
blob = json.loads((src / SESSION_FILE).read_text(encoding="utf-8"))
|
|
305
|
+
except (OSError, ValueError) as exc:
|
|
306
|
+
raise DataError(f"cannot read {src / SESSION_FILE}: {exc}", path=str(src)) from exc
|
|
307
|
+
self.n_rows = int(blob["n_rows"])
|
|
308
|
+
self._cold = bool(blob["cold"])
|
|
309
|
+
if self._cov is not None and blob.get("covariates") is not None:
|
|
310
|
+
self._cov.load_state_dict(blob["covariates"])
|
|
311
|
+
|
|
312
|
+
# -- forecasting ---------------------------------------------------------------------------
|
|
313
|
+
|
|
314
|
+
def forecast(
|
|
315
|
+
self,
|
|
316
|
+
horizon: int | None = None,
|
|
317
|
+
*,
|
|
318
|
+
n_sim: int | None = None,
|
|
319
|
+
seed: int | None = None,
|
|
320
|
+
history: PreparedDataset | None = None,
|
|
321
|
+
) -> ForecastResult:
|
|
322
|
+
"""Monte-Carlo forecast from the current state (defaults: `forecast.horizon`, `forecast.n_sim`).
|
|
323
|
+
|
|
324
|
+
Without `history` a one-row history of the last processed row is used, which supports models without
|
|
325
|
+
covariates; with covariates pass the prepared `history` ending at the current step.
|
|
326
|
+
"""
|
|
327
|
+
cfg = self.config.forecast
|
|
328
|
+
data = history if history is not None else self._one_row_history()
|
|
329
|
+
return self.filter.forecast(
|
|
330
|
+
self.state,
|
|
331
|
+
cfg.horizon if horizon is None else horizon,
|
|
332
|
+
cfg.n_sim if n_sim is None else n_sim,
|
|
333
|
+
data,
|
|
334
|
+
seed=self.config.project.seed if seed is None else seed,
|
|
335
|
+
quantiles=cfg.quantiles,
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
def _one_row_history(self) -> PreparedDataset:
|
|
339
|
+
from hsmmkit.data.contracts import PreparedDataset
|
|
340
|
+
|
|
341
|
+
if self._cov is not None:
|
|
342
|
+
raise ConfigError("forecasting a model with covariates needs history=", path="history")
|
|
343
|
+
if self._last_obs is None or self.state.last_time is None:
|
|
344
|
+
raise ConfigError("forecasting needs a processed row", path="state.t")
|
|
345
|
+
import jax.numpy as jnp
|
|
346
|
+
|
|
347
|
+
last = self.state.last_time
|
|
348
|
+
times = (
|
|
349
|
+
np.asarray([last]) if isinstance(last, np.datetime64) else np.asarray([int(last)], dtype=np.int64)
|
|
350
|
+
)
|
|
351
|
+
return PreparedDataset(
|
|
352
|
+
times=times,
|
|
353
|
+
observations=jnp.asarray(self._last_obs[None, :]),
|
|
354
|
+
dt=jnp.asarray([self.filter.nominal_dt or 1.0]),
|
|
355
|
+
mask=jnp.asarray(~np.isnan(self._last_obs[None, :])),
|
|
356
|
+
cov_transition=None,
|
|
357
|
+
cov_duration=None,
|
|
358
|
+
cov_emission=None,
|
|
359
|
+
cov_names={},
|
|
360
|
+
clock=self.config.data.clock,
|
|
361
|
+
nominal_dt=float(self.filter.nominal_dt or 1.0),
|
|
362
|
+
prep_stats=self.fit.prep_stats,
|
|
363
|
+
snapshot_ids=(),
|
|
364
|
+
)
|
hsmmkit/online/state.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""`OnlineState`: the persistable state of a streaming filter (E15-T01).
|
|
2
|
+
|
|
3
|
+
Concept refs: Part II §14.11, §15.2 (`OnlineState`). The state is the unnormalized forward log-vector
|
|
4
|
+
`log_alpha` at step `t` together with the running log-likelihood; saving writes `state.safetensors`
|
|
5
|
+
(arrays) and `state.json` (`t`, `last_time`, `spec_hash`, library version). `spec_hash` ties a state to
|
|
6
|
+
the fit it came from: `load_state` refuses a state of a different model structure or parameter layout.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
import jax
|
|
18
|
+
import jax.numpy as jnp
|
|
19
|
+
import numpy as np
|
|
20
|
+
from safetensors.numpy import load_file, save_file
|
|
21
|
+
|
|
22
|
+
from hsmmkit.online.buffer import RingBuffer
|
|
23
|
+
from hsmmkit.utils.errors import PersistenceError
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
from hsmmkit.estimation.results import FitResult
|
|
27
|
+
from hsmmkit.model.spec import ModelSpec
|
|
28
|
+
from hsmmkit.utils.typing import Array
|
|
29
|
+
|
|
30
|
+
STATE_ARRAYS = "state.safetensors"
|
|
31
|
+
STATE_META = "state.json"
|
|
32
|
+
STATE_VERSION = 2
|
|
33
|
+
"""Version 2 adds the optional online-EM arrays (`em.*`); version-1 states load without them."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class OnlineState:
|
|
38
|
+
"""Streaming filter state (a pytree; `last_time`, `buffer` and `spec_hash` are static metadata).
|
|
39
|
+
|
|
40
|
+
Attributes:
|
|
41
|
+
log_alpha: `(S,)` unnormalized forward log-probabilities at step `t` (before the first observation:
|
|
42
|
+
the initial log-distribution).
|
|
43
|
+
log_norm: `()` running log-likelihood `log p(y_1:t)` (`0` before the first observation).
|
|
44
|
+
t: `()` int64, the number of observations processed.
|
|
45
|
+
carry: emission carry; `None` for every family that has no recurrent state.
|
|
46
|
+
last_time: the last timestamp / step index seen (for `dt` under calendar clocks), or `None`.
|
|
47
|
+
buffer: the fixed-lag smoothing `RingBuffer` (E15-T02); `None` without a lag.
|
|
48
|
+
spec_hash: `spec_hash(fit)` of the fit the state belongs to.
|
|
49
|
+
alerts: `(n_rules,)` bool active flags of the alert rules (E15-T03), or `None` without rules.
|
|
50
|
+
em: the online-EM state (`online.em`: current parameters and running statistics), or `None`.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
log_alpha: Array
|
|
54
|
+
log_norm: Array
|
|
55
|
+
t: Array
|
|
56
|
+
carry: Any
|
|
57
|
+
last_time: Any
|
|
58
|
+
buffer: Any
|
|
59
|
+
spec_hash: str
|
|
60
|
+
alerts: Any = None
|
|
61
|
+
em: Any = None
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def step(self) -> int:
|
|
65
|
+
"""`t` as a Python int."""
|
|
66
|
+
return int(self.t)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _flatten(state: OnlineState) -> tuple[tuple[Any, ...], tuple[Any, ...]]:
|
|
70
|
+
return (state.log_alpha, state.log_norm, state.t, state.carry, state.buffer, state.alerts, state.em), (
|
|
71
|
+
state.last_time,
|
|
72
|
+
state.spec_hash,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _unflatten(aux: tuple[Any, ...], children: tuple[Any, ...]) -> OnlineState:
|
|
77
|
+
log_alpha, log_norm, t, carry, buffer, alerts, em = children
|
|
78
|
+
last_time, spec_hash_ = aux
|
|
79
|
+
return OnlineState(log_alpha, log_norm, t, carry, last_time, buffer, spec_hash_, alerts, em)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
jax.tree_util.register_pytree_node(OnlineState, _flatten, _unflatten)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def spec_hash(fit: FitResult) -> str:
|
|
86
|
+
"""sha256 of the model structure, the parameter names and shapes and the parameter values of `fit`.
|
|
87
|
+
|
|
88
|
+
The values are included because a state is a filter result under *these* parameters: two fits of the same
|
|
89
|
+
structure must not exchange states.
|
|
90
|
+
"""
|
|
91
|
+
spec: ModelSpec = fit.spec
|
|
92
|
+
payload = {
|
|
93
|
+
"n_states": spec.n_states,
|
|
94
|
+
"n_series": spec.n_series,
|
|
95
|
+
"order": spec.order,
|
|
96
|
+
"d_max": spec.d_max,
|
|
97
|
+
"engine": spec.engine,
|
|
98
|
+
"initial": spec.initial,
|
|
99
|
+
"duration_conditioning": spec.duration_conditioning,
|
|
100
|
+
"memory_mode": spec.memory_mode,
|
|
101
|
+
"n_groups": spec.n_groups,
|
|
102
|
+
"emission": type(spec.emission).__name__,
|
|
103
|
+
"duration": type(spec.duration).__name__,
|
|
104
|
+
"transition": type(spec.transition).__name__,
|
|
105
|
+
"params": [[s.name, list(s.shape)] for s in spec.param_specs],
|
|
106
|
+
}
|
|
107
|
+
digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8"))
|
|
108
|
+
for name in sorted(fit.params):
|
|
109
|
+
digest.update(name.encode("utf-8"))
|
|
110
|
+
digest.update(np.array(fit.params[name], dtype=np.float64, order="C").tobytes())
|
|
111
|
+
return digest.hexdigest()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _time_to_json(value: Any) -> Any: # noqa: ANN401
|
|
115
|
+
if value is None:
|
|
116
|
+
return None
|
|
117
|
+
if isinstance(value, np.datetime64):
|
|
118
|
+
return {"kind": "datetime64", "value": str(np.datetime_as_string(value, unit="ns"))}
|
|
119
|
+
if isinstance(value, (int, np.integer)):
|
|
120
|
+
return {"kind": "int", "value": int(value)}
|
|
121
|
+
if isinstance(value, (float, np.floating)):
|
|
122
|
+
return {"kind": "float", "value": float(value)}
|
|
123
|
+
raise PersistenceError(f"cannot save last_time of type {type(value).__name__}", path="state.last_time")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _time_from_json(blob: Any) -> Any: # noqa: ANN401
|
|
127
|
+
if blob is None:
|
|
128
|
+
return None
|
|
129
|
+
kind = blob["kind"]
|
|
130
|
+
if kind == "datetime64":
|
|
131
|
+
return np.datetime64(blob["value"], "ns")
|
|
132
|
+
if kind == "int":
|
|
133
|
+
return int(blob["value"])
|
|
134
|
+
if kind == "float":
|
|
135
|
+
return float(blob["value"])
|
|
136
|
+
raise PersistenceError(f"unknown last_time kind {kind!r}", path="state.json")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
_BUFFER_FIELDS = ("ell", "z_pi", "z_d", "dt", "log_alpha", "head", "count")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _load_buffer(arrays: dict[str, np.ndarray], lag: int | None) -> RingBuffer | None:
|
|
143
|
+
if lag is None:
|
|
144
|
+
return None
|
|
145
|
+
try:
|
|
146
|
+
return RingBuffer(**{name: jnp.asarray(arrays[f"buffer.{name}"]) for name in _BUFFER_FIELDS})
|
|
147
|
+
except KeyError as exc:
|
|
148
|
+
raise PersistenceError(f"the state is missing the buffer array {exc}", path=STATE_ARRAYS) from exc
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _load_em(arrays: dict[str, np.ndarray], fit: FitResult) -> Any: # noqa: ANN401
|
|
152
|
+
from hsmmkit.online.em import EMState
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
theta = {name: jnp.asarray(arrays[f"em.theta.{name}"]) for name in fit.params}
|
|
156
|
+
return EMState(
|
|
157
|
+
theta=theta,
|
|
158
|
+
rho=jnp.asarray(arrays["em.rho"]),
|
|
159
|
+
n_updates=jnp.asarray(arrays["em.n_updates"], dtype=jnp.int64),
|
|
160
|
+
nominal_dt=jnp.asarray(arrays["em.nominal_dt"]),
|
|
161
|
+
)
|
|
162
|
+
except KeyError as exc:
|
|
163
|
+
raise PersistenceError(f"the state is missing the online-EM array {exc}", path=STATE_ARRAYS) from exc
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def save_state(state: OnlineState, path: Path | str) -> Path:
|
|
167
|
+
"""Write `state.safetensors` and `state.json` into the directory `path` (created if needed)."""
|
|
168
|
+
if state.carry is not None:
|
|
169
|
+
raise PersistenceError("saving an emission carry is not supported yet", path="state.carry")
|
|
170
|
+
from hsmmkit import __version__
|
|
171
|
+
|
|
172
|
+
out = Path(path)
|
|
173
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
174
|
+
arrays = {
|
|
175
|
+
"log_alpha": np.array(state.log_alpha, order="C"),
|
|
176
|
+
"log_norm": np.array(state.log_norm, order="C"),
|
|
177
|
+
}
|
|
178
|
+
if state.alerts is not None:
|
|
179
|
+
arrays["alerts"] = np.array(state.alerts, dtype=np.uint8, order="C") # safetensors has no bool
|
|
180
|
+
if state.buffer is not None:
|
|
181
|
+
for name in _BUFFER_FIELDS:
|
|
182
|
+
arrays[f"buffer.{name}"] = np.array(getattr(state.buffer, name), order="C")
|
|
183
|
+
if state.em is not None:
|
|
184
|
+
arrays["em.rho"] = np.array(state.em.rho, order="C")
|
|
185
|
+
arrays["em.n_updates"] = np.array(state.em.n_updates, order="C")
|
|
186
|
+
arrays["em.nominal_dt"] = np.array(state.em.nominal_dt, order="C")
|
|
187
|
+
for name, value in state.em.theta.items():
|
|
188
|
+
arrays[f"em.theta.{name}"] = np.array(value, dtype=np.float64, order="C")
|
|
189
|
+
save_file(arrays, str(out / STATE_ARRAYS))
|
|
190
|
+
meta = {
|
|
191
|
+
"state_version": STATE_VERSION,
|
|
192
|
+
"t": state.step,
|
|
193
|
+
"last_time": _time_to_json(state.last_time),
|
|
194
|
+
"spec_hash": state.spec_hash,
|
|
195
|
+
"n_alerts": None if state.alerts is None else int(np.asarray(state.alerts).shape[0]),
|
|
196
|
+
"buffer_lag": None if state.buffer is None else state.buffer.lag,
|
|
197
|
+
"online_em": state.em is not None,
|
|
198
|
+
"library_version": __version__,
|
|
199
|
+
}
|
|
200
|
+
(out / STATE_META).write_text(json.dumps(meta, indent=2), encoding="utf-8")
|
|
201
|
+
return out
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def load_state(path: Path | str, fit: FitResult) -> OnlineState:
|
|
205
|
+
"""Read a state saved by `save_state`; it must belong to `fit`.
|
|
206
|
+
|
|
207
|
+
Raises:
|
|
208
|
+
PersistenceError: missing or corrupt files, or a `spec_hash` that differs from `fit`'s (the message
|
|
209
|
+
names both hashes).
|
|
210
|
+
"""
|
|
211
|
+
src = Path(path)
|
|
212
|
+
try:
|
|
213
|
+
meta = json.loads((src / STATE_META).read_text(encoding="utf-8"))
|
|
214
|
+
arrays = load_file(str(src / STATE_ARRAYS))
|
|
215
|
+
except (OSError, ValueError, KeyError) as exc:
|
|
216
|
+
raise PersistenceError(f"cannot read the online state in {src}: {exc}", path=str(src)) from exc
|
|
217
|
+
version = int(meta.get("state_version", 1))
|
|
218
|
+
if version > STATE_VERSION:
|
|
219
|
+
raise PersistenceError(
|
|
220
|
+
f"the state has format version {version}; this version reads up to {STATE_VERSION}",
|
|
221
|
+
path=str(src / STATE_META),
|
|
222
|
+
)
|
|
223
|
+
expected = spec_hash(fit)
|
|
224
|
+
if meta.get("spec_hash") != expected:
|
|
225
|
+
raise PersistenceError(
|
|
226
|
+
f"the state was saved for another model: spec_hash {meta.get('spec_hash')} "
|
|
227
|
+
f"!= {expected} of the given fit",
|
|
228
|
+
path=str(src / STATE_META),
|
|
229
|
+
)
|
|
230
|
+
return OnlineState(
|
|
231
|
+
log_alpha=jnp.asarray(arrays["log_alpha"]),
|
|
232
|
+
log_norm=jnp.asarray(arrays["log_norm"]),
|
|
233
|
+
t=jnp.asarray(meta["t"], dtype=jnp.int64),
|
|
234
|
+
carry=None,
|
|
235
|
+
last_time=_time_from_json(meta["last_time"]),
|
|
236
|
+
buffer=_load_buffer(arrays, meta.get("buffer_lag")),
|
|
237
|
+
alerts=None if meta.get("n_alerts") is None else np.asarray(arrays["alerts"], dtype=bool),
|
|
238
|
+
spec_hash=expected,
|
|
239
|
+
em=_load_em(arrays, fit) if meta.get("online_em") else None,
|
|
240
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Model bundle store and result serialization."""
|