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,97 @@
|
|
|
1
|
+
"""`PosteriorResult` and `ForecastResult` (E1-T05): plain result containers, not pytrees.
|
|
2
|
+
|
|
3
|
+
Neither is jitted or traced directly (both are post-hoc, Python-level consumption/serialization
|
|
4
|
+
objects assembled once inference/forecasting has finished), so no pytree registration is needed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from hsmmkit.engine.base import Posterior
|
|
16
|
+
from hsmmkit.utils.typing import Array
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class PosteriorResult:
|
|
21
|
+
"""Decoded posterior: filtered/smoothed regime probabilities, Viterbi path, segments, IC."""
|
|
22
|
+
|
|
23
|
+
times: np.ndarray
|
|
24
|
+
filtered: Array # (T, N)
|
|
25
|
+
smoothed: Array # (T, N)
|
|
26
|
+
viterbi: np.ndarray # (T,) regime path
|
|
27
|
+
segments: list[tuple[int, int, int]] # (start, end, regime), end inclusive
|
|
28
|
+
augmented: Posterior
|
|
29
|
+
loglik: float
|
|
30
|
+
aic: float
|
|
31
|
+
bic: float
|
|
32
|
+
icl: float
|
|
33
|
+
path_samples: np.ndarray | None = None # (R, T) posterior regime paths (`decode(..., samples=R)`)
|
|
34
|
+
boundary_prob: np.ndarray | None = None # (T,) P(a new segment starts at t), from the path samples
|
|
35
|
+
pruned_states: tuple[int, ...] = () # regimes a VB fit reports as unused (`FitResult.pruned_states`)
|
|
36
|
+
|
|
37
|
+
def to_pandas(self, *, state_names: Sequence[str] | None = None) -> Any: # noqa: ANN401
|
|
38
|
+
"""The long table `time, sequence, state, filtered, smoothed, viterbi` (E16-T02)."""
|
|
39
|
+
from hsmmkit.interop.pandas import posterior_frame
|
|
40
|
+
|
|
41
|
+
return posterior_frame(self, state_names=state_names)
|
|
42
|
+
|
|
43
|
+
def to_xarray(self, *, state_names: Sequence[str] | None = None) -> Any: # noqa: ANN401
|
|
44
|
+
"""A `Dataset` with a `sequence` dimension of length 1 (extra `xarray`; E16-T02)."""
|
|
45
|
+
from hsmmkit.interop.xarray import posterior_to_dataset
|
|
46
|
+
|
|
47
|
+
return posterior_to_dataset(self, state_names=state_names)
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_xarray(cls, ds: Any) -> PosteriorResult: # noqa: ANN401
|
|
51
|
+
"""The result of a one-sequence dataset (batches: `hsmmkit.interop.xarray.posterior_from_dataset`)."""
|
|
52
|
+
from hsmmkit.interop.xarray import posterior_from_dataset
|
|
53
|
+
|
|
54
|
+
results = posterior_from_dataset(ds)
|
|
55
|
+
if len(results) != 1:
|
|
56
|
+
raise ValueError(f"the dataset holds {len(results)} sequences: use posterior_from_dataset")
|
|
57
|
+
return results[0]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class ForecastResult:
|
|
62
|
+
"""A Monte Carlo forecast from a given origin: samples, cumulative quantiles, moments."""
|
|
63
|
+
|
|
64
|
+
origin_time: np.datetime64
|
|
65
|
+
horizon_times: np.ndarray # (h,)
|
|
66
|
+
regime_probs: Array # (h, N)
|
|
67
|
+
samples: Array # (n_sim, h, M) per-step log-values
|
|
68
|
+
cum_quantiles: Array # (h, Q, M)
|
|
69
|
+
mean: Array # (h, M) of cumulative log-return
|
|
70
|
+
var: Array # (h, M) of cumulative log-return
|
|
71
|
+
quantile_levels: tuple[float, ...]
|
|
72
|
+
covariate_forecaster: str
|
|
73
|
+
seed: int
|
|
74
|
+
|
|
75
|
+
def to_pandas(self, *, series_names: Sequence[str] | None = None, samples: bool = False) -> Any: # noqa: ANN401
|
|
76
|
+
"""The quantile table `horizon, time, series, quantile, value` (E16-T02).
|
|
77
|
+
|
|
78
|
+
With `samples=True` a dict with the `sim, horizon, series, value` table too.
|
|
79
|
+
"""
|
|
80
|
+
from hsmmkit.interop.pandas import forecast_frames
|
|
81
|
+
|
|
82
|
+
return forecast_frames(self, series_names=series_names, samples=samples)
|
|
83
|
+
|
|
84
|
+
def to_xarray(
|
|
85
|
+
self, *, state_names: Sequence[str] | None = None, series_names: Sequence[str] | None = None
|
|
86
|
+
) -> Any: # noqa: ANN401
|
|
87
|
+
"""A `Dataset` with `samples`, `regime_probs`, `cum_quantiles` (extra `xarray`; E16-T02)."""
|
|
88
|
+
from hsmmkit.interop.xarray import forecast_to_dataset
|
|
89
|
+
|
|
90
|
+
return forecast_to_dataset(self, state_names=state_names, series_names=series_names)
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def from_xarray(cls, ds: Any) -> ForecastResult: # noqa: ANN401
|
|
94
|
+
"""The result of a dataset written by `to_xarray` (bitwise)."""
|
|
95
|
+
from hsmmkit.interop.xarray import forecast_from_dataset
|
|
96
|
+
|
|
97
|
+
return forecast_from_dataset(ds)
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
"""Path simulation from any model/parameters (E6-T01): `simulate_paths`, `simulate_dataset`.
|
|
2
|
+
|
|
3
|
+
Concept refs: §5.5, §6.3 item 2 (`simulate_paths` is a JIT boundary), §6.4.2. States advance one step
|
|
4
|
+
per `jax.lax.scan` iteration using `space.transition_fn` (the same per-step `A_t` builder the engines
|
|
5
|
+
use, CLAUDE.md §3.7's timing convention: `A_t` moves index `t-1` to `t` using covariate/`dt` row `t`).
|
|
6
|
+
Observations are then drawn in one vectorized call per path via `spec.emission.sample`, which already
|
|
7
|
+
takes whole `(T,)` `regime`/`dt`/`z` arrays (not a per-step call) -- the ticket's per-step narrative
|
|
8
|
+
describes the *semantics*, not literally one `emission.sample` call per step.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import dataclasses
|
|
14
|
+
from collections.abc import Sequence
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from functools import partial
|
|
17
|
+
from typing import TYPE_CHECKING
|
|
18
|
+
|
|
19
|
+
import jax
|
|
20
|
+
import jax.numpy as jnp
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from hsmmkit.data.contracts import PreparedDataset, PrepStats, lag_names, own_lag_columns
|
|
24
|
+
from hsmmkit.engine.viterbi import segments
|
|
25
|
+
from hsmmkit.statespace.builders import initial_log_rho
|
|
26
|
+
from hsmmkit.utils.errors import ConfigError, NumericalError
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from hsmmkit.data.batch import SequenceBatch
|
|
30
|
+
from hsmmkit.model.params.manager import Params
|
|
31
|
+
from hsmmkit.model.spec import ModelSpec
|
|
32
|
+
from hsmmkit.statespace.index import StateSpace
|
|
33
|
+
from hsmmkit.utils.typing import Array
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _block(x: Array | None, t: int) -> Array:
|
|
37
|
+
"""A covariate block, or `(T, 0)` zeros when absent (CLAUDE.md §3.7)."""
|
|
38
|
+
return jnp.zeros((t, 0)) if x is None else x
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _check_finite(values: Array) -> None:
|
|
42
|
+
"""Public-boundary guard (CLAUDE.md §4): no NaN/Inf may leave `simulate_paths`."""
|
|
43
|
+
if not bool(jnp.all(jnp.isfinite(values))):
|
|
44
|
+
raise NumericalError("non-finite value in simulated values", path="values")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class SimResult:
|
|
49
|
+
"""`n_paths` simulated paths from `simulate_paths`."""
|
|
50
|
+
|
|
51
|
+
states: Array # (n_paths, T) int, expanded state index
|
|
52
|
+
regimes: Array # (n_paths, T) int, regime index
|
|
53
|
+
values: Array # (n_paths, T, M)
|
|
54
|
+
log_rho: Array # (S,) initial log-distribution actually used (for tests/diagnostics)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _simulate_one_path(
|
|
58
|
+
key: Array,
|
|
59
|
+
theta: Params,
|
|
60
|
+
spec: ModelSpec,
|
|
61
|
+
space: StateSpace,
|
|
62
|
+
dt: Array,
|
|
63
|
+
z_pi: Array,
|
|
64
|
+
z_d: Array,
|
|
65
|
+
z_e: Array,
|
|
66
|
+
init_state: Array,
|
|
67
|
+
nominal_dt: float = 1.0,
|
|
68
|
+
) -> tuple[Array, Array, Array]:
|
|
69
|
+
"""One path: `(states (T,), regimes (T,), values (T, M))`."""
|
|
70
|
+
if spec.engine == "explicit":
|
|
71
|
+
return _simulate_explicit_path(key, theta, spec, space, dt, z_pi, z_d, z_e, init_state, nominal_dt)
|
|
72
|
+
if spec.duration_dependent_jumps:
|
|
73
|
+
raise ConfigError(
|
|
74
|
+
"simulating duration-dependent jumps is not supported yet",
|
|
75
|
+
path="model.duration.duration_dependent_jumps",
|
|
76
|
+
)
|
|
77
|
+
t_len = dt.shape[0]
|
|
78
|
+
step_key, emit_key = jax.random.split(key)
|
|
79
|
+
|
|
80
|
+
def step(s_prev: Array, xs_t: tuple[Array, Array, Array, Array]) -> tuple[Array, Array]:
|
|
81
|
+
z_pi_t, z_d_t, dt_t, key_t = xs_t
|
|
82
|
+
_, log_a = space.transition_fn(theta, z_pi_t, z_d_t, dt_t)
|
|
83
|
+
# `categorical`'s output dtype need not match `s_prev`'s (e.g. index arrays are int32,
|
|
84
|
+
# `categorical` defaults to int64 under x64) -- the scan carry's dtype must stay fixed.
|
|
85
|
+
s_t = jax.random.categorical(key_t, log_a[s_prev]).astype(s_prev.dtype)
|
|
86
|
+
return s_t, s_t
|
|
87
|
+
|
|
88
|
+
if t_len > 1:
|
|
89
|
+
step_keys = jax.random.split(step_key, t_len - 1)
|
|
90
|
+
xs = (z_pi[1:], z_d[1:], dt[1:], step_keys)
|
|
91
|
+
_, rest = jax.lax.scan(step, init_state, xs)
|
|
92
|
+
states = jnp.concatenate([init_state[None], rest])
|
|
93
|
+
else:
|
|
94
|
+
states = init_state[None]
|
|
95
|
+
|
|
96
|
+
regimes = space.index.regime_of[states]
|
|
97
|
+
if hasattr(spec.emission, "sample_path"):
|
|
98
|
+
# Autoregressive emissions (`msar`) feed each draw back into the next lags.
|
|
99
|
+
values = spec.emission.sample_path(emit_key, regimes, dt, theta)
|
|
100
|
+
else:
|
|
101
|
+
values = spec.emission.sample(emit_key, regimes, dt, theta, z_e)
|
|
102
|
+
return states, regimes, values
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _simulate_explicit_path(
|
|
106
|
+
key: Array,
|
|
107
|
+
theta: Params,
|
|
108
|
+
spec: ModelSpec,
|
|
109
|
+
space: StateSpace,
|
|
110
|
+
dt: Array,
|
|
111
|
+
z_pi: Array,
|
|
112
|
+
z_d: Array,
|
|
113
|
+
z_e: Array,
|
|
114
|
+
init_state: Array,
|
|
115
|
+
nominal_dt: float,
|
|
116
|
+
) -> tuple[Array, Array, Array]:
|
|
117
|
+
"""One path of the explicit-duration model: draw a sojourn from the pmf, then jump by `pi`.
|
|
118
|
+
|
|
119
|
+
State index `regime * D_max + (elapsed - 1)`, like the engine's. A regime without an allowed jump
|
|
120
|
+
(absorbing) stays for the rest of the path. Entry-time covariates are not supported (constant pmf).
|
|
121
|
+
"""
|
|
122
|
+
if spec.duration_dependent_jumps:
|
|
123
|
+
raise ConfigError(
|
|
124
|
+
"simulating duration-dependent jumps is not supported yet",
|
|
125
|
+
path="model.duration.duration_dependent_jumps",
|
|
126
|
+
)
|
|
127
|
+
if getattr(spec.duration, "cov_idx", ()):
|
|
128
|
+
raise ConfigError(
|
|
129
|
+
"simulating an explicit model with duration covariates is not supported yet",
|
|
130
|
+
path="model.duration.covariates",
|
|
131
|
+
)
|
|
132
|
+
d_max, t_len = spec.d_max, dt.shape[0]
|
|
133
|
+
step_key, dur_key, emit_key = jax.random.split(key, 3)
|
|
134
|
+
log_pmf = spec.duration.log_pmf(theta, d_max, nominal_dt, None) # (N, D_max)
|
|
135
|
+
j0 = (init_state // d_max).astype(jnp.int64)
|
|
136
|
+
d0 = (jax.random.categorical(dur_key, log_pmf[j0]) + 1).astype(jnp.int64)
|
|
137
|
+
|
|
138
|
+
def step(
|
|
139
|
+
carry: tuple[Array, Array, Array], xs: tuple[Array, Array]
|
|
140
|
+
) -> tuple[tuple[Array, Array, Array], tuple[Array, Array]]:
|
|
141
|
+
j, e, d = carry
|
|
142
|
+
z_pi_t, key_t = xs
|
|
143
|
+
key_j, key_d = jax.random.split(key_t)
|
|
144
|
+
pi = spec.transition.jump_probs_t(theta, z_pi_t, space.layout)[j]
|
|
145
|
+
can_leave = jnp.any(pi > 0)
|
|
146
|
+
log_pi = jnp.where(pi > 0, jnp.log(jnp.where(pi > 0, pi, 1.0)), -jnp.inf)
|
|
147
|
+
j_new = jax.random.categorical(key_j, jnp.where(can_leave, log_pi, 0.0)).astype(jnp.int64)
|
|
148
|
+
d_new = (jax.random.categorical(key_d, log_pmf[j_new]) + 1).astype(jnp.int64)
|
|
149
|
+
ended = (e >= d) & can_leave
|
|
150
|
+
j2 = jnp.where(ended, j_new, j)
|
|
151
|
+
e2 = jnp.where(ended, jnp.int64(1), e + 1)
|
|
152
|
+
d2 = jnp.where(ended, d_new, d)
|
|
153
|
+
return (j2, e2, d2), (j2 * d_max + jnp.minimum(e2, d_max) - 1, j2)
|
|
154
|
+
|
|
155
|
+
first = (j0 * d_max, j0)
|
|
156
|
+
if t_len > 1:
|
|
157
|
+
carry0 = (j0, jnp.int64(1), d0)
|
|
158
|
+
_, (states_rest, regimes_rest) = jax.lax.scan(
|
|
159
|
+
step, carry0, (z_pi[1:], jax.random.split(step_key, t_len - 1))
|
|
160
|
+
)
|
|
161
|
+
states = jnp.concatenate([first[0][None], states_rest])
|
|
162
|
+
regimes = jnp.concatenate([first[1][None], regimes_rest])
|
|
163
|
+
else:
|
|
164
|
+
states, regimes = first[0][None], first[1][None]
|
|
165
|
+
values = spec.emission.sample(emit_key, regimes, dt, theta, z_e)
|
|
166
|
+
return states.astype(init_state.dtype), regimes.astype(init_state.dtype), values
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@partial(jax.jit, static_argnames=("spec", "n_paths", "nominal_dt"))
|
|
170
|
+
def _simulate_core(
|
|
171
|
+
key: Array,
|
|
172
|
+
theta: Params,
|
|
173
|
+
spec: ModelSpec,
|
|
174
|
+
space: StateSpace,
|
|
175
|
+
dt: Array,
|
|
176
|
+
z_pi: Array,
|
|
177
|
+
z_d: Array,
|
|
178
|
+
z_e: Array,
|
|
179
|
+
n_paths: int,
|
|
180
|
+
init_state: Array,
|
|
181
|
+
nominal_dt: float,
|
|
182
|
+
) -> tuple[Array, Array, Array]:
|
|
183
|
+
path_keys = jax.random.split(key, n_paths)
|
|
184
|
+
in_axes = (0, None, None, None, None, None, None, None, 0, None)
|
|
185
|
+
return jax.vmap(_simulate_one_path, in_axes=in_axes)(
|
|
186
|
+
path_keys, theta, spec, space, dt, z_pi, z_d, z_e, init_state, nominal_dt
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def simulate_paths(
|
|
191
|
+
key: Array,
|
|
192
|
+
theta: Params,
|
|
193
|
+
spec: ModelSpec,
|
|
194
|
+
space: StateSpace,
|
|
195
|
+
dt: Array,
|
|
196
|
+
z_pi: Array | None,
|
|
197
|
+
z_d: Array | None,
|
|
198
|
+
z_e: Array | None,
|
|
199
|
+
n_paths: int,
|
|
200
|
+
init_state: Array | None = None,
|
|
201
|
+
) -> SimResult:
|
|
202
|
+
"""Sample `n_paths` independent expanded-state paths and observations, deterministic per `key`.
|
|
203
|
+
|
|
204
|
+
Without `init_state`, the initial expanded state is drawn from `initial_log_rho(spec, space,
|
|
205
|
+
theta)` (uniform/free: `phase == 1` support only; stationary: every state) using `nominal_dt =
|
|
206
|
+
median(dt)`. `init_state (n_paths,)` (forecasting: a filtered-posterior sample) skips that draw.
|
|
207
|
+
`spec`/`n_paths` are static; the state-path scan and emission sampling are jitted together
|
|
208
|
+
(`_simulate_core`).
|
|
209
|
+
"""
|
|
210
|
+
t_len = dt.shape[0]
|
|
211
|
+
z_pi_b, z_d_b, z_e_b = _block(z_pi, t_len), _block(z_d, t_len), _block(z_e, t_len)
|
|
212
|
+
log_rho = initial_log_rho(spec, space, theta, float(jnp.median(dt)))
|
|
213
|
+
|
|
214
|
+
if init_state is None:
|
|
215
|
+
init_key, key = jax.random.split(key)
|
|
216
|
+
logits = jnp.broadcast_to(log_rho, (n_paths, log_rho.shape[0]))
|
|
217
|
+
init_state = jax.random.categorical(init_key, logits)
|
|
218
|
+
init_state = jnp.asarray(init_state, dtype=space.index.regime_of.dtype)
|
|
219
|
+
|
|
220
|
+
states, regimes, values = _simulate_core(
|
|
221
|
+
key, theta, spec, space, dt, z_pi_b, z_d_b, z_e_b, n_paths, init_state, float(jnp.median(dt))
|
|
222
|
+
)
|
|
223
|
+
_check_finite(values)
|
|
224
|
+
return SimResult(states=states, regimes=regimes, values=values, log_rho=log_rho)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def segments_of(regimes: Array | np.ndarray) -> list[list[tuple[int, int, int]]]:
|
|
228
|
+
"""`[segments(regimes[i]) for i in range(n_paths)]` (NumPy, outside jit; `end` inclusive)."""
|
|
229
|
+
arr = np.asarray(regimes)
|
|
230
|
+
return [segments(arr[i]) for i in range(arr.shape[0])]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def simulate_dataset(
|
|
234
|
+
key: Array,
|
|
235
|
+
theta: Params,
|
|
236
|
+
spec: ModelSpec,
|
|
237
|
+
space: StateSpace,
|
|
238
|
+
dt: Array,
|
|
239
|
+
z_pi: Array | None = None,
|
|
240
|
+
z_d: Array | None = None,
|
|
241
|
+
z_e: Array | None = None,
|
|
242
|
+
*,
|
|
243
|
+
clock: str,
|
|
244
|
+
nominal_dt: float | None = None,
|
|
245
|
+
) -> PreparedDataset:
|
|
246
|
+
"""A single simulated path (`n_paths=1`) wrapped as a synthetic `PreparedDataset` (tests/recovery).
|
|
247
|
+
|
|
248
|
+
`mask` is all-`True` (nothing missing); `PrepStats` is the zero/identity "no transform applied"
|
|
249
|
+
default, matching a dataset that was never run through `Preparer`.
|
|
250
|
+
"""
|
|
251
|
+
result = simulate_paths(key, theta, spec, space, dt, z_pi, z_d, z_e, n_paths=1)
|
|
252
|
+
y = result.values[0]
|
|
253
|
+
t_len = y.shape[0]
|
|
254
|
+
mask = jnp.ones(y.shape, dtype=bool)
|
|
255
|
+
emission_names: tuple[str, ...] = ()
|
|
256
|
+
p = int(getattr(spec.emission, "requires_own_lags", 0))
|
|
257
|
+
if p: # an autoregressive emission: the own lags are emission covariates and the first `p` steps masked
|
|
258
|
+
lags, ok = own_lag_columns(np.asarray(y), np.ones(y.shape, dtype=bool), p)
|
|
259
|
+
z_e = jnp.asarray(lags) if z_e is None else jnp.concatenate([z_e, jnp.asarray(lags)], axis=1)
|
|
260
|
+
emission_names = lag_names(tuple(f"y{m}" for m in range(y.shape[1])), p)
|
|
261
|
+
mask = jnp.asarray(np.broadcast_to(ok[:, None], y.shape))
|
|
262
|
+
stats = PrepStats(
|
|
263
|
+
cov_mean=np.zeros(0), cov_std=np.ones(0), train_window=("", ""), cov_names=(), transforms={}, lags={}
|
|
264
|
+
)
|
|
265
|
+
return PreparedDataset(
|
|
266
|
+
times=np.arange(t_len).astype("datetime64[D]").astype("datetime64[ns]"),
|
|
267
|
+
observations=y,
|
|
268
|
+
dt=dt,
|
|
269
|
+
mask=mask,
|
|
270
|
+
cov_transition=z_pi,
|
|
271
|
+
cov_duration=z_d,
|
|
272
|
+
cov_emission=z_e,
|
|
273
|
+
cov_names={"transition": (), "duration": (), "emission": emission_names},
|
|
274
|
+
clock=clock,
|
|
275
|
+
nominal_dt=float(jnp.median(dt)) if nominal_dt is None else nominal_dt,
|
|
276
|
+
prep_stats=stats,
|
|
277
|
+
snapshot_ids=(),
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def simulate_batch(
|
|
282
|
+
params: Params,
|
|
283
|
+
spec: ModelSpec,
|
|
284
|
+
lengths: Sequence[int],
|
|
285
|
+
key: Array,
|
|
286
|
+
groups: Sequence[str] | None = None,
|
|
287
|
+
*,
|
|
288
|
+
clock: str = "steps",
|
|
289
|
+
nominal_dt: float = 1.0,
|
|
290
|
+
) -> SequenceBatch:
|
|
291
|
+
"""Simulate one sequence of each length in `lengths` as a `SequenceBatch` (E12-T02).
|
|
292
|
+
|
|
293
|
+
Sequence `b` is drawn with `jax.random.fold_in(key, b)` on a regular grid of step `nominal_dt`, so the
|
|
294
|
+
result is deterministic per `key` and independent of the other sequences. With `groups` (one name per
|
|
295
|
+
sequence; the model must have `initial.logits` of shape `(G, S_phase1)`) sequence `b` starts from the
|
|
296
|
+
row of its group (`sorted(set(groups))` indexes the rows, as `SequenceBatch.group_names` does) and
|
|
297
|
+
carries `group = groups[b]`. Covariate-free models only.
|
|
298
|
+
|
|
299
|
+
Raises:
|
|
300
|
+
ConfigError: `groups` given for a model without per-group initial distributions (or the wrong
|
|
301
|
+
number of groups), or a model with covariates.
|
|
302
|
+
"""
|
|
303
|
+
from hsmmkit.data.batch import (
|
|
304
|
+
SequenceBatch,
|
|
305
|
+
)
|
|
306
|
+
from hsmmkit.statespace.builders import build_expanded, build_explicit
|
|
307
|
+
|
|
308
|
+
lengths = [int(n) for n in lengths]
|
|
309
|
+
if any(n < 1 for n in lengths):
|
|
310
|
+
raise ConfigError("every sequence length must be >= 1", path="lengths")
|
|
311
|
+
grouped = "initial.logits" in params and params["initial.logits"].ndim == 2
|
|
312
|
+
names: tuple[str, ...] = ()
|
|
313
|
+
if groups is not None:
|
|
314
|
+
if not grouped:
|
|
315
|
+
raise ConfigError("groups need a model with initial_groups: per_group", path="groups")
|
|
316
|
+
if len(groups) != len(lengths):
|
|
317
|
+
raise ConfigError("groups and lengths differ in length", path="groups")
|
|
318
|
+
names = tuple(sorted(set(groups)))
|
|
319
|
+
if len(names) != params["initial.logits"].shape[0]:
|
|
320
|
+
raise ConfigError(
|
|
321
|
+
f"the model has {params['initial.logits'].shape[0]} groups, groups has {len(names)}",
|
|
322
|
+
path="groups",
|
|
323
|
+
)
|
|
324
|
+
elif grouped:
|
|
325
|
+
raise ConfigError("a per_group model needs groups= to simulate", path="groups")
|
|
326
|
+
space = build_explicit(spec) if spec.engine == "explicit" else build_expanded(spec)
|
|
327
|
+
datasets = []
|
|
328
|
+
for b, n in enumerate(lengths):
|
|
329
|
+
theta = params
|
|
330
|
+
if groups is not None:
|
|
331
|
+
theta = {**params, "initial.logits": params["initial.logits"][names.index(groups[b])]}
|
|
332
|
+
ds = simulate_dataset(
|
|
333
|
+
jax.random.fold_in(key, b),
|
|
334
|
+
theta,
|
|
335
|
+
spec,
|
|
336
|
+
space,
|
|
337
|
+
jnp.full((n,), float(nominal_dt)),
|
|
338
|
+
clock=clock,
|
|
339
|
+
nominal_dt=float(nominal_dt),
|
|
340
|
+
)
|
|
341
|
+
datasets.append(dataclasses.replace(ds, group=None if groups is None else str(groups[b])))
|
|
342
|
+
return SequenceBatch(tuple(datasets), (), tuple(str(b) for b in range(len(lengths))))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Interoperability with third-party libraries (lazy imports behind extras)."""
|
hsmmkit/interop/arviz.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""ArviZ output of the Bayesian estimators (E13-T06a, ADR-0024).
|
|
2
|
+
|
|
3
|
+
`to_inference_data` turns draws of constrained parameters into an ArviZ object: a `DataTree` with ArviZ 1.x,
|
|
4
|
+
an `InferenceData` with ArviZ 0.x. Groups: `posterior` (one variable per `ParamSpec` name, dims
|
|
5
|
+
`(chain, draw, <axis names>)`), `sample_stats` (sampler diagnostics) and `log_likelihood` (per sequence).
|
|
6
|
+
ArviZ is imported lazily through `optional_import(..., extra="bayes")`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from hsmmkit.utils.optional import optional_import
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from collections.abc import Mapping
|
|
19
|
+
|
|
20
|
+
__all__ = ["axis_names", "summary_table", "to_inference_data"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_KNOWN = {
|
|
24
|
+
"emission": ("regime", "series"),
|
|
25
|
+
"duration": ("regime", "covariate"),
|
|
26
|
+
"transition.pi_rows": ("memory_row", "target"),
|
|
27
|
+
"transition.a": ("memory_row", "target"),
|
|
28
|
+
"transition.b": ("memory_row", "target", "covariate"),
|
|
29
|
+
"initial.logits": ("group", "state"),
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def axis_names(name: str, shape: tuple[int, ...]) -> list[str]:
|
|
34
|
+
"""Dimension names of the parameter `name` (`regime`, `series`, `memory_row`, `target`, ...).
|
|
35
|
+
|
|
36
|
+
Emission parameters are `(regime, series, ...)`, duration parameters `(regime, covariate)`, jump
|
|
37
|
+
parameters `(memory_row, target[, covariate])`; any other axis is called `<name>_axis<i>`.
|
|
38
|
+
"""
|
|
39
|
+
dotted = name.replace(".", "_")
|
|
40
|
+
known = _KNOWN.get(name) or _KNOWN.get(name.split(".")[0]) or ()
|
|
41
|
+
if name == "initial.logits" and len(shape) == 1:
|
|
42
|
+
known = ("state",)
|
|
43
|
+
return [known[i] if i < len(known) else f"{dotted}_axis{i}" for i in range(len(shape))]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _dims_and_coords(
|
|
47
|
+
posterior: Mapping[str, np.ndarray], coords_extra: Mapping[str, Any]
|
|
48
|
+
) -> tuple[dict[str, list[str]], dict[str, Any]]:
|
|
49
|
+
dims: dict[str, list[str]] = {}
|
|
50
|
+
coords: dict[str, Any] = dict(coords_extra)
|
|
51
|
+
for name, draws in posterior.items():
|
|
52
|
+
shape = tuple(draws.shape[2:])
|
|
53
|
+
names = axis_names(name, shape)
|
|
54
|
+
# a dimension name shared by parameters of different lengths gets a parameter-specific name
|
|
55
|
+
for i, (axis, size) in enumerate(zip(names, shape, strict=True)):
|
|
56
|
+
if axis in coords and len(coords[axis]) != size:
|
|
57
|
+
names[i] = f"{name.replace('.', '_')}_{axis}"
|
|
58
|
+
coords.setdefault(names[i], np.arange(size))
|
|
59
|
+
dims[name] = names
|
|
60
|
+
return dims, coords
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def to_inference_data(
|
|
64
|
+
posterior: Mapping[str, np.ndarray],
|
|
65
|
+
sample_stats: Mapping[str, np.ndarray] | None = None,
|
|
66
|
+
log_likelihood: np.ndarray | None = None,
|
|
67
|
+
*,
|
|
68
|
+
sequence_ids: list[str] | None = None,
|
|
69
|
+
attrs: dict[str, Any] | None = None,
|
|
70
|
+
extra_groups: Mapping[str, Mapping[str, np.ndarray]] | None = None,
|
|
71
|
+
) -> Any: # noqa: ANN401
|
|
72
|
+
"""Draws (`(chain, draw, *shape)` arrays per parameter name) as an ArviZ object.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
posterior: constrained parameters by `ParamSpec` name.
|
|
76
|
+
sample_stats: `(chain, draw)` sampler diagnostics (`diverging`, `tree_depth`, `energy`, ...).
|
|
77
|
+
log_likelihood: `(chain, draw, n_sequences)` per-sequence log-likelihoods.
|
|
78
|
+
sequence_ids: coordinate of the `sequence` dimension.
|
|
79
|
+
attrs: free-form attributes (versions, seed, ...).
|
|
80
|
+
extra_groups: further groups, e.g. `path_samples`: `{"regime_path": (chain, draw, sequence, time)}`.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
ImportError: ArviZ is not installed (`pip install 'hsmmkit[bayes]'`).
|
|
84
|
+
"""
|
|
85
|
+
az = optional_import("arviz", extra="bayes")
|
|
86
|
+
post = {k: np.asarray(v) for k, v in posterior.items()}
|
|
87
|
+
dims, coords = _dims_and_coords(post, {})
|
|
88
|
+
groups: dict[str, Any] = {"posterior": post}
|
|
89
|
+
if sample_stats:
|
|
90
|
+
groups["sample_stats"] = {k: np.asarray(v) for k, v in sample_stats.items()}
|
|
91
|
+
if log_likelihood is not None:
|
|
92
|
+
ll = np.asarray(log_likelihood)
|
|
93
|
+
groups["log_likelihood"] = {"loglik": ll}
|
|
94
|
+
dims["loglik"] = ["sequence"]
|
|
95
|
+
coords["sequence"] = np.asarray(sequence_ids if sequence_ids is not None else range(ll.shape[-1]))
|
|
96
|
+
for group, variables in (extra_groups or {}).items():
|
|
97
|
+
groups[group] = {k: np.asarray(v) for k, v in variables.items()}
|
|
98
|
+
for k, v in variables.items():
|
|
99
|
+
dims[k] = ["sequence", "time"][: np.ndim(v) - 2]
|
|
100
|
+
coords.setdefault("time", np.arange(np.shape(v)[-1]))
|
|
101
|
+
coords.setdefault(
|
|
102
|
+
"sequence", np.asarray(sequence_ids if sequence_ids is not None else range(np.shape(v)[2]))
|
|
103
|
+
)
|
|
104
|
+
if int(str(az.__version__).split(".")[0]) < 1: # ArviZ 0.x
|
|
105
|
+
data = az.from_dict(**groups, dims=dims, coords=coords, attrs=attrs or {})
|
|
106
|
+
else: # ArviZ 1.x (DataTree)
|
|
107
|
+
data = az.from_dict(groups, dims=dims, coords=coords, attrs=attrs or {})
|
|
108
|
+
return data
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def summary_table(idata: Any) -> Any: # noqa: ANN401
|
|
112
|
+
"""`az.summary` of the posterior (a pandas DataFrame with `r_hat`, `ess_bulk`, `ess_tail`)."""
|
|
113
|
+
az = optional_import("arviz", extra="bayes")
|
|
114
|
+
return az.summary(idata)
|