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,495 @@
|
|
|
1
|
+
"""Result writers/readers: the prepared dataset of `hsmmkit fetch`, decode, forecast and simulation outputs.
|
|
2
|
+
|
|
3
|
+
`prepared.parquet` layout: one row per observation; columns `time` (timestamp[ns]), `obs_<m>`,
|
|
4
|
+
`mask_<m>`, `dt`, `cov_<entry point>_<k>` and `label_<n>`; everything else (`clock`, `nominal_dt`,
|
|
5
|
+
covariate names per entry point, `snapshot_ids`, `prep_stats`, the Part II hooks) is JSON in the
|
|
6
|
+
schema metadata under `hsmmkit`. Arrays round-trip bit for bit.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
import jax.numpy as jnp
|
|
16
|
+
import numpy as np
|
|
17
|
+
import pandas as pd
|
|
18
|
+
import pyarrow as pa
|
|
19
|
+
import pyarrow.parquet as pq
|
|
20
|
+
|
|
21
|
+
from hsmmkit.data.contracts import BoundaryConstraints, PreparedDataset
|
|
22
|
+
from hsmmkit.data.prepare import prep_stats_from_json, prep_stats_to_json
|
|
23
|
+
from hsmmkit.evaluation.results import BacktestResult
|
|
24
|
+
from hsmmkit.inference.results import ForecastResult
|
|
25
|
+
from hsmmkit.utils.errors import PersistenceError
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from hsmmkit.inference.results import PosteriorResult
|
|
29
|
+
|
|
30
|
+
_META_KEY = b"hsmmkit"
|
|
31
|
+
_FORMAT = 1
|
|
32
|
+
_ENTRY_POINTS = ("transition", "duration", "emission")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def write_prepared(dataset: PreparedDataset, path: Path | str) -> Path:
|
|
36
|
+
"""Write `dataset` to a parquet file (parent directories are created).
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
The written path (so `read_prepared(write_prepared(ds, p)) == ds`).
|
|
40
|
+
"""
|
|
41
|
+
path = Path(path)
|
|
42
|
+
observations = np.asarray(dataset.observations)
|
|
43
|
+
mask = np.asarray(dataset.mask)
|
|
44
|
+
columns: dict[str, Any] = {"time": pa.array(np.asarray(dataset.times, dtype="datetime64[ns]"))}
|
|
45
|
+
for m in range(observations.shape[1]):
|
|
46
|
+
columns[f"obs_{m}"] = pa.array(observations[:, m])
|
|
47
|
+
columns[f"mask_{m}"] = pa.array(mask[:, m])
|
|
48
|
+
columns["dt"] = pa.array(np.asarray(dataset.dt))
|
|
49
|
+
blocks: dict[str, int | None] = {}
|
|
50
|
+
for ep in _ENTRY_POINTS:
|
|
51
|
+
block = getattr(dataset, f"cov_{ep}")
|
|
52
|
+
blocks[ep] = None if block is None else int(block.shape[1])
|
|
53
|
+
if block is not None:
|
|
54
|
+
values = np.asarray(block)
|
|
55
|
+
for k in range(values.shape[1]):
|
|
56
|
+
columns[f"cov_{ep}_{k}"] = pa.array(values[:, k])
|
|
57
|
+
n_labels = None
|
|
58
|
+
if dataset.labels is not None:
|
|
59
|
+
labels = np.asarray(dataset.labels)
|
|
60
|
+
n_labels = int(labels.shape[1])
|
|
61
|
+
for n in range(n_labels):
|
|
62
|
+
columns[f"label_{n}"] = pa.array(labels[:, n])
|
|
63
|
+
boundaries = dataset.boundaries
|
|
64
|
+
meta = {
|
|
65
|
+
"format": _FORMAT,
|
|
66
|
+
"n_series": int(observations.shape[1]),
|
|
67
|
+
"clock": dataset.clock,
|
|
68
|
+
"nominal_dt": dataset.nominal_dt,
|
|
69
|
+
"blocks": blocks,
|
|
70
|
+
"cov_names": {k: list(v) for k, v in dataset.cov_names.items()},
|
|
71
|
+
"snapshot_ids": list(dataset.snapshot_ids),
|
|
72
|
+
"prep_stats": prep_stats_to_json(dataset.prep_stats),
|
|
73
|
+
"support": dataset.support,
|
|
74
|
+
"series_support": None if dataset.series_support is None else list(dataset.series_support),
|
|
75
|
+
"n_categories": dataset.n_categories,
|
|
76
|
+
"n_labels": n_labels,
|
|
77
|
+
"boundaries": None
|
|
78
|
+
if boundaries is None
|
|
79
|
+
else {
|
|
80
|
+
"must_switch_at": list(boundaries.must_switch_at),
|
|
81
|
+
"must_not_switch_at": list(boundaries.must_not_switch_at),
|
|
82
|
+
},
|
|
83
|
+
"group": dataset.group,
|
|
84
|
+
}
|
|
85
|
+
table = pa.table(columns).replace_schema_metadata({_META_KEY: json.dumps(meta).encode("utf-8")})
|
|
86
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
pq.write_table(table, path)
|
|
88
|
+
return path
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def read_prepared(path: Path | str) -> PreparedDataset:
|
|
92
|
+
"""Read a dataset written by `write_prepared`.
|
|
93
|
+
|
|
94
|
+
Raises:
|
|
95
|
+
PersistenceError: missing file, not a hsmmkit dataset, or an unsupported format version.
|
|
96
|
+
"""
|
|
97
|
+
path = Path(path)
|
|
98
|
+
try:
|
|
99
|
+
table = pq.read_table(path)
|
|
100
|
+
except (OSError, pa.ArrowInvalid) as exc:
|
|
101
|
+
raise PersistenceError(f"cannot read prepared dataset {path}: {exc}", path=str(path)) from exc
|
|
102
|
+
raw = (table.schema.metadata or {}).get(_META_KEY)
|
|
103
|
+
if raw is None:
|
|
104
|
+
raise PersistenceError(f"{path} is not a hsmmkit prepared dataset", path=str(path))
|
|
105
|
+
meta = json.loads(raw)
|
|
106
|
+
if meta.get("format") != _FORMAT:
|
|
107
|
+
raise PersistenceError(f"unsupported prepared-dataset format {meta.get('format')!r}", path=str(path))
|
|
108
|
+
|
|
109
|
+
def col(name: str) -> np.ndarray:
|
|
110
|
+
return np.asarray(table.column(name).to_numpy())
|
|
111
|
+
|
|
112
|
+
def stack(names: list[str], dtype: type) -> np.ndarray:
|
|
113
|
+
if not names: # a (T, 0) block (CLAUDE.md §3.7) has no columns
|
|
114
|
+
return np.empty((table.num_rows, 0), dtype=dtype)
|
|
115
|
+
return np.stack([col(n) for n in names], axis=1)
|
|
116
|
+
|
|
117
|
+
n_series = meta["n_series"]
|
|
118
|
+
observations = np.stack([col(f"obs_{m}") for m in range(n_series)], axis=1)
|
|
119
|
+
mask = np.stack([col(f"mask_{m}") for m in range(n_series)], axis=1)
|
|
120
|
+
blocks: dict[str, Any] = {}
|
|
121
|
+
for ep in _ENTRY_POINTS:
|
|
122
|
+
k = meta["blocks"][ep]
|
|
123
|
+
blocks[ep] = (
|
|
124
|
+
None if k is None else jnp.asarray(stack([f"cov_{ep}_{i}" for i in range(k)], np.float64))
|
|
125
|
+
)
|
|
126
|
+
labels = None
|
|
127
|
+
if meta["n_labels"] is not None:
|
|
128
|
+
labels = jnp.asarray(stack([f"label_{n}" for n in range(meta["n_labels"])], np.bool_))
|
|
129
|
+
b = meta["boundaries"]
|
|
130
|
+
return PreparedDataset(
|
|
131
|
+
times=col("time").astype("datetime64[ns]"),
|
|
132
|
+
observations=jnp.asarray(observations),
|
|
133
|
+
dt=jnp.asarray(col("dt")),
|
|
134
|
+
mask=jnp.asarray(mask),
|
|
135
|
+
cov_transition=blocks["transition"],
|
|
136
|
+
cov_duration=blocks["duration"],
|
|
137
|
+
cov_emission=blocks["emission"],
|
|
138
|
+
cov_names={k: tuple(v) for k, v in meta["cov_names"].items()},
|
|
139
|
+
clock=meta["clock"],
|
|
140
|
+
nominal_dt=meta["nominal_dt"],
|
|
141
|
+
prep_stats=prep_stats_from_json(meta["prep_stats"]),
|
|
142
|
+
snapshot_ids=tuple(meta["snapshot_ids"]),
|
|
143
|
+
support=meta["support"],
|
|
144
|
+
series_support=None if meta.get("series_support") is None else tuple(meta["series_support"]),
|
|
145
|
+
n_categories=meta["n_categories"],
|
|
146
|
+
labels=labels,
|
|
147
|
+
boundaries=None
|
|
148
|
+
if b is None
|
|
149
|
+
else BoundaryConstraints(tuple(b["must_switch_at"]), tuple(b["must_not_switch_at"])),
|
|
150
|
+
group=meta["group"],
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def write_posterior(result: PosteriorResult, out_dir: Path | str, *, augmented: bool = False) -> None:
|
|
155
|
+
"""Write `decode`'s `PosteriorResult` (E6-T02): `posterior.parquet`, `segments.json`, `criteria.json`.
|
|
156
|
+
|
|
157
|
+
`posterior.parquet` has `T` rows and `2N+2` columns: `time`, `filtered_0..N-1`, `smoothed_0..N-1`,
|
|
158
|
+
`viterbi` (the regime path), plus `boundary_prob` after a decode with samples; then
|
|
159
|
+
`path_samples.parquet` (long: `sample`, `t`, `regime`) is written too. `augmented=True` also writes
|
|
160
|
+
`augmented.parquet` (`time` x `S` smoothed expanded-state posterior, `state_0..S-1`).
|
|
161
|
+
|
|
162
|
+
Raises:
|
|
163
|
+
PersistenceError: the output directory cannot be written.
|
|
164
|
+
"""
|
|
165
|
+
out = Path(out_dir)
|
|
166
|
+
try:
|
|
167
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
168
|
+
filtered = np.asarray(result.filtered)
|
|
169
|
+
smoothed = np.asarray(result.smoothed)
|
|
170
|
+
n = filtered.shape[1]
|
|
171
|
+
time_col = pa.array(np.asarray(result.times, dtype="datetime64[ns]"))
|
|
172
|
+
columns: dict[str, Any] = {"time": time_col}
|
|
173
|
+
for i in range(n):
|
|
174
|
+
columns[f"filtered_{i}"] = pa.array(filtered[:, i])
|
|
175
|
+
for i in range(n):
|
|
176
|
+
columns[f"smoothed_{i}"] = pa.array(smoothed[:, i])
|
|
177
|
+
columns["viterbi"] = pa.array(np.asarray(result.viterbi))
|
|
178
|
+
if result.boundary_prob is not None:
|
|
179
|
+
columns["boundary_prob"] = pa.array(np.asarray(result.boundary_prob))
|
|
180
|
+
pq.write_table(pa.table(columns), out / "posterior.parquet")
|
|
181
|
+
if result.path_samples is not None:
|
|
182
|
+
paths = np.asarray(result.path_samples)
|
|
183
|
+
n_draw, t_len = paths.shape
|
|
184
|
+
pq.write_table(
|
|
185
|
+
pa.table(
|
|
186
|
+
{
|
|
187
|
+
"sample": pa.array(np.repeat(np.arange(n_draw, dtype=np.int32), t_len)),
|
|
188
|
+
"t": pa.array(np.tile(np.arange(t_len, dtype=np.int32), n_draw)),
|
|
189
|
+
"regime": pa.array(paths.reshape(-1).astype(np.int32)),
|
|
190
|
+
}
|
|
191
|
+
),
|
|
192
|
+
out / "path_samples.parquet",
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
if augmented:
|
|
196
|
+
aug_smoothed = np.asarray(result.augmented.smoothed)
|
|
197
|
+
aug_columns: dict[str, Any] = {"time": time_col}
|
|
198
|
+
for j in range(aug_smoothed.shape[1]):
|
|
199
|
+
aug_columns[f"state_{j}"] = pa.array(aug_smoothed[:, j])
|
|
200
|
+
pq.write_table(pa.table(aug_columns), out / "augmented.parquet")
|
|
201
|
+
|
|
202
|
+
segments_payload = [{"start": s, "end": e, "regime": r} for s, e, r in result.segments]
|
|
203
|
+
(out / "segments.json").write_text(json.dumps(segments_payload, indent=2), encoding="utf-8")
|
|
204
|
+
criteria_payload = {
|
|
205
|
+
"loglik": result.loglik,
|
|
206
|
+
"aic": result.aic,
|
|
207
|
+
"bic": result.bic,
|
|
208
|
+
"icl": result.icl,
|
|
209
|
+
}
|
|
210
|
+
(out / "criteria.json").write_text(json.dumps(criteria_payload, indent=2), encoding="utf-8")
|
|
211
|
+
except OSError as exc:
|
|
212
|
+
raise PersistenceError(f"cannot write decode outputs to {out}: {exc}", path=str(out)) from exc
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
_FORECAST_COLUMNS = ("origin_time", "horizon_time", "step", "kind", "key", "series", "value")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def write_forecast(
|
|
219
|
+
result: ForecastResult,
|
|
220
|
+
out_dir: Path | str,
|
|
221
|
+
*,
|
|
222
|
+
samples: bool = False,
|
|
223
|
+
snapshot_ids: tuple[str, ...] = (),
|
|
224
|
+
) -> None:
|
|
225
|
+
"""Write `forecast.parquet` (long format), `forecast.json` and optionally `forecast_samples.parquet`.
|
|
226
|
+
|
|
227
|
+
`forecast.parquet` columns: `origin_time`, `horizon_time` (timestamp[ns]), `step` (int64, 1-based),
|
|
228
|
+
`kind` (`regime_prob` | `quantile` | `mean` | `var`), `key` (string: regime index, quantile level as
|
|
229
|
+
`repr(float)`, or series index), `series` (int64; 0 for `regime_prob`) and `value` (float64, bitwise).
|
|
230
|
+
`forecast_samples.parquet` (`samples=True`): `path`, `step`, `series`, `value`.
|
|
231
|
+
|
|
232
|
+
Raises:
|
|
233
|
+
PersistenceError: the output directory cannot be written.
|
|
234
|
+
"""
|
|
235
|
+
out = Path(out_dir)
|
|
236
|
+
probs = np.asarray(result.regime_probs)
|
|
237
|
+
quant = np.asarray(result.cum_quantiles)
|
|
238
|
+
mean, var = np.asarray(result.mean), np.asarray(result.var)
|
|
239
|
+
n_sim, h, m = np.asarray(result.samples).shape
|
|
240
|
+
rows: list[tuple[int, str, str, int, float]] = []
|
|
241
|
+
for k in range(h):
|
|
242
|
+
rows += [(k, "regime_prob", str(i), 0, float(probs[k, i])) for i in range(probs.shape[1])]
|
|
243
|
+
for qi, level in enumerate(result.quantile_levels):
|
|
244
|
+
rows += [(k, "quantile", repr(float(level)), s, float(quant[k, qi, s])) for s in range(m)]
|
|
245
|
+
rows += [(k, "mean", str(s), s, float(mean[k, s])) for s in range(m)]
|
|
246
|
+
rows += [(k, "var", str(s), s, float(var[k, s])) for s in range(m)]
|
|
247
|
+
origin = np.datetime64(result.origin_time, "ns")
|
|
248
|
+
horizon = np.asarray(result.horizon_times, dtype="datetime64[ns]")
|
|
249
|
+
try:
|
|
250
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
251
|
+
table = pa.table(
|
|
252
|
+
{
|
|
253
|
+
"origin_time": pa.array(np.full(len(rows), origin, dtype="datetime64[ns]")),
|
|
254
|
+
"horizon_time": pa.array(horizon[[r[0] for r in rows]]),
|
|
255
|
+
"step": pa.array(np.asarray([r[0] + 1 for r in rows], dtype=np.int64)),
|
|
256
|
+
"kind": pa.array([r[1] for r in rows], type=pa.string()),
|
|
257
|
+
"key": pa.array([r[2] for r in rows], type=pa.string()),
|
|
258
|
+
"series": pa.array(np.asarray([r[3] for r in rows], dtype=np.int64)),
|
|
259
|
+
"value": pa.array(np.asarray([r[4] for r in rows], dtype=np.float64)),
|
|
260
|
+
}
|
|
261
|
+
)
|
|
262
|
+
pq.write_table(table, out / "forecast.parquet")
|
|
263
|
+
summary = {
|
|
264
|
+
"origin_time": str(origin),
|
|
265
|
+
"horizon": h,
|
|
266
|
+
"n_sim": n_sim,
|
|
267
|
+
"n_series": m,
|
|
268
|
+
"n_states": int(probs.shape[1]),
|
|
269
|
+
"covariate_forecaster": result.covariate_forecaster,
|
|
270
|
+
"seed": result.seed,
|
|
271
|
+
"quantile_levels": [float(q) for q in result.quantile_levels],
|
|
272
|
+
"snapshot_ids": list(snapshot_ids),
|
|
273
|
+
}
|
|
274
|
+
(out / "forecast.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
|
|
275
|
+
samples_path = out / "forecast_samples.parquet"
|
|
276
|
+
if samples:
|
|
277
|
+
arr = np.asarray(result.samples, dtype=np.float64)
|
|
278
|
+
path_idx, step_idx, series_idx = np.meshgrid(
|
|
279
|
+
np.arange(n_sim), np.arange(h), np.arange(m), indexing="ij"
|
|
280
|
+
)
|
|
281
|
+
pq.write_table(
|
|
282
|
+
pa.table(
|
|
283
|
+
{
|
|
284
|
+
"path": pa.array(path_idx.reshape(-1).astype(np.int64)),
|
|
285
|
+
"step": pa.array(step_idx.reshape(-1).astype(np.int64) + 1),
|
|
286
|
+
"series": pa.array(series_idx.reshape(-1).astype(np.int64)),
|
|
287
|
+
"value": pa.array(arr.reshape(-1)),
|
|
288
|
+
}
|
|
289
|
+
),
|
|
290
|
+
samples_path,
|
|
291
|
+
)
|
|
292
|
+
elif samples_path.exists():
|
|
293
|
+
samples_path.unlink() # a stale file from an earlier run must not pair with this forecast
|
|
294
|
+
except OSError as exc:
|
|
295
|
+
raise PersistenceError(f"cannot write forecast outputs to {out}: {exc}", path=str(out)) from exc
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def read_forecast(path: Path | str) -> ForecastResult:
|
|
299
|
+
"""Read a `write_forecast` directory back into a `ForecastResult` (values bitwise).
|
|
300
|
+
|
|
301
|
+
`samples` is restored from `forecast_samples.parquet` when present, else it is an empty
|
|
302
|
+
`(0, h, M)` array (`forecast.json` keeps the original `n_sim`).
|
|
303
|
+
|
|
304
|
+
Raises:
|
|
305
|
+
PersistenceError: the directory holds no readable forecast.
|
|
306
|
+
"""
|
|
307
|
+
src = Path(path)
|
|
308
|
+
try:
|
|
309
|
+
table = pq.read_table(src / "forecast.parquet").to_pandas()
|
|
310
|
+
meta = json.loads((src / "forecast.json").read_text(encoding="utf-8"))
|
|
311
|
+
except (OSError, ValueError, pa.ArrowException) as exc:
|
|
312
|
+
raise PersistenceError(f"{src} holds no readable forecast: {exc}", path=str(src)) from exc
|
|
313
|
+
|
|
314
|
+
try:
|
|
315
|
+
h, m, n = int(meta["horizon"]), int(meta["n_series"]), int(meta["n_states"])
|
|
316
|
+
levels = tuple(float(q) for q in meta["quantile_levels"])
|
|
317
|
+
|
|
318
|
+
step = table["step"].to_numpy(dtype=np.int64) - 1
|
|
319
|
+
kind = table["kind"].to_numpy(dtype=object)
|
|
320
|
+
key = table["key"].to_numpy(dtype=object)
|
|
321
|
+
series = table["series"].to_numpy(dtype=np.int64)
|
|
322
|
+
value = table["value"].to_numpy(dtype=np.float64)
|
|
323
|
+
level_pos = {repr(q): i for i, q in enumerate(levels)}
|
|
324
|
+
|
|
325
|
+
probs = np.zeros((h, n))
|
|
326
|
+
quant = np.zeros((h, len(levels), m))
|
|
327
|
+
mean, var = np.zeros((h, m)), np.zeros((h, m))
|
|
328
|
+
for i in range(len(table)):
|
|
329
|
+
if kind[i] == "regime_prob":
|
|
330
|
+
probs[step[i], int(key[i])] = value[i]
|
|
331
|
+
elif kind[i] == "quantile":
|
|
332
|
+
quant[step[i], level_pos[key[i]], series[i]] = value[i]
|
|
333
|
+
elif kind[i] == "mean":
|
|
334
|
+
mean[step[i], series[i]] = value[i]
|
|
335
|
+
elif kind[i] == "var":
|
|
336
|
+
var[step[i], series[i]] = value[i]
|
|
337
|
+
horizon_times = (
|
|
338
|
+
table.drop_duplicates("step")
|
|
339
|
+
.sort_values("step")["horizon_time"]
|
|
340
|
+
.to_numpy()
|
|
341
|
+
.astype("datetime64[ns]")
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
samples_path = src / "forecast_samples.parquet"
|
|
345
|
+
if samples_path.exists():
|
|
346
|
+
flat = pq.read_table(samples_path).to_pandas().sort_values(["path", "step", "series"])
|
|
347
|
+
samples = flat["value"].to_numpy().reshape(-1, h, m)
|
|
348
|
+
else:
|
|
349
|
+
samples = np.zeros((0, h, m))
|
|
350
|
+
|
|
351
|
+
except (KeyError, IndexError, ValueError) as exc:
|
|
352
|
+
raise PersistenceError(f"{src} holds a malformed forecast: {exc!r}", path=str(src)) from exc
|
|
353
|
+
|
|
354
|
+
return ForecastResult(
|
|
355
|
+
origin_time=np.datetime64(meta["origin_time"], "ns"),
|
|
356
|
+
horizon_times=horizon_times,
|
|
357
|
+
regime_probs=jnp.asarray(probs),
|
|
358
|
+
samples=jnp.asarray(samples),
|
|
359
|
+
cum_quantiles=jnp.asarray(quant),
|
|
360
|
+
mean=jnp.asarray(mean),
|
|
361
|
+
var=jnp.asarray(var),
|
|
362
|
+
quantile_levels=levels,
|
|
363
|
+
covariate_forecaster=str(meta["covariate_forecaster"]),
|
|
364
|
+
seed=int(meta["seed"]),
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
_VALUE_COLUMN = "return" # column of `simulation.parquet` (Part I name, kept for compatibility)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def write_simulation(
|
|
372
|
+
out_dir: Path | str,
|
|
373
|
+
*,
|
|
374
|
+
times: np.ndarray,
|
|
375
|
+
regimes: np.ndarray,
|
|
376
|
+
phases: np.ndarray,
|
|
377
|
+
values: np.ndarray,
|
|
378
|
+
segments: list[list[tuple[int, int, int]]],
|
|
379
|
+
) -> None:
|
|
380
|
+
"""Write `simulation.parquet` and `simulation_segments.json`.
|
|
381
|
+
|
|
382
|
+
`simulation.parquet` is long: `path`, `step`, `time`, `regime`, `phase`, `return`
|
|
383
|
+
(the Part I column name, kept for compatibility). `regimes`/`phases` are `(P, T)`, `values`
|
|
384
|
+
`(P, T, M)`, `times` `(T,)`; `step` is 1-based. With `M > 1` the column is split into one per series
|
|
385
|
+
(`<column>_0 .. <column>_{M-1}`). `phase` is the 1-based phase within the regime
|
|
386
|
+
(`StateIndex.phase_of`); segments are `{start, end, regime}`, `end` inclusive.
|
|
387
|
+
|
|
388
|
+
Raises:
|
|
389
|
+
PersistenceError: the output directory cannot be written.
|
|
390
|
+
"""
|
|
391
|
+
out = Path(out_dir)
|
|
392
|
+
n_paths, t_len = regimes.shape
|
|
393
|
+
m = values.shape[2]
|
|
394
|
+
columns: dict[str, Any] = {
|
|
395
|
+
"path": pa.array(np.repeat(np.arange(n_paths, dtype=np.int64), t_len)),
|
|
396
|
+
"step": pa.array(np.tile(np.arange(1, t_len + 1, dtype=np.int64), n_paths)),
|
|
397
|
+
"time": pa.array(np.tile(np.asarray(times, dtype="datetime64[ns]"), n_paths)),
|
|
398
|
+
"regime": pa.array(regimes.reshape(-1).astype(np.int64)),
|
|
399
|
+
"phase": pa.array(phases.reshape(-1).astype(np.int64)),
|
|
400
|
+
}
|
|
401
|
+
if m == 1:
|
|
402
|
+
columns[_VALUE_COLUMN] = pa.array(values[:, :, 0].reshape(-1).astype(np.float64))
|
|
403
|
+
else:
|
|
404
|
+
for s in range(m):
|
|
405
|
+
columns[f"{_VALUE_COLUMN}_{s}"] = pa.array(values[:, :, s].reshape(-1).astype(np.float64))
|
|
406
|
+
payload = [
|
|
407
|
+
{"path": p, "segments": [{"start": a, "end": b, "regime": r} for a, b, r in segs]}
|
|
408
|
+
for p, segs in enumerate(segments)
|
|
409
|
+
]
|
|
410
|
+
try:
|
|
411
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
412
|
+
pq.write_table(pa.table(columns), out / "simulation.parquet")
|
|
413
|
+
(out / "simulation_segments.json").write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
|
414
|
+
except OSError as exc:
|
|
415
|
+
raise PersistenceError(f"cannot write simulation outputs to {out}: {exc}", path=str(out)) from exc
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
# --- backtest (E7-T04) -------------------------------------------------------------------------------
|
|
419
|
+
|
|
420
|
+
_BACKTEST_PARQUET = {
|
|
421
|
+
"metrics": "backtest_metrics.parquet",
|
|
422
|
+
"folds": "backtest_folds.parquet",
|
|
423
|
+
"summary": "backtest_summary.parquet",
|
|
424
|
+
}
|
|
425
|
+
BACKTEST_META = "backtest.json"
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _table(frame: pd.DataFrame) -> pa.Table:
|
|
429
|
+
"""Arrow table of `frame` (no index): `timestamp[ns]` for datetimes, plain `string` for text."""
|
|
430
|
+
cast = {
|
|
431
|
+
c: frame[c].astype("datetime64[ns]")
|
|
432
|
+
for c in frame.columns
|
|
433
|
+
if str(frame[c].dtype).startswith("datetime64")
|
|
434
|
+
}
|
|
435
|
+
table = pa.Table.from_pandas(frame.assign(**cast), preserve_index=False)
|
|
436
|
+
fields = [pa.field(f.name, pa.string()) if pa.types.is_large_string(f.type) else f for f in table.schema]
|
|
437
|
+
return table.cast(pa.schema(fields))
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _stale_extras(out: Path) -> list[str]:
|
|
441
|
+
"""Extras frames of an earlier run in `out` (listed in its `backtest.json`)."""
|
|
442
|
+
try:
|
|
443
|
+
previous = json.loads((out / BACKTEST_META).read_text(encoding="utf-8"))
|
|
444
|
+
return [str(n) for n in previous.get("extras", [])]
|
|
445
|
+
except (OSError, ValueError, AttributeError):
|
|
446
|
+
return []
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def write_backtest(result: BacktestResult, out_dir: Path | str, meta: dict[str, Any]) -> None:
|
|
450
|
+
"""Write a `BacktestResult` and its metadata.
|
|
451
|
+
|
|
452
|
+
Files: `backtest_metrics.parquet` (long: `fold, horizon, metric, value`), `backtest_folds.parquet`,
|
|
453
|
+
`backtest_summary.parquet` (`horizon, metric, mean, sd, n`), one `<name>.parquet` per entry of
|
|
454
|
+
`result.extras` (the names are listed under `extras` in `backtest.json`; files of an earlier run that
|
|
455
|
+
are not in `result.extras` are removed) and `backtest.json` (`meta`).
|
|
456
|
+
|
|
457
|
+
`horizon == 0` marks per-fold model and hook metrics. `meta` must be JSON-serializable.
|
|
458
|
+
|
|
459
|
+
Raises:
|
|
460
|
+
PersistenceError: the output directory cannot be written.
|
|
461
|
+
"""
|
|
462
|
+
out = Path(out_dir)
|
|
463
|
+
try:
|
|
464
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
465
|
+
pq.write_table(_table(result.metrics), out / _BACKTEST_PARQUET["metrics"])
|
|
466
|
+
pq.write_table(_table(result.folds), out / _BACKTEST_PARQUET["folds"])
|
|
467
|
+
pq.write_table(_table(result.summary), out / _BACKTEST_PARQUET["summary"])
|
|
468
|
+
for old in _stale_extras(out):
|
|
469
|
+
(out / f"{old}.parquet").unlink(missing_ok=True)
|
|
470
|
+
for name, frame in result.extras.items():
|
|
471
|
+
pq.write_table(_table(frame), out / f"{name}.parquet")
|
|
472
|
+
stored = {**meta, "extras": sorted(result.extras)} if result.extras else dict(meta)
|
|
473
|
+
(out / BACKTEST_META).write_text(json.dumps(stored, indent=2, sort_keys=True), encoding="utf-8")
|
|
474
|
+
except OSError as exc:
|
|
475
|
+
raise PersistenceError(f"cannot write backtest outputs to {out}: {exc}", path=str(out)) from exc
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def read_backtest(out_dir: Path | str) -> tuple[BacktestResult, dict[str, Any]]:
|
|
479
|
+
"""Restore `(BacktestResult, meta)` written by `write_backtest`.
|
|
480
|
+
|
|
481
|
+
Raises:
|
|
482
|
+
PersistenceError: a file is missing or unreadable.
|
|
483
|
+
"""
|
|
484
|
+
out = Path(out_dir)
|
|
485
|
+
try:
|
|
486
|
+
frames = {k: pq.read_table(out / name).to_pandas() for k, name in _BACKTEST_PARQUET.items()}
|
|
487
|
+
meta = json.loads((out / BACKTEST_META).read_text(encoding="utf-8"))
|
|
488
|
+
names = list(meta.get("extras", [])) if isinstance(meta, dict) else []
|
|
489
|
+
extras = {name: pq.read_table(out / f"{name}.parquet").to_pandas() for name in names}
|
|
490
|
+
except (OSError, ValueError, pa.ArrowException) as exc:
|
|
491
|
+
raise PersistenceError(f"cannot read backtest outputs from {out}: {exc}", path=str(out)) from exc
|
|
492
|
+
if not isinstance(meta, dict) or "snapshot_ids" not in meta:
|
|
493
|
+
raise PersistenceError(f"{out / BACKTEST_META} has no snapshot_ids", path=str(out))
|
|
494
|
+
meta.pop("extras", None)
|
|
495
|
+
return BacktestResult(frames["folds"], frames["metrics"], frames["summary"], extras), meta
|