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
hsmmkit/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""hsmmkit: domain-neutral hidden semi-Markov models (JAX)."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version as _version
|
|
4
|
+
|
|
5
|
+
from hsmmkit.utils.jax_setup import setup as _setup
|
|
6
|
+
|
|
7
|
+
__version__ = _version("hsmmkit")
|
|
8
|
+
|
|
9
|
+
_setup()
|
|
10
|
+
|
|
11
|
+
from hsmmkit.project import Project # noqa: E402 (after x64 setup)
|
|
12
|
+
|
|
13
|
+
__all__ = ["Project", "__version__"]
|
hsmmkit/cli/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Command-line interface."""
|
hsmmkit/cli/app.py
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
"""The CLI app factory (E10-T07b): `build_app` makes a Typer app over a `Project` class and its config class.
|
|
2
|
+
|
|
3
|
+
The core ships a complete domain-neutral application (`hsmmkit`): `validate-config`, `config-schema`,
|
|
4
|
+
`fit`, `decode`, `forecast`, `simulate`, `backtest`, `compare` and `selftest`, all taking their data from
|
|
5
|
+
`data.source`. An application builds its own app with extra commands and registers its own exit codes (see
|
|
6
|
+
`regimekit`, an example extension).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import importlib
|
|
12
|
+
import sys
|
|
13
|
+
import traceback
|
|
14
|
+
from collections.abc import Callable, Iterator, Sequence
|
|
15
|
+
from contextlib import contextmanager
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Annotated
|
|
19
|
+
|
|
20
|
+
import typer
|
|
21
|
+
|
|
22
|
+
from hsmmkit.config.schema import ProjectConfig
|
|
23
|
+
from hsmmkit.config.yaml_io import export_json_schema, load_config
|
|
24
|
+
from hsmmkit.data.contracts import PreparedDataset
|
|
25
|
+
from hsmmkit.estimation.selftest import SelftestResult
|
|
26
|
+
from hsmmkit.persistence.results import read_prepared
|
|
27
|
+
from hsmmkit.presets import get_preset, list_presets, write_preset
|
|
28
|
+
from hsmmkit.project import Project, apply_overrides, check_simulate_args
|
|
29
|
+
from hsmmkit.utils.errors import (
|
|
30
|
+
ConfigError,
|
|
31
|
+
ConstraintError,
|
|
32
|
+
DataError,
|
|
33
|
+
HsmmkitError,
|
|
34
|
+
NumericalError,
|
|
35
|
+
PersistenceError,
|
|
36
|
+
)
|
|
37
|
+
from hsmmkit.utils.jax_setup import setup as jax_setup
|
|
38
|
+
from hsmmkit.utils.logging import configure_logging, get_logger
|
|
39
|
+
|
|
40
|
+
EXIT_CODES: dict[type[BaseException], int] = {
|
|
41
|
+
ConfigError: 2,
|
|
42
|
+
DataError: 3,
|
|
43
|
+
ConstraintError: 3, # Part II overview §5.4: data / constraint
|
|
44
|
+
NumericalError: 4,
|
|
45
|
+
PersistenceError: 1, # CLAUDE.md §3.8 (the ticket text says 2; the existing behaviour is kept)
|
|
46
|
+
}
|
|
47
|
+
"""Exit codes by exception class (others exit with 1); applications add theirs with `register_exit_code`."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def register_exit_code(exc: type[BaseException], code: int) -> None:
|
|
51
|
+
"""Map `exc` (and its subclasses, unless they have their own entry) to the exit `code`."""
|
|
52
|
+
EXIT_CODES[exc] = code
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def exit_code_of(exc: BaseException) -> int:
|
|
56
|
+
"""The exit code of `exc`: the entry of its most specific registered class, else 1."""
|
|
57
|
+
for cls in type(exc).__mro__:
|
|
58
|
+
if cls in EXIT_CODES:
|
|
59
|
+
return EXIT_CODES[cls]
|
|
60
|
+
return 1
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class GlobalOptions:
|
|
65
|
+
"""The options of the app callback, read by the subcommands."""
|
|
66
|
+
|
|
67
|
+
out: Path | None = None
|
|
68
|
+
offline: bool = False
|
|
69
|
+
device: str | None = None
|
|
70
|
+
seed: int | None = None
|
|
71
|
+
log_level: str | None = None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class CliContext:
|
|
76
|
+
"""What the commands of one app share: its classes and the parsed global options."""
|
|
77
|
+
|
|
78
|
+
name: str
|
|
79
|
+
config_cls: type[ProjectConfig]
|
|
80
|
+
project_cls: type[Project]
|
|
81
|
+
options: GlobalOptions = field(default_factory=GlobalOptions)
|
|
82
|
+
|
|
83
|
+
def overrides(self) -> dict[str, object]:
|
|
84
|
+
"""The config overrides the global `--seed` / `--device` / `--log-level` options stand for."""
|
|
85
|
+
found: dict[str, object] = {}
|
|
86
|
+
if self.options.seed is not None:
|
|
87
|
+
found["project.seed"] = self.options.seed
|
|
88
|
+
if self.options.device is not None:
|
|
89
|
+
found["estimation.device"] = self.options.device
|
|
90
|
+
if self.options.log_level is not None:
|
|
91
|
+
found["project.log_level"] = self.options.log_level
|
|
92
|
+
return found
|
|
93
|
+
|
|
94
|
+
def project(self, config_path: Path, *, logging: bool = True) -> Project:
|
|
95
|
+
"""Load `config_path`, apply the global options, set up logging and wrap it in the project class."""
|
|
96
|
+
config = load_config(config_path, self.config_cls)
|
|
97
|
+
apply_overrides(config, self.overrides())
|
|
98
|
+
if logging:
|
|
99
|
+
configure_logging(config.project.log_level)
|
|
100
|
+
jax_setup(config.estimation.device) # --device takes effect before any JAX use
|
|
101
|
+
return self.project_cls(
|
|
102
|
+
config,
|
|
103
|
+
config_dir=config_path.resolve().parent,
|
|
104
|
+
out_dir=self.options.out,
|
|
105
|
+
offline=self.options.offline,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
def load_prepared(self, project: Project) -> PreparedDataset:
|
|
109
|
+
"""Read `prepared.parquet` from the output directory, loading (and writing) the data when missing."""
|
|
110
|
+
prepared_path = project.out_dir / "prepared.parquet"
|
|
111
|
+
if not prepared_path.exists():
|
|
112
|
+
if project.offline and project.needs_network():
|
|
113
|
+
raise DataError(f"no prepared dataset at {prepared_path} and --offline forbids fetching one")
|
|
114
|
+
project.load_data(write=True)
|
|
115
|
+
return read_prepared(prepared_path)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class CliApp(typer.Typer):
|
|
119
|
+
"""A Typer app that carries its `CliContext` (extra commands read it)."""
|
|
120
|
+
|
|
121
|
+
context: CliContext
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@contextmanager
|
|
125
|
+
def exit_on_error() -> Iterator[None]:
|
|
126
|
+
"""Map a `HsmmkitError` to its message on stderr and its exit code (overview section 4.4)."""
|
|
127
|
+
try:
|
|
128
|
+
yield
|
|
129
|
+
except HsmmkitError as exc:
|
|
130
|
+
typer.echo(str(exc), err=True)
|
|
131
|
+
raise typer.Exit(code=exit_code_of(exc)) from exc
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _selftest_lines(result: SelftestResult) -> list[str]:
|
|
135
|
+
"""The printed report: backend, per-scenario information table, determinism, verdict."""
|
|
136
|
+
lines = [
|
|
137
|
+
f"backend: {result.backend}",
|
|
138
|
+
f"selftest: seed {result.seed}, T={result.t_len}, restarts={result.restarts}",
|
|
139
|
+
]
|
|
140
|
+
for run in result.runs:
|
|
141
|
+
lines.append(
|
|
142
|
+
f"scenario {run.scenario} seed {run.seed} (statistical rows are informational at this size)"
|
|
143
|
+
)
|
|
144
|
+
lines.append(f" {'parameter':<28}{'truth':>10}{'estimate':>12} {'tolerance':<30}within")
|
|
145
|
+
for c in run.rows:
|
|
146
|
+
within = "yes" if c.passed else ("no" if c.evaluated else "n/a")
|
|
147
|
+
lines.append(f" {c.name:<28}{c.truth:>10.4g}{c.estimate:>12.4g} {c.rule:<30}{within}")
|
|
148
|
+
lines.append(f" all fitted values finite: {'yes' if run.finite else 'NO'}")
|
|
149
|
+
lines.append(
|
|
150
|
+
f" determinism (bitwise u over two fits): {'identical' if run.deterministic else 'DIFFERS'}"
|
|
151
|
+
)
|
|
152
|
+
lines.append("selftest " + ("passed" if result.passed else "FAILED"))
|
|
153
|
+
return lines
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _plugin_lines(kind: str | None) -> list[str]:
|
|
157
|
+
"""Rows `kind name distribution version status` of the registered components."""
|
|
158
|
+
from importlib import metadata
|
|
159
|
+
|
|
160
|
+
from hsmmkit.evaluation.metrics.registry import _load_builtin
|
|
161
|
+
from hsmmkit.plugins import KINDS, REGISTRY
|
|
162
|
+
|
|
163
|
+
if kind is not None and kind not in KINDS:
|
|
164
|
+
raise ConfigError(f"unknown registry kind {kind!r}; kinds: {', '.join(KINDS)}", path="--kind")
|
|
165
|
+
_load_builtin()
|
|
166
|
+
core_version = metadata.version("hsmmkit")
|
|
167
|
+
rows: list[tuple[str, str, str, str, str]] = []
|
|
168
|
+
for k in KINDS:
|
|
169
|
+
if kind not in (None, k):
|
|
170
|
+
continue
|
|
171
|
+
infos = {i.name: i for i in REGISTRY.plugin_infos(k, load=True)}
|
|
172
|
+
for entry in REGISTRY.entries(k): # type: ignore[arg-type]
|
|
173
|
+
if entry.name not in infos:
|
|
174
|
+
rows.append((k, entry.name, entry.provenance, core_version, "core"))
|
|
175
|
+
for info in infos.values():
|
|
176
|
+
rows.append((k, info.name, info.distribution, info.version, info.status.splitlines()[0]))
|
|
177
|
+
widths = [max(len(r[i]) for r in rows) if rows else 0 for i in range(4)]
|
|
178
|
+
return [
|
|
179
|
+
f"{r[0]:<{widths[0]}} {r[1]:<{widths[1]}} {r[2]:<{widths[2]}} {r[3]:<{widths[3]}} {r[4]}"
|
|
180
|
+
for r in rows
|
|
181
|
+
]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _import_config_class(dotted: str) -> type[ProjectConfig]:
|
|
185
|
+
"""The `ProjectConfig` subclass at `module.Class`.
|
|
186
|
+
|
|
187
|
+
Raises:
|
|
188
|
+
ConfigError: the module or class does not exist, or is not a `ProjectConfig` subclass.
|
|
189
|
+
"""
|
|
190
|
+
module, _, cls_name = dotted.rpartition(".")
|
|
191
|
+
try:
|
|
192
|
+
cls = getattr(importlib.import_module(module), cls_name)
|
|
193
|
+
except (ImportError, AttributeError, ValueError) as exc:
|
|
194
|
+
raise ConfigError(f"cannot import config class '{dotted}': {exc}", path="--config-class") from exc
|
|
195
|
+
if not (isinstance(cls, type) and issubclass(cls, ProjectConfig)):
|
|
196
|
+
raise ConfigError(f"'{dotted}' is not a ProjectConfig subclass", path="--config-class")
|
|
197
|
+
return cls
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def build_app(
|
|
201
|
+
*,
|
|
202
|
+
name: str,
|
|
203
|
+
config_cls: type[ProjectConfig],
|
|
204
|
+
project_cls: type[Project],
|
|
205
|
+
extra_commands: Sequence[Callable[[typer.Typer], None]] = (),
|
|
206
|
+
) -> CliApp:
|
|
207
|
+
"""A CLI over `project_cls` / `config_cls`; `extra_commands` register further commands on the app.
|
|
208
|
+
|
|
209
|
+
Each extra command is a function of the Typer app (a `CliApp` with its `context`).
|
|
210
|
+
"""
|
|
211
|
+
app = CliApp(name=name)
|
|
212
|
+
ctx = CliContext(name=name, config_cls=config_cls, project_cls=project_cls)
|
|
213
|
+
app.context = ctx
|
|
214
|
+
|
|
215
|
+
@app.callback()
|
|
216
|
+
def _main_callback(
|
|
217
|
+
out: Path | None = typer.Option(
|
|
218
|
+
None, "--out", help="Output directory (overrides project.output_dir)."
|
|
219
|
+
),
|
|
220
|
+
offline: bool = typer.Option(
|
|
221
|
+
False, "--offline", help="Do not access the network (ignored by sources that have none)."
|
|
222
|
+
),
|
|
223
|
+
device: str | None = typer.Option(
|
|
224
|
+
None, "--device", help="cpu|gpu|auto (overrides estimation.device)"
|
|
225
|
+
),
|
|
226
|
+
seed: int | None = typer.Option(None, "--seed", help="Overrides project.seed."),
|
|
227
|
+
log_level: str | None = typer.Option(None, "--log-level", help="Overrides project.log_level."),
|
|
228
|
+
) -> None:
|
|
229
|
+
"""Hidden semi-Markov model regime detection and forecasting."""
|
|
230
|
+
ctx.options = GlobalOptions(out=out, offline=offline, device=device, seed=seed, log_level=log_level)
|
|
231
|
+
|
|
232
|
+
@app.command("validate-config")
|
|
233
|
+
def validate_config_cmd(config_path: Path) -> None:
|
|
234
|
+
"""Validate `config_path`, print a summary, and write the resolved config alongside it."""
|
|
235
|
+
with exit_on_error():
|
|
236
|
+
lines = ctx.project(config_path, logging=False).validate(write=True)
|
|
237
|
+
for line in lines:
|
|
238
|
+
typer.echo(line)
|
|
239
|
+
|
|
240
|
+
@app.command("config-schema")
|
|
241
|
+
def config_schema_cmd(
|
|
242
|
+
out_path: Path,
|
|
243
|
+
config_class: Annotated[
|
|
244
|
+
str | None, typer.Option("--config-class", help="dotted path of a ProjectConfig subclass")
|
|
245
|
+
] = None,
|
|
246
|
+
) -> None:
|
|
247
|
+
"""Write the JSON-Schema of the configuration (or of `--config-class`) to `out_path`."""
|
|
248
|
+
with exit_on_error():
|
|
249
|
+
export_json_schema(out_path, _import_config_class(config_class) if config_class else config_cls)
|
|
250
|
+
|
|
251
|
+
presets_app = typer.Typer(help="Preset configurations with synthetic data.", no_args_is_help=True)
|
|
252
|
+
app.add_typer(presets_app, name="presets")
|
|
253
|
+
|
|
254
|
+
@presets_app.command("list")
|
|
255
|
+
def presets_list_cmd() -> None:
|
|
256
|
+
"""List the registered presets."""
|
|
257
|
+
for preset in list_presets():
|
|
258
|
+
typer.echo(f"{preset.name}\t{preset.description}")
|
|
259
|
+
|
|
260
|
+
@presets_app.command("show")
|
|
261
|
+
def presets_show_cmd(name: str) -> None:
|
|
262
|
+
"""Print the YAML of preset NAME."""
|
|
263
|
+
with exit_on_error():
|
|
264
|
+
typer.echo(get_preset(name).yaml, nl=False)
|
|
265
|
+
|
|
266
|
+
@presets_app.command("write")
|
|
267
|
+
def presets_write_cmd(name: str, directory: Path, seed: int = 0) -> None:
|
|
268
|
+
"""Write preset NAME (YAML and, if it has one, its synthetic data files) into DIRECTORY."""
|
|
269
|
+
with exit_on_error():
|
|
270
|
+
for path in write_preset(name, directory, seed=seed):
|
|
271
|
+
typer.echo(str(path))
|
|
272
|
+
|
|
273
|
+
@app.command("fit")
|
|
274
|
+
def fit_cmd(config_path: Path) -> None:
|
|
275
|
+
"""Load the data, fit, and write the model bundle, `fit_report.json` and `config.resolved.yaml`."""
|
|
276
|
+
with exit_on_error():
|
|
277
|
+
project = ctx.project(config_path)
|
|
278
|
+
data = project.load_data(write=True)
|
|
279
|
+
project.fit(data, write=True)
|
|
280
|
+
|
|
281
|
+
@app.command("decode")
|
|
282
|
+
def decode_cmd(
|
|
283
|
+
config_path: Path,
|
|
284
|
+
model: Path = typer.Option(..., "--model", help="Model bundle directory."),
|
|
285
|
+
augmented: bool = typer.Option(False, "--augmented", help="Also write augmented.parquet."),
|
|
286
|
+
samples: int = typer.Option(
|
|
287
|
+
0, "--samples", min=0, help="Posterior path samples (FFBS): path_samples.parquet, boundary_prob."
|
|
288
|
+
),
|
|
289
|
+
) -> None:
|
|
290
|
+
"""Decode a fitted model against `config_path`'s data: filtered/smoothed/Viterbi/segments/IC."""
|
|
291
|
+
with exit_on_error():
|
|
292
|
+
project = ctx.project(config_path)
|
|
293
|
+
data = ctx.load_prepared(project)
|
|
294
|
+
project.decode(project_cls.load(model), data, write=True, augmented=augmented, samples=samples)
|
|
295
|
+
|
|
296
|
+
@app.command("bootstrap")
|
|
297
|
+
def bootstrap_cmd(
|
|
298
|
+
config_path: Path,
|
|
299
|
+
model: Path = typer.Option(..., "--model", help="Model bundle directory."),
|
|
300
|
+
n_boot: int = typer.Option(200, "--R", min=2, help="Bootstrap replicates."),
|
|
301
|
+
refit_from: str = typer.Option(
|
|
302
|
+
"mle", "--refit-from", help="mle (warm start) or init (init methods)."
|
|
303
|
+
),
|
|
304
|
+
workers: int = typer.Option(1, "--workers", min=1, help="Processes for the replicates."),
|
|
305
|
+
) -> None:
|
|
306
|
+
"""Parametric-bootstrap standard errors: `bootstrap.parquet` and a `## Bootstrap` report section."""
|
|
307
|
+
with exit_on_error():
|
|
308
|
+
configure_logging(ctx.options.log_level or "INFO")
|
|
309
|
+
if refit_from not in ("mle", "init"):
|
|
310
|
+
raise ConfigError("--refit-from must be 'mle' or 'init'", path="refit_from")
|
|
311
|
+
project = ctx.project(config_path)
|
|
312
|
+
data = project.load_batch() if project.is_multi_sequence() else ctx.load_prepared(project)
|
|
313
|
+
project.bootstrap(
|
|
314
|
+
project_cls.load(model),
|
|
315
|
+
data,
|
|
316
|
+
n_boot=n_boot,
|
|
317
|
+
refit_from="init" if refit_from == "init" else "mle",
|
|
318
|
+
workers=workers,
|
|
319
|
+
write=True,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
@app.command("forecast")
|
|
323
|
+
def forecast_cmd(
|
|
324
|
+
config_path: Path,
|
|
325
|
+
model: Path = typer.Option(..., "--model", help="Model bundle directory."),
|
|
326
|
+
horizon: int | None = typer.Option(None, "--horizon", help="Steps ahead (default forecast.horizon)."),
|
|
327
|
+
n_sim: int | None = typer.Option(None, "--n-sim", help="Simulated paths (default forecast.n_sim)."),
|
|
328
|
+
scenario: Path | None = typer.Option(None, "--scenario", help="Scenario CSV of future covariates."),
|
|
329
|
+
samples: bool = typer.Option(False, "--samples", help="Also write forecast_samples.parquet."),
|
|
330
|
+
) -> None:
|
|
331
|
+
"""Monte-Carlo forecast from the end of `config_path`'s data: regime probabilities, quantiles."""
|
|
332
|
+
with exit_on_error():
|
|
333
|
+
project = ctx.project(config_path)
|
|
334
|
+
data = ctx.load_prepared(project)
|
|
335
|
+
project.forecast(
|
|
336
|
+
project_cls.load(model),
|
|
337
|
+
data,
|
|
338
|
+
horizon=horizon,
|
|
339
|
+
n_sim=n_sim,
|
|
340
|
+
scenario=scenario,
|
|
341
|
+
samples=samples,
|
|
342
|
+
write=True,
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
@app.command("simulate")
|
|
346
|
+
def simulate_cmd(
|
|
347
|
+
config_path: Path,
|
|
348
|
+
params: str = typer.Option("config", "--params", help="'config' (init values) or 'model'."),
|
|
349
|
+
model: Path | None = typer.Option(None, "--model", help="Model directory for --params model."),
|
|
350
|
+
steps: int | None = typer.Option(None, "--steps", help="Steps per path (default: dataset length)."),
|
|
351
|
+
n_paths: int = typer.Option(1, "--n-paths", help="Number of simulated paths."),
|
|
352
|
+
) -> None:
|
|
353
|
+
"""Simulate regime/observation paths from the configured (or a fitted) model."""
|
|
354
|
+
with exit_on_error():
|
|
355
|
+
project = ctx.project(config_path)
|
|
356
|
+
check_simulate_args(params, steps, n_paths) # before any data is loaded: it may need the network
|
|
357
|
+
data = ctx.load_prepared(project)
|
|
358
|
+
project.simulate(params, model=model, steps=steps, n_paths=n_paths, data=data, write=True)
|
|
359
|
+
|
|
360
|
+
@app.command("cv")
|
|
361
|
+
def cv_cmd(config_path: Path) -> None:
|
|
362
|
+
"""Cross-validation (`evaluation.cv`): `cv_scores`, `cv_summary` and a `report.md` section."""
|
|
363
|
+
with exit_on_error():
|
|
364
|
+
configure_logging(ctx.options.log_level or "INFO")
|
|
365
|
+
ctx.project(config_path).cross_validate(write=True)
|
|
366
|
+
|
|
367
|
+
@app.command("backtest")
|
|
368
|
+
def backtest_cmd(config_path: Path) -> None:
|
|
369
|
+
"""Walk-forward backtest: metrics, folds, the hooks' frames and `report.md` in the output dir."""
|
|
370
|
+
with exit_on_error():
|
|
371
|
+
ctx.project(config_path).backtest(write=True)
|
|
372
|
+
|
|
373
|
+
@app.command("compare")
|
|
374
|
+
def compare_cmd(
|
|
375
|
+
configs: list[Path] = typer.Argument(
|
|
376
|
+
..., help="Two or more configuration files (one file with --estimators)."
|
|
377
|
+
),
|
|
378
|
+
estimators: str = typer.Option(
|
|
379
|
+
"",
|
|
380
|
+
"--estimators",
|
|
381
|
+
help="Comma-separated estimators (map,em,gem,vb,mcmc): fit ONE config with each.",
|
|
382
|
+
),
|
|
383
|
+
grid: bool = typer.Option(
|
|
384
|
+
False, "--grid", help="Grid model selection over `evaluation.grid` for ONE config."
|
|
385
|
+
),
|
|
386
|
+
allow_mixed: bool = typer.Option(
|
|
387
|
+
False, "--allow-mixed", help="Compare runs on different data snapshots."
|
|
388
|
+
),
|
|
389
|
+
metric: list[str] = typer.Option([], "--metric", help="Only these metrics (repeatable)."),
|
|
390
|
+
reuse: bool = typer.Option(
|
|
391
|
+
False, "--reuse", help="Use a config's stored backtest instead of re-running."
|
|
392
|
+
),
|
|
393
|
+
) -> None:
|
|
394
|
+
"""Backtest several configs and tabulate them (`compare.parquet`, `compare.md` in the output dir)."""
|
|
395
|
+
with exit_on_error():
|
|
396
|
+
configure_logging(ctx.options.log_level or "INFO")
|
|
397
|
+
if grid:
|
|
398
|
+
if len(configs) != 1 or estimators:
|
|
399
|
+
raise ConfigError("--grid takes exactly one configuration file", path="compare")
|
|
400
|
+
ctx.project(configs[0]).compare_grid(
|
|
401
|
+
write=True, out_dir=ctx.options.out or Path("runs") / "compare"
|
|
402
|
+
)
|
|
403
|
+
return
|
|
404
|
+
if estimators:
|
|
405
|
+
if len(configs) != 1:
|
|
406
|
+
raise ConfigError("--estimators takes exactly one configuration file", path="compare")
|
|
407
|
+
project = ctx.project(configs[0])
|
|
408
|
+
project.compare_estimators(
|
|
409
|
+
[e.strip() for e in estimators.split(",") if e.strip()],
|
|
410
|
+
write=True,
|
|
411
|
+
out_dir=ctx.options.out or Path("runs") / "compare",
|
|
412
|
+
)
|
|
413
|
+
return
|
|
414
|
+
project_cls.compare(
|
|
415
|
+
configs,
|
|
416
|
+
allow_mixed=allow_mixed,
|
|
417
|
+
reuse=reuse,
|
|
418
|
+
metrics=metric or None,
|
|
419
|
+
offline=ctx.options.offline,
|
|
420
|
+
overrides=ctx.overrides(),
|
|
421
|
+
out_dir=ctx.options.out or Path("runs") / "compare",
|
|
422
|
+
write=True,
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
@app.command("selftest")
|
|
426
|
+
def selftest_cmd(
|
|
427
|
+
full: bool = typer.Option(
|
|
428
|
+
False,
|
|
429
|
+
"--full/--quick",
|
|
430
|
+
help="--quick (default): R1 and R7; --full: R1-R11, all at the quick size.",
|
|
431
|
+
),
|
|
432
|
+
scenario: list[str] = typer.Option(
|
|
433
|
+
[], "--scenario", help="R1 ... R11 (repeatable); overrides --quick."
|
|
434
|
+
),
|
|
435
|
+
seeds: int = typer.Option(1, "--seeds", min=1, help="Consecutive seeds per scenario."),
|
|
436
|
+
) -> None:
|
|
437
|
+
"""Fit simulated data twice on this backend; exit 4 unless the fits are finite and reproducible."""
|
|
438
|
+
with exit_on_error():
|
|
439
|
+
configure_logging(ctx.options.log_level or "INFO")
|
|
440
|
+
result: SelftestResult = project_cls.selftest(
|
|
441
|
+
seed=ctx.options.seed if ctx.options.seed is not None else 0,
|
|
442
|
+
seeds=seeds,
|
|
443
|
+
scenarios=scenario or None,
|
|
444
|
+
full=full,
|
|
445
|
+
device=ctx.options.device or "cpu",
|
|
446
|
+
)
|
|
447
|
+
for line in _selftest_lines(result):
|
|
448
|
+
typer.echo(line)
|
|
449
|
+
if not result.passed:
|
|
450
|
+
failing = [f"{r.scenario}: {c.line()}" for r in result.runs for c in r.non_finite_rows()]
|
|
451
|
+
bad = [f"{r.scenario} (seed {r.seed})" for r in result.runs if not r.passed]
|
|
452
|
+
detail = "; ".join(failing) if failing else "non-reproducible fit"
|
|
453
|
+
raise NumericalError(f"selftest failed for {', '.join(bad)} ({detail})")
|
|
454
|
+
|
|
455
|
+
plugins_app = typer.Typer(
|
|
456
|
+
help="Components contributed by installed plug-in packages.", no_args_is_help=True
|
|
457
|
+
)
|
|
458
|
+
app.add_typer(plugins_app, name="plugins")
|
|
459
|
+
|
|
460
|
+
@plugins_app.command("list")
|
|
461
|
+
def plugins_list_cmd(
|
|
462
|
+
kind: str | None = typer.Option(None, "--kind", help="Only this registry kind (e.g. emission)."),
|
|
463
|
+
) -> None:
|
|
464
|
+
"""List components: kind, name, distribution, version, status (plug-in modules are imported)."""
|
|
465
|
+
with exit_on_error():
|
|
466
|
+
for line in _plugin_lines(kind):
|
|
467
|
+
typer.echo(line)
|
|
468
|
+
|
|
469
|
+
@app.command("new-family")
|
|
470
|
+
def new_family_cmd(
|
|
471
|
+
name: str,
|
|
472
|
+
kind: str = typer.Option("emission", "--kind", help="emission or duration."),
|
|
473
|
+
directory: Path = typer.Option(Path(), "--dir", help="Parent directory of the new package."),
|
|
474
|
+
) -> None:
|
|
475
|
+
"""Generate an installable plug-in package `hsmmkit-NAME` whose contract tests pass out of the box."""
|
|
476
|
+
with exit_on_error():
|
|
477
|
+
from hsmmkit.scaffold import new_family
|
|
478
|
+
|
|
479
|
+
target = new_family(name, kind=kind, directory=directory)
|
|
480
|
+
typer.echo(f"wrote {target}")
|
|
481
|
+
typer.echo(f"next: cd {target} && pip install -e . && pytest")
|
|
482
|
+
|
|
483
|
+
from hsmmkit.cli.stream import add_stream_command
|
|
484
|
+
|
|
485
|
+
add_stream_command(app, exit_on_error)
|
|
486
|
+
for add in extra_commands:
|
|
487
|
+
add(app)
|
|
488
|
+
return app
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def run(app: typer.Typer) -> None:
|
|
492
|
+
"""Run `app`: `HsmmkitError`s map to their exit codes, anything else to 1 (traceback at DEBUG)."""
|
|
493
|
+
try:
|
|
494
|
+
app()
|
|
495
|
+
except HsmmkitError as exc:
|
|
496
|
+
typer.echo(str(exc), err=True)
|
|
497
|
+
sys.exit(exit_code_of(exc))
|
|
498
|
+
except Exception as exc:
|
|
499
|
+
get_logger("hsmmkit.cli").debug("unexpected_error", traceback=traceback.format_exc())
|
|
500
|
+
typer.echo(f"unexpected error: {exc!r} (rerun with --log-level DEBUG for the traceback)", err=True)
|
|
501
|
+
sys.exit(1)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
app = build_app(name="hsmmkit", config_cls=ProjectConfig, project_cls=Project)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def main() -> None:
|
|
508
|
+
"""Entry point of the core console script `hsmmkit`."""
|
|
509
|
+
run(app)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
if __name__ == "__main__": # pragma: no cover
|
|
513
|
+
main()
|