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.
Files changed (192) hide show
  1. hsmmkit/__init__.py +13 -0
  2. hsmmkit/cli/__init__.py +1 -0
  3. hsmmkit/cli/app.py +513 -0
  4. hsmmkit/cli/stream.py +194 -0
  5. hsmmkit/config/__init__.py +1 -0
  6. hsmmkit/config/defaults.py +13 -0
  7. hsmmkit/config/gates.py +39 -0
  8. hsmmkit/config/migrate.py +53 -0
  9. hsmmkit/config/schema.py +996 -0
  10. hsmmkit/config/yaml_io.py +67 -0
  11. hsmmkit/data/__init__.py +1 -0
  12. hsmmkit/data/batch.py +311 -0
  13. hsmmkit/data/calendar.py +314 -0
  14. hsmmkit/data/clocks.py +165 -0
  15. hsmmkit/data/contracts.py +543 -0
  16. hsmmkit/data/labels.py +150 -0
  17. hsmmkit/data/prepare.py +706 -0
  18. hsmmkit/data/provenance.py +34 -0
  19. hsmmkit/data/quality.py +112 -0
  20. hsmmkit/data/sources/__init__.py +92 -0
  21. hsmmkit/data/sources/base.py +247 -0
  22. hsmmkit/data/sources/csv.py +36 -0
  23. hsmmkit/data/sources/numpy.py +143 -0
  24. hsmmkit/data/sources/pandas.py +33 -0
  25. hsmmkit/data/sources/parquet.py +37 -0
  26. hsmmkit/data/sources/xarray.py +62 -0
  27. hsmmkit/data/transforms.py +129 -0
  28. hsmmkit/engine/__init__.py +1 -0
  29. hsmmkit/engine/approx.py +51 -0
  30. hsmmkit/engine/augmented.py +93 -0
  31. hsmmkit/engine/base.py +134 -0
  32. hsmmkit/engine/batch.py +414 -0
  33. hsmmkit/engine/constraints.py +173 -0
  34. hsmmkit/engine/criteria.py +67 -0
  35. hsmmkit/engine/estep.py +314 -0
  36. hsmmkit/engine/estep_explicit.py +260 -0
  37. hsmmkit/engine/expanded_hmm.py +336 -0
  38. hsmmkit/engine/explicit_dd.py +114 -0
  39. hsmmkit/engine/explicit_duration.py +721 -0
  40. hsmmkit/engine/ffbs.py +229 -0
  41. hsmmkit/engine/parallel.py +98 -0
  42. hsmmkit/engine/viterbi.py +85 -0
  43. hsmmkit/estimation/__init__.py +36 -0
  44. hsmmkit/estimation/compare.py +154 -0
  45. hsmmkit/estimation/ecm.py +106 -0
  46. hsmmkit/estimation/em.py +460 -0
  47. hsmmkit/estimation/gem.py +467 -0
  48. hsmmkit/estimation/gibbs.py +136 -0
  49. hsmmkit/estimation/init.py +578 -0
  50. hsmmkit/estimation/map.py +287 -0
  51. hsmmkit/estimation/mcmc.py +370 -0
  52. hsmmkit/estimation/mstep.py +304 -0
  53. hsmmkit/estimation/newton.py +104 -0
  54. hsmmkit/estimation/objective.py +232 -0
  55. hsmmkit/estimation/optimizers.py +195 -0
  56. hsmmkit/estimation/recovery.py +748 -0
  57. hsmmkit/estimation/recovery_ext.py +557 -0
  58. hsmmkit/estimation/relabel.py +85 -0
  59. hsmmkit/estimation/report.py +167 -0
  60. hsmmkit/estimation/results.py +53 -0
  61. hsmmkit/estimation/selftest.py +154 -0
  62. hsmmkit/estimation/vb.py +508 -0
  63. hsmmkit/evaluation/__init__.py +1 -0
  64. hsmmkit/evaluation/backtest.py +616 -0
  65. hsmmkit/evaluation/compare.py +172 -0
  66. hsmmkit/evaluation/metrics/__init__.py +1 -0
  67. hsmmkit/evaluation/metrics/clustering.py +111 -0
  68. hsmmkit/evaluation/metrics/labels.py +40 -0
  69. hsmmkit/evaluation/metrics/matching.py +103 -0
  70. hsmmkit/evaluation/metrics/model.py +53 -0
  71. hsmmkit/evaluation/metrics/predictive.py +337 -0
  72. hsmmkit/evaluation/metrics/registry.py +154 -0
  73. hsmmkit/evaluation/metrics/segmentation.py +182 -0
  74. hsmmkit/evaluation/padding.py +72 -0
  75. hsmmkit/evaluation/report.py +170 -0
  76. hsmmkit/evaluation/results.py +28 -0
  77. hsmmkit/inference/__init__.py +1 -0
  78. hsmmkit/inference/covariate_forecasters.py +344 -0
  79. hsmmkit/inference/decode.py +185 -0
  80. hsmmkit/inference/forecast.py +475 -0
  81. hsmmkit/inference/results.py +97 -0
  82. hsmmkit/inference/simulate.py +342 -0
  83. hsmmkit/interop/__init__.py +1 -0
  84. hsmmkit/interop/arviz.py +114 -0
  85. hsmmkit/interop/hmmlearn.py +163 -0
  86. hsmmkit/interop/pandas.py +116 -0
  87. hsmmkit/interop/sklearn.py +505 -0
  88. hsmmkit/interop/xarray.py +296 -0
  89. hsmmkit/model/__init__.py +1 -0
  90. hsmmkit/model/build.py +404 -0
  91. hsmmkit/model/conjugate.py +260 -0
  92. hsmmkit/model/dists.py +244 -0
  93. hsmmkit/model/duration/__init__.py +23 -0
  94. hsmmkit/model/duration/base.py +215 -0
  95. hsmmkit/model/duration/explicit.py +205 -0
  96. hsmmkit/model/duration/gamma.py +53 -0
  97. hsmmkit/model/duration/geometric.py +106 -0
  98. hsmmkit/model/duration/hazard.py +23 -0
  99. hsmmkit/model/duration/lognormal.py +56 -0
  100. hsmmkit/model/duration/negbin.py +115 -0
  101. hsmmkit/model/duration/nonparametric.py +120 -0
  102. hsmmkit/model/duration/per_state.py +107 -0
  103. hsmmkit/model/duration/poisson.py +56 -0
  104. hsmmkit/model/duration/weibull.py +61 -0
  105. hsmmkit/model/emission/__init__.py +24 -0
  106. hsmmkit/model/emission/_discrete.py +104 -0
  107. hsmmkit/model/emission/base.py +105 -0
  108. hsmmkit/model/emission/bernoulli.py +131 -0
  109. hsmmkit/model/emission/categorical.py +158 -0
  110. hsmmkit/model/emission/gaussian.py +754 -0
  111. hsmmkit/model/emission/mixture.py +387 -0
  112. hsmmkit/model/emission/msar.py +545 -0
  113. hsmmkit/model/emission/poisson.py +144 -0
  114. hsmmkit/model/emission/product.py +390 -0
  115. hsmmkit/model/emission/student_t.py +454 -0
  116. hsmmkit/model/lattice.py +246 -0
  117. hsmmkit/model/params/__init__.py +45 -0
  118. hsmmkit/model/params/bijectors.py +238 -0
  119. hsmmkit/model/params/manager.py +307 -0
  120. hsmmkit/model/params/priors.py +84 -0
  121. hsmmkit/model/params/spec.py +65 -0
  122. hsmmkit/model/spec.py +43 -0
  123. hsmmkit/model/topology.py +97 -0
  124. hsmmkit/model/transition.py +419 -0
  125. hsmmkit/online/__init__.py +24 -0
  126. hsmmkit/online/alerts.py +181 -0
  127. hsmmkit/online/buffer.py +203 -0
  128. hsmmkit/online/covariates.py +162 -0
  129. hsmmkit/online/em.py +304 -0
  130. hsmmkit/online/filter.py +682 -0
  131. hsmmkit/online/session.py +364 -0
  132. hsmmkit/online/state.py +240 -0
  133. hsmmkit/persistence/__init__.py +1 -0
  134. hsmmkit/persistence/results.py +495 -0
  135. hsmmkit/persistence/store.py +394 -0
  136. hsmmkit/plot/__init__.py +13 -0
  137. hsmmkit/plot/_common.py +56 -0
  138. hsmmkit/plot/diagnostics.py +176 -0
  139. hsmmkit/plot/durations.py +74 -0
  140. hsmmkit/plot/forecast.py +55 -0
  141. hsmmkit/plot/regimes.py +146 -0
  142. hsmmkit/plugins.py +311 -0
  143. hsmmkit/presets/__init__.py +116 -0
  144. hsmmkit/presets/core/counts_poisson_hazard.yaml +61 -0
  145. hsmmkit/presets/core/msar2_hamilton.yaml +59 -0
  146. hsmmkit/presets/core/segmentation_gaussian_ltr.yaml +82 -0
  147. hsmmkit/presets/core/two_regime_gaussian.yaml +60 -0
  148. hsmmkit/presets/fixtures.py +330 -0
  149. hsmmkit/project.py +1106 -0
  150. hsmmkit/py.typed +0 -0
  151. hsmmkit/scaffold.py +80 -0
  152. hsmmkit/selection/__init__.py +30 -0
  153. hsmmkit/selection/bootstrap.py +388 -0
  154. hsmmkit/selection/cv.py +301 -0
  155. hsmmkit/selection/grid.py +412 -0
  156. hsmmkit/selection/ppc.py +199 -0
  157. hsmmkit/selection/pseudo_residuals.py +265 -0
  158. hsmmkit/selection/replicate.py +57 -0
  159. hsmmkit/selection/splitters.py +213 -0
  160. hsmmkit/statespace/__init__.py +1 -0
  161. hsmmkit/statespace/builders.py +317 -0
  162. hsmmkit/statespace/factorial.py +249 -0
  163. hsmmkit/statespace/index.py +85 -0
  164. hsmmkit/statespace/transitions.py +143 -0
  165. hsmmkit/templates/family-plugin/common/README.md.tmpl +9 -0
  166. hsmmkit/templates/family-plugin/common/pyproject.toml.tmpl +19 -0
  167. hsmmkit/templates/family-plugin/common/src/__pkg__/__init__.py.tmpl +7 -0
  168. hsmmkit/templates/family-plugin/common/src/__pkg__/tests/__init__.py.tmpl +0 -0
  169. hsmmkit/templates/family-plugin/duration/family.py.tmpl +19 -0
  170. hsmmkit/templates/family-plugin/duration/test_contract.py.tmpl +14 -0
  171. hsmmkit/templates/family-plugin/emission/family.py.tmpl +95 -0
  172. hsmmkit/templates/family-plugin/emission/test_contract.py.tmpl +48 -0
  173. hsmmkit/testing/__init__.py +6 -0
  174. hsmmkit/testing/clock_contract.py +53 -0
  175. hsmmkit/testing/duration_contract.py +218 -0
  176. hsmmkit/testing/family_contract.py +339 -0
  177. hsmmkit/testing/metric_contract.py +157 -0
  178. hsmmkit/testing/source_contract.py +196 -0
  179. hsmmkit/utils/__init__.py +1 -0
  180. hsmmkit/utils/clock.py +109 -0
  181. hsmmkit/utils/deprecation.py +125 -0
  182. hsmmkit/utils/errors.py +56 -0
  183. hsmmkit/utils/jax_setup.py +48 -0
  184. hsmmkit/utils/logging.py +30 -0
  185. hsmmkit/utils/optional.py +25 -0
  186. hsmmkit/utils/rng.py +49 -0
  187. hsmmkit/utils/typing.py +32 -0
  188. hsmmkit-0.5.0.dist-info/METADATA +84 -0
  189. hsmmkit-0.5.0.dist-info/RECORD +192 -0
  190. hsmmkit-0.5.0.dist-info/WHEEL +4 -0
  191. hsmmkit-0.5.0.dist-info/entry_points.txt +2 -0
  192. hsmmkit-0.5.0.dist-info/licenses/LICENSE +190 -0
@@ -0,0 +1,34 @@
1
+ """Content hashes for snapshot ids (E10-T04b): the clock- and domain-neutral part of the cache machinery."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from collections.abc import Sequence
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+
12
+ def hash_bytes(data: bytes) -> str:
13
+ """Hex sha256 of `data`."""
14
+ return hashlib.sha256(data).hexdigest()
15
+
16
+
17
+ def hash_file(path: Path) -> str:
18
+ """Hex sha256 of the file's bytes."""
19
+ digest = hashlib.sha256()
20
+ with path.open("rb") as handle:
21
+ for block in iter(lambda: handle.read(1 << 20), b""):
22
+ digest.update(block)
23
+ return digest.hexdigest()
24
+
25
+
26
+ def hash_arrays(names: Sequence[str], arrays: Sequence[np.ndarray]) -> str:
27
+ """Hex sha256 over the names and the contiguous array buffers (dtype and shape included)."""
28
+ digest = hashlib.sha256()
29
+ for name, array in zip(names, arrays, strict=True):
30
+ digest.update(name.encode("utf-8") + b"\0")
31
+ arr = np.ascontiguousarray(array)
32
+ digest.update(str(arr.dtype).encode() + str(arr.shape).encode() + b"\0")
33
+ digest.update(arr.tobytes())
34
+ return digest.hexdigest()
@@ -0,0 +1,112 @@
1
+ """Domain-neutral data-quality checks (E10-T05, FR-D06).
2
+
3
+ Run on the raw observations of a source, before the master grid is built:
4
+
5
+ - duplicated timestamps,
6
+ - gaps in the time index (spacing `> 1.5 x` the median spacing; needs timestamps),
7
+ - outliers `|y - median| > 8 x MAD` per series (flag only; the MAD is raw, not rescaled),
8
+ - the staleness histogram of the covariates (from the preparer's `PrepDiagnostics`).
9
+
10
+ An application adds its own checks on top (the finance application: weekday gaps, non-positive values,
11
+ adjustment discontinuities).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Mapping
17
+ from dataclasses import dataclass, field
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from hsmmkit.data.contracts import ObservationSet
24
+
25
+ GAP_FACTOR = 1.5
26
+ OUTLIER_MADS = 8.0
27
+
28
+
29
+ def iso(t: np.datetime64 | pd.Timestamp) -> str:
30
+ """A timestamp as `YYYY-MM-DD` (midnight) or ISO-8601."""
31
+ ts = pd.Timestamp(t)
32
+ return str(ts.date()) if ts == ts.normalize() else ts.isoformat()
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class GenericQuality:
37
+ """Findings of the generic checks; every finding carries its index or timestamp."""
38
+
39
+ n_rows: int
40
+ duplicates: list[str] = field(default_factory=list)
41
+ index_gaps: list[str] = field(default_factory=list)
42
+ outliers: list[dict[str, Any]] = field(default_factory=list)
43
+ staleness: dict[str, dict[str, int]] = field(default_factory=dict)
44
+
45
+
46
+ def staleness_histogram(staleness: np.ndarray) -> dict[str, int]:
47
+ """Counts of grid steps since the print in use became visible; `no_value` where none was usable."""
48
+ values = np.asarray(staleness)
49
+ counts = {
50
+ str(int(v)): int(n) for v, n in zip(*np.unique(values[values >= 0], return_counts=True), strict=True)
51
+ }
52
+ never = int((values < 0).sum())
53
+ if never:
54
+ counts["no_value"] = never
55
+ return counts
56
+
57
+
58
+ def duplicate_times(times: np.ndarray) -> list[str]:
59
+ """The timestamps that occur more than once (listed once each)."""
60
+ index = pd.DatetimeIndex(times)
61
+ return [iso(t) for t in index[index.duplicated(keep="first")].unique()]
62
+
63
+
64
+ def index_gaps(times: np.ndarray) -> list[str]:
65
+ """Timestamps that follow a gap of more than `1.5 x` the median spacing (the first one after the gap)."""
66
+ if times.shape[0] < 3:
67
+ return []
68
+ stamps = np.asarray(times).astype("datetime64[ns]")
69
+ steps = np.diff(stamps).astype(np.int64)
70
+ positive = steps[steps > 0]
71
+ if positive.size == 0:
72
+ return []
73
+ limit = GAP_FACTOR * float(np.median(positive))
74
+ return [iso(stamps[i + 1]) for i in np.flatnonzero(steps > limit)]
75
+
76
+
77
+ def mad_outliers(obs: ObservationSet) -> list[dict[str, Any]]:
78
+ """Values with `|y - median| > 8 x MAD` per series; a series with MAD 0 gets no check."""
79
+ found: list[dict[str, Any]] = []
80
+ values = np.asarray(obs.values, dtype=np.float64)
81
+ for c, name in enumerate(obs.series_names):
82
+ column = values[:, c]
83
+ finite = np.isfinite(column)
84
+ if finite.sum() < 3:
85
+ continue
86
+ median = float(np.median(column[finite]))
87
+ mad = float(np.median(np.abs(column[finite] - median)))
88
+ if mad <= 0:
89
+ continue
90
+ for r in np.flatnonzero(finite & (np.abs(column - median) > OUTLIER_MADS * mad)):
91
+ where = iso(obs.times[r]) if obs.times is not None else str(int(r))
92
+ found.append(
93
+ {
94
+ "at": where,
95
+ "series": name,
96
+ "value": float(column[r]),
97
+ "mads": float(abs(column[r] - median) / mad),
98
+ }
99
+ )
100
+ return sorted(found, key=lambda o: (o["at"], o["series"]))
101
+
102
+
103
+ def generic_checks(obs: ObservationSet, staleness: Mapping[str, np.ndarray] | None = None) -> GenericQuality:
104
+ """Run the generic checks on `obs`; `staleness` maps covariate names to their staleness on the grid."""
105
+ has_times = obs.times is not None
106
+ return GenericQuality(
107
+ n_rows=int(obs.values.shape[0]),
108
+ duplicates=duplicate_times(np.asarray(obs.times)) if has_times else [],
109
+ index_gaps=index_gaps(np.asarray(obs.times)) if has_times else [],
110
+ outliers=mad_outliers(obs),
111
+ staleness={name: staleness_histogram(s) for name, s in (staleness or {}).items()},
112
+ )
@@ -0,0 +1,92 @@
1
+ """Domain-neutral data sources (E10-T04a/b): `numpy`, `pandas`, `csv`, `parquet`, `xarray`.
2
+
3
+ Importing the package registers the sources under the kind `source`. `load_data` is the config-driven
4
+ entry point: it resolves `data.source`, loads, and checks the result against `data.clock`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from hsmmkit.config.schema import DataSection
12
+ from hsmmkit.data.contracts import CovariateSeries, ObservationSet
13
+ from hsmmkit.data.labels import attach_label_file
14
+ from hsmmkit.data.sources import csv as csv # registers `csv`
15
+ from hsmmkit.data.sources import numpy as numpy # registers `numpy`
16
+ from hsmmkit.data.sources import pandas as pandas # registers `pandas`
17
+ from hsmmkit.data.sources import parquet as parquet # registers `parquet`
18
+ from hsmmkit.data.sources import xarray as xarray # registers `xarray` (the library loads lazily)
19
+ from hsmmkit.data.sources.base import Source, TabularOpts, get_source, validate_options
20
+ from hsmmkit.utils.clock import get_clock
21
+ from hsmmkit.utils.errors import ConfigError
22
+
23
+ __all__ = ["Source", "TabularOpts", "get_source", "load_data", "validate_options"]
24
+
25
+
26
+ def load_data(data: DataSection, *, obj: Any | None = None) -> tuple[ObservationSet, list[CovariateSeries]]: # noqa: ANN401
27
+ """Load the observations and the declared covariates of a `data:` section.
28
+
29
+ Covariates without their own `source` are taken from the primary source's covariate columns
30
+ (`column`, else `name`); a covariate with its own `source` takes the first observation series of that
31
+ source.
32
+
33
+ Args:
34
+ data: the `data:` config section.
35
+ obj: the in-memory object of the primary source (a `DataFrame`, a dict of arrays), if any.
36
+
37
+ Returns:
38
+ The observations and one `CovariateSeries` per `data.covariates[i]`, in declared order.
39
+
40
+ Raises:
41
+ ConfigError: unknown source, invalid options, time-less data under a clock that needs times
42
+ (`path="data.clock"`), an unknown covariate column.
43
+ DataError: the data does not satisfy the source contract.
44
+ """
45
+ kind = data.source.kind
46
+ source = get_source(kind)
47
+ options = data.source.options()
48
+ if data.sequences is not None and data.sequences.group_by is not None:
49
+ options["group_column"] = data.sequences.group_by # tabular sources only (others reject the key)
50
+ if data.labels is not None and data.labels.source == "column":
51
+ options["label_column"] = data.labels.column # tabular sources only (others reject the key)
52
+ opts = validate_options(kind, options, "data.source")
53
+ assert opts is not None
54
+ obs, available = source.load(opts, obj=obj)
55
+ if data.labels is not None and data.labels.source == "file":
56
+ assert data.labels.path is not None
57
+ obs = attach_label_file(obs, data.labels.path)
58
+ if obs.times is None and get_clock(data.clock).unit != "step":
59
+ raise ConfigError(
60
+ f"data without a time column needs a step clock (data.clock: steps), not '{data.clock}'",
61
+ path="data.clock",
62
+ )
63
+ by_name = {c.name: c for c in available}
64
+ covs: list[CovariateSeries] = []
65
+ for i, cov in enumerate(data.covariates):
66
+ if cov.source is not None:
67
+ other = get_source(cov.source.kind)
68
+ other_opts = validate_options(
69
+ cov.source.kind, cov.source.options(), f"data.covariates[{i}].source"
70
+ )
71
+ assert other_opts is not None
72
+ other_obs, _ = other.load(other_opts)
73
+ covs.append(
74
+ CovariateSeries(
75
+ name=cov.name,
76
+ times=other_obs.times,
77
+ values=other_obs.values[:, 0].astype("float64"),
78
+ source=other_obs.source,
79
+ series_id=other_obs.series_names[0],
80
+ snapshot_id=other_obs.snapshot_id,
81
+ frequency="grid",
82
+ )
83
+ )
84
+ continue
85
+ column = cov.column or cov.name
86
+ if column not in by_name:
87
+ raise ConfigError(
88
+ f"covariate column '{column}' not found; available: {', '.join(by_name) or '<none>'}",
89
+ path=f"data.covariates[{i}].column",
90
+ )
91
+ covs.append(by_name[column])
92
+ return obs, covs
@@ -0,0 +1,247 @@
1
+ """The `Source` protocol, the tabular options and the shared loading logic (E10-T04a, FR-G04, FR-PL02).
2
+
3
+ A source turns a file or an in-memory object into an `ObservationSet` plus covariate series, without any
4
+ domain knowledge. Sources are registered under the kind `source`; their `options_model` validates the extra
5
+ keys of `data.source:` (error path `data.source.<key>`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping, Sequence
11
+ from pathlib import Path
12
+ from typing import Any, Literal, Protocol, runtime_checkable
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+ import pydantic
17
+ from pydantic import BaseModel, ConfigDict, Field
18
+
19
+ from hsmmkit.data.contracts import CovariateSeries, ObservationSet, times_increase
20
+ from hsmmkit.data.provenance import hash_arrays, hash_file
21
+ from hsmmkit.plugins import REGISTRY
22
+ from hsmmkit.utils.errors import ConfigError, DataError
23
+
24
+ Loaded = tuple[ObservationSet, list[CovariateSeries]]
25
+
26
+
27
+ @runtime_checkable
28
+ class Source(Protocol):
29
+ """A registered data source."""
30
+
31
+ name: str
32
+ options_model: type[BaseModel]
33
+
34
+ def load(self, opts: BaseModel, *, obj: Any | None = None) -> Loaded: # noqa: ANN401
35
+ """Load the observations and the covariate series described by `opts` (or held by `obj`)."""
36
+ ...
37
+
38
+
39
+ class TabularOpts(BaseModel):
40
+ """Options shared by the tabular sources (`pandas`, `csv`, `parquet`).
41
+
42
+ Attributes:
43
+ path: file to read (`csv`, `parquet`).
44
+ observation_columns: the observed series, in model order; `M = len(observation_columns)`.
45
+ time_column: timestamp column (parsed as UTC); `None` = time-less data (valid under a `steps` clock).
46
+ sequence_column: column of sequence ids (`ObservationSet.sequence_ids`, E12-T01a).
47
+ group_column: column holding each sequence's initial-distribution group (`data.sequences.group_by`);
48
+ kept as `ObservationSet.meta["group_values"]`.
49
+ label_column: column of regime labels (`data.labels.column`, E12-T06); kept raw as
50
+ `ObservationSet.meta["label_values"]` (one entry per row) for `Preparer`.
51
+ covariate_columns: columns offered as covariate series.
52
+ dtype: dtype of the observation values.
53
+ """
54
+
55
+ model_config = ConfigDict(extra="forbid")
56
+
57
+ path: Path | None = None
58
+ observation_columns: list[str] = Field(default_factory=list)
59
+ time_column: str | None = None
60
+ sequence_column: str | None = None
61
+ group_column: str | None = None
62
+ label_column: str | None = None
63
+ covariate_columns: list[str] = Field(default_factory=list)
64
+ dtype: Literal["float64", "int64"] = "float64"
65
+
66
+
67
+ def get_source(name: str) -> Source:
68
+ """The registered source `name` (the core sources are registered on first use).
69
+
70
+ Raises:
71
+ ConfigError: unknown name or not a source object (`path="data.source.kind"`).
72
+ """
73
+ import hsmmkit.data.sources # noqa: F401 (registers the core sources)
74
+
75
+ entry = REGISTRY.get("source", name)
76
+ if not isinstance(entry, Source):
77
+ raise ConfigError(
78
+ f"source '{name}' is a configuration section, not a loadable source", path="data.source.kind"
79
+ )
80
+ return entry
81
+
82
+
83
+ def validate_options(
84
+ kind: str, raw: Mapping[str, Any], path: str, *, covariate: bool = False
85
+ ) -> BaseModel | None:
86
+ """`raw` validated by the options model of the source `kind`; `None` if `kind` has no options model.
87
+
88
+ `covariate=True` uses the source's `covariate_options_model` when it declares one.
89
+
90
+ Raises:
91
+ ConfigError: unknown kind or an invalid option (`path="<path>.<key>"`).
92
+ """
93
+ import hsmmkit.data.sources # noqa: F401
94
+
95
+ entry = REGISTRY.get("source", kind)
96
+ options_model = getattr(entry, "options_model", None)
97
+ if covariate:
98
+ options_model = getattr(entry, "covariate_options_model", options_model)
99
+ if options_model is None:
100
+ return None
101
+ try:
102
+ parsed: BaseModel = options_model.model_validate(dict(raw))
103
+ except pydantic.ValidationError as exc:
104
+ first = exc.errors()[0]
105
+ loc = ".".join(str(part) for part in first["loc"])
106
+ raise ConfigError(first["msg"], path=f"{path}.{loc}" if loc else path) from exc
107
+ return parsed
108
+
109
+
110
+ def sha256_file(path: Path) -> str:
111
+ """Hex sha256 of the file's bytes (see `hsmmkit.data.provenance`)."""
112
+ return hash_file(path)
113
+
114
+
115
+ def sha256_arrays(names: Sequence[str], arrays: Sequence[np.ndarray]) -> str:
116
+ """Hex sha256 over the column names and the array buffers (see `hsmmkit.data.provenance`)."""
117
+ return hash_arrays(names, arrays)
118
+
119
+
120
+ def _require_columns(frame: pd.DataFrame, columns: Sequence[str], path: str) -> None:
121
+ for column in columns:
122
+ if column not in frame.columns:
123
+ raise DataError(
124
+ f"column {column!r} not found; available: {', '.join(map(str, frame.columns))}", path=path
125
+ )
126
+
127
+
128
+ def parse_times(
129
+ raw: Any, # noqa: ANN401
130
+ path: str = "data.source.time_column",
131
+ sequence_ids: np.ndarray | None = None,
132
+ ) -> np.ndarray:
133
+ """Timestamps as strictly increasing naive-UTC `datetime64[ns]`.
134
+
135
+ Raises:
136
+ DataError: unparseable or not strictly increasing times (`path`).
137
+ """
138
+ try:
139
+ stamps = pd.to_datetime(pd.Series(np.asarray(raw)), utc=True)
140
+ except (ValueError, TypeError) as exc:
141
+ raise DataError(f"cannot parse the time column: {exc}", path=path) from exc
142
+ if stamps.isna().any():
143
+ raise DataError("the time column holds missing values", path=path)
144
+ times = stamps.dt.tz_localize(None).to_numpy().astype("datetime64[ns]")
145
+ if not times_increase(times, sequence_ids):
146
+ raise DataError("times must be strictly increasing (within each sequence)", path=path)
147
+ return times
148
+
149
+
150
+ def frame_to_loaded(
151
+ frame: pd.DataFrame, opts: TabularOpts, *, source: str, snapshot_id: str | None
152
+ ) -> Loaded:
153
+ """The pandas logic every tabular source delegates to.
154
+
155
+ Args:
156
+ frame: the data.
157
+ opts: the tabular options.
158
+ source: name recorded in `ObservationSet.source`.
159
+ snapshot_id: the sha256 of the file bytes, or `None` to hash the arrays (in-memory data).
160
+
161
+ Raises:
162
+ ConfigError: no `observation_columns`.
163
+ DataError: a missing column (the message names it), bad times, values not convertible to `dtype`.
164
+ """
165
+ if not opts.observation_columns:
166
+ raise ConfigError(
167
+ "observation_columns must name at least one column", path="data.source.observation_columns"
168
+ )
169
+ _require_columns(frame, opts.observation_columns, "data.source.observation_columns")
170
+ if opts.time_column is not None:
171
+ _require_columns(frame, [opts.time_column], "data.source.time_column")
172
+ if opts.sequence_column is not None:
173
+ _require_columns(frame, [opts.sequence_column], "data.source.sequence_column")
174
+ if opts.group_column is not None:
175
+ _require_columns(frame, [opts.group_column], "data.sequences.group_by")
176
+ if bool(frame[opts.group_column].isna().any()):
177
+ raise DataError("the group column has missing values", path="data.sequences.group_by")
178
+ if opts.label_column is not None:
179
+ _require_columns(frame, [opts.label_column], "data.labels.column")
180
+ _require_columns(frame, opts.covariate_columns, "data.source.covariate_columns")
181
+
182
+ try:
183
+ values = frame[opts.observation_columns].to_numpy(dtype=np.dtype(opts.dtype))
184
+ except (ValueError, TypeError) as exc:
185
+ raise DataError(
186
+ f"observation columns cannot be converted to {opts.dtype}: {exc}", path="data.source.dtype"
187
+ ) from exc
188
+ if opts.dtype == "int64" and not np.array_equal(
189
+ values, frame[opts.observation_columns].to_numpy(dtype="float64")
190
+ ):
191
+ raise DataError("observation values are not integral (dtype: int64)", path="data.source.dtype")
192
+ sequence_ids = frame[opts.sequence_column].to_numpy() if opts.sequence_column is not None else None
193
+ times = (
194
+ parse_times(frame[opts.time_column], sequence_ids=sequence_ids)
195
+ if opts.time_column is not None
196
+ else None
197
+ )
198
+ cov_values = {c: frame[c].to_numpy(dtype=np.float64) for c in opts.covariate_columns}
199
+
200
+ if snapshot_id is None:
201
+ names = ["<observations>:" + ",".join(opts.observation_columns), *opts.covariate_columns]
202
+ arrays = [values, *cov_values.values()]
203
+ if times is not None:
204
+ names.append("<time>")
205
+ arrays.append(times.astype("int64"))
206
+ if sequence_ids is not None:
207
+ names.append("<sequence>")
208
+ arrays.append(np.asarray(sequence_ids))
209
+ if opts.group_column is not None:
210
+ names.append("<group>")
211
+ arrays.append(frame[opts.group_column].astype(str).to_numpy())
212
+ if opts.label_column is not None:
213
+ names.append("<labels>")
214
+ arrays.append(frame[opts.label_column].astype(str).to_numpy())
215
+ snapshot_id = sha256_arrays(names, arrays)
216
+
217
+ obs = ObservationSet(
218
+ series_names=tuple(opts.observation_columns),
219
+ times=times,
220
+ values=values,
221
+ source=source,
222
+ snapshot_id=snapshot_id,
223
+ sequence_ids=sequence_ids,
224
+ meta={
225
+ **(
226
+ {}
227
+ if opts.group_column is None
228
+ else {"group_values": frame[opts.group_column].astype(str).tolist()}
229
+ ),
230
+ **({} if opts.label_column is None else {"label_values": frame[opts.label_column].tolist()}),
231
+ },
232
+ )
233
+ obs.validate()
234
+ cov_times = times if times is not None else np.arange(values.shape[0], dtype=np.int64)
235
+ covs = [
236
+ CovariateSeries(
237
+ name=column,
238
+ times=cov_times,
239
+ values=series,
240
+ source=source,
241
+ series_id=column,
242
+ snapshot_id=snapshot_id,
243
+ frequency="grid",
244
+ )
245
+ for column, series in cov_values.items()
246
+ ]
247
+ return obs, covs
@@ -0,0 +1,36 @@
1
+ """The `csv` source: a CSV file read with pandas."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import pandas as pd
8
+ from pydantic import BaseModel
9
+
10
+ from hsmmkit.data.sources.base import Loaded, TabularOpts, frame_to_loaded, sha256_file
11
+ from hsmmkit.plugins import REGISTRY, provenance_of
12
+ from hsmmkit.utils.errors import ConfigError, DataError
13
+
14
+
15
+ class CsvSource:
16
+ """Observations and covariates from a CSV file (`path`)."""
17
+
18
+ name = "csv"
19
+ options_model: type[BaseModel] = TabularOpts
20
+
21
+ def load(self, opts: BaseModel, *, obj: Any | None = None) -> Loaded: # noqa: ANN401
22
+ """Read `opts.path` and delegate to the tabular logic; the snapshot id hashes the file bytes."""
23
+ assert isinstance(opts, TabularOpts)
24
+ if opts.path is None:
25
+ raise ConfigError("the `csv` source needs a path", path="data.source.path")
26
+ path = opts.path.expanduser()
27
+ if not path.is_file():
28
+ raise DataError(f"file not found: {path}", path="data.source.path")
29
+ try:
30
+ frame = pd.read_csv(path)
31
+ except (ValueError, pd.errors.ParserError) as exc:
32
+ raise DataError(f"cannot read {path}: {exc}", path="data.source.path") from exc
33
+ return frame_to_loaded(frame, opts, source=self.name, snapshot_id=sha256_file(path))
34
+
35
+
36
+ REGISTRY.register("source", CsvSource.name, CsvSource(), provenance=provenance_of(__name__))
@@ -0,0 +1,143 @@
1
+ """The `numpy` source: a `.npy` / `.npz` file, or a dict of arrays passed through the Python API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ import numpy as np
10
+ from pydantic import BaseModel, ConfigDict, Field
11
+
12
+ from hsmmkit.data.contracts import CovariateSeries, ObservationSet
13
+ from hsmmkit.data.sources.base import Loaded, parse_times, sha256_arrays, sha256_file
14
+ from hsmmkit.plugins import REGISTRY, provenance_of
15
+ from hsmmkit.utils.errors import ConfigError, DataError
16
+
17
+ _KEYS = ("observations", "times", "covariates", "covariate_names", "sequence_ids")
18
+
19
+
20
+ class NumpyOpts(BaseModel):
21
+ """Options of the `numpy` source.
22
+
23
+ Attributes:
24
+ path: a `.npy` file (observations only) or a `.npz` file with the keys `observations` and the
25
+ optional `times`, `covariates` `(T0, K)`, `covariate_names`, `sequence_ids`.
26
+ observation_columns: optional names of the observed series (default `x0, x1, ...`).
27
+ dtype: dtype of the observation values.
28
+ """
29
+
30
+ model_config = ConfigDict(extra="forbid")
31
+
32
+ path: Path | None = None
33
+ observation_columns: list[str] = Field(default_factory=list)
34
+ dtype: Literal["float64", "int64"] = "float64"
35
+
36
+
37
+ def _arrays_of(opts: NumpyOpts, obj: Any) -> tuple[dict[str, np.ndarray], str | None]: # noqa: ANN401
38
+ """The named arrays and the file digest (`None` for in-memory data)."""
39
+ if obj is not None:
40
+ if not isinstance(obj, Mapping):
41
+ raise ConfigError("the `numpy` source takes a dict of arrays as `obj`", path="data.source.kind")
42
+ arrays = {str(k): np.asarray(v) for k, v in obj.items()}
43
+ digest = None
44
+ else:
45
+ if opts.path is None:
46
+ raise ConfigError("the `numpy` source needs a path or an object", path="data.source.path")
47
+ path = opts.path.expanduser()
48
+ if not path.is_file():
49
+ raise DataError(f"file not found: {path}", path="data.source.path")
50
+ try:
51
+ loaded = np.load(path, allow_pickle=False)
52
+ except (OSError, ValueError) as exc:
53
+ raise DataError(f"cannot read {path}: {exc}", path="data.source.path") from exc
54
+ if isinstance(loaded, np.ndarray):
55
+ arrays = {"observations": loaded}
56
+ else:
57
+ with loaded:
58
+ arrays = {key: np.asarray(loaded[key]) for key in loaded.files}
59
+ digest = sha256_file(path)
60
+ unknown = sorted(set(arrays) - set(_KEYS))
61
+ if unknown:
62
+ raise DataError(f"unknown array key(s) {unknown}; expected {list(_KEYS)}", path="data.source.path")
63
+ if "observations" not in arrays:
64
+ raise DataError("the key 'observations' is missing", path="data.source.observation_columns")
65
+ return arrays, digest
66
+
67
+
68
+ class NumpySource:
69
+ """Observations (and optional times, covariates, sequence ids) from numpy arrays."""
70
+
71
+ name = "numpy"
72
+ options_model: type[BaseModel] = NumpyOpts
73
+
74
+ def load(self, opts: BaseModel, *, obj: Any | None = None) -> Loaded: # noqa: ANN401
75
+ """Load `.npy`/`.npz` (or a dict of arrays); the snapshot id hashes the file or the array buffers."""
76
+ assert isinstance(opts, NumpyOpts)
77
+ arrays, digest = _arrays_of(opts, obj)
78
+ raw = arrays["observations"]
79
+ values = raw.reshape(-1, 1) if raw.ndim == 1 else raw
80
+ try:
81
+ values = values.astype(np.dtype(opts.dtype))
82
+ except (ValueError, TypeError) as exc:
83
+ raise DataError(
84
+ f"observations cannot be converted to {opts.dtype}: {exc}", path="data.source.dtype"
85
+ ) from exc
86
+ if values.ndim != 2:
87
+ raise DataError("observations must be 1-D or 2-D", path="data.source.observation_columns")
88
+ names = tuple(opts.observation_columns) or tuple(f"x{j}" for j in range(values.shape[1]))
89
+ if len(names) != values.shape[1]:
90
+ raise DataError(
91
+ f"observation_columns has {len(names)} names, the observations {values.shape[1]} columns",
92
+ path="data.source.observation_columns",
93
+ )
94
+ times = parse_times(arrays["times"], "data.source.path") if "times" in arrays else None
95
+ sequence_ids = arrays.get("sequence_ids")
96
+ if digest is None:
97
+ labels = ["<names>:" + ",".join(names), *(f"<{k}>" for k in arrays if k != "observations")]
98
+ bufs = [
99
+ values,
100
+ *(
101
+ times.astype("int64") if k == "times" and times is not None else arrays[k]
102
+ for k in arrays
103
+ if k != "observations"
104
+ ),
105
+ ]
106
+ digest = sha256_arrays(labels[:1] + labels[1:], bufs)
107
+ obs = ObservationSet(
108
+ series_names=names,
109
+ times=times,
110
+ values=values,
111
+ source=self.name,
112
+ snapshot_id=digest,
113
+ sequence_ids=sequence_ids,
114
+ )
115
+ obs.validate()
116
+ covs: list[CovariateSeries] = []
117
+ if "covariates" in arrays:
118
+ block = np.asarray(arrays["covariates"], dtype=np.float64)
119
+ block = block.reshape(-1, 1) if block.ndim == 1 else block
120
+ cov_names = (
121
+ [str(n) for n in arrays["covariate_names"]]
122
+ if "covariate_names" in arrays
123
+ else [f"c{k}" for k in range(block.shape[1])]
124
+ )
125
+ if block.shape[0] != values.shape[0] or len(cov_names) != block.shape[1]:
126
+ raise DataError("covariates must have shape (T0, K) with K names", path="data.source.path")
127
+ cov_times = times if times is not None else np.arange(values.shape[0], dtype=np.int64)
128
+ covs = [
129
+ CovariateSeries(
130
+ name=cov_names[k],
131
+ times=cov_times,
132
+ values=block[:, k],
133
+ source=self.name,
134
+ series_id=cov_names[k],
135
+ snapshot_id=digest,
136
+ frequency="grid",
137
+ )
138
+ for k in range(block.shape[1])
139
+ ]
140
+ return obs, covs
141
+
142
+
143
+ REGISTRY.register("source", NumpySource.name, NumpySource(), provenance=provenance_of(__name__))