ectype-data 0.1.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.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
|
@@ -0,0 +1,674 @@
|
|
|
1
|
+
"""Regular single-series temporal model (M19): ``y_t = T_t + S_t + R_t``.
|
|
2
|
+
|
|
3
|
+
* **Trend** ``T_t``: linear, log-linear or piecewise-linear (up to 3 hinge changepoints),
|
|
4
|
+
chosen by held-out extrapolation error on the last 20% of the deseasonalised series.
|
|
5
|
+
* **Seasonality** ``S_t``: one Fourier profile per period (supplied, or detected by FFT). The
|
|
6
|
+
components come from statsmodels MSTL when it is installed (``decomposition="auto"`` or
|
|
7
|
+
``"mstl"``), otherwise from a joint trend + Fourier least-squares fit. Each profile is stored
|
|
8
|
+
as policy-coarsened Fourier coefficients (``K x 2`` array of cosine/sine weights).
|
|
9
|
+
* **Residual** ``R_t``: AR(p), ``p <= 7`` chosen by AIC, with innovations drawn from a fitted
|
|
10
|
+
marginal (``profiling.univariate.fit_marginal``). With several value columns the innovations
|
|
11
|
+
are joined by a Gaussian copula (``models.copulas.GaussianCopula``).
|
|
12
|
+
|
|
13
|
+
The time index ``t`` counts cadence steps from the training start. Generation is deterministic
|
|
14
|
+
(``rng.stream`` + inverse-CDF sampling) and starts each AR recursion with a discarded burn-in.
|
|
15
|
+
Generating a new period extrapolates the trend: that is a modeling assumption, recorded in the
|
|
16
|
+
section's ``"assumptions"`` list, not a verified forecast.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import datetime as dt
|
|
22
|
+
import importlib.util
|
|
23
|
+
import math
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from typing import Any, ClassVar
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
import polars as pl
|
|
29
|
+
from scipy import signal, special
|
|
30
|
+
|
|
31
|
+
from ectype.errors import GenerationError, ProfilingError
|
|
32
|
+
from ectype.fingerprint.core import ArrayStore
|
|
33
|
+
from ectype.fingerprint.disclosure import coarsen, coarsen_array, resolve_policy
|
|
34
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, ModelSpec
|
|
35
|
+
from ectype.models.base import MarginalModel, marginal_from_spec
|
|
36
|
+
from ectype.models.copulas import GaussianCopula
|
|
37
|
+
from ectype.profiling.univariate import fit_marginal
|
|
38
|
+
from ectype.rng import stream
|
|
39
|
+
from ectype.temporal.contract import TemporalRequest, TimeUnit, time_index
|
|
40
|
+
from ectype.temporal.detect import (
|
|
41
|
+
detect_periods,
|
|
42
|
+
duration_us,
|
|
43
|
+
epoch_us,
|
|
44
|
+
infer_cadence,
|
|
45
|
+
is_calendar,
|
|
46
|
+
is_temporal_dtype,
|
|
47
|
+
months_of,
|
|
48
|
+
)
|
|
49
|
+
from ectype.types import LogicalType
|
|
50
|
+
|
|
51
|
+
SECTION_KIND = "regular_series"
|
|
52
|
+
SECTION_FORMAT = 1
|
|
53
|
+
MAX_AR_ORDER = 7
|
|
54
|
+
MAX_CHANGEPOINTS = 3
|
|
55
|
+
MAX_HARMONICS = 10
|
|
56
|
+
MIN_STEPS = 30
|
|
57
|
+
HOLDOUT_FRACTION = 0.2
|
|
58
|
+
#: an alternative trend must beat linear's held-out RMSE by this factor to be chosen
|
|
59
|
+
TREND_PREFERENCE = 0.95
|
|
60
|
+
|
|
61
|
+
_INSTALL_HINT = ("statsmodels is required for MSTL decomposition; install it with "
|
|
62
|
+
"`pip install ectype-data[temporal]` (or use decomposition='fourier')")
|
|
63
|
+
|
|
64
|
+
_DTYPES: dict[str, pl.DataType] = {
|
|
65
|
+
"Float64": pl.Float64(), "Float32": pl.Float32(), "Int64": pl.Int64(), "Int32": pl.Int32(),
|
|
66
|
+
"Int16": pl.Int16(), "Int8": pl.Int8(), "UInt64": pl.UInt64(), "UInt32": pl.UInt32(),
|
|
67
|
+
"UInt16": pl.UInt16(), "UInt8": pl.UInt8(),
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def has_statsmodels() -> bool:
|
|
72
|
+
return importlib.util.find_spec("statsmodels") is not None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _mstl(): # noqa: ANN202 - lazy optional import
|
|
76
|
+
try:
|
|
77
|
+
from statsmodels.tsa.seasonal import MSTL
|
|
78
|
+
except ImportError as e: # pragma: no cover - exercised only without the extra
|
|
79
|
+
raise ImportError(_INSTALL_HINT) from e
|
|
80
|
+
return MSTL
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ---------------------------------------------------------------------------------------------
|
|
84
|
+
# Components
|
|
85
|
+
# ---------------------------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def fourier_basis(t: np.ndarray, period: float, k: int) -> np.ndarray:
|
|
89
|
+
"""``(n, 2k)`` columns ``cos(2 pi j t / P), sin(2 pi j t / P)`` for ``j = 1..k``."""
|
|
90
|
+
t = np.asarray(t, dtype=np.float64)
|
|
91
|
+
cols = []
|
|
92
|
+
for j in range(1, k + 1):
|
|
93
|
+
w = 2.0 * np.pi * j * t / period
|
|
94
|
+
cols += [np.cos(w), np.sin(w)]
|
|
95
|
+
return np.column_stack(cols) if cols else np.zeros((t.size, 0))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _max_harmonics(period: float) -> int:
|
|
99
|
+
return int(max(1, min(MAX_HARMONICS, math.floor((period - 1e-9) / 2.0))))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass
|
|
103
|
+
class SeasonalProfile:
|
|
104
|
+
period: float # in cadence steps
|
|
105
|
+
coef: np.ndarray # (K, 2): cosine and sine weights per harmonic
|
|
106
|
+
|
|
107
|
+
def __call__(self, t: np.ndarray) -> np.ndarray:
|
|
108
|
+
k = self.coef.shape[0]
|
|
109
|
+
return fourier_basis(t, self.period, k) @ self.coef.reshape(-1)
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def amplitude(self) -> float:
|
|
113
|
+
"""Amplitude of the first harmonic."""
|
|
114
|
+
return float(np.hypot(*self.coef[0])) if self.coef.size else 0.0
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def phase(self) -> float:
|
|
118
|
+
"""Peak position of the first harmonic, in steps within ``[0, period)``."""
|
|
119
|
+
if not self.coef.size:
|
|
120
|
+
return 0.0
|
|
121
|
+
a, b = self.coef[0]
|
|
122
|
+
return float((math.atan2(b, a) * self.period / (2 * np.pi)) % self.period)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass
|
|
126
|
+
class Trend:
|
|
127
|
+
kind: str # "linear" | "log_linear" | "piecewise"
|
|
128
|
+
intercept: float
|
|
129
|
+
slope: float # per step (log scale for log_linear)
|
|
130
|
+
changepoints: list[float] = field(default_factory=list) # in steps
|
|
131
|
+
deltas: list[float] = field(default_factory=list) # slope changes at changepoints
|
|
132
|
+
|
|
133
|
+
def __call__(self, t: np.ndarray) -> np.ndarray:
|
|
134
|
+
t = np.asarray(t, dtype=np.float64)
|
|
135
|
+
lin = self.intercept + self.slope * t
|
|
136
|
+
for c, d in zip(self.changepoints, self.deltas, strict=True):
|
|
137
|
+
lin = lin + d * np.maximum(0.0, t - c)
|
|
138
|
+
return np.exp(lin) if self.kind == "log_linear" else lin
|
|
139
|
+
|
|
140
|
+
def final_slope(self) -> float:
|
|
141
|
+
return self.slope + float(sum(self.deltas))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _lstsq(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, float]:
|
|
145
|
+
beta, *_ = np.linalg.lstsq(x, y, rcond=None)
|
|
146
|
+
sse = float(np.sum((y - x @ beta) ** 2))
|
|
147
|
+
return beta, sse
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _bic(sse: float, n: int, k: int) -> float:
|
|
151
|
+
return n * math.log(max(sse, 1e-300) / n) + k * math.log(n)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _fit_piecewise(t: np.ndarray, d: np.ndarray, max_cp: int) -> Trend:
|
|
155
|
+
"""Greedy hinge selection on a candidate grid, keeping changepoints while BIC improves."""
|
|
156
|
+
n = t.size
|
|
157
|
+
lo, hi = t[0] + 0.1 * (t[-1] - t[0]), t[0] + 0.9 * (t[-1] - t[0])
|
|
158
|
+
grid = np.unique(np.round(np.linspace(lo, hi, 25)))
|
|
159
|
+
x = np.column_stack([np.ones(n), t])
|
|
160
|
+
beta, sse = _lstsq(x, d)
|
|
161
|
+
best_bic = _bic(sse, n, 2)
|
|
162
|
+
cps: list[float] = []
|
|
163
|
+
for _ in range(max_cp):
|
|
164
|
+
cand = None
|
|
165
|
+
for g in grid:
|
|
166
|
+
if any(abs(g - c) < 0.05 * (t[-1] - t[0]) for c in cps):
|
|
167
|
+
continue
|
|
168
|
+
xg = np.column_stack([x, np.maximum(0.0, t - g)])
|
|
169
|
+
b, s = _lstsq(xg, d)
|
|
170
|
+
if cand is None or s < cand[1]:
|
|
171
|
+
cand = (g, s, b, xg)
|
|
172
|
+
if cand is None:
|
|
173
|
+
break
|
|
174
|
+
bic = _bic(cand[1], n, x.shape[1] + 2) # slope change + location
|
|
175
|
+
if bic >= best_bic - 2.0:
|
|
176
|
+
break
|
|
177
|
+
best_bic, x, beta = bic, cand[3], cand[2]
|
|
178
|
+
cps.append(float(cand[0]))
|
|
179
|
+
return Trend("piecewise", float(beta[0]), float(beta[1]), cps,
|
|
180
|
+
[float(b) for b in beta[2:]])
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _fit_trend_kind(kind: str, t: np.ndarray, d: np.ndarray) -> Trend | None:
|
|
184
|
+
x = np.column_stack([np.ones(t.size), t])
|
|
185
|
+
if kind == "linear":
|
|
186
|
+
b, _ = _lstsq(x, d)
|
|
187
|
+
return Trend("linear", float(b[0]), float(b[1]))
|
|
188
|
+
if kind == "log_linear":
|
|
189
|
+
if np.min(d) <= 0:
|
|
190
|
+
return None
|
|
191
|
+
b, _ = _lstsq(x, np.log(d))
|
|
192
|
+
return Trend("log_linear", float(b[0]), float(b[1]))
|
|
193
|
+
if kind == "piecewise":
|
|
194
|
+
tr = _fit_piecewise(t, d, MAX_CHANGEPOINTS)
|
|
195
|
+
return tr if tr.changepoints else None
|
|
196
|
+
raise ValueError(kind)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def select_trend(t: np.ndarray, d: np.ndarray, kinds: tuple[str, ...] = (
|
|
200
|
+
"linear", "log_linear", "piecewise")) -> tuple[Trend, dict[str, float]]:
|
|
201
|
+
"""Pick the trend family by held-out extrapolation RMSE, then refit it on all data."""
|
|
202
|
+
n = t.size
|
|
203
|
+
n_hold = max(5, int(round(HOLDOUT_FRACTION * n)))
|
|
204
|
+
tr_t, tr_d, ho_t, ho_d = t[:-n_hold], d[:-n_hold], t[-n_hold:], d[-n_hold:]
|
|
205
|
+
scores: dict[str, float] = {}
|
|
206
|
+
for k in kinds:
|
|
207
|
+
m = _fit_trend_kind(k, tr_t, tr_d)
|
|
208
|
+
if m is None:
|
|
209
|
+
continue
|
|
210
|
+
with np.errstate(all="ignore"):
|
|
211
|
+
err = float(np.sqrt(np.mean((ho_d - m(ho_t)) ** 2)))
|
|
212
|
+
if math.isfinite(err):
|
|
213
|
+
scores[k] = err
|
|
214
|
+
best = "linear"
|
|
215
|
+
for k, err in scores.items():
|
|
216
|
+
if k != "linear" and err < TREND_PREFERENCE * scores.get("linear", math.inf) \
|
|
217
|
+
and err < scores.get(best, math.inf):
|
|
218
|
+
best = k
|
|
219
|
+
final = _fit_trend_kind(best, t, d) or _fit_trend_kind("linear", t, d)
|
|
220
|
+
assert final is not None
|
|
221
|
+
return final, scores
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def fit_ar(r: np.ndarray, max_order: int = MAX_AR_ORDER) -> tuple[np.ndarray, dict[str, float]]:
|
|
225
|
+
"""AR(p) by conditional least squares on a common sample; ``p`` minimises AIC."""
|
|
226
|
+
r = np.asarray(r, dtype=np.float64)
|
|
227
|
+
m = r.size - max_order
|
|
228
|
+
if m < 10:
|
|
229
|
+
return np.zeros(0), {}
|
|
230
|
+
y = r[max_order:]
|
|
231
|
+
lags = np.column_stack([r[max_order - i: r.size - i] for i in range(1, max_order + 1)])
|
|
232
|
+
aic: dict[str, float] = {}
|
|
233
|
+
best: tuple[float, np.ndarray] | None = None
|
|
234
|
+
for p in range(0, max_order + 1):
|
|
235
|
+
if p == 0:
|
|
236
|
+
phi, sse = np.zeros(0), float(np.sum(y ** 2))
|
|
237
|
+
else:
|
|
238
|
+
phi, sse = _lstsq(lags[:, :p], y)
|
|
239
|
+
a = m * math.log(max(sse, 1e-300) / m) + 2 * p
|
|
240
|
+
aic[str(p)] = a
|
|
241
|
+
if best is None or a < best[0] - 1e-9:
|
|
242
|
+
best = (a, phi)
|
|
243
|
+
assert best is not None
|
|
244
|
+
return _stationary(best[1]), aic
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _stationary(phi: np.ndarray) -> np.ndarray:
|
|
248
|
+
phi = np.asarray(phi, dtype=np.float64)
|
|
249
|
+
for _ in range(200):
|
|
250
|
+
if phi.size == 0 or np.all(np.abs(np.roots(np.r_[1.0, -phi])) < 0.995):
|
|
251
|
+
return phi
|
|
252
|
+
phi = phi * 0.97
|
|
253
|
+
return np.zeros(0) # pragma: no cover
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def ar_innovations(r: np.ndarray, phi: np.ndarray, start: int) -> np.ndarray:
|
|
257
|
+
out = r[start:].copy()
|
|
258
|
+
for i, c in enumerate(phi, start=1):
|
|
259
|
+
out -= c * r[start - i: r.size - i]
|
|
260
|
+
return out
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# ---------------------------------------------------------------------------------------------
|
|
264
|
+
# Model
|
|
265
|
+
# ---------------------------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
@dataclass
|
|
269
|
+
class SeriesComponents:
|
|
270
|
+
trend: Trend
|
|
271
|
+
seasonal: list[SeasonalProfile]
|
|
272
|
+
phi: np.ndarray
|
|
273
|
+
innovation: MarginalModel
|
|
274
|
+
dtype: str = "Float64"
|
|
275
|
+
residual_std: float = 0.0
|
|
276
|
+
diagnostics: dict[str, Any] = field(default_factory=dict)
|
|
277
|
+
|
|
278
|
+
def mean(self, t: np.ndarray) -> np.ndarray:
|
|
279
|
+
out = self.trend(t)
|
|
280
|
+
for s in self.seasonal:
|
|
281
|
+
out = out + s(t)
|
|
282
|
+
return out
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class RegularSeriesModel:
|
|
286
|
+
"""Trend + Fourier seasonality + AR residual for value columns on a regular cadence."""
|
|
287
|
+
|
|
288
|
+
kind: ClassVar[str] = SECTION_KIND
|
|
289
|
+
|
|
290
|
+
def __init__(self) -> None:
|
|
291
|
+
self.time_col: str = ""
|
|
292
|
+
self.value_cols: list[str] = []
|
|
293
|
+
self.cadence: str = ""
|
|
294
|
+
self.start: dt.date | dt.datetime | None = None
|
|
295
|
+
self.end: dt.date | dt.datetime | None = None
|
|
296
|
+
self.n_steps: int = 0
|
|
297
|
+
self.time_kind: str = "datetime" # "date" | "datetime"
|
|
298
|
+
self.time_unit: TimeUnit = "us"
|
|
299
|
+
self.time_zone: str | None = None
|
|
300
|
+
self.periods: list[float] = []
|
|
301
|
+
self.decomposition: str = "fourier"
|
|
302
|
+
self.components: dict[str, SeriesComponents] = {}
|
|
303
|
+
self.copula: GaussianCopula | None = None
|
|
304
|
+
self.assumptions: list[str] = []
|
|
305
|
+
self.diagnostics: dict[str, Any] = {}
|
|
306
|
+
self.last_generation: dict[str, Any] = {}
|
|
307
|
+
|
|
308
|
+
# -- time helpers --------------------------------------------------------------------------
|
|
309
|
+
def _steps(self, ts: pl.Series) -> np.ndarray:
|
|
310
|
+
"""Cadence steps of timestamps ``ts`` since the training start."""
|
|
311
|
+
assert self.start is not None
|
|
312
|
+
if is_calendar(self.cadence):
|
|
313
|
+
k = months_of(self.cadence)
|
|
314
|
+
s0 = pl.Series([self.start])
|
|
315
|
+
m0 = s0.dt.year().item() * 12 + s0.dt.month().item() - 1
|
|
316
|
+
m = (ts.dt.year().cast(pl.Int64) * 12 + ts.dt.month().cast(pl.Int64) - 1).to_numpy()
|
|
317
|
+
return (m - m0) / k
|
|
318
|
+
t0 = epoch_us(pl.Series([self.start]).cast(ts.dtype) if ts.dtype != pl.Date
|
|
319
|
+
else pl.Series([self.start]))[0]
|
|
320
|
+
return (epoch_us(ts) - t0) / duration_us(self.cadence)
|
|
321
|
+
|
|
322
|
+
def _coerce_time(self, x: dt.date | dt.datetime) -> dt.date | dt.datetime:
|
|
323
|
+
if self.time_kind == "date":
|
|
324
|
+
return x.date() if isinstance(x, dt.datetime) else x
|
|
325
|
+
if not isinstance(x, dt.datetime):
|
|
326
|
+
return dt.datetime(x.year, x.month, x.day)
|
|
327
|
+
return x
|
|
328
|
+
|
|
329
|
+
def _index(self, start: dt.date | dt.datetime, periods: int | None,
|
|
330
|
+
end: dt.date | dt.datetime | None) -> pl.Series:
|
|
331
|
+
s = time_index(self._coerce_time(start), self.cadence, periods=periods,
|
|
332
|
+
end=None if end is None else self._coerce_time(end),
|
|
333
|
+
time_unit=self.time_unit, time_zone=self.time_zone)
|
|
334
|
+
if self.time_kind == "date":
|
|
335
|
+
return s.cast(pl.Date)
|
|
336
|
+
return s.cast(pl.Datetime(self.time_unit, self.time_zone))
|
|
337
|
+
|
|
338
|
+
# -- fit -------------------------------------------------------------------------------------
|
|
339
|
+
def fit(self, df: pl.DataFrame, time_col: str, value_cols: list[str] | str,
|
|
340
|
+
policy: DisclosurePolicySpec | str | None = None, seed: int = 0, *,
|
|
341
|
+
periods: list[float] | None = None, decomposition: str = "auto",
|
|
342
|
+
max_periods: int = 3) -> RegularSeriesModel:
|
|
343
|
+
"""Fit on ``df``. ``periods`` (in cadence steps) override FFT detection;
|
|
344
|
+
``decomposition`` is ``"auto"`` (MSTL if statsmodels is installed, else Fourier),
|
|
345
|
+
``"mstl"`` or ``"fourier"``."""
|
|
346
|
+
pol = resolve_policy(policy)
|
|
347
|
+
cols = [value_cols] if isinstance(value_cols, str) else list(value_cols)
|
|
348
|
+
if time_col not in df.columns:
|
|
349
|
+
raise ProfilingError(f"time column {time_col!r} not found")
|
|
350
|
+
if not is_temporal_dtype(df.schema[time_col]):
|
|
351
|
+
raise ProfilingError(f"time column {time_col!r} must be pl.Date or pl.Datetime, "
|
|
352
|
+
f"not {df.schema[time_col]}")
|
|
353
|
+
for c in cols:
|
|
354
|
+
if c not in df.columns or not df.schema[c].is_numeric():
|
|
355
|
+
raise ProfilingError(f"value column {c!r} must be an existing numeric column")
|
|
356
|
+
if not cols:
|
|
357
|
+
raise ProfilingError("at least one value column is required")
|
|
358
|
+
if decomposition not in ("auto", "mstl", "fourier"):
|
|
359
|
+
raise ProfilingError(f"unknown decomposition {decomposition!r}")
|
|
360
|
+
if decomposition == "mstl" and not has_statsmodels():
|
|
361
|
+
raise ImportError(_INSTALL_HINT)
|
|
362
|
+
use_mstl = decomposition == "mstl" or (decomposition == "auto" and has_statsmodels())
|
|
363
|
+
|
|
364
|
+
tdt = df.schema[time_col]
|
|
365
|
+
self.time_kind = "date" if tdt == pl.Date else "datetime"
|
|
366
|
+
if isinstance(tdt, pl.Datetime):
|
|
367
|
+
self.time_unit, self.time_zone = tdt.time_unit or "us", tdt.time_zone
|
|
368
|
+
self.time_col, self.value_cols = time_col, cols
|
|
369
|
+
|
|
370
|
+
# ---- regular grid ----------------------------------------------------------------
|
|
371
|
+
d0 = df.select([time_col, *cols]).filter(pl.col(time_col).is_not_null())
|
|
372
|
+
n_dup = d0.height - d0[time_col].n_unique()
|
|
373
|
+
d0 = d0.group_by(time_col).agg([pl.col(c).cast(pl.Float64).mean() for c in cols]) \
|
|
374
|
+
.sort(time_col)
|
|
375
|
+
cad = infer_cadence(epoch_us(d0[time_col]))
|
|
376
|
+
if cad.cadence is None or d0.height < MIN_STEPS:
|
|
377
|
+
raise ProfilingError(f"{time_col!r} is not a regular series with >= {MIN_STEPS} "
|
|
378
|
+
f"steps (regularity {cad.regularity:.2f}, {d0.height} "
|
|
379
|
+
f"distinct timestamps); use an event or panel model")
|
|
380
|
+
self.cadence = cad.cadence
|
|
381
|
+
self.start, self.end = d0[time_col][0], d0[time_col][-1]
|
|
382
|
+
grid = self._index(self.start, None, self.end).alias(time_col).to_frame()
|
|
383
|
+
full = grid.join(d0, on=time_col, how="left")
|
|
384
|
+
n_filled = {c: int(full[c].null_count()) for c in cols}
|
|
385
|
+
full = full.with_columns([pl.col(c).interpolate().forward_fill().backward_fill()
|
|
386
|
+
for c in cols])
|
|
387
|
+
self.n_steps = full.height
|
|
388
|
+
if self.n_steps < MIN_STEPS:
|
|
389
|
+
raise ProfilingError(f"series too short: {self.n_steps} < {MIN_STEPS} steps")
|
|
390
|
+
t = np.arange(self.n_steps, dtype=np.float64)
|
|
391
|
+
|
|
392
|
+
# ---- periods ---------------------------------------------------------------------
|
|
393
|
+
if periods is not None:
|
|
394
|
+
per = sorted(float(p) for p in periods)
|
|
395
|
+
else:
|
|
396
|
+
found: set[float] = set()
|
|
397
|
+
for c in cols:
|
|
398
|
+
found.update(detect_periods(full[c].to_numpy(), cadence=self.cadence,
|
|
399
|
+
max_periods=max_periods))
|
|
400
|
+
per = []
|
|
401
|
+
for p in sorted(found): # merge near-identical estimates from different columns
|
|
402
|
+
if not per or p > 1.05 * per[-1]:
|
|
403
|
+
per.append(p)
|
|
404
|
+
per = per[:max_periods]
|
|
405
|
+
per = [p for p in per if 2.0 <= p < self.n_steps / 2.0]
|
|
406
|
+
self.periods = [coarsen(p, pol) for p in per]
|
|
407
|
+
self.decomposition = "mstl" if (use_mstl and per) else "fourier"
|
|
408
|
+
|
|
409
|
+
# ---- per-column components -------------------------------------------------------
|
|
410
|
+
innov: dict[str, np.ndarray] = {}
|
|
411
|
+
for c in cols:
|
|
412
|
+
y = full[c].to_numpy().astype(np.float64)
|
|
413
|
+
seasonal = self._fit_seasonal(t, y, per, pol)
|
|
414
|
+
s_sum = sum((s(t) for s in seasonal), np.zeros_like(t))
|
|
415
|
+
dseas = y - s_sum
|
|
416
|
+
trend, scores = select_trend(t, dseas)
|
|
417
|
+
trend = _coarsen_trend(trend, pol)
|
|
418
|
+
r = dseas - trend(t)
|
|
419
|
+
phi, aic = fit_ar(r)
|
|
420
|
+
phi = _stationary(coarsen_array(phi, pol)) if phi.size else phi
|
|
421
|
+
e = ar_innovations(r, phi, MAX_AR_ORDER)
|
|
422
|
+
innov[c] = e
|
|
423
|
+
col_schema = ColumnSchema(name=f"{c}__innovation",
|
|
424
|
+
logical_type=LogicalType.CONTINUOUS,
|
|
425
|
+
physical_dtype="Float64")
|
|
426
|
+
marg, mdiag = fit_marginal(e, col_schema, pol, stream(seed, "temporal", "regular",
|
|
427
|
+
"innovation", c))
|
|
428
|
+
self.components[c] = SeriesComponents(
|
|
429
|
+
trend=trend, seasonal=seasonal, phi=phi, innovation=marg,
|
|
430
|
+
dtype=str(df.schema[c]), residual_std=coarsen(float(np.std(r)), pol),
|
|
431
|
+
diagnostics={"trend_holdout_rmse": {k: coarsen(v, pol)
|
|
432
|
+
for k, v in scores.items()},
|
|
433
|
+
"ar_aic": {k: coarsen(v, pol) for k, v in aic.items()},
|
|
434
|
+
"innovation_marginal": mdiag.get("chosen"),
|
|
435
|
+
"n_filled": n_filled[c]})
|
|
436
|
+
|
|
437
|
+
# ---- innovation copula -----------------------------------------------------------
|
|
438
|
+
self.copula = None
|
|
439
|
+
if len(cols) > 1:
|
|
440
|
+
z = np.column_stack([
|
|
441
|
+
special.ndtri(np.clip(self.components[c].innovation.cdf(innov[c]),
|
|
442
|
+
1e-6, 1 - 1e-6)) for c in cols])
|
|
443
|
+
self.copula = GaussianCopula.fit(z, cols, policy=pol)
|
|
444
|
+
|
|
445
|
+
self.diagnostics = {"n_steps": self.n_steps, "n_duplicate_timestamps": int(n_dup),
|
|
446
|
+
"regularity": coarsen(cad.regularity, pol),
|
|
447
|
+
"n_gaps": cad.n_gaps,
|
|
448
|
+
"periods_source": "supplied" if periods is not None else "fft"}
|
|
449
|
+
self.assumptions = self._assumptions()
|
|
450
|
+
return self
|
|
451
|
+
|
|
452
|
+
def _fit_seasonal(self, t: np.ndarray, y: np.ndarray, per: list[float],
|
|
453
|
+
pol: DisclosurePolicySpec) -> list[SeasonalProfile]:
|
|
454
|
+
if not per:
|
|
455
|
+
return []
|
|
456
|
+
n = t.size
|
|
457
|
+
ones = np.column_stack([np.ones(n), t])
|
|
458
|
+
if self.decomposition == "mstl":
|
|
459
|
+
mstl = _mstl()
|
|
460
|
+
res = mstl(y, periods=[max(2, int(round(p))) for p in per]).fit()
|
|
461
|
+
comps = np.asarray(res.seasonal).reshape(n, -1)
|
|
462
|
+
out = []
|
|
463
|
+
for j, p in enumerate(per):
|
|
464
|
+
k = _choose_k(t, comps[:, j], [p], ones[:, :1], j=0)
|
|
465
|
+
x = fourier_basis(t, p, k)
|
|
466
|
+
b, _ = _lstsq(np.column_stack([np.ones(n), x]), comps[:, j])
|
|
467
|
+
out.append(SeasonalProfile(p, coarsen_array(b[1:].reshape(k, 2), pol)))
|
|
468
|
+
return out
|
|
469
|
+
# joint trend + Fourier least squares
|
|
470
|
+
ks = [_max_harmonics(p) for p in per]
|
|
471
|
+
for j, p in enumerate(per):
|
|
472
|
+
others = [fourier_basis(t, q, ks[i]) for i, q in enumerate(per) if i != j]
|
|
473
|
+
base = np.column_stack([ones, *others]) if others else ones
|
|
474
|
+
ks[j] = _choose_k(t, y, [p], base, j=0)
|
|
475
|
+
x = np.column_stack([ones, *[fourier_basis(t, p, k) for p, k in zip(per, ks,
|
|
476
|
+
strict=True)]])
|
|
477
|
+
b, _ = _lstsq(x, y)
|
|
478
|
+
out, pos = [], 2
|
|
479
|
+
for p, k in zip(per, ks, strict=True):
|
|
480
|
+
out.append(SeasonalProfile(p, coarsen_array(b[pos: pos + 2 * k].reshape(k, 2), pol)))
|
|
481
|
+
pos += 2 * k
|
|
482
|
+
return out
|
|
483
|
+
|
|
484
|
+
def _assumptions(self) -> list[str]:
|
|
485
|
+
out = []
|
|
486
|
+
for c, comp in self.components.items():
|
|
487
|
+
tr = comp.trend
|
|
488
|
+
out.append(f"new_period generation extrapolates the fitted {tr.kind} trend of {c!r} "
|
|
489
|
+
f"beyond the training window ({self.start} .. {self.end}); this is a "
|
|
490
|
+
f"modeling assumption, not a verified forecast")
|
|
491
|
+
if self.periods:
|
|
492
|
+
out.append(f"seasonal profiles (periods {self.periods} steps of {self.cadence}) are "
|
|
493
|
+
f"assumed stable over time")
|
|
494
|
+
out.append("the AR residual process is assumed stationary; innovations are i.i.d. "
|
|
495
|
+
"draws from the fitted marginal" + (" joined by a Gaussian copula"
|
|
496
|
+
if self.copula is not None else ""))
|
|
497
|
+
return out
|
|
498
|
+
|
|
499
|
+
# -- generate ----------------------------------------------------------------------------
|
|
500
|
+
def generate(self, request: TemporalRequest, seed: int) -> pl.DataFrame:
|
|
501
|
+
if not self.components or self.start is None or self.end is None:
|
|
502
|
+
raise GenerationError("model is not fitted")
|
|
503
|
+
if request.freq is not None and request.freq != self.cadence:
|
|
504
|
+
raise GenerationError(f"this model was fitted at cadence {self.cadence!r}; it cannot "
|
|
505
|
+
f"generate at freq {request.freq!r} (resampling the cadence "
|
|
506
|
+
f"is not supported)")
|
|
507
|
+
if request.n_entities not in (None, 1):
|
|
508
|
+
raise GenerationError("RegularSeriesModel generates a single series; "
|
|
509
|
+
f"n_entities={request.n_entities} needs a panel model")
|
|
510
|
+
if request.mode == "new_period":
|
|
511
|
+
start = request.start or self._index(self.end, 2, None)[1]
|
|
512
|
+
idx = self._index(start, None if request.end is not None
|
|
513
|
+
else request.n_periods(), request.end)
|
|
514
|
+
else:
|
|
515
|
+
start = request.start or self.start
|
|
516
|
+
n = request.n_periods()
|
|
517
|
+
if request.end is not None:
|
|
518
|
+
idx = self._index(start, None, request.end)
|
|
519
|
+
elif n is not None:
|
|
520
|
+
idx = self._index(start, n, None)
|
|
521
|
+
else:
|
|
522
|
+
idx = self._index(start, None, self.end)
|
|
523
|
+
if idx.len() == 0:
|
|
524
|
+
raise GenerationError("the requested window contains no time steps")
|
|
525
|
+
steps = self._steps(idx)
|
|
526
|
+
if not np.allclose(steps, np.round(steps)):
|
|
527
|
+
raise GenerationError(f"start {start} is not aligned with the fitted cadence "
|
|
528
|
+
f"{self.cadence!r} from {self.start}")
|
|
529
|
+
n_out = idx.len()
|
|
530
|
+
max_p = max(comp.phi.size for comp in self.components.values())
|
|
531
|
+
burn = int(request.warmup_periods) + (10 * max_p + 50 if max_p else 0)
|
|
532
|
+
total = burn + n_out
|
|
533
|
+
d = len(self.value_cols)
|
|
534
|
+
rng = stream(seed, "temporal", "regular", "innovations")
|
|
535
|
+
if self.copula is not None:
|
|
536
|
+
u = special.ndtr(self.copula.sample(total, rng))
|
|
537
|
+
else:
|
|
538
|
+
u = rng.random((total, d))
|
|
539
|
+
u = np.clip(u, 1e-12, 1 - 1e-12)
|
|
540
|
+
|
|
541
|
+
out: dict[str, Any] = {self.time_col: idx.alias(self.time_col)}
|
|
542
|
+
for j, c in enumerate(self.value_cols):
|
|
543
|
+
comp = self.components[c]
|
|
544
|
+
e = comp.innovation.ppf(u[:, j])
|
|
545
|
+
r = signal.lfilter([1.0], np.r_[1.0, -comp.phi], e) if comp.phi.size else e
|
|
546
|
+
y = comp.mean(steps) + r[burn:]
|
|
547
|
+
out[c] = _cast_values(y, comp.dtype, c)
|
|
548
|
+
beyond = request.mode == "new_period" and steps.max() > self.n_steps - 1
|
|
549
|
+
self.last_generation = {"mode": request.mode, "n_rows": n_out, "burn_in": burn,
|
|
550
|
+
"trend_extrapolated": bool(beyond)}
|
|
551
|
+
return pl.DataFrame(out)
|
|
552
|
+
|
|
553
|
+
# -- serialisation -----------------------------------------------------------------------
|
|
554
|
+
def to_section(self, store: ArrayStore, prefix: str = "temporal.") -> dict[str, Any]:
|
|
555
|
+
cols: dict[str, Any] = {}
|
|
556
|
+
for c, comp in self.components.items():
|
|
557
|
+
tr = comp.trend
|
|
558
|
+
seas = []
|
|
559
|
+
for s in comp.seasonal:
|
|
560
|
+
ref = store.put(f"{prefix}{c}.seasonal.{s.period:g}", s.coef)
|
|
561
|
+
seas.append({"period": s.period, "harmonics": int(s.coef.shape[0]),
|
|
562
|
+
"coefficients": ref, "amplitude": s.amplitude, "phase": s.phase})
|
|
563
|
+
cols[c] = {
|
|
564
|
+
"dtype": comp.dtype,
|
|
565
|
+
"trend": {"kind": tr.kind, "intercept": tr.intercept, "slope": tr.slope,
|
|
566
|
+
"changepoints": list(tr.changepoints), "deltas": list(tr.deltas)},
|
|
567
|
+
"seasonal": seas,
|
|
568
|
+
"ar": {"order": int(comp.phi.size), "coef": [float(v) for v in comp.phi]},
|
|
569
|
+
"innovation": comp.innovation.to_spec(store, f"{prefix}{c}.innovation.")
|
|
570
|
+
.model_dump(mode="json"),
|
|
571
|
+
"residual_std": comp.residual_std,
|
|
572
|
+
"diagnostics": comp.diagnostics,
|
|
573
|
+
}
|
|
574
|
+
return {
|
|
575
|
+
"kind": SECTION_KIND, "format": SECTION_FORMAT, "enabled": True,
|
|
576
|
+
"time_col": self.time_col,
|
|
577
|
+
"time_dtype": {"kind": self.time_kind, "time_unit": self.time_unit,
|
|
578
|
+
"time_zone": self.time_zone},
|
|
579
|
+
"cadence": self.cadence, "start": _iso(self.start), "end": _iso(self.end),
|
|
580
|
+
"n_steps": self.n_steps, "value_cols": list(self.value_cols),
|
|
581
|
+
"periods": list(self.periods), "decomposition": self.decomposition,
|
|
582
|
+
"columns": cols,
|
|
583
|
+
"innovation_copula": (self.copula.to_spec(store, f"{prefix}innovation.")
|
|
584
|
+
.model_dump(mode="json") if self.copula is not None
|
|
585
|
+
else None),
|
|
586
|
+
"assumptions": list(self.assumptions),
|
|
587
|
+
"diagnostics": dict(self.diagnostics),
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
@classmethod
|
|
591
|
+
def from_section(cls, section: dict[str, Any], store: ArrayStore) -> RegularSeriesModel:
|
|
592
|
+
if section.get("kind") != SECTION_KIND:
|
|
593
|
+
raise GenerationError(f"not a {SECTION_KIND} section: kind={section.get('kind')!r}")
|
|
594
|
+
if int(section.get("format", 0)) > SECTION_FORMAT:
|
|
595
|
+
raise GenerationError(f"unsupported {SECTION_KIND} section format "
|
|
596
|
+
f"{section.get('format')}")
|
|
597
|
+
m = cls()
|
|
598
|
+
m.time_col = str(section["time_col"])
|
|
599
|
+
td = section["time_dtype"]
|
|
600
|
+
m.time_kind, m.time_unit, m.time_zone = td["kind"], td["time_unit"], td["time_zone"]
|
|
601
|
+
m.cadence = str(section["cadence"])
|
|
602
|
+
m.start = _parse_time(section["start"], m.time_kind)
|
|
603
|
+
m.end = _parse_time(section["end"], m.time_kind)
|
|
604
|
+
m.n_steps = int(section["n_steps"])
|
|
605
|
+
m.value_cols = [str(c) for c in section["value_cols"]]
|
|
606
|
+
m.periods = [float(p) for p in section.get("periods", [])]
|
|
607
|
+
m.decomposition = str(section.get("decomposition", "fourier"))
|
|
608
|
+
for c in m.value_cols:
|
|
609
|
+
cs = section["columns"][c]
|
|
610
|
+
tr = cs["trend"]
|
|
611
|
+
m.components[c] = SeriesComponents(
|
|
612
|
+
trend=Trend(tr["kind"], float(tr["intercept"]), float(tr["slope"]),
|
|
613
|
+
[float(v) for v in tr.get("changepoints", [])],
|
|
614
|
+
[float(v) for v in tr.get("deltas", [])]),
|
|
615
|
+
seasonal=[SeasonalProfile(float(s["period"]),
|
|
616
|
+
np.asarray(store.get(s["coefficients"]),
|
|
617
|
+
dtype=np.float64).reshape(-1, 2))
|
|
618
|
+
for s in cs["seasonal"]],
|
|
619
|
+
phi=np.asarray(cs["ar"]["coef"], dtype=np.float64),
|
|
620
|
+
innovation=marginal_from_spec(ModelSpec.model_validate(cs["innovation"]), store),
|
|
621
|
+
dtype=str(cs.get("dtype", "Float64")),
|
|
622
|
+
residual_std=float(cs.get("residual_std", 0.0)),
|
|
623
|
+
diagnostics=dict(cs.get("diagnostics", {})))
|
|
624
|
+
cop = section.get("innovation_copula")
|
|
625
|
+
m.copula = GaussianCopula.from_spec(ModelSpec.model_validate(cop), store) if cop else None
|
|
626
|
+
m.assumptions = [str(a) for a in section.get("assumptions", [])]
|
|
627
|
+
m.diagnostics = dict(section.get("diagnostics", {}))
|
|
628
|
+
return m
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
# ---------------------------------------------------------------------------------------------
|
|
632
|
+
# helpers
|
|
633
|
+
# ---------------------------------------------------------------------------------------------
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def _choose_k(t: np.ndarray, y: np.ndarray, per: list[float], base: np.ndarray,
|
|
637
|
+
j: int) -> int:
|
|
638
|
+
"""Harmonic count for ``per[j]`` by BIC, given the other regressors in ``base``."""
|
|
639
|
+
n = t.size
|
|
640
|
+
best_k, best = 1, math.inf
|
|
641
|
+
for k in range(1, _max_harmonics(per[j]) + 1):
|
|
642
|
+
x = np.column_stack([base, fourier_basis(t, per[j], k)])
|
|
643
|
+
_, sse = _lstsq(x, y)
|
|
644
|
+
b = _bic(sse, n, x.shape[1])
|
|
645
|
+
if b < best - 1e-9:
|
|
646
|
+
best_k, best = k, b
|
|
647
|
+
return best_k
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def _coarsen_trend(tr: Trend, pol: DisclosurePolicySpec) -> Trend:
|
|
651
|
+
return Trend(tr.kind, coarsen(tr.intercept, pol), coarsen(tr.slope, pol),
|
|
652
|
+
[float(round(c)) for c in tr.changepoints],
|
|
653
|
+
[coarsen(d, pol) for d in tr.deltas])
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _cast_values(y: np.ndarray, dtype: str, name: str) -> pl.Series:
|
|
657
|
+
target = _DTYPES.get(dtype, pl.Float64())
|
|
658
|
+
if target.is_integer():
|
|
659
|
+
return pl.Series(name, np.round(y)).cast(target, strict=False)
|
|
660
|
+
return pl.Series(name, y, dtype=pl.Float64).cast(target)
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def _iso(x: dt.date | dt.datetime | None) -> str | None:
|
|
664
|
+
return None if x is None else x.isoformat()
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _parse_time(s: str | None, kind: str) -> dt.date | dt.datetime | None:
|
|
668
|
+
if s is None:
|
|
669
|
+
return None
|
|
670
|
+
return dt.date.fromisoformat(s) if kind == "date" else dt.datetime.fromisoformat(s)
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
__all__ = ["RegularSeriesModel", "SeasonalProfile", "Trend", "fit_ar", "fourier_basis",
|
|
674
|
+
"select_trend", "has_statsmodels"]
|