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,144 @@
|
|
|
1
|
+
"""Poisson emission for counts: `y_tm | i ~ Poisson(exp(eta_im + gamma_im . z_t) s(dt))` (E11-T04).
|
|
2
|
+
|
|
3
|
+
`s(dt) = dt` with `scale_by_dt` (the default: `dt` is the exposure), else 1. The rate per unit exposure is
|
|
4
|
+
`lambda = exp(eta)`; `params.rate.init` is given in natural units and converted to `eta = log(rate)`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import TYPE_CHECKING, Literal
|
|
11
|
+
|
|
12
|
+
import jax
|
|
13
|
+
import jax.numpy as jnp
|
|
14
|
+
import jax.scipy.special as jsp
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from hsmmkit.model.conjugate import GammaConjugate
|
|
18
|
+
from hsmmkit.model.emission._discrete import (
|
|
19
|
+
CLIP,
|
|
20
|
+
DiscreteBase,
|
|
21
|
+
check_free,
|
|
22
|
+
eta_spec,
|
|
23
|
+
gamma_spec,
|
|
24
|
+
natural_init,
|
|
25
|
+
safe_ratio,
|
|
26
|
+
)
|
|
27
|
+
from hsmmkit.model.emission.base import Support
|
|
28
|
+
from hsmmkit.model.params.spec import ParamSpec
|
|
29
|
+
from hsmmkit.plugins import register
|
|
30
|
+
from hsmmkit.utils.errors import ConfigError
|
|
31
|
+
from hsmmkit.utils.typing import Array
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from hsmmkit.config.schema import EmissionCfg
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@register("emission", "poisson")
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class PoissonFamily(DiscreteBase):
|
|
40
|
+
"""Per-regime, per-series Poisson counts with a log link and an optional exposure `dt`."""
|
|
41
|
+
|
|
42
|
+
name: str = "poisson"
|
|
43
|
+
native_time: Literal["continuous", "discrete"] = field(default="discrete", init=False)
|
|
44
|
+
support: Support = "count"
|
|
45
|
+
scale_by_dt: bool = True
|
|
46
|
+
mean_idx: tuple[int, ...] = ()
|
|
47
|
+
|
|
48
|
+
def __post_init__(self) -> None:
|
|
49
|
+
"""`native_time` follows `scale_by_dt`."""
|
|
50
|
+
object.__setattr__(self, "native_time", "continuous" if self.scale_by_dt else "discrete")
|
|
51
|
+
|
|
52
|
+
def param_specs(self, n_states: int, n_series: int, cov_names: tuple[str, ...]) -> tuple[ParamSpec, ...]:
|
|
53
|
+
"""`emission.eta (N, M)` (rate 1 per unit exposure)."""
|
|
54
|
+
del cov_names
|
|
55
|
+
return (eta_spec(n_states, n_series, None),)
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_config(
|
|
59
|
+
cls, cfg: EmissionCfg, n_states: int, n_series: int, cov_names: tuple[str, ...]
|
|
60
|
+
) -> tuple[PoissonFamily, tuple[ParamSpec, ...]]:
|
|
61
|
+
"""`params.rate` (natural units) -> `eta`; covariates under `covariates.mean`."""
|
|
62
|
+
if "rate" not in cfg.params:
|
|
63
|
+
raise ConfigError("poisson emission requires params.rate", path="model.emission.params.rate")
|
|
64
|
+
check_free(cfg.params["rate"], "model.emission.params.rate")
|
|
65
|
+
rate = natural_init(cfg.params["rate"].init, n_states, n_series, "model.emission.params.rate.init")
|
|
66
|
+
if rate is not None and bool(np.any(rate <= 0)):
|
|
67
|
+
raise ConfigError("rates must be positive", path="model.emission.params.rate.init")
|
|
68
|
+
try:
|
|
69
|
+
idx = tuple(cov_names.index(c) for c in cfg.covariates.mean)
|
|
70
|
+
except ValueError as exc:
|
|
71
|
+
raise ConfigError(str(exc), path="model.emission.covariates.mean") from exc
|
|
72
|
+
family = cls(scale_by_dt=True if cfg.scale_by_dt is None else bool(cfg.scale_by_dt), mean_idx=idx)
|
|
73
|
+
specs = [eta_spec(n_states, n_series, None if rate is None else np.log(rate))]
|
|
74
|
+
if idx:
|
|
75
|
+
specs.append(gamma_spec(n_states, n_series, len(idx)))
|
|
76
|
+
return family, tuple(specs)
|
|
77
|
+
|
|
78
|
+
def _rate(self, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
79
|
+
"""`(T, N, M)` Poisson means `exp(eta_t) s(dt)`."""
|
|
80
|
+
lam = jnp.exp(self._linear(theta, z, dt.shape[0]))
|
|
81
|
+
return lam * dt[:, None, None] if self.scale_by_dt else lam
|
|
82
|
+
|
|
83
|
+
def log_prob_series(self, y: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
84
|
+
"""`(T, N, M)` log-pmf `y log(lambda) - lambda - log(y!)`."""
|
|
85
|
+
lam = self._rate(dt, theta, z)
|
|
86
|
+
yy = y[:, None, :]
|
|
87
|
+
return yy * jnp.log(lam) - lam - jsp.gammaln(yy + 1.0)
|
|
88
|
+
|
|
89
|
+
def log_prob(self, y: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
90
|
+
"""`(T, N)` log-pmf summed over the series."""
|
|
91
|
+
return jnp.sum(self.log_prob_series(y, dt, theta, z), axis=-1)
|
|
92
|
+
|
|
93
|
+
def cdf(self, y: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
94
|
+
"""`(T, N, M)` `P(Y <= y)` (regularized upper incomplete gamma)."""
|
|
95
|
+
lam = self._rate(dt, theta, z)
|
|
96
|
+
out: Array = jsp.gammaincc(jnp.floor(y[:, None, :]) + 1.0, lam)
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
def sample(self, key: Array, regime: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
100
|
+
"""`(T, M)` Poisson draws from the active regime."""
|
|
101
|
+
lam = self._rate(dt, theta, z)[jnp.arange(dt.shape[0]), regime, :]
|
|
102
|
+
return jax.random.poisson(key, lam).astype(lam.dtype)
|
|
103
|
+
|
|
104
|
+
def moments(
|
|
105
|
+
self, regime: Array, dt: Array, theta: dict[str, Array], z: Array | None
|
|
106
|
+
) -> tuple[Array, Array]:
|
|
107
|
+
"""Mean = variance = `lambda`."""
|
|
108
|
+
lam = self._rate(dt, theta, z)[jnp.arange(dt.shape[0]), regime, :]
|
|
109
|
+
return lam, lam
|
|
110
|
+
|
|
111
|
+
def sufficient_stats(
|
|
112
|
+
self, y: Array, dt: Array, gamma: Array, z: Array | None = None
|
|
113
|
+
) -> dict[str, Array] | None:
|
|
114
|
+
"""`w_s = sum gamma s`, `wy = sum gamma y` (`None` with covariate links: ECM)."""
|
|
115
|
+
del z
|
|
116
|
+
if self.mean_idx:
|
|
117
|
+
return None
|
|
118
|
+
s = dt if self.scale_by_dt else jnp.ones_like(dt)
|
|
119
|
+
return {"w_s": jnp.sum(gamma * s[:, None], axis=0), "wy": gamma.T @ y}
|
|
120
|
+
|
|
121
|
+
def m_step(self, stats: object) -> dict[str, Array] | None:
|
|
122
|
+
"""`lambda = sum gamma y / sum gamma s` (clipped to `>= 1e-12`), returned as `eta = log lambda`."""
|
|
123
|
+
if not isinstance(stats, dict):
|
|
124
|
+
return None
|
|
125
|
+
lam = safe_ratio(stats["wy"], stats["w_s"][:, None])
|
|
126
|
+
return {"emission.eta": jnp.log(jnp.maximum(lam, CLIP))}
|
|
127
|
+
|
|
128
|
+
def conjugate_prior(self) -> GammaConjugate | None:
|
|
129
|
+
"""`Gamma(1, 1)` on the rate per unit exposure (`None` with covariate links)."""
|
|
130
|
+
return None if self.mean_idx else GammaConjugate()
|
|
131
|
+
|
|
132
|
+
def expected_log_prob(self, y: Array, dt: Array, q_theta: object, z: Array | None) -> Array | None:
|
|
133
|
+
"""`E_q[log Poisson(y | lambda s)]`, `(T, N)`, under `Gamma(a, b)` rates (`a`, `b`: `(N, M)`)."""
|
|
134
|
+
if self.mean_idx or not isinstance(q_theta, dict):
|
|
135
|
+
return None
|
|
136
|
+
del z
|
|
137
|
+
log_rate = jsp.digamma(q_theta["a"]) - jnp.log(q_theta["b"]) # (N, M)
|
|
138
|
+
rate = q_theta["a"] / q_theta["b"]
|
|
139
|
+
s = dt[:, None, None] if self.scale_by_dt else 1.0
|
|
140
|
+
yy = y[:, None, :]
|
|
141
|
+
out: Array = jnp.sum(
|
|
142
|
+
yy * (log_rate[None] + jnp.log(s)) - rate[None] * s - jsp.gammaln(yy + 1.0), axis=-1
|
|
143
|
+
)
|
|
144
|
+
return out
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""`ProductEmission`: independent per-series emissions sharing one regime process (E9-T01, FR-M12).
|
|
2
|
+
|
|
3
|
+
For `M > 1` series the joint emission density given regime `i` is the product of the series' own
|
|
4
|
+
densities, `f_i(y_t) = prod_m f_i^{(m)}(y_{t,m})`, so `log f_i = sum_m log f_i^{(m)}`. A series that is not
|
|
5
|
+
observed at step `t` (`mask[t, m] == False`) contributes `0` to that sum while the other series keep
|
|
6
|
+
their contribution (the engines' older rule dropped the whole step). The wrapped family supplies the
|
|
7
|
+
per-series densities (`log_prob_series`, shape `(T, N, M)`); GBM and Student-t already evaluate every
|
|
8
|
+
series independently, so the wrapper adds the masking and the handling of parameters shared across
|
|
9
|
+
series (`model.emission.per_series: false`, spec shape `(N,)` instead of `(N, M)`).
|
|
10
|
+
|
|
11
|
+
Everything else (`param_specs`, `cdf`, `sample`, the carry hooks) is delegated to the base family;
|
|
12
|
+
`n_series == 1` models keep the bare family (`model/build.py`), so `M = 1` results are untouched.
|
|
13
|
+
Per-series *family* choice (one family per series) is a follow-up: it needs per-series parameter names.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import dataclasses
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast
|
|
21
|
+
|
|
22
|
+
import jax
|
|
23
|
+
import jax.numpy as jnp
|
|
24
|
+
|
|
25
|
+
from hsmmkit.model.emission.base import BaseEmission, EmissionFamily, Support
|
|
26
|
+
from hsmmkit.model.params import ParamSpec
|
|
27
|
+
from hsmmkit.plugins import REGISTRY, register
|
|
28
|
+
from hsmmkit.utils.errors import ConfigError
|
|
29
|
+
from hsmmkit.utils.typing import Array
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from hsmmkit.config.schema import EmissionCfg
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class ProductEmission(BaseEmission):
|
|
37
|
+
"""Product of independent per-series emission densities over a shared regime (`n_series` series).
|
|
38
|
+
|
|
39
|
+
Attributes:
|
|
40
|
+
base: the wrapped family; it must provide `log_prob_series` and `series_param_names`
|
|
41
|
+
(GBM and Student-t do).
|
|
42
|
+
n_series: number of series `M`.
|
|
43
|
+
name, native_time, support, scale_by_dt: copied from `base` (build with `ProductEmission.of`).
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
base: Any
|
|
47
|
+
n_series: int
|
|
48
|
+
name: str
|
|
49
|
+
native_time: Literal["continuous", "discrete"]
|
|
50
|
+
support: Support
|
|
51
|
+
scale_by_dt: bool
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def of(cls, base: EmissionFamily, n_series: int) -> ProductEmission:
|
|
55
|
+
"""Wrap `base`, copying its identity attributes."""
|
|
56
|
+
return cls(
|
|
57
|
+
base=base,
|
|
58
|
+
n_series=n_series,
|
|
59
|
+
name=base.name,
|
|
60
|
+
native_time=base.native_time,
|
|
61
|
+
support=base.support,
|
|
62
|
+
scale_by_dt=base.scale_by_dt,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def _per_series_theta(self, theta: dict[str, Array]) -> dict[str, Array]:
|
|
66
|
+
"""`theta` with series-shared `(N,)` parameters tiled to `(N, M)` (unchanged when per series)."""
|
|
67
|
+
names: tuple[str, ...] = self.base.series_param_names
|
|
68
|
+
return {
|
|
69
|
+
k: jnp.tile(v[:, None], (1, self.n_series)) if k in names and v.ndim == 1 else v
|
|
70
|
+
for k, v in theta.items()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
# --- protocol: parameter layout ---------------------------------------------------------
|
|
74
|
+
|
|
75
|
+
def param_specs(self, n_states: int, n_series: int, cov_names: tuple[str, ...]) -> tuple[ParamSpec, ...]:
|
|
76
|
+
"""The base family's specs (a series axis `(N, M)` where the family has one)."""
|
|
77
|
+
return cast("tuple[ParamSpec, ...]", self.base.param_specs(n_states, n_series, cov_names))
|
|
78
|
+
|
|
79
|
+
# --- protocol: numerics ------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
def log_prob_series(self, y: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
82
|
+
"""`(T, N, M)` per-regime, per-series log-density."""
|
|
83
|
+
return cast("Array", self.base.log_prob_series(y, dt, self._per_series_theta(theta), z))
|
|
84
|
+
|
|
85
|
+
def log_prob(self, y: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
86
|
+
"""`(T, N)` log-density summed over all series (no mask: every series observed)."""
|
|
87
|
+
return jnp.sum(self.log_prob_series(y, dt, theta, z), axis=-1)
|
|
88
|
+
|
|
89
|
+
def log_prob_masked(
|
|
90
|
+
self, y: Array, mask: Array, dt: Array, theta: dict[str, Array], z: Array | None
|
|
91
|
+
) -> Array:
|
|
92
|
+
"""`(T, N)` log-density where only observed series contribute: `sum_m mask[t, m] * log f^{(m)}`.
|
|
93
|
+
|
|
94
|
+
`y` must be finite at masked entries (the engines pass `where(mask, y, 0)`), so the unselected
|
|
95
|
+
branch of the `where` is finite and its gradient cannot turn into NaN (CLAUDE.md §5).
|
|
96
|
+
"""
|
|
97
|
+
per_series = self.log_prob_series(y, dt, theta, z) # (T, N, M)
|
|
98
|
+
return jnp.sum(jnp.where(mask[:, None, :], per_series, 0.0), axis=-1)
|
|
99
|
+
|
|
100
|
+
def cdf(self, y: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
101
|
+
"""`(T, N, M)` per-regime, per-series predictive CDF."""
|
|
102
|
+
return cast("Array", self.base.cdf(y, dt, self._per_series_theta(theta), z))
|
|
103
|
+
|
|
104
|
+
def sample(self, key: Array, regime: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
105
|
+
"""`(T, M)` samples: one independent draw per series from the active regime's density."""
|
|
106
|
+
return cast("Array", self.base.sample(key, regime, dt, self._per_series_theta(theta), z))
|
|
107
|
+
|
|
108
|
+
def moments(
|
|
109
|
+
self, regime: Array, dt: Array, theta: dict[str, Array], z: Array | None
|
|
110
|
+
) -> tuple[Array, Array] | None:
|
|
111
|
+
"""Delegated to the base family (independent series: the moments are per series)."""
|
|
112
|
+
return cast(
|
|
113
|
+
"tuple[Array, Array] | None", self.base.moments(regime, dt, self._per_series_theta(theta), z)
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def init_carry(self) -> object:
|
|
117
|
+
"""No path-dependent state (the base families have none)."""
|
|
118
|
+
return self.base.init_carry()
|
|
119
|
+
|
|
120
|
+
def step_carry(self, carry: object, y_t: Array, theta: dict[str, Array]) -> object:
|
|
121
|
+
"""Delegated to the base family (identity for GBM / Student-t)."""
|
|
122
|
+
return self.base.step_carry(carry, y_t, theta)
|
|
123
|
+
|
|
124
|
+
def sufficient_stats(self, y: Array, dt: Array, gamma: Array, z: Array | None = None) -> object | None:
|
|
125
|
+
"""Delegated to the base family."""
|
|
126
|
+
return cast("object | None", self.base.sufficient_stats(y, dt, gamma, z))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass(frozen=True)
|
|
130
|
+
class BlockPrior:
|
|
131
|
+
"""Product of the blocks' conjugate priors: `update(stats)` updates each block with its own statistics."""
|
|
132
|
+
|
|
133
|
+
priors: tuple[Any, ...]
|
|
134
|
+
|
|
135
|
+
def update(self, stats: tuple[Any, ...]) -> tuple[Any, ...]:
|
|
136
|
+
"""Per-block posterior hyperparameters."""
|
|
137
|
+
return tuple(p.update(s) for p, s in zip(self.priors, stats, strict=True))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@register("emission", "product")
|
|
141
|
+
@dataclass(frozen=True)
|
|
142
|
+
class BlockProductEmission(BaseEmission):
|
|
143
|
+
"""Independent **blocks** of series, each block any registered family (E11-T08, FR-M12, FR-EM07).
|
|
144
|
+
|
|
145
|
+
`f_i(y_t) = prod_b f_i^{(b)}(y_t[cols_b])`; the blocks partition the `M` observation columns. A block of
|
|
146
|
+
one series is the bare family; a block of several series is the family itself when it is joint
|
|
147
|
+
(full-covariance Gaussian, multivariate Student-t, `msar`, a mixture) and the independent
|
|
148
|
+
`ProductEmission` of the series otherwise. Parameters are prefixed `emission.b{b}.<name>`.
|
|
149
|
+
|
|
150
|
+
Masking: a joint block drops its whole row when any of its series is unobserved (marginalizing a partially
|
|
151
|
+
missing joint Gaussian is backlog); an independent block keeps the other series' contribution (E9-T01).
|
|
152
|
+
|
|
153
|
+
Attributes:
|
|
154
|
+
blocks: the block families (each for the block's own series count).
|
|
155
|
+
columns: the observation columns of each block (indices into `observation_columns`).
|
|
156
|
+
n_series: `M`.
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
blocks: tuple[Any, ...]
|
|
160
|
+
columns: tuple[tuple[int, ...], ...]
|
|
161
|
+
n_series: int
|
|
162
|
+
name: str = "product"
|
|
163
|
+
native_time: Literal["continuous", "discrete"] = "discrete"
|
|
164
|
+
support: Support = "real"
|
|
165
|
+
scale_by_dt: bool = False
|
|
166
|
+
|
|
167
|
+
joint: ClassVar[bool] = True
|
|
168
|
+
"""Handles its own per-block masking: `model/build.py` does not wrap it in a `ProductEmission`."""
|
|
169
|
+
|
|
170
|
+
@classmethod
|
|
171
|
+
def of(cls, blocks: tuple[Any, ...], columns: tuple[tuple[int, ...], ...]) -> BlockProductEmission:
|
|
172
|
+
"""Assemble from the block families and their columns (a partition of `0..M-1`)."""
|
|
173
|
+
n_series = sum(len(c) for c in columns)
|
|
174
|
+
if sorted(i for c in columns for i in c) != list(range(n_series)):
|
|
175
|
+
raise ConfigError(
|
|
176
|
+
f"block columns must partition the columns 0..{n_series - 1}, got {list(columns)}",
|
|
177
|
+
path="model.emission.blocks",
|
|
178
|
+
)
|
|
179
|
+
supports = [b.support for b in blocks]
|
|
180
|
+
return cls(
|
|
181
|
+
blocks=blocks,
|
|
182
|
+
columns=columns,
|
|
183
|
+
n_series=n_series,
|
|
184
|
+
native_time="continuous" if any(b.native_time == "continuous" for b in blocks) else "discrete",
|
|
185
|
+
support=next((s for s in supports if s != "real"), "real"),
|
|
186
|
+
scale_by_dt=all(b.scale_by_dt for b in blocks),
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
@property
|
|
190
|
+
def series_support(self) -> tuple[Support, ...]:
|
|
191
|
+
"""Support of each observation column."""
|
|
192
|
+
out: list[Support] = ["real"] * self.n_series
|
|
193
|
+
for block, cols in zip(self.blocks, self.columns, strict=True):
|
|
194
|
+
for c in cols:
|
|
195
|
+
out[c] = block.support
|
|
196
|
+
return tuple(out)
|
|
197
|
+
|
|
198
|
+
# --- parameter layout ---------------------------------------------------------------------------
|
|
199
|
+
|
|
200
|
+
@staticmethod
|
|
201
|
+
def _prefix(b: int) -> str:
|
|
202
|
+
return f"emission.b{b}."
|
|
203
|
+
|
|
204
|
+
def _block_theta(self, theta: dict[str, Array], b: int) -> dict[str, Array]:
|
|
205
|
+
p = self._prefix(b)
|
|
206
|
+
return {f"emission.{k[len(p) :]}": v for k, v in theta.items() if k.startswith(p)}
|
|
207
|
+
|
|
208
|
+
@staticmethod
|
|
209
|
+
def _prefixed(specs: tuple[ParamSpec, ...], b: int) -> tuple[ParamSpec, ...]:
|
|
210
|
+
return tuple(
|
|
211
|
+
dataclasses.replace(sp, name=BlockProductEmission._prefix(b) + sp.name.removeprefix("emission."))
|
|
212
|
+
for sp in specs
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
def param_specs(self, n_states: int, n_series: int, cov_names: tuple[str, ...]) -> tuple[ParamSpec, ...]:
|
|
216
|
+
"""The blocks' specs, prefixed `emission.b{b}.`."""
|
|
217
|
+
del n_series
|
|
218
|
+
out: tuple[ParamSpec, ...] = ()
|
|
219
|
+
for b, (block, cols) in enumerate(zip(self.blocks, self.columns, strict=True)):
|
|
220
|
+
out += self._prefixed(tuple(block.param_specs(n_states, len(cols), cov_names)), b)
|
|
221
|
+
return out
|
|
222
|
+
|
|
223
|
+
@classmethod
|
|
224
|
+
def from_config(
|
|
225
|
+
cls, cfg: EmissionCfg, n_states: int, n_series: int, cov_names: tuple[str, ...]
|
|
226
|
+
) -> tuple[BlockProductEmission, tuple[ParamSpec, ...]]:
|
|
227
|
+
"""`family: product`, `blocks: [{family, columns, params, ...}]` -> family and prefixed specs."""
|
|
228
|
+
if not cfg.blocks:
|
|
229
|
+
raise ConfigError("family 'product' requires model.emission.blocks", path="model.emission.blocks")
|
|
230
|
+
blocks: list[Any] = []
|
|
231
|
+
columns: list[tuple[int, ...]] = []
|
|
232
|
+
specs: list[ParamSpec] = []
|
|
233
|
+
for b, bcfg in enumerate(cfg.blocks):
|
|
234
|
+
path = f"model.emission.blocks[{b}]"
|
|
235
|
+
if bcfg.columns is None:
|
|
236
|
+
raise ConfigError("every block needs its `columns`", path=f"{path}.columns")
|
|
237
|
+
if any(isinstance(c, str) for c in bcfg.columns):
|
|
238
|
+
raise ConfigError(
|
|
239
|
+
"block columns are indices into observation_columns (names are not supported yet)",
|
|
240
|
+
path=f"{path}.columns",
|
|
241
|
+
)
|
|
242
|
+
cols = tuple(int(c) for c in bcfg.columns)
|
|
243
|
+
if bcfg.family == "msar":
|
|
244
|
+
raise ConfigError(
|
|
245
|
+
"an msar emission cannot be a product block yet (own lags, time-step state space)",
|
|
246
|
+
path=f"{path}.family",
|
|
247
|
+
)
|
|
248
|
+
if bcfg.family == "product" or not REGISTRY.has("emission", bcfg.family):
|
|
249
|
+
raise ConfigError(f"unknown block family {bcfg.family!r}", path=f"{path}.family")
|
|
250
|
+
family, block_specs = REGISTRY.get("emission", bcfg.family).from_config(
|
|
251
|
+
bcfg, n_states, len(cols), cov_names
|
|
252
|
+
)
|
|
253
|
+
if len(cols) > 1 and not getattr(family, "joint", False):
|
|
254
|
+
family = ProductEmission.of(family, len(cols))
|
|
255
|
+
blocks.append(family)
|
|
256
|
+
columns.append(cols)
|
|
257
|
+
specs.extend(cls._prefixed(tuple(block_specs), b))
|
|
258
|
+
product = cls.of(tuple(blocks), tuple(columns))
|
|
259
|
+
if product.n_series != n_series:
|
|
260
|
+
raise ConfigError(
|
|
261
|
+
f"the blocks cover {product.n_series} columns but the data has {n_series} series",
|
|
262
|
+
path="model.emission.blocks",
|
|
263
|
+
)
|
|
264
|
+
return product, tuple(specs)
|
|
265
|
+
|
|
266
|
+
# --- numerics ---------------------------------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
def _y(self, y: Array, b: int) -> Array:
|
|
269
|
+
return y[:, jnp.asarray(self.columns[b])]
|
|
270
|
+
|
|
271
|
+
def log_prob(self, y: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
272
|
+
"""`(T, N)` sum of the blocks' log-densities (every series observed)."""
|
|
273
|
+
total = 0.0
|
|
274
|
+
for b, block in enumerate(self.blocks):
|
|
275
|
+
total = total + block.log_prob(self._y(y, b), dt, self._block_theta(theta, b), z)
|
|
276
|
+
return cast("Array", total)
|
|
277
|
+
|
|
278
|
+
def log_prob_masked(
|
|
279
|
+
self, y: Array, mask: Array, dt: Array, theta: dict[str, Array], z: Array | None
|
|
280
|
+
) -> Array:
|
|
281
|
+
"""`(T, N)`: joint blocks drop a row with any unobserved series, independent blocks keep the rest.
|
|
282
|
+
|
|
283
|
+
`y` must be finite at masked entries (the engines pass `where(mask, y, 0)`), as for `ProductEmission`.
|
|
284
|
+
"""
|
|
285
|
+
total = 0.0
|
|
286
|
+
for b, block in enumerate(self.blocks):
|
|
287
|
+
yb, mb, tb = self._y(y, b), self._y(mask, b), self._block_theta(theta, b)
|
|
288
|
+
if hasattr(block, "log_prob_masked"):
|
|
289
|
+
ll = block.log_prob_masked(yb, mb, dt, tb, z)
|
|
290
|
+
else:
|
|
291
|
+
ll = jnp.where(jnp.all(mb, axis=-1)[:, None], block.log_prob(yb, dt, tb, z), 0.0)
|
|
292
|
+
total = total + ll
|
|
293
|
+
return cast("Array", total)
|
|
294
|
+
|
|
295
|
+
def cdf(self, y: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
296
|
+
"""`(T, N, M)`: each block's CDFs placed at its columns."""
|
|
297
|
+
out = None
|
|
298
|
+
for b, block in enumerate(self.blocks):
|
|
299
|
+
c = block.cdf(self._y(y, b), dt, self._block_theta(theta, b), z)
|
|
300
|
+
if out is None:
|
|
301
|
+
out = jnp.zeros((c.shape[0], c.shape[1], self.n_series), dtype=c.dtype)
|
|
302
|
+
out = out.at[:, :, jnp.asarray(self.columns[b])].set(c)
|
|
303
|
+
assert out is not None
|
|
304
|
+
return out
|
|
305
|
+
|
|
306
|
+
def sample(self, key: Array, regime: Array, dt: Array, theta: dict[str, Array], z: Array | None) -> Array:
|
|
307
|
+
"""`(T, M)`: independent block draws (one key per block) placed at their columns."""
|
|
308
|
+
keys = jax.random.split(key, len(self.blocks))
|
|
309
|
+
out = jnp.zeros((dt.shape[0], self.n_series))
|
|
310
|
+
for b, block in enumerate(self.blocks):
|
|
311
|
+
draw = block.sample(keys[b], regime, dt, self._block_theta(theta, b), z)
|
|
312
|
+
out = out.at[:, jnp.asarray(self.columns[b])].set(draw.astype(out.dtype))
|
|
313
|
+
return out
|
|
314
|
+
|
|
315
|
+
def moments(
|
|
316
|
+
self, regime: Array, dt: Array, theta: dict[str, Array], z: Array | None
|
|
317
|
+
) -> tuple[Array, Array] | None:
|
|
318
|
+
"""Per-column mean and variance (`None` if any block has none)."""
|
|
319
|
+
mean = jnp.zeros((dt.shape[0], self.n_series))
|
|
320
|
+
var = jnp.zeros((dt.shape[0], self.n_series))
|
|
321
|
+
for b, block in enumerate(self.blocks):
|
|
322
|
+
m = block.moments(regime, dt, self._block_theta(theta, b), z)
|
|
323
|
+
if m is None:
|
|
324
|
+
return None
|
|
325
|
+
idx = jnp.asarray(self.columns[b])
|
|
326
|
+
mean, var = mean.at[:, idx].set(m[0]), var.at[:, idx].set(m[1])
|
|
327
|
+
return mean, var
|
|
328
|
+
|
|
329
|
+
def init_carry(self) -> object:
|
|
330
|
+
"""No path-dependent state (blocks with a recurrent emission are not supported)."""
|
|
331
|
+
return None
|
|
332
|
+
|
|
333
|
+
def step_carry(self, carry: object, y_t: Array, theta: dict[str, Array]) -> object:
|
|
334
|
+
"""Identity."""
|
|
335
|
+
del y_t, theta
|
|
336
|
+
return carry
|
|
337
|
+
|
|
338
|
+
# --- estimation hooks -----------------------------------------------------------------------------
|
|
339
|
+
|
|
340
|
+
def sufficient_stats(self, y: Array, dt: Array, gamma: Array, z: Array | None = None) -> tuple[Any, ...]:
|
|
341
|
+
"""The tuple of the blocks' statistics (a block without any has `None`)."""
|
|
342
|
+
return tuple(
|
|
343
|
+
block.sufficient_stats(self._y(y, b), dt, gamma, z) for b, block in enumerate(self.blocks)
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
def m_step_partial(self, stats: object) -> tuple[dict[str, Array] | None, ...]:
|
|
347
|
+
"""Per block: its (prefixed) closed-form update, or `None` (that block needs ECM)."""
|
|
348
|
+
assert isinstance(stats, tuple)
|
|
349
|
+
out: list[dict[str, Array] | None] = []
|
|
350
|
+
for b, (block, st) in enumerate(zip(self.blocks, stats, strict=True)):
|
|
351
|
+
hat = None if st is None else block.m_step(st)
|
|
352
|
+
out.append(
|
|
353
|
+
None
|
|
354
|
+
if hat is None
|
|
355
|
+
else {self._prefix(b) + k.removeprefix("emission."): v for k, v in hat.items()}
|
|
356
|
+
)
|
|
357
|
+
return tuple(out)
|
|
358
|
+
|
|
359
|
+
def m_step(self, stats: object) -> dict[str, Array] | None:
|
|
360
|
+
"""All blocks' updates merged, or `None` if any block has no closed form."""
|
|
361
|
+
parts = self.m_step_partial(stats)
|
|
362
|
+
if any(p is None for p in parts):
|
|
363
|
+
return None
|
|
364
|
+
return {k: v for p in parts if p is not None for k, v in p.items()}
|
|
365
|
+
|
|
366
|
+
def conjugate_prior(self) -> BlockPrior | None:
|
|
367
|
+
"""The product of the blocks' priors if every block has one."""
|
|
368
|
+
priors = tuple(block.conjugate_prior() for block in self.blocks)
|
|
369
|
+
return None if any(p is None for p in priors) else BlockPrior(priors)
|
|
370
|
+
|
|
371
|
+
# --- state relabelling ----------------------------------------------------------------------------
|
|
372
|
+
|
|
373
|
+
def default_sort_name(self, theta: dict[str, Array]) -> str | None:
|
|
374
|
+
"""The parameter that orders the states (`post_sort_states`): first scale-like of a plain block."""
|
|
375
|
+
for b, block in enumerate(self.blocks):
|
|
376
|
+
if hasattr(block, "n_components"):
|
|
377
|
+
continue
|
|
378
|
+
for base in ("scale", "sigma", "s", "chol", "eta"):
|
|
379
|
+
name = f"{self._prefix(b)}{base}"
|
|
380
|
+
if name in theta:
|
|
381
|
+
return name
|
|
382
|
+
return None
|
|
383
|
+
|
|
384
|
+
def permute_state_axis(self, name: str, value: Array, perm: Array) -> Array:
|
|
385
|
+
"""Relabel the states of one parameter; delegated to the owning block when it has a hook."""
|
|
386
|
+
b = int(name.split(".")[1][1:])
|
|
387
|
+
block = self.blocks[b]
|
|
388
|
+
hook = getattr(block, "permute_state_axis", None)
|
|
389
|
+
local = "emission." + name.split(".", 2)[2]
|
|
390
|
+
return value[perm] if hook is None else cast("Array", hook(local, value, perm))
|