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,67 @@
|
|
|
1
|
+
"""Load/save `ProjectConfig` (or an application's subclass) from/to YAML; JSON-Schema export."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from ruamel.yaml import YAML
|
|
10
|
+
|
|
11
|
+
from hsmmkit.config.migrate import migrate
|
|
12
|
+
from hsmmkit.config.schema import ProjectConfig, _registered_names, parse_project_config
|
|
13
|
+
from hsmmkit.plugins import REGISTRY
|
|
14
|
+
|
|
15
|
+
_SAFE_YAML = YAML(typ="safe")
|
|
16
|
+
_ROUND_TRIP_YAML = YAML()
|
|
17
|
+
_ROUND_TRIP_YAML.default_flow_style = False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def load_config(path: str | Path, config_cls: type[ProjectConfig] = ProjectConfig) -> ProjectConfig:
|
|
21
|
+
"""Load a `config_cls` from a YAML file: safe-load -> `migrate()` -> validate.
|
|
22
|
+
|
|
23
|
+
Environment variables are **not** expanded (API keys come from the environment at the point of use,
|
|
24
|
+
never from config).
|
|
25
|
+
"""
|
|
26
|
+
raw = _SAFE_YAML.load(Path(path))
|
|
27
|
+
migrated = migrate(raw, config_cls)
|
|
28
|
+
return parse_project_config(migrated, config_cls)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def dump_resolved(config: ProjectConfig, path: str | Path) -> None:
|
|
32
|
+
"""Write the fully resolved config (every field, including defaults) as YAML to `path`."""
|
|
33
|
+
data = config.model_dump(mode="json")
|
|
34
|
+
with Path(path).open("w", encoding="utf-8") as f:
|
|
35
|
+
_ROUND_TRIP_YAML.dump(data, f)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _enum_of(schema: dict[str, Any], defs: str, field: str, names: list[str], *, items: bool = False) -> None:
|
|
39
|
+
"""Set the enum of `field` in every schema definition named `defs` (or an extension's `<X>defs`)."""
|
|
40
|
+
for name, definition in schema.get("$defs", {}).items():
|
|
41
|
+
prop = definition.get("properties", {}).get(field)
|
|
42
|
+
if prop is None or not name.endswith(defs):
|
|
43
|
+
continue
|
|
44
|
+
target = prop["items"] if items and "items" in prop else prop
|
|
45
|
+
nullable = any(option.get("type") == "null" for option in target.get("anyOf", []))
|
|
46
|
+
target.pop("anyOf", None)
|
|
47
|
+
target["type"] = ["string", "null"] if nullable else "string"
|
|
48
|
+
target["enum"] = [*names, None] if nullable else names
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def json_schema(config_cls: type[ProjectConfig] = ProjectConfig) -> dict[str, Any]:
|
|
52
|
+
"""`config_cls.model_json_schema()` with the registered names of registry-validated fields as enums."""
|
|
53
|
+
schema = config_cls.model_json_schema()
|
|
54
|
+
_enum_of(schema, "EmissionCfg", "family", _registered_names("emission", needs="from_config"))
|
|
55
|
+
_enum_of(schema, "DurationCfg", "family", _registered_names("duration", needs="from_config"))
|
|
56
|
+
_enum_of(schema, "EstimationSection", "init", _registered_names("init"), items=True)
|
|
57
|
+
_enum_of(schema, "CovariateForecasterCfg", "type", _registered_names("covariate_forecaster"))
|
|
58
|
+
_enum_of(schema, "EvaluationSection", "metrics", _registered_names("metric"), items=True)
|
|
59
|
+
sources = list(REGISTRY.names("source"))
|
|
60
|
+
if sources:
|
|
61
|
+
_enum_of(schema, "SourceCfg", "kind", sources)
|
|
62
|
+
return schema
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def export_json_schema(path: str | Path, config_cls: type[ProjectConfig] = ProjectConfig) -> None:
|
|
66
|
+
"""Write the JSON-Schema of `config_cls` as JSON to `path` (editor-support hook)."""
|
|
67
|
+
Path(path).write_text(json.dumps(json_schema(config_cls), indent=2), encoding="utf-8")
|
hsmmkit/data/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Domain-neutral data contracts, caching, calendar and preparation."""
|
hsmmkit/data/batch.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""Multi-sequence data: `SequenceBatch` and its padded, bucketed view `PaddedBatch` (E12-T01a, ADR-0021).
|
|
2
|
+
|
|
3
|
+
Many independent sequences of different lengths are kept as single-sequence `PreparedDataset`s (the contracts
|
|
4
|
+
have no batch dimension); `SequenceBatch.padded()` stacks them into `(B, T_max, ...)` arrays for the batched
|
|
5
|
+
engines of E12-T01b. Shapes are bucketed so that compiled shapes do not vary with the data:
|
|
6
|
+
|
|
7
|
+
* `T_max` is the smallest bucket edge `>=` the longest sequence (else the longest length rounded up to a
|
|
8
|
+
multiple of the last edge);
|
|
9
|
+
* `B` is padded up to the next power of two with **empty sequences** (`valid` all `False`, length 0).
|
|
10
|
+
|
|
11
|
+
Padding semantics (engines, E12-T01b): a step with `valid == False` has emission log-density 0 and
|
|
12
|
+
`A_t = I`; this module only provides `valid`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import dataclasses
|
|
18
|
+
from collections.abc import Sequence
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from functools import partial
|
|
21
|
+
|
|
22
|
+
import jax
|
|
23
|
+
import jax.numpy as jnp
|
|
24
|
+
import numpy as np
|
|
25
|
+
|
|
26
|
+
from hsmmkit.data.contracts import CovariateSeries, ObservationSet, PreparedDataset
|
|
27
|
+
from hsmmkit.engine.constraints import boundary_code
|
|
28
|
+
from hsmmkit.utils.errors import ConfigError, DataError
|
|
29
|
+
from hsmmkit.utils.typing import Array
|
|
30
|
+
|
|
31
|
+
__all__ = ["PaddedBatch", "SequenceBatch", "split_sequences"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def split_sequences(
|
|
35
|
+
obs: ObservationSet, covs: Sequence[CovariateSeries]
|
|
36
|
+
) -> list[tuple[str, ObservationSet, list[CovariateSeries]]]:
|
|
37
|
+
"""Group the rows of `obs` by `obs.sequence_ids` (first-appearance order) into one data set per sequence.
|
|
38
|
+
|
|
39
|
+
Without `sequence_ids` the result is the single pair `("0", obs, covs)`. Covariate series must be
|
|
40
|
+
row-aligned columns of the source (one value per observation row) to be split.
|
|
41
|
+
|
|
42
|
+
Raises:
|
|
43
|
+
ConfigError: a covariate series that is not aligned with the observation rows.
|
|
44
|
+
"""
|
|
45
|
+
if obs.sequence_ids is None:
|
|
46
|
+
if obs.meta.get("group_values") is not None:
|
|
47
|
+
raise ConfigError(
|
|
48
|
+
"data.sequences.group_by needs data.source.sequence_column (one group per sequence)",
|
|
49
|
+
path="data.sequences.group_by",
|
|
50
|
+
)
|
|
51
|
+
return [("0", obs, list(covs))]
|
|
52
|
+
ids = np.asarray(obs.sequence_ids)
|
|
53
|
+
uniq, first = np.unique(ids, return_index=True)
|
|
54
|
+
order = uniq[np.argsort(first)]
|
|
55
|
+
out: list[tuple[str, ObservationSet, list[CovariateSeries]]] = []
|
|
56
|
+
for sid in order:
|
|
57
|
+
rows = np.flatnonzero(ids == sid)
|
|
58
|
+
sub_obs = dataclasses.replace(
|
|
59
|
+
obs,
|
|
60
|
+
times=None if obs.times is None else obs.times[rows],
|
|
61
|
+
values=obs.values[rows],
|
|
62
|
+
sequence_ids=None,
|
|
63
|
+
)
|
|
64
|
+
sub_covs: list[CovariateSeries] = []
|
|
65
|
+
for c in covs:
|
|
66
|
+
if np.asarray(c.values).shape[0] != ids.shape[0]:
|
|
67
|
+
raise ConfigError(
|
|
68
|
+
f"covariate '{c.name}' has {np.asarray(c.values).shape[0]} values for {ids.shape[0]} "
|
|
69
|
+
"observation rows: covariates of a multi-sequence data set must be row-aligned columns",
|
|
70
|
+
path="data.covariates",
|
|
71
|
+
)
|
|
72
|
+
sub_covs.append(
|
|
73
|
+
dataclasses.replace(
|
|
74
|
+
c,
|
|
75
|
+
times=None if obs.times is None else obs.times[rows],
|
|
76
|
+
values=np.asarray(c.values)[rows],
|
|
77
|
+
)
|
|
78
|
+
)
|
|
79
|
+
label_values = obs.meta.get("label_values")
|
|
80
|
+
if label_values is not None:
|
|
81
|
+
sub_obs = dataclasses.replace(
|
|
82
|
+
sub_obs, meta={**sub_obs.meta, "label_values": [label_values[int(r)] for r in rows]}
|
|
83
|
+
)
|
|
84
|
+
group_values = obs.meta.get("group_values")
|
|
85
|
+
if group_values is not None:
|
|
86
|
+
groups = np.unique(np.asarray(group_values, dtype=object)[rows].astype(str))
|
|
87
|
+
if groups.shape[0] != 1:
|
|
88
|
+
raise ConfigError(
|
|
89
|
+
f"the group column varies within sequence {sid!r} ({groups.tolist()})",
|
|
90
|
+
path="data.sequences.group_by",
|
|
91
|
+
)
|
|
92
|
+
meta = {k: v for k, v in sub_obs.meta.items() if k != "group_values"}
|
|
93
|
+
sub_obs = dataclasses.replace(sub_obs, meta={**meta, "group": str(groups[0])})
|
|
94
|
+
out.append((str(sid), sub_obs, sub_covs))
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@partial(
|
|
99
|
+
jax.tree_util.register_dataclass,
|
|
100
|
+
data_fields=[
|
|
101
|
+
"observations",
|
|
102
|
+
"mask",
|
|
103
|
+
"valid",
|
|
104
|
+
"dt",
|
|
105
|
+
"cov_transition",
|
|
106
|
+
"cov_duration",
|
|
107
|
+
"cov_emission",
|
|
108
|
+
"labels",
|
|
109
|
+
"lengths",
|
|
110
|
+
"group_index",
|
|
111
|
+
"boundary_code",
|
|
112
|
+
],
|
|
113
|
+
meta_fields=["nominal_dt", "clock"],
|
|
114
|
+
)
|
|
115
|
+
@dataclass(frozen=True)
|
|
116
|
+
class PaddedBatch:
|
|
117
|
+
"""The padded array view of a `SequenceBatch` (a pytree; every leaf is a `jnp` array or `None`).
|
|
118
|
+
|
|
119
|
+
Attributes:
|
|
120
|
+
observations: `(B, T_max, M)`, padded with 0.
|
|
121
|
+
mask: `(B, T_max, M)`, `False` on padding.
|
|
122
|
+
valid: `(B, T_max)`, `True` for `t < T_b`.
|
|
123
|
+
dt: `(B, T_max)`; padding steps carry `nominal_dt` (a positive dummy).
|
|
124
|
+
cov_transition, cov_duration, cov_emission: `(B, T_max, K)`, 0 on padding (`K = 0` when absent).
|
|
125
|
+
labels: `(B, T_max, N)` or `None`; `True` on padding (everything allowed).
|
|
126
|
+
lengths: `(B,)` int32 (0 for the empty padding sequences).
|
|
127
|
+
group_index: `(B,)` int32 initial-distribution group (0 if there are no groups).
|
|
128
|
+
boundary_code: `(B, T_max)` int8 (1 = `must_switch_at`, 2 = `must_not_switch_at`) or `None` when
|
|
129
|
+
no sequence has boundaries (E12-T06).
|
|
130
|
+
nominal_dt, clock: static metadata of the grid (`PreparedDataset.nominal_dt` / `clock`).
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
observations: Array
|
|
134
|
+
mask: Array
|
|
135
|
+
valid: Array
|
|
136
|
+
dt: Array
|
|
137
|
+
cov_transition: Array
|
|
138
|
+
cov_duration: Array
|
|
139
|
+
cov_emission: Array
|
|
140
|
+
labels: Array | None
|
|
141
|
+
lengths: Array
|
|
142
|
+
group_index: Array
|
|
143
|
+
nominal_dt: float = 1.0
|
|
144
|
+
clock: str = "steps"
|
|
145
|
+
boundary_code: Array | None = None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _bucket(max_len: int, edges: tuple[int, ...]) -> int:
|
|
149
|
+
"""Smallest edge `>= max_len`; else `max_len` rounded up to a multiple of the last edge."""
|
|
150
|
+
if not edges:
|
|
151
|
+
return max_len
|
|
152
|
+
for e in edges:
|
|
153
|
+
if e >= max_len:
|
|
154
|
+
return e
|
|
155
|
+
return -(-max_len // edges[-1]) * edges[-1]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _next_pow2(n: int) -> int:
|
|
159
|
+
return 1 << max(n - 1, 0).bit_length()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass(frozen=True)
|
|
163
|
+
class SequenceBatch:
|
|
164
|
+
"""`B >= 1` independent sequences (same `M`, covariate layout and clock) with their bucket edges.
|
|
165
|
+
|
|
166
|
+
Attributes:
|
|
167
|
+
sequences: the single-sequence datasets.
|
|
168
|
+
bucket_edges: strictly increasing time-length edges (may be empty: `T_max` is the longest length).
|
|
169
|
+
ids: the sequence ids, in input order.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
sequences: tuple[PreparedDataset, ...]
|
|
173
|
+
bucket_edges: tuple[int, ...] = ()
|
|
174
|
+
ids: tuple[str, ...] = field(default=())
|
|
175
|
+
|
|
176
|
+
def __post_init__(self) -> None:
|
|
177
|
+
"""Validate the layout shared by all sequences."""
|
|
178
|
+
if not self.sequences:
|
|
179
|
+
raise DataError("a SequenceBatch needs at least one sequence", path="sequences")
|
|
180
|
+
if any(b <= a for a, b in zip(self.bucket_edges, self.bucket_edges[1:], strict=False)) or any(
|
|
181
|
+
e < 1 for e in self.bucket_edges
|
|
182
|
+
):
|
|
183
|
+
raise ConfigError(
|
|
184
|
+
"bucket_edges must be strictly increasing and >= 1", path="data.sequences.bucket_edges"
|
|
185
|
+
)
|
|
186
|
+
ids = self.ids or tuple(str(i) for i in range(len(self.sequences)))
|
|
187
|
+
if len(ids) != len(self.sequences):
|
|
188
|
+
raise DataError("ids and sequences differ in length", path="ids")
|
|
189
|
+
object.__setattr__(self, "ids", tuple(ids))
|
|
190
|
+
first = self.sequences[0]
|
|
191
|
+
for i, s in enumerate(self.sequences):
|
|
192
|
+
if self._layout(s) != self._layout(first):
|
|
193
|
+
raise DataError(
|
|
194
|
+
f"sequence {self.ids[i]!r} differs from sequence {self.ids[0]!r} in series count, "
|
|
195
|
+
"covariate layout, clock or labels",
|
|
196
|
+
path=f"sequences[{i}]",
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
@staticmethod
|
|
200
|
+
def _layout(s: PreparedDataset) -> tuple[object, ...]:
|
|
201
|
+
def width(a: Array | None) -> int | None:
|
|
202
|
+
return None if a is None else int(a.shape[1])
|
|
203
|
+
|
|
204
|
+
return (
|
|
205
|
+
int(s.observations.shape[1]),
|
|
206
|
+
width(s.cov_transition),
|
|
207
|
+
width(s.cov_duration),
|
|
208
|
+
width(s.cov_emission),
|
|
209
|
+
width(s.labels),
|
|
210
|
+
s.clock,
|
|
211
|
+
s.support,
|
|
212
|
+
s.series_support,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
@classmethod
|
|
216
|
+
def of(cls, ds: PreparedDataset, bucket_edges: tuple[int, ...] = (), seq_id: str = "0") -> SequenceBatch:
|
|
217
|
+
"""A single `PreparedDataset` as a `B = 1` batch."""
|
|
218
|
+
return cls((ds,), tuple(bucket_edges), (seq_id,))
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def lengths(self) -> np.ndarray:
|
|
222
|
+
"""`(B,)` sequence lengths."""
|
|
223
|
+
return np.asarray([s.observations.shape[0] for s in self.sequences], dtype=np.int64)
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def t_max(self) -> int:
|
|
227
|
+
"""The bucketed time length of the padded view."""
|
|
228
|
+
return _bucket(int(self.lengths.max()), self.bucket_edges)
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def b_pad(self) -> int:
|
|
232
|
+
"""`B` padded to the next power of two."""
|
|
233
|
+
return _next_pow2(len(self.sequences))
|
|
234
|
+
|
|
235
|
+
@property
|
|
236
|
+
def group_names(self) -> tuple[str | None, ...]:
|
|
237
|
+
"""The distinct initial-distribution groups, sorted (`group_index` indexes this tuple)."""
|
|
238
|
+
names = {s.group for s in self.sequences if s.group is not None}
|
|
239
|
+
if names and any(s.group is None for s in self.sequences):
|
|
240
|
+
raise DataError("some sequences have a group and some have none", path="data.sequences.group_by")
|
|
241
|
+
return tuple(sorted(names)) if names else (None,)
|
|
242
|
+
|
|
243
|
+
def padded(self) -> PaddedBatch:
|
|
244
|
+
"""Stack the sequences into `(B_pad, T_max, ...)` arrays (see `PaddedBatch`)."""
|
|
245
|
+
b, t_max, first = self.b_pad, self.t_max, self.sequences[0]
|
|
246
|
+
m = int(first.observations.shape[1])
|
|
247
|
+
obs_dtype = np.result_type(*[np.asarray(s.observations).dtype for s in self.sequences])
|
|
248
|
+
observations = np.zeros((b, t_max, m), dtype=obs_dtype)
|
|
249
|
+
mask = np.zeros((b, t_max, m), dtype=bool)
|
|
250
|
+
valid = np.zeros((b, t_max), dtype=bool)
|
|
251
|
+
dt = np.full((b, t_max), first.nominal_dt, dtype=np.float64)
|
|
252
|
+
blocks = {}
|
|
253
|
+
for name in ("transition", "duration", "emission"):
|
|
254
|
+
block = getattr(first, f"cov_{name}")
|
|
255
|
+
blocks[name] = np.zeros((b, t_max, 0 if block is None else int(block.shape[1])))
|
|
256
|
+
n_labels = None if first.labels is None else int(first.labels.shape[1])
|
|
257
|
+
labels = None if n_labels is None else np.ones((b, t_max, n_labels), dtype=bool)
|
|
258
|
+
groups = {g: i for i, g in enumerate(self.group_names)}
|
|
259
|
+
group_index = np.zeros(b, dtype=np.int32)
|
|
260
|
+
for i, s in enumerate(self.sequences):
|
|
261
|
+
n = int(s.observations.shape[0])
|
|
262
|
+
observations[i, :n] = np.asarray(s.observations)
|
|
263
|
+
mask[i, :n] = np.asarray(s.mask)
|
|
264
|
+
valid[i, :n] = True
|
|
265
|
+
dt[i, :n] = np.asarray(s.dt)
|
|
266
|
+
for name, arr in blocks.items():
|
|
267
|
+
src = getattr(s, f"cov_{name}")
|
|
268
|
+
if src is not None:
|
|
269
|
+
arr[i, :n] = np.asarray(src)
|
|
270
|
+
if labels is not None and s.labels is not None:
|
|
271
|
+
labels[i, :n] = np.asarray(s.labels)
|
|
272
|
+
group_index[i] = groups[s.group if s.group is not None else self.group_names[0]]
|
|
273
|
+
lengths = np.zeros(b, dtype=np.int32)
|
|
274
|
+
lengths[: len(self.sequences)] = self.lengths
|
|
275
|
+
codes = None
|
|
276
|
+
if any(s.boundaries is not None for s in self.sequences):
|
|
277
|
+
codes = np.zeros((b, t_max), dtype=np.int8)
|
|
278
|
+
for i, s in enumerate(self.sequences):
|
|
279
|
+
code = boundary_code(s.boundaries, int(s.observations.shape[0]))
|
|
280
|
+
if code is not None:
|
|
281
|
+
codes[i, : code.shape[0]] = code
|
|
282
|
+
return PaddedBatch(
|
|
283
|
+
observations=jnp.asarray(observations),
|
|
284
|
+
mask=jnp.asarray(mask),
|
|
285
|
+
valid=jnp.asarray(valid),
|
|
286
|
+
dt=jnp.asarray(dt),
|
|
287
|
+
cov_transition=jnp.asarray(blocks["transition"]),
|
|
288
|
+
cov_duration=jnp.asarray(blocks["duration"]),
|
|
289
|
+
cov_emission=jnp.asarray(blocks["emission"]),
|
|
290
|
+
labels=None if labels is None else jnp.asarray(labels),
|
|
291
|
+
lengths=jnp.asarray(lengths),
|
|
292
|
+
group_index=jnp.asarray(group_index),
|
|
293
|
+
nominal_dt=float(first.nominal_dt),
|
|
294
|
+
clock=first.clock,
|
|
295
|
+
boundary_code=None if codes is None else jnp.asarray(codes),
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
def unpad(self, arr: Array, *, time_axis: int = 1) -> tuple[Array, ...]:
|
|
299
|
+
"""`(B_pad, T_max, ...)` -> per-sequence `(T_b, ...)` arrays (the padding sequences are dropped).
|
|
300
|
+
|
|
301
|
+
`time_axis` is the axis of `arr` that carries time (default 1, right after the batch axis).
|
|
302
|
+
"""
|
|
303
|
+
if time_axis < 1:
|
|
304
|
+
raise DataError("time_axis must be >= 1 (axis 0 is the batch)", path="time_axis")
|
|
305
|
+
out = []
|
|
306
|
+
for i, n in enumerate(self.lengths):
|
|
307
|
+
row = arr[i]
|
|
308
|
+
index = [slice(None)] * row.ndim
|
|
309
|
+
index[time_axis - 1] = slice(0, int(n))
|
|
310
|
+
out.append(row[tuple(index)])
|
|
311
|
+
return tuple(out)
|