ts-ara 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.
ts_ara/__init__.py ADDED
@@ -0,0 +1,166 @@
1
+ """ts-ara: Training-free runtime optimization and calibration for t0-gamma."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+
11
+ from ts_ara.calibration import (
12
+ AdaptiveConformalCalibrator,
13
+ CalibratedInterval,
14
+ ConformalQuantileCalibrator,
15
+ DynamicAdaptiveConformalCalibrator,
16
+ empirical_coverage,
17
+ winkler_score,
18
+ )
19
+ from ts_ara.preprocessing import (
20
+ CalendarMode,
21
+ MaskType,
22
+ VariateType,
23
+ batch_series,
24
+ bucket_ragged_series,
25
+ evaluate_covariate_channel,
26
+ filter_uninformative_covariates,
27
+ select_fourier_calendar_cycles,
28
+ )
29
+ from ts_ara.protocol import (
30
+ TIER_SPECS,
31
+ BackendKind,
32
+ Forecast,
33
+ InferenceBackend,
34
+ PrecisionTier,
35
+ TierSpec,
36
+ resolve_tier_path,
37
+ )
38
+
39
+ __version__ = "0.5.0"
40
+
41
+ __all__ = [
42
+ "AdaptiveConformalCalibrator",
43
+ "BackendKind",
44
+ "CalendarMode",
45
+ "CalibratedInterval",
46
+ "ConformalQuantileCalibrator",
47
+ "DynamicAdaptiveConformalCalibrator",
48
+ "Forecast",
49
+ "InferenceBackend",
50
+ "MaskType",
51
+ "PrecisionTier",
52
+ "TIER_SPECS",
53
+ "TSAraForecaster",
54
+ "TierSpec",
55
+ "VariateType",
56
+ "__version__",
57
+ "batch_series",
58
+ "bucket_ragged_series",
59
+ "empirical_coverage",
60
+ "evaluate_covariate_channel",
61
+ "filter_uninformative_covariates",
62
+ "load_tier",
63
+ "resolve_tier_path",
64
+ "select_fourier_calendar_cycles",
65
+ "winkler_score",
66
+ ]
67
+
68
+
69
+ def load_tier(
70
+ tier: PrecisionTier = "ts-ara",
71
+ *,
72
+ backend: BackendKind | None = None,
73
+ exports_dir: str | Path = "exports",
74
+ **kwargs: Any,
75
+ ) -> InferenceBackend:
76
+ """Load a standardized ts-ara tier (``ts-ara`` or ``ts-ara-small``)."""
77
+ key = tier.strip().lower()
78
+ if key not in TIER_SPECS:
79
+ valid = ", ".join(TIER_SPECS)
80
+ raise ValueError(f"Unknown precision tier {tier!r}; expected one of: {valid}")
81
+ target = "onnx" if backend is None else backend.strip().lower()
82
+ if target == "onnx":
83
+ from ts_ara.backends.onnx_backend import OnnxBackend
84
+
85
+ return OnnxBackend.from_tier(key, exports_dir=exports_dir, **kwargs) # type: ignore[arg-type]
86
+ if target == "torch":
87
+ from ts_ara.backends.torch_backend import TorchBackend
88
+
89
+ return TorchBackend.from_tier(key, exports_dir=exports_dir, **kwargs) # type: ignore[arg-type]
90
+ raise ValueError(f"Unknown backend {backend!r}; expected 'torch' or 'onnx'")
91
+
92
+
93
+ class TSAraForecaster:
94
+ """High-level zero-training forecasting facade across dev and deploy tiers."""
95
+
96
+ def __init__(self, backend: InferenceBackend) -> None:
97
+ self.backend = backend
98
+
99
+ @classmethod
100
+ def from_tier(
101
+ cls,
102
+ tier: PrecisionTier = "ts-ara",
103
+ *,
104
+ backend: BackendKind | None = None,
105
+ exports_dir: str | Path = "exports",
106
+ **kwargs: Any,
107
+ ) -> TSAraForecaster:
108
+ """Load any ``ts-ara`` or ``ts-ara-small`` tier."""
109
+ return cls(load_tier(tier, backend=backend, exports_dir=exports_dir, **kwargs))
110
+
111
+ def predict(
112
+ self,
113
+ context: np.ndarray,
114
+ horizon: int,
115
+ quantile_levels: Sequence[float] = (0.1, 0.5, 0.9),
116
+ *,
117
+ future_covariates: np.ndarray | None = None,
118
+ mask: np.ndarray | None = None,
119
+ group_ids: np.ndarray | None = None,
120
+ symmetric_averaging: bool = False,
121
+ drop_constant_covariates: bool = True,
122
+ guard_covariates: bool = False,
123
+ trim_leading_missing: bool = False,
124
+ clip_nonnegative: bool = False,
125
+ snap_integers: bool = False,
126
+ context_scales: Sequence[int] | None = None,
127
+ ) -> Forecast:
128
+ """Forecast from NumPy arrays (set ``guard_covariates=True`` for noisy drivers)."""
129
+ return self.backend.predict_arrays(
130
+ context,
131
+ horizon,
132
+ quantile_levels,
133
+ future_covariates=future_covariates,
134
+ mask=mask,
135
+ group_ids=group_ids,
136
+ symmetric_averaging=symmetric_averaging,
137
+ drop_constant_covariates=drop_constant_covariates,
138
+ guard_covariates=guard_covariates,
139
+ trim_leading_missing=trim_leading_missing,
140
+ clip_nonnegative=clip_nonnegative,
141
+ snap_integers=snap_integers,
142
+ context_scales=context_scales,
143
+ )
144
+
145
+ def predict_df(
146
+ self,
147
+ df: Any,
148
+ horizon: int,
149
+ quantile_levels: Sequence[float] = (0.1, 0.5, 0.9),
150
+ *,
151
+ guard_covariates: bool = False,
152
+ add_calendar_features: CalendarMode = False,
153
+ **kwargs: Any,
154
+ ) -> Any:
155
+ """Forecast a long-format DataFrame (pandas/Polars/PyArrow) via ``narwhals``."""
156
+ from ts_ara.dataframe import predict_df
157
+
158
+ return predict_df(
159
+ self.backend,
160
+ df,
161
+ horizon,
162
+ quantile_levels,
163
+ guard_covariates=guard_covariates,
164
+ add_calendar_features=add_calendar_features,
165
+ **kwargs,
166
+ )
@@ -0,0 +1,19 @@
1
+ """Runtime backends for ts-ara."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__: list[str] = []
6
+
7
+ try:
8
+ from ts_ara.backends.torch_backend import TorchBackend as TorchBackend
9
+
10
+ __all__.append("TorchBackend")
11
+ except ImportError: # pragma: no cover - optional [torch] extra
12
+ pass
13
+
14
+ try:
15
+ from ts_ara.backends.onnx_backend import OnnxBackend as OnnxBackend
16
+
17
+ __all__.append("OnnxBackend")
18
+ except ImportError: # pragma: no cover - optional [onnx] extra
19
+ pass
@@ -0,0 +1,168 @@
1
+ """Shared pure-NumPy backend orchestration helpers (DRY across Torch & ONNX)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Sequence
6
+
7
+ import numpy as np
8
+
9
+ from ts_ara.preprocessing import (
10
+ PreparedBatch,
11
+ apply_history_bounds,
12
+ apply_symmetric_averaging,
13
+ averaged_row_mask,
14
+ bucket_ragged_series,
15
+ make_negated_batch,
16
+ prepare_array_batch,
17
+ run_vincentized_context_predict,
18
+ stack_symmetric_batches,
19
+ unbucket_quantiles,
20
+ validate_quantile_levels,
21
+ with_mirror_levels,
22
+ )
23
+ from ts_ara.protocol import Forecast, InferenceBackend
24
+
25
+ __all__ = ["BatchRolloutFn", "run_predict_arrays", "run_predict_ragged"]
26
+
27
+ BatchRolloutFn = Callable[[PreparedBatch, int, tuple[float, ...]], np.ndarray]
28
+
29
+
30
+ def run_predict_arrays(
31
+ run_batch: BatchRolloutFn,
32
+ context: np.ndarray,
33
+ horizon: int,
34
+ quantile_levels: Sequence[float] = (0.1, 0.5, 0.9),
35
+ *,
36
+ future_covariates: np.ndarray | None = None,
37
+ mask: np.ndarray | None = None,
38
+ group_ids: np.ndarray | None = None,
39
+ symmetric_averaging: bool = False,
40
+ drop_constant_covariates: bool = True,
41
+ guard_covariates: bool = False,
42
+ trim_leading_missing: bool = False,
43
+ clip_nonnegative: bool = False,
44
+ snap_integers: bool = False,
45
+ context_scales: Sequence[int] | None = None,
46
+ stack_symmetric: bool = True,
47
+ ) -> Forecast:
48
+ """Shared array-level prediction orchestration across inference backends."""
49
+ if context_scales is not None:
50
+ return run_vincentized_context_predict(
51
+ lambda ctx, h, future_covariates=None, mask=None, group_ids=None: run_predict_arrays(
52
+ run_batch,
53
+ ctx,
54
+ h,
55
+ quantile_levels,
56
+ future_covariates=future_covariates,
57
+ mask=mask,
58
+ group_ids=group_ids,
59
+ symmetric_averaging=symmetric_averaging,
60
+ drop_constant_covariates=drop_constant_covariates,
61
+ guard_covariates=guard_covariates,
62
+ trim_leading_missing=trim_leading_missing,
63
+ clip_nonnegative=clip_nonnegative,
64
+ snap_integers=snap_integers,
65
+ context_scales=None,
66
+ stack_symmetric=stack_symmetric,
67
+ ),
68
+ context,
69
+ horizon,
70
+ quantile_levels,
71
+ context_scales=context_scales,
72
+ future_covariates=future_covariates,
73
+ mask=mask,
74
+ group_ids=group_ids,
75
+ )
76
+
77
+ requested_levels = validate_quantile_levels(quantile_levels)
78
+ need_history = symmetric_averaging or clip_nonnegative or snap_integers
79
+ batch = prepare_array_batch(
80
+ context,
81
+ horizon,
82
+ future_covariates=future_covariates,
83
+ mask=mask,
84
+ group_ids=group_ids,
85
+ drop_constant_covariates=drop_constant_covariates,
86
+ guard_covariates=guard_covariates,
87
+ trim_leading_missing=trim_leading_missing,
88
+ collect_history=need_history,
89
+ )
90
+
91
+ levels = with_mirror_levels(requested_levels) if symmetric_averaging else requested_levels
92
+ history = batch.observed_history
93
+
94
+ if symmetric_averaging and history is not None and averaged_row_mask(history).any():
95
+ neg_batch = make_negated_batch(batch)
96
+ if stack_symmetric:
97
+ stacked = stack_symmetric_batches(batch, neg_batch)
98
+ out_np = run_batch(stacked, horizon, levels)
99
+ n_targets = len(batch.target_rows)
100
+ pos_np, neg_np = out_np[:n_targets], out_np[n_targets:]
101
+ else:
102
+ pos_np = run_batch(batch, horizon, levels)
103
+ neg_np = run_batch(neg_batch, horizon, levels)
104
+ values = apply_symmetric_averaging(pos_np, neg_np, levels, requested_levels, history)
105
+ else:
106
+ values = run_batch(batch, horizon, levels)
107
+ if symmetric_averaging and history is not None:
108
+ # All rows floored at zero: select requested levels without a second pass.
109
+ values = apply_symmetric_averaging(values, values, levels, requested_levels, history)
110
+
111
+ if history is not None and (clip_nonnegative or snap_integers):
112
+ values = apply_history_bounds(
113
+ values, history, clip_nonnegative=clip_nonnegative, snap_integers=snap_integers
114
+ )
115
+
116
+ if batch.batch_shape is not None:
117
+ values = values.reshape(*batch.batch_shape, *values.shape[1:])
118
+
119
+ return Forecast(
120
+ quantiles=np.ascontiguousarray(values, dtype=np.float32),
121
+ quantile_levels=requested_levels,
122
+ )
123
+
124
+
125
+ def run_predict_ragged(
126
+ backend: InferenceBackend,
127
+ series: Sequence[np.ndarray],
128
+ horizon: int,
129
+ quantile_levels: Sequence[float] = (0.1, 0.5, 0.9),
130
+ *,
131
+ future_covariates: Sequence[np.ndarray | None] | None = None,
132
+ bucket_widths: Sequence[int] | None = None,
133
+ symmetric_averaging: bool = False,
134
+ drop_constant_covariates: bool = True,
135
+ guard_covariates: bool = False,
136
+ trim_leading_missing: bool = False,
137
+ clip_nonnegative: bool = False,
138
+ snap_integers: bool = False,
139
+ context_scales: Sequence[int] | None = None,
140
+ ) -> Forecast:
141
+ """Shared length-bucketed ragged batch orchestration across backends."""
142
+ requested_levels = validate_quantile_levels(quantile_levels)
143
+ buckets, total_rows = bucket_ragged_series(
144
+ series,
145
+ future_covariates=future_covariates,
146
+ patch_size=backend.patch_size,
147
+ bucket_widths=bucket_widths,
148
+ )
149
+ outputs = []
150
+ for bucket in buckets:
151
+ fc = backend.predict_arrays(
152
+ bucket.context,
153
+ horizon,
154
+ requested_levels,
155
+ future_covariates=bucket.future_covariates,
156
+ mask=bucket.mask,
157
+ group_ids=bucket.group_ids,
158
+ symmetric_averaging=symmetric_averaging,
159
+ drop_constant_covariates=drop_constant_covariates,
160
+ guard_covariates=guard_covariates,
161
+ trim_leading_missing=trim_leading_missing,
162
+ clip_nonnegative=clip_nonnegative,
163
+ snap_integers=snap_integers,
164
+ context_scales=context_scales,
165
+ )
166
+ outputs.append((bucket, fc.quantiles))
167
+ merged = unbucket_quantiles(outputs, total_rows)
168
+ return Forecast(quantiles=merged, quantile_levels=requested_levels)
@@ -0,0 +1,235 @@
1
+ # Derived from theforecastingcompany/tfc-t0 under the Apache License, Version 2.0.
2
+ # Modified for ts-ara: dependency-free ONNX Runtime backend sharing pure-NumPy
3
+ # preprocessing, rollout, and quantile logic from ts_ara.preprocessing.
4
+
5
+ """ONNX Runtime inference backend for ts-ara."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from collections.abc import Sequence
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import onnxruntime as ort
16
+
17
+ from ts_ara.backends._common import run_predict_arrays, run_predict_ragged
18
+ from ts_ara.preprocessing import PreparedBatch, run_rollout_np
19
+ from ts_ara.protocol import Forecast, PrecisionTier, resolve_tier_path
20
+
21
+ __all__ = ["OnnxBackend"]
22
+
23
+ DEFAULT_MAX_HORIZON = 1024
24
+
25
+
26
+ def _resolve_config_path(model_path: Path, config_path: str | Path | None) -> Path:
27
+ if config_path is not None:
28
+ p = Path(config_path)
29
+ if not p.is_file():
30
+ raise FileNotFoundError(f"ONNX config file not found: {p}")
31
+ return p
32
+ candidates = [
33
+ model_path.parent / "config.json",
34
+ model_path.parent.parent / "config.json",
35
+ Path("exports") / "config.json",
36
+ Path("models") / "t0-gamma" / "config.json",
37
+ ]
38
+ for candidate in candidates:
39
+ if candidate.is_file():
40
+ return candidate
41
+ raise FileNotFoundError(
42
+ f"Could not locate config.json near {model_path}; pass config_path explicitly."
43
+ )
44
+
45
+
46
+ def _default_session_options() -> ort.SessionOptions:
47
+ """Configure physical-core CPU threading and full graph optimization by default."""
48
+ opts = ort.SessionOptions()
49
+ opts.intra_op_num_threads = max(1, (os.cpu_count() or 2) // 2)
50
+ opts.inter_op_num_threads = 1
51
+ opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
52
+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
53
+ return opts
54
+
55
+
56
+ class OnnxBackend:
57
+ """ONNX Runtime inference backend implementing ``InferenceBackend``."""
58
+
59
+ def __init__(
60
+ self,
61
+ model_path: str | Path,
62
+ config_path: str | Path | None = None,
63
+ *,
64
+ providers: Sequence[str] = ("CPUExecutionProvider",),
65
+ max_horizon: int = DEFAULT_MAX_HORIZON,
66
+ stack_symmetric: bool = True,
67
+ sess_options: ort.SessionOptions | None = None,
68
+ ) -> None:
69
+ self.model_path = Path(model_path)
70
+ if not self.model_path.is_file():
71
+ raise FileNotFoundError(f"ONNX model not found: {self.model_path}")
72
+
73
+ cfg_path = _resolve_config_path(self.model_path, config_path)
74
+ with cfg_path.open("r", encoding="utf-8") as fh:
75
+ cfg = json.load(fh)
76
+
77
+ self._patch_size = int(cfg["patch_size"])
78
+ self._quantile_levels = tuple(float(q) for q in cfg["quantile_levels"])
79
+ self._max_horizon = int(max_horizon)
80
+ self._stack_symmetric = stack_symmetric
81
+
82
+ opts = sess_options if sess_options is not None else _default_session_options()
83
+ self._sess_options = opts
84
+ self.session = ort.InferenceSession(
85
+ str(self.model_path),
86
+ sess_options=opts,
87
+ providers=list(providers),
88
+ )
89
+
90
+ @property
91
+ def sess_options(self) -> ort.SessionOptions:
92
+ """SessionOptions instance passed to ONNX Runtime."""
93
+ return self._sess_options
94
+
95
+ @classmethod
96
+ def from_tier(
97
+ cls,
98
+ tier: PrecisionTier = "ts-ara",
99
+ *,
100
+ exports_dir: str | Path = "exports",
101
+ config_path: str | Path | None = None,
102
+ providers: Sequence[str] = ("CPUExecutionProvider",),
103
+ max_horizon: int = DEFAULT_MAX_HORIZON,
104
+ stack_symmetric: bool = True,
105
+ sess_options: ort.SessionOptions | None = None,
106
+ ) -> OnnxBackend:
107
+ """Load an exported ONNX tier (``ts-ara`` or ``ts-ara-small``)."""
108
+ model_path = resolve_tier_path(tier, backend="onnx", exports_dir=exports_dir)
109
+ return cls(
110
+ model_path,
111
+ config_path=config_path,
112
+ providers=providers,
113
+ max_horizon=max_horizon,
114
+ stack_symmetric=stack_symmetric,
115
+ sess_options=sess_options,
116
+ )
117
+
118
+ @property
119
+ def quantile_levels(self) -> tuple[float, ...]:
120
+ return self._quantile_levels
121
+
122
+ @property
123
+ def patch_size(self) -> int:
124
+ return self._patch_size
125
+
126
+ @property
127
+ def max_horizon(self) -> int:
128
+ return self._max_horizon
129
+
130
+ def _step(
131
+ self,
132
+ variates: np.ndarray,
133
+ mask: np.ndarray,
134
+ group_ids: np.ndarray,
135
+ variate_type: np.ndarray,
136
+ context_patches: int,
137
+ horizon_patches: int,
138
+ ) -> np.ndarray:
139
+ """Run one ONNX graph pass and return ``(rows, horizon_patches * patch_size, Q)``."""
140
+ feeds = {
141
+ "variates": np.ascontiguousarray(variates, dtype=np.float32),
142
+ "mask": np.ascontiguousarray(mask, dtype=np.int8),
143
+ "group_ids": np.ascontiguousarray(group_ids, dtype=np.int64),
144
+ "variate_type": np.ascontiguousarray(variate_type, dtype=np.int64),
145
+ }
146
+ (all_patches,) = self.session.run(["predictions"], feeds)
147
+ rows = all_patches.shape[0]
148
+ p = self._patch_size
149
+ n_q = len(self._quantile_levels)
150
+ sliced = all_patches[:, context_patches - 1 : context_patches - 1 + horizon_patches]
151
+ return np.ascontiguousarray(
152
+ sliced.reshape(rows, horizon_patches * p, n_q), dtype=np.float32
153
+ )
154
+
155
+ def _run_batch(
156
+ self, batch: PreparedBatch, horizon: int, levels: tuple[float, ...]
157
+ ) -> np.ndarray:
158
+ return run_rollout_np(
159
+ self._step,
160
+ batch,
161
+ horizon,
162
+ levels,
163
+ self._quantile_levels,
164
+ self._patch_size,
165
+ self._max_horizon,
166
+ )
167
+
168
+ def predict_arrays(
169
+ self,
170
+ context: np.ndarray,
171
+ horizon: int,
172
+ quantile_levels: Sequence[float] = (0.1, 0.5, 0.9),
173
+ *,
174
+ future_covariates: np.ndarray | None = None,
175
+ mask: np.ndarray | None = None,
176
+ group_ids: np.ndarray | None = None,
177
+ symmetric_averaging: bool = False,
178
+ drop_constant_covariates: bool = True,
179
+ guard_covariates: bool = False,
180
+ trim_leading_missing: bool = False,
181
+ clip_nonnegative: bool = False,
182
+ snap_integers: bool = False,
183
+ context_scales: Sequence[int] | None = None,
184
+ ) -> Forecast:
185
+ """Run ONNX Runtime inference on pure NumPy arrays and return a ``Forecast``."""
186
+ return run_predict_arrays(
187
+ self._run_batch,
188
+ context,
189
+ horizon,
190
+ quantile_levels,
191
+ future_covariates=future_covariates,
192
+ mask=mask,
193
+ group_ids=group_ids,
194
+ symmetric_averaging=symmetric_averaging,
195
+ drop_constant_covariates=drop_constant_covariates,
196
+ guard_covariates=guard_covariates,
197
+ trim_leading_missing=trim_leading_missing,
198
+ clip_nonnegative=clip_nonnegative,
199
+ snap_integers=snap_integers,
200
+ context_scales=context_scales,
201
+ stack_symmetric=self._stack_symmetric,
202
+ )
203
+
204
+ def predict_ragged(
205
+ self,
206
+ series: Sequence[np.ndarray],
207
+ horizon: int,
208
+ quantile_levels: Sequence[float] = (0.1, 0.5, 0.9),
209
+ *,
210
+ future_covariates: Sequence[np.ndarray | None] | None = None,
211
+ bucket_widths: Sequence[int] | None = None,
212
+ symmetric_averaging: bool = False,
213
+ drop_constant_covariates: bool = True,
214
+ guard_covariates: bool = False,
215
+ trim_leading_missing: bool = False,
216
+ clip_nonnegative: bool = False,
217
+ snap_integers: bool = False,
218
+ context_scales: Sequence[int] | None = None,
219
+ ) -> Forecast:
220
+ """Predict ragged series via length-bucketed batching."""
221
+ return run_predict_ragged(
222
+ self,
223
+ series,
224
+ horizon,
225
+ quantile_levels,
226
+ future_covariates=future_covariates,
227
+ bucket_widths=bucket_widths,
228
+ symmetric_averaging=symmetric_averaging,
229
+ drop_constant_covariates=drop_constant_covariates,
230
+ guard_covariates=guard_covariates,
231
+ trim_leading_missing=trim_leading_missing,
232
+ clip_nonnegative=clip_nonnegative,
233
+ snap_integers=snap_integers,
234
+ context_scales=context_scales,
235
+ )