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,307 @@
|
|
|
1
|
+
"""`ParamManager`: maps the flat unconstrained vector `u` to the constrained pytree `theta`.
|
|
2
|
+
|
|
3
|
+
`ParamManager` is a plain (non-pytree) Python object built once from a tuple of `ParamSpec`s; it
|
|
4
|
+
is meant to be captured by closure inside jitted functions (`unflatten`/`flatten`/`log_det_jac`/
|
|
5
|
+
`log_prior` are ordinary methods that trace to JAX ops parameterized by the manager's static,
|
|
6
|
+
Python-level layout plan -- there is no need to register it as a pytree or make it hashable for
|
|
7
|
+
`jax.jit` to work, since it is never itself passed as a traced argument).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
|
|
15
|
+
import jax.numpy as jnp
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from hsmmkit.model.params.bijectors import (
|
|
19
|
+
Bijector,
|
|
20
|
+
CholeskyLowerBijector,
|
|
21
|
+
IdentityBijector,
|
|
22
|
+
IncreasingBijector,
|
|
23
|
+
IntervalBijector,
|
|
24
|
+
NuGt2Bijector,
|
|
25
|
+
PmfBijector,
|
|
26
|
+
PositiveBijector,
|
|
27
|
+
SimplexRefBijector,
|
|
28
|
+
)
|
|
29
|
+
from hsmmkit.model.params.spec import Mode, ParamSpec
|
|
30
|
+
from hsmmkit.utils.errors import ConfigError
|
|
31
|
+
from hsmmkit.utils.typing import Array
|
|
32
|
+
|
|
33
|
+
Params = dict[str, Array]
|
|
34
|
+
|
|
35
|
+
_FIXED: Mode = "fixed"
|
|
36
|
+
_TIED: Mode = "tied"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _base_bijector(spec: ParamSpec) -> Bijector:
|
|
40
|
+
if spec.domain == "real":
|
|
41
|
+
return IdentityBijector()
|
|
42
|
+
if spec.domain == "positive":
|
|
43
|
+
return PositiveBijector()
|
|
44
|
+
if spec.domain == "interval":
|
|
45
|
+
if spec.bounds is None:
|
|
46
|
+
raise ConfigError("domain='interval' requires bounds", path=spec.name)
|
|
47
|
+
lo, hi = spec.bounds
|
|
48
|
+
return IntervalBijector(lo=lo, hi=hi)
|
|
49
|
+
if spec.domain == "simplex_ref":
|
|
50
|
+
return SimplexRefBijector()
|
|
51
|
+
if spec.domain == "nu_gt_2":
|
|
52
|
+
return NuGt2Bijector()
|
|
53
|
+
if spec.domain == "pmf":
|
|
54
|
+
return PmfBijector()
|
|
55
|
+
if spec.domain == "cholesky":
|
|
56
|
+
return CholeskyLowerBijector()
|
|
57
|
+
if spec.domain == "increasing":
|
|
58
|
+
return IncreasingBijector(base=IdentityBijector())
|
|
59
|
+
if spec.domain == "increasing_positive":
|
|
60
|
+
return IncreasingBijector(base=PositiveBijector())
|
|
61
|
+
raise ConfigError(f"unknown domain {spec.domain!r}", path=spec.name)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _free_count(domain: str, cell_size: int) -> int:
|
|
65
|
+
return cell_size - 1 if domain in ("simplex_ref", "pmf") else cell_size
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class _Coord:
|
|
70
|
+
"""One allocated `u` slot group: a contiguous slice, its bijector, and its label."""
|
|
71
|
+
|
|
72
|
+
start: int
|
|
73
|
+
size: int
|
|
74
|
+
bijector: Bijector
|
|
75
|
+
cell_shape: tuple[int, ...]
|
|
76
|
+
label: str
|
|
77
|
+
|
|
78
|
+
def slice_of(self, u: Array) -> Array:
|
|
79
|
+
return u[self.start : self.start + self.size]
|
|
80
|
+
|
|
81
|
+
def forward(self, u: Array) -> Array:
|
|
82
|
+
return self.bijector.forward(self.slice_of(u)).reshape(self.cell_shape)
|
|
83
|
+
|
|
84
|
+
def inverse(self, theta_cell: Array) -> Array:
|
|
85
|
+
return self.bijector.inverse(theta_cell.reshape(-1))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass
|
|
89
|
+
class _SpecPlan:
|
|
90
|
+
spec: ParamSpec
|
|
91
|
+
n0: int
|
|
92
|
+
rest: tuple[int, ...]
|
|
93
|
+
is_increasing: bool
|
|
94
|
+
# non-increasing: one entry per state, in state order; increasing: a single entry
|
|
95
|
+
state_modes: list[Mode] = field(default_factory=list)
|
|
96
|
+
coords: dict[int, _Coord] = field(default_factory=dict) # state_index -> its own/tied _Coord
|
|
97
|
+
increasing_coord: _Coord | None = None
|
|
98
|
+
prior_states: list[int] = field(default_factory=list)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class ParamManager:
|
|
102
|
+
"""Maps `u in R^p` to/from the constrained parameter pytree `theta` (`Params`)."""
|
|
103
|
+
|
|
104
|
+
def __init__(self, specs: tuple[ParamSpec, ...]) -> None:
|
|
105
|
+
"""Build the flatten/unflatten layout plan from `specs`."""
|
|
106
|
+
self._specs = specs
|
|
107
|
+
self._plans: list[_SpecPlan] = []
|
|
108
|
+
self._coord_order: list[_Coord] = []
|
|
109
|
+
tie_coords: dict[str, _Coord] = {}
|
|
110
|
+
offset = 0
|
|
111
|
+
|
|
112
|
+
for spec in specs:
|
|
113
|
+
if spec.constraint == "increasing":
|
|
114
|
+
offset = self._plan_increasing(spec, offset)
|
|
115
|
+
else:
|
|
116
|
+
offset = self._plan_regular(spec, offset, tie_coords)
|
|
117
|
+
|
|
118
|
+
self._n_free = offset
|
|
119
|
+
|
|
120
|
+
def __hash__(self) -> int:
|
|
121
|
+
"""Hash of the specs: the layout is a pure function of them (a static jit argument, CLAUDE.md 5)."""
|
|
122
|
+
return hash(self._specs)
|
|
123
|
+
|
|
124
|
+
def __eq__(self, other: object) -> bool:
|
|
125
|
+
"""Managers over equal specs share one layout, so jitted functions keyed on one serve the other."""
|
|
126
|
+
return isinstance(other, ParamManager) and self._specs == other._specs
|
|
127
|
+
|
|
128
|
+
# --- planning ------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
def _plan_regular(self, spec: ParamSpec, offset: int, tie_coords: dict[str, _Coord]) -> int:
|
|
131
|
+
n0 = spec.shape[0] if spec.shape else 1
|
|
132
|
+
rest = spec.shape[1:] if spec.shape else ()
|
|
133
|
+
cell_size = math.prod(rest) if rest else 1
|
|
134
|
+
modes = (spec.mode,) * n0 if isinstance(spec.mode, str) else spec.mode
|
|
135
|
+
if len(modes) != n0:
|
|
136
|
+
raise ConfigError(f"mode tuple length {len(modes)} != leading shape {n0}", path=spec.name)
|
|
137
|
+
if any(m == _FIXED for m in modes) and spec.value is None:
|
|
138
|
+
raise ConfigError("mode='fixed' requires value", path=spec.name)
|
|
139
|
+
if any(m == "bounded" for m in modes) and (spec.domain != "interval" or spec.bounds is None):
|
|
140
|
+
raise ConfigError("mode='bounded' requires domain='interval' and bounds", path=spec.name)
|
|
141
|
+
if any(m == "prior" for m in modes) and spec.prior is None:
|
|
142
|
+
raise ConfigError("mode='prior' requires prior", path=spec.name)
|
|
143
|
+
if any(m == "tied" for m in modes) and spec.tie_group is None:
|
|
144
|
+
raise ConfigError("mode='tied' requires tie_group", path=spec.name)
|
|
145
|
+
|
|
146
|
+
plan = _SpecPlan(spec=spec, n0=n0, rest=rest, is_increasing=False, state_modes=list(modes))
|
|
147
|
+
bijector = _base_bijector(spec)
|
|
148
|
+
free_count = _free_count(spec.domain, cell_size)
|
|
149
|
+
|
|
150
|
+
for i, mode in enumerate(modes):
|
|
151
|
+
if mode == _FIXED:
|
|
152
|
+
continue
|
|
153
|
+
if mode == "prior":
|
|
154
|
+
plan.prior_states.append(i)
|
|
155
|
+
if mode == _TIED:
|
|
156
|
+
group = spec.tie_group
|
|
157
|
+
assert group is not None
|
|
158
|
+
if group not in tie_coords:
|
|
159
|
+
label = f"{spec.name}[tied:{group}]"
|
|
160
|
+
tie_coords[group] = _Coord(offset, free_count, bijector, rest, label)
|
|
161
|
+
self._coord_order.append(tie_coords[group])
|
|
162
|
+
offset += free_count
|
|
163
|
+
elif tie_coords[group].cell_shape != rest or tie_coords[group].size != free_count:
|
|
164
|
+
raise ConfigError(
|
|
165
|
+
f"tie_group {group!r} members have incompatible domain/cell shape "
|
|
166
|
+
f"({tie_coords[group].cell_shape} vs {rest})",
|
|
167
|
+
path=spec.name,
|
|
168
|
+
)
|
|
169
|
+
plan.coords[i] = tie_coords[group]
|
|
170
|
+
else:
|
|
171
|
+
label = f"{spec.name}[{i}]"
|
|
172
|
+
coord = _Coord(offset, free_count, bijector, rest, label)
|
|
173
|
+
self._coord_order.append(coord)
|
|
174
|
+
offset += free_count
|
|
175
|
+
plan.coords[i] = coord
|
|
176
|
+
|
|
177
|
+
self._plans.append(plan)
|
|
178
|
+
return offset
|
|
179
|
+
|
|
180
|
+
def _plan_increasing(self, spec: ParamSpec, offset: int) -> int:
|
|
181
|
+
if len(spec.shape) != 1:
|
|
182
|
+
raise ConfigError("constraint='increasing' requires shape=(N,)", path=spec.name)
|
|
183
|
+
if not isinstance(spec.mode, str):
|
|
184
|
+
raise ConfigError(
|
|
185
|
+
"constraint='increasing' requires one uniform mode, not per-state", path=spec.name
|
|
186
|
+
)
|
|
187
|
+
if spec.mode == _FIXED or spec.mode == _TIED:
|
|
188
|
+
raise ConfigError(
|
|
189
|
+
"constraint='increasing' cannot be combined with mode='fixed'/'tied'", path=spec.name
|
|
190
|
+
)
|
|
191
|
+
if spec.mode == "prior" and spec.prior is None:
|
|
192
|
+
raise ConfigError("mode='prior' requires prior", path=spec.name)
|
|
193
|
+
|
|
194
|
+
n0 = spec.shape[0]
|
|
195
|
+
base = _base_bijector(spec)
|
|
196
|
+
bijector = IncreasingBijector(base=base)
|
|
197
|
+
coord = _Coord(offset, n0, bijector, (n0,), f"{spec.name}[increasing]")
|
|
198
|
+
self._coord_order.append(coord)
|
|
199
|
+
|
|
200
|
+
plan = _SpecPlan(
|
|
201
|
+
spec=spec,
|
|
202
|
+
n0=n0,
|
|
203
|
+
rest=(),
|
|
204
|
+
is_increasing=True,
|
|
205
|
+
state_modes=[spec.mode] * n0,
|
|
206
|
+
increasing_coord=coord,
|
|
207
|
+
prior_states=list(range(n0)) if spec.mode == "prior" else [],
|
|
208
|
+
)
|
|
209
|
+
self._plans.append(plan)
|
|
210
|
+
return offset + n0
|
|
211
|
+
|
|
212
|
+
# --- public API ------------------------------------------------------------------------
|
|
213
|
+
|
|
214
|
+
@property
|
|
215
|
+
def n_free(self) -> int:
|
|
216
|
+
"""`p`: the number of entries `u` carries."""
|
|
217
|
+
return self._n_free
|
|
218
|
+
|
|
219
|
+
def names(self) -> list[str]:
|
|
220
|
+
"""One label per `u` coordinate group, in flattening order."""
|
|
221
|
+
labels = []
|
|
222
|
+
for coord in self._coord_order:
|
|
223
|
+
if coord.size == 1:
|
|
224
|
+
labels.append(coord.label)
|
|
225
|
+
else:
|
|
226
|
+
labels.extend(f"{coord.label}:{k}" for k in range(coord.size))
|
|
227
|
+
return labels
|
|
228
|
+
|
|
229
|
+
def unflatten(self, u: Array) -> Params:
|
|
230
|
+
"""`u -> theta` (full shapes, dict keyed by spec name)."""
|
|
231
|
+
theta: Params = {}
|
|
232
|
+
for plan in self._plans:
|
|
233
|
+
if plan.is_increasing:
|
|
234
|
+
assert plan.increasing_coord is not None
|
|
235
|
+
theta[plan.spec.name] = plan.increasing_coord.forward(u)
|
|
236
|
+
continue
|
|
237
|
+
cells = []
|
|
238
|
+
for i in range(plan.n0):
|
|
239
|
+
if plan.state_modes[i] == _FIXED:
|
|
240
|
+
assert plan.spec.value is not None
|
|
241
|
+
cells.append(jnp.asarray(plan.spec.value[i] if plan.spec.shape else plan.spec.value))
|
|
242
|
+
else:
|
|
243
|
+
cells.append(plan.coords[i].forward(u))
|
|
244
|
+
theta[plan.spec.name] = jnp.stack(cells, axis=0) if plan.spec.shape else jnp.asarray(cells[0])
|
|
245
|
+
return theta
|
|
246
|
+
|
|
247
|
+
def flatten(self, theta: Params) -> Array:
|
|
248
|
+
"""`theta -> u` (only the free/tied/bounded/prior coordinates)."""
|
|
249
|
+
u = jnp.zeros((self._n_free,))
|
|
250
|
+
for plan in self._plans:
|
|
251
|
+
value = theta[plan.spec.name]
|
|
252
|
+
if plan.is_increasing:
|
|
253
|
+
assert plan.increasing_coord is not None
|
|
254
|
+
coord = plan.increasing_coord
|
|
255
|
+
u = u.at[coord.start : coord.start + coord.size].set(coord.inverse(value))
|
|
256
|
+
continue
|
|
257
|
+
seen_tied: set[int] = set()
|
|
258
|
+
for i in range(plan.n0):
|
|
259
|
+
if plan.state_modes[i] == _FIXED:
|
|
260
|
+
continue
|
|
261
|
+
coord = plan.coords[i]
|
|
262
|
+
if id(coord) in seen_tied:
|
|
263
|
+
continue
|
|
264
|
+
seen_tied.add(id(coord))
|
|
265
|
+
cell = value[i] if plan.spec.shape else value
|
|
266
|
+
u = u.at[coord.start : coord.start + coord.size].set(coord.inverse(cell))
|
|
267
|
+
return u
|
|
268
|
+
|
|
269
|
+
def log_det_jac(self, u: Array) -> Array:
|
|
270
|
+
"""`sum(log |det d(theta)/d(u)|)` over every distinct coordinate group."""
|
|
271
|
+
total = jnp.zeros(())
|
|
272
|
+
for coord in self._coord_order:
|
|
273
|
+
total = total + coord.bijector.log_det_jac(coord.slice_of(u))
|
|
274
|
+
return total
|
|
275
|
+
|
|
276
|
+
def log_prior(self, theta: Params) -> Array:
|
|
277
|
+
"""`sum(prior.log_prob(theta))` over every spec/state with `mode == 'prior'`."""
|
|
278
|
+
total = jnp.zeros(())
|
|
279
|
+
for plan in self._plans:
|
|
280
|
+
if not plan.prior_states:
|
|
281
|
+
continue
|
|
282
|
+
assert plan.spec.prior is not None
|
|
283
|
+
value = theta[plan.spec.name]
|
|
284
|
+
selected = value[jnp.asarray(plan.prior_states)] if plan.spec.shape else value
|
|
285
|
+
total = total + plan.spec.prior.log_prob(selected)
|
|
286
|
+
return total
|
|
287
|
+
|
|
288
|
+
def init_u(self) -> Array:
|
|
289
|
+
"""`flatten` of the specs' `init` (or `value`, where fixed) values."""
|
|
290
|
+
theta0: Params = {}
|
|
291
|
+
for plan in self._plans:
|
|
292
|
+
spec = plan.spec
|
|
293
|
+
if spec.shape:
|
|
294
|
+
cells = []
|
|
295
|
+
for i in range(plan.n0):
|
|
296
|
+
if plan.state_modes[i] == _FIXED:
|
|
297
|
+
assert spec.value is not None
|
|
298
|
+
cells.append(np.asarray(spec.value[i]))
|
|
299
|
+
else:
|
|
300
|
+
assert spec.init is not None
|
|
301
|
+
cells.append(np.asarray(spec.init[i]))
|
|
302
|
+
theta0[spec.name] = jnp.asarray(np.stack(cells, axis=0))
|
|
303
|
+
else:
|
|
304
|
+
source = spec.value if plan.state_modes[0] == _FIXED else spec.init
|
|
305
|
+
assert source is not None
|
|
306
|
+
theta0[spec.name] = jnp.asarray(source)
|
|
307
|
+
return self.flatten(theta0)
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Log-prior densities evaluated on constrained `theta`, summed to a scalar (E1-T03a)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
import equinox as eqx
|
|
8
|
+
import jax
|
|
9
|
+
import jax.numpy as jnp
|
|
10
|
+
import jax.scipy.special as jsp_special
|
|
11
|
+
|
|
12
|
+
from hsmmkit.model.params.bijectors import lower_diag_mask
|
|
13
|
+
from hsmmkit.utils.typing import Array
|
|
14
|
+
|
|
15
|
+
_LOG_2PI = math.log(2.0 * math.pi)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NormalPrior(eqx.Module):
|
|
19
|
+
"""`Normal(mean, sd)` on `theta`."""
|
|
20
|
+
|
|
21
|
+
sd: float = eqx.field(static=True)
|
|
22
|
+
mean: float = eqx.field(static=True, default=0.0)
|
|
23
|
+
|
|
24
|
+
def log_prob(self, theta: Array) -> Array:
|
|
25
|
+
"""`sum(-0.5 * ((theta - mean) / sd) ** 2 - log(sd) - 0.5 * log(2 * pi))`."""
|
|
26
|
+
z = (theta - self.mean) / self.sd
|
|
27
|
+
return jnp.sum(-0.5 * z**2 - jnp.log(self.sd) - 0.5 * _LOG_2PI)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class LogNormalPrior(eqx.Module):
|
|
31
|
+
"""`LogNormal(mean_log, sd)` on `theta` (i.e. `Normal(mean_log, sd)` on `log(theta)`)."""
|
|
32
|
+
|
|
33
|
+
mean_log: float = eqx.field(static=True)
|
|
34
|
+
sd: float = eqx.field(static=True)
|
|
35
|
+
|
|
36
|
+
def log_prob(self, theta: Array) -> Array:
|
|
37
|
+
"""`sum(-0.5 * ((log(theta) - mean_log) / sd) ** 2 - log(sd) - 0.5 * log(2 * pi) - log(theta))`."""
|
|
38
|
+
log_theta = jnp.log(theta)
|
|
39
|
+
z = (log_theta - self.mean_log) / self.sd
|
|
40
|
+
return jnp.sum(-0.5 * z**2 - jnp.log(self.sd) - 0.5 * _LOG_2PI - log_theta)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class DirichletPrior(eqx.Module):
|
|
44
|
+
"""Symmetric `Dirichlet(alpha)` on each row of a jump matrix (or a single row)."""
|
|
45
|
+
|
|
46
|
+
alpha: float = eqx.field(static=True)
|
|
47
|
+
|
|
48
|
+
def log_prob(self, p: Array) -> Array:
|
|
49
|
+
"""`sum((alpha - 1) * log(p))` per row, plus the Dirichlet normalizing constant."""
|
|
50
|
+
n = p.shape[-1]
|
|
51
|
+
const = jsp_special.gammaln(n * self.alpha) - n * jsp_special.gammaln(self.alpha)
|
|
52
|
+
per_row = jnp.sum((self.alpha - 1.0) * jnp.log(p), axis=-1) + const
|
|
53
|
+
return jnp.sum(per_row)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CholeskyDiagPrior(eqx.Module):
|
|
57
|
+
"""A scalar prior (`LogNormal`, ...) on the diagonal of packed Cholesky factors `(..., M(M+1)/2)`."""
|
|
58
|
+
|
|
59
|
+
base: LogNormalPrior | NormalPrior
|
|
60
|
+
|
|
61
|
+
def log_prob(self, theta: Array) -> Array:
|
|
62
|
+
"""`base.log_prob` of the diagonal entries."""
|
|
63
|
+
diag = jnp.asarray(lower_diag_mask(theta.shape[-1]))
|
|
64
|
+
return self.base.log_prob(theta[..., diag])
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class LkjPrior(eqx.Module):
|
|
68
|
+
"""`LKJ(eta)` on the correlation matrix of packed Cholesky covariance factors `(..., M(M+1)/2)`."""
|
|
69
|
+
|
|
70
|
+
eta: float = eqx.field(static=True, default=1.0)
|
|
71
|
+
|
|
72
|
+
def log_prob(self, theta: Array) -> Array:
|
|
73
|
+
"""Sum over the leading axes of `lkj_logpdf` of the correlation factor of each covariance factor."""
|
|
74
|
+
from hsmmkit.model.dists import lkj_logpdf, unpack_lower
|
|
75
|
+
|
|
76
|
+
m = round((math.sqrt(8 * theta.shape[-1] + 1) - 1) / 2)
|
|
77
|
+
chol = unpack_lower(theta, m) # (..., M, M)
|
|
78
|
+
rows = chol / jnp.sqrt(jnp.sum(chol**2, axis=-1, keepdims=True)) # unit-norm rows: Cholesky of R
|
|
79
|
+
flat = rows.reshape(-1, m, m)
|
|
80
|
+
return jnp.sum(jax.vmap(lambda c: lkj_logpdf(c, self.eta))(flat))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
DEFAULT_COEF_PRIOR = NormalPrior(mean=0.0, sd=1.0)
|
|
84
|
+
"""Default coefficient prior (`coef_prior_sd = 1.0`), per overview Appendix A defaults."""
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""`ParamSpec`: a single named parameter block's layout and estimation mode (E1-T03b)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Literal, Protocol
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from hsmmkit.utils.typing import Array
|
|
11
|
+
|
|
12
|
+
Mode = Literal["free", "fixed", "tied", "bounded", "prior"]
|
|
13
|
+
Domain = Literal[
|
|
14
|
+
"real",
|
|
15
|
+
"positive",
|
|
16
|
+
"interval",
|
|
17
|
+
"simplex_ref",
|
|
18
|
+
"nu_gt_2",
|
|
19
|
+
"pmf",
|
|
20
|
+
"cholesky",
|
|
21
|
+
"increasing",
|
|
22
|
+
"increasing_positive",
|
|
23
|
+
]
|
|
24
|
+
"""`increasing` / `increasing_positive`: each *row cell* (the trailing axes, a vector) is strictly increasing
|
|
25
|
+
(a real, resp. positive, first entry plus cumulative-softplus steps): the within-state ordering of the
|
|
26
|
+
components of a mixture (E11-T06), as opposed to `constraint="increasing"` which orders the state axis."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Prior(Protocol):
|
|
30
|
+
"""Structural type for the prior objects (`NormalPrior`, `LogNormalPrior`, `DirichletPrior`)."""
|
|
31
|
+
|
|
32
|
+
def log_prob(self, theta: Array) -> Array:
|
|
33
|
+
"""Summed log-density of `theta` under this prior."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, eq=False)
|
|
38
|
+
class ParamSpec:
|
|
39
|
+
"""A single named parameter's shape, domain, and per-state (or uniform) estimation mode.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
name: Dotted parameter name, e.g. `"emission.sigma"`.
|
|
43
|
+
shape: Full shape of `theta[name]`, e.g. `(N,)` or `(N, K)`. The leading axis (if any) is
|
|
44
|
+
the "state" axis that `mode`, when given per-state, indexes.
|
|
45
|
+
domain: Bijector domain for every free/tied/bounded/prior entry.
|
|
46
|
+
mode: One mode for the whole spec, or one per leading-index (state).
|
|
47
|
+
value: Required wherever `mode == "fixed"`; broadcast/sliced to match `shape`.
|
|
48
|
+
init: Initial `theta` wherever `mode != "fixed"`; used by `ParamManager.init_u`.
|
|
49
|
+
bounds: `(lo, hi)`, required when `domain == "interval"`.
|
|
50
|
+
prior: Evaluated on entries where `mode == "prior"`.
|
|
51
|
+
tie_group: Entries (within or across specs) sharing this string share one `u` entry.
|
|
52
|
+
constraint: `"increasing"` applies the `increasing` bijector across the whole state axis
|
|
53
|
+
(requires `shape = (N,)`, a single uniform `mode != "fixed"`, no `tie_group`).
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
name: str
|
|
57
|
+
shape: tuple[int, ...]
|
|
58
|
+
domain: Domain
|
|
59
|
+
mode: Mode | tuple[Mode, ...]
|
|
60
|
+
value: np.ndarray | None = None
|
|
61
|
+
init: np.ndarray | None = None
|
|
62
|
+
bounds: tuple[float, float] | None = None
|
|
63
|
+
prior: Prior | None = None
|
|
64
|
+
tie_group: str | None = None
|
|
65
|
+
constraint: Literal["none", "increasing"] = "none"
|
hsmmkit/model/spec.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""`ModelSpec`: structure only, no data (E1-T05)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Literal
|
|
6
|
+
|
|
7
|
+
import equinox as eqx
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from hsmmkit.model.duration.base import DurationFamily
|
|
11
|
+
from hsmmkit.model.emission.base import EmissionFamily
|
|
12
|
+
from hsmmkit.model.params.spec import ParamSpec
|
|
13
|
+
from hsmmkit.model.transition import TransitionModel
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ModelSpec(eqx.Module):
|
|
17
|
+
"""The full model structure: family instances, state-space shape, and the union of param specs.
|
|
18
|
+
|
|
19
|
+
Every field is static (`ModelSpec` carries no array data of its own; all array-valued
|
|
20
|
+
parameters live in `Params`/`u`, managed separately by `ParamManager`).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
n_states: int = eqx.field(static=True)
|
|
24
|
+
n_series: int = eqx.field(static=True)
|
|
25
|
+
emission: EmissionFamily = eqx.field(static=True)
|
|
26
|
+
duration: DurationFamily = eqx.field(static=True)
|
|
27
|
+
transition: TransitionModel = eqx.field(static=True)
|
|
28
|
+
order: int = eqx.field(static=True)
|
|
29
|
+
duration_conditioning: Literal["current", "pair"] = eqx.field(static=True)
|
|
30
|
+
engine: Literal["expanded", "explicit"] = eqx.field(static=True)
|
|
31
|
+
d_max: int = eqx.field(static=True)
|
|
32
|
+
initial: Literal["uniform", "stationary", "free"] = eqx.field(static=True)
|
|
33
|
+
param_specs: tuple[ParamSpec, ...] = eqx.field(static=True)
|
|
34
|
+
duration_dependent_jumps: bool = eqx.field(static=True, default=False)
|
|
35
|
+
"""`pi_ij` depends on the duration of the segment being left (E12-T05, explicit engine only)."""
|
|
36
|
+
left_censored: bool = eqx.field(static=True, default=False)
|
|
37
|
+
"""The sequence starts inside a running segment (E12-T04): residual-life first segment (explicit)."""
|
|
38
|
+
n_groups: int = eqx.field(static=True, default=1)
|
|
39
|
+
"""Initial-distribution groups (E12-T02): `1` is one shared `initial.logits`; `G > 1` (`initial_groups:
|
|
40
|
+
per_group`, `initial_state: free`) gives `initial.logits` the shape `(G, S_phase1)`, one row per group."""
|
|
41
|
+
memory_mode: Literal["segments", "steps"] = eqx.field(static=True, default="segments")
|
|
42
|
+
"""`segments`: the segment memory of Part I (`transition.order`); `steps`: time-step tuples with repeats
|
|
43
|
+
`(s_{t-p}, ..., s_t)` for an emission that depends on the regimes of the previous steps (E11-T05)."""
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Transition topology `Omega`: which regime-to-regime jumps are allowed (E12-T03, FR-DU01, FR-DU02, D16).
|
|
2
|
+
|
|
3
|
+
`Topology.allowed (N, N)` is the boolean jump matrix (diagonal `False`: a regime never jumps to itself, the
|
|
4
|
+
duration family models staying); `absorbing` lists the regimes with no allowed target. Shorthands
|
|
5
|
+
(`model.topology`): `full` (every off-diagonal), `left_to_right` (`j > i`, the last regime is absorbing),
|
|
6
|
+
`cyclic` (`j = (i + 1) mod N`), `{banded: k}` (`0 < |j - i| <= k`) and `{matrix: [[0/1]]}` as given.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from hsmmkit.utils.errors import ConfigError
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from hsmmkit.config.schema import BandedCfg, MatrixCfg
|
|
20
|
+
|
|
21
|
+
__all__ = ["Topology", "from_config"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, eq=False)
|
|
25
|
+
class Topology:
|
|
26
|
+
"""The allowed jumps `allowed (N, N)` (diagonal `False`) and the absorbing regimes."""
|
|
27
|
+
|
|
28
|
+
allowed: np.ndarray
|
|
29
|
+
absorbing: tuple[int, ...]
|
|
30
|
+
|
|
31
|
+
def __eq__(self, other: object) -> bool:
|
|
32
|
+
"""Structural equality (the numpy array makes the dataclass default unusable)."""
|
|
33
|
+
if not isinstance(other, Topology):
|
|
34
|
+
return NotImplemented
|
|
35
|
+
return bool(np.array_equal(self.allowed, other.allowed))
|
|
36
|
+
|
|
37
|
+
def __hash__(self) -> int:
|
|
38
|
+
"""Content-based hash (a `ModelSpec` field is a static jit argument)."""
|
|
39
|
+
return hash((self.allowed.shape, self.allowed.tobytes()))
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def n_states(self) -> int:
|
|
43
|
+
"""`N`."""
|
|
44
|
+
return int(self.allowed.shape[0])
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def is_full(self) -> bool:
|
|
48
|
+
"""Every off-diagonal jump is allowed (Part I behaviour)."""
|
|
49
|
+
n = self.n_states
|
|
50
|
+
return bool(np.array_equal(self.allowed, ~np.eye(n, dtype=bool)))
|
|
51
|
+
|
|
52
|
+
def n_targets(self) -> np.ndarray:
|
|
53
|
+
"""`(N,)` number of allowed targets of each regime."""
|
|
54
|
+
return self.allowed.sum(axis=1)
|
|
55
|
+
|
|
56
|
+
def n_free_per_row(self) -> np.ndarray:
|
|
57
|
+
"""`(N,)` free logits of each regime's row: `max(0, |A_i| - 1)` (Appendix F)."""
|
|
58
|
+
return np.asarray(np.maximum(self.n_targets() - 1, 0))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _of(allowed: np.ndarray) -> Topology:
|
|
62
|
+
absorbing = tuple(int(i) for i in np.flatnonzero(~allowed.any(axis=1)))
|
|
63
|
+
return Topology(allowed=allowed, absorbing=absorbing)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def from_config(cfg: str | BandedCfg | MatrixCfg, n_states: int) -> Topology:
|
|
67
|
+
"""The `Topology` of `model.topology` for `n_states` regimes.
|
|
68
|
+
|
|
69
|
+
Raises:
|
|
70
|
+
ConfigError: an unknown shorthand, a matrix of the wrong shape, a non-zero diagonal or a non 0/1 entry
|
|
71
|
+
(`path="model.topology"`).
|
|
72
|
+
"""
|
|
73
|
+
n = n_states
|
|
74
|
+
idx = np.arange(n)
|
|
75
|
+
off = idx[None, :] != idx[:, None]
|
|
76
|
+
if isinstance(cfg, str):
|
|
77
|
+
if cfg == "full":
|
|
78
|
+
return _of(off.copy())
|
|
79
|
+
if cfg == "left_to_right":
|
|
80
|
+
return _of(idx[None, :] > idx[:, None])
|
|
81
|
+
if cfg == "cyclic":
|
|
82
|
+
return _of(idx[None, :] == (idx[:, None] + 1) % n)
|
|
83
|
+
raise ConfigError(f"unknown topology {cfg!r}", path="model.topology")
|
|
84
|
+
banded = getattr(cfg, "banded", None)
|
|
85
|
+
if banded is not None:
|
|
86
|
+
return _of(off & (np.abs(idx[None, :] - idx[:, None]) <= banded))
|
|
87
|
+
matrix = getattr(cfg, "matrix", None)
|
|
88
|
+
if matrix is None:
|
|
89
|
+
raise ConfigError(f"unknown topology {cfg!r}", path="model.topology")
|
|
90
|
+
arr = np.asarray(matrix)
|
|
91
|
+
if arr.shape != (n, n):
|
|
92
|
+
raise ConfigError(f"matrix must be {n} x {n}", path="model.topology.matrix")
|
|
93
|
+
if not bool(np.all((arr == 0) | (arr == 1))):
|
|
94
|
+
raise ConfigError("matrix entries must be 0 or 1", path="model.topology.matrix")
|
|
95
|
+
if bool(np.any(np.diag(arr) != 0)):
|
|
96
|
+
raise ConfigError("matrix must have a zero diagonal", path="model.topology.matrix")
|
|
97
|
+
return _of(arr.astype(bool))
|