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.
Files changed (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,937 @@
1
+ """Regular panel model (M20): many entities, each a regular series.
2
+
3
+ For value column ``y``, entity ``i`` and cadence step ``t`` (counted from the training start)::
4
+
5
+ y_it = G(t) + a_i + b_i (t - m_i) + (s_i - 1) S(t) + r_it
6
+ G(t) = mu + beta t + S(t) + level(regime(t))
7
+
8
+ * **Global component** ``G``: estimated on the composition-adjusted time effects of a two-way
9
+ fixed-effects decomposition (``y_it = alpha_i + delta_t``), as a linear trend, a Fourier
10
+ seasonal profile ``S`` (periods supplied or detected by FFT) and **regimes**: level shifts at
11
+ changepoints found by greedy binary segmentation of the mean (a step regressor is added while
12
+ its SSE reduction beats a BIC-type penalty inflated for residual autocorrelation).
13
+ * **Entity deviations** ``theta_i = (a_i, b_i, s_i)`` per value column (intercept at the
14
+ entity's own mid-life ``m_i``, slope, seasonal amplitude scale) are estimated per entity and
15
+ summarised as a **multivariate normal** (mean + covariance, with the per-entity sampling
16
+ covariance subtracted, method-of-moments style). Per-entity values are never stored.
17
+ * **Residual** ``r_it``: pooled AR(p) (``p <= 7`` by AIC) with innovations from a fitted
18
+ marginal; optionally GARCH(1,1) volatility (Gaussian quasi-MLE, kept only when it beats
19
+ constant variance by AIC). Several value columns share a Gaussian innovation copula; lagged
20
+ cross-correlations of the residuals are stored as statistical diagnostics (not causal).
21
+ * **Lifetimes**: policy-coarsened quantiles of the start offset (fraction of the window) and the
22
+ length (fraction of the remaining window).
23
+
24
+ Generation creates ``request.n_entities`` (default ``None``: as many as the source) *new*
25
+ entities with regenerated ids, drawing their parameters from the stored distribution. With
26
+ ``count_policy="fixed"`` every entity spans the whole window (``periods x n_entities`` rows);
27
+ with ``"natural"`` lifetimes are sampled.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import datetime as dt
33
+ import math
34
+ from dataclasses import dataclass, field
35
+ from typing import Any, ClassVar, cast
36
+
37
+ import numpy as np
38
+ import polars as pl
39
+ from scipy import optimize, signal, special
40
+
41
+ from ectype.errors import GenerationError, ProfilingError
42
+ from ectype.fingerprint.core import ArrayStore
43
+ from ectype.fingerprint.disclosure import (
44
+ coarsen,
45
+ coarsen_array,
46
+ quantile_levels,
47
+ resolve_policy,
48
+ )
49
+ from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, ModelSpec
50
+ from ectype.models.base import MarginalModel, marginal_from_spec
51
+ from ectype.models.copulas import GaussianCopula
52
+ from ectype.profiling.univariate import fit_marginal
53
+ from ectype.rng import stream
54
+ from ectype.temporal.contract import TemporalRequest
55
+ from ectype.temporal.detect import (
56
+ _calendar_cadence,
57
+ detect_periods,
58
+ epoch_us,
59
+ format_duration,
60
+ is_temporal_dtype,
61
+ )
62
+ from ectype.temporal.regular import (
63
+ MAX_AR_ORDER,
64
+ RegularSeriesModel,
65
+ _cast_values,
66
+ _choose_k,
67
+ _iso,
68
+ _lstsq,
69
+ _parse_time,
70
+ _stationary,
71
+ fourier_basis,
72
+ )
73
+ from ectype.types import LogicalType
74
+
75
+ SECTION_KIND = "panel"
76
+ SECTION_FORMAT = 1
77
+ MIN_STEPS = 12
78
+ MIN_ENTITIES = 3
79
+ MAX_REGIMES = 6
80
+ MAX_INNOVATION_SAMPLE = 20_000
81
+ #: a GARCH fit must beat constant variance by this much AIC to be enabled
82
+ GARCH_MIN_AIC_GAIN = 2.0
83
+
84
+
85
+ @dataclass
86
+ class Regime:
87
+ start_step: float
88
+ level: float # added to the global component from ``start_step`` on
89
+
90
+
91
+ @dataclass
92
+ class GlobalComponent:
93
+ intercept: float
94
+ slope: float
95
+ seasonal: list[tuple[float, np.ndarray]] = field(default_factory=list) # (period, Kx2)
96
+ regimes: list[Regime] = field(default_factory=list)
97
+
98
+ def seasonal_part(self, t: np.ndarray) -> np.ndarray:
99
+ out = np.zeros(np.shape(t), dtype=np.float64)
100
+ for p, c in self.seasonal:
101
+ out = out + fourier_basis(t, p, c.shape[0]) @ c.reshape(-1)
102
+ return out
103
+
104
+ def level(self, t: np.ndarray) -> np.ndarray:
105
+ t = np.asarray(t, dtype=np.float64)
106
+ out = np.zeros_like(t)
107
+ for r in self.regimes:
108
+ out = np.where(t >= r.start_step - 1e-9, r.level, out)
109
+ return out
110
+
111
+ def __call__(self, t: np.ndarray) -> np.ndarray:
112
+ t = np.asarray(t, dtype=np.float64)
113
+ return self.intercept + self.slope * t + self.seasonal_part(t) + self.level(t)
114
+
115
+
116
+ @dataclass
117
+ class Garch:
118
+ omega: float
119
+ alpha: float
120
+ beta: float
121
+
122
+ @property
123
+ def unconditional(self) -> float:
124
+ return self.omega / max(1e-12, 1.0 - self.alpha - self.beta)
125
+
126
+
127
+ @dataclass
128
+ class ResidualModel:
129
+ phi: np.ndarray
130
+ innovation: MarginalModel
131
+ garch: Garch | None = None
132
+ dtype: str = "Float64"
133
+ diagnostics: dict[str, Any] = field(default_factory=dict)
134
+
135
+
136
+ # ---------------------------------------------------------------------------------------------
137
+ # Building blocks (public for tests)
138
+ # ---------------------------------------------------------------------------------------------
139
+
140
+
141
+ def detect_level_shifts(y: np.ndarray, base: np.ndarray | None = None, *,
142
+ max_changepoints: int = MAX_REGIMES - 1,
143
+ min_segment: int | None = None,
144
+ penalty: float | None = None,
145
+ weights: np.ndarray | None = None) -> list[int]:
146
+ """Changepoints in the mean of ``y`` (step indices where a new level starts).
147
+
148
+ Greedy binary segmentation: on top of the regressors ``base`` (default: intercept + linear
149
+ trend) repeatedly add the step regressor ``1[t >= tau]`` that reduces the SSE most, while
150
+ the reduction exceeds ``penalty * sigma^2``. ``sigma^2`` is the current residual variance
151
+ and the default penalty ``3 log n`` is inflated by ``(1 + rho) / (1 - rho)`` for lag-1
152
+ residual autocorrelation ``rho`` (AR noise otherwise produces spurious shifts).
153
+ ``weights`` (e.g. the number of entities behind each point) give weighted least squares.
154
+ """
155
+ y = np.asarray(y, dtype=np.float64)
156
+ n = y.size
157
+ t = np.arange(n, dtype=np.float64)
158
+ x = np.column_stack([np.ones(n), t]) if base is None else np.asarray(base, dtype=np.float64)
159
+ sw = (np.ones(n) if weights is None
160
+ else np.sqrt(np.asarray(weights, dtype=np.float64) / np.mean(weights)))
161
+ y, x = y * sw, x * sw[:, None]
162
+ seg = max(3, int(0.05 * n)) if min_segment is None else int(min_segment)
163
+ if n < 2 * seg + 2:
164
+ return []
165
+ cps: list[int] = []
166
+ beta, _ = _lstsq(x, y)
167
+ for _ in range(max_changepoints):
168
+ resid = y - x @ beta
169
+ # SSE reduction of every candidate step, from the residualised step regressors
170
+ q, _ = np.linalg.qr(x)
171
+ best: tuple[float, int] | None = None
172
+ for tau in range(seg, n - seg + 1):
173
+ if any(abs(tau - c) < seg for c in cps):
174
+ continue
175
+ z = (t >= tau).astype(np.float64) * sw
176
+ z = z - q @ (q.T @ z)
177
+ zz = float(z @ z)
178
+ if zz <= 1e-9:
179
+ continue
180
+ gain = float(z @ resid) ** 2 / zz
181
+ if best is None or gain > best[0]:
182
+ best = (gain, tau)
183
+ if best is None:
184
+ break
185
+ # noise level and autocorrelation judged on the residual *with* the candidate step
186
+ # (an unmodelled shift would otherwise inflate both)
187
+ x_new = np.column_stack([x, (t >= best[1]).astype(np.float64) * sw])
188
+ b_new, sse_new = _lstsq(x_new, y)
189
+ r_new = y - x_new @ b_new
190
+ sig2 = sse_new / max(1, n - x_new.shape[1])
191
+ rho = _lag1(r_new)
192
+ pen = (3.0 * math.log(n) if penalty is None else penalty) * (1 + rho) / (1 - rho)
193
+ if best[0] < pen * sig2:
194
+ break
195
+ cps.append(best[1])
196
+ x, beta = x_new, b_new
197
+ return sorted(cps)
198
+
199
+
200
+ def _lag1(r: np.ndarray) -> float:
201
+ a, b = r[1:], r[:-1]
202
+ den = float(np.sqrt(np.sum(a * a) * np.sum(b * b)))
203
+ rho = float(np.sum(a * b)) / den if den > 0 else 0.0
204
+ return float(np.clip(rho if math.isfinite(rho) else 0.0, 0.0, 0.95))
205
+
206
+
207
+ def fit_garch(e: np.ndarray) -> tuple[Garch | None, dict[str, float]]:
208
+ """GARCH(1,1) by Gaussian quasi-MLE on the rows of ``e`` (entities x time, NaN = missing).
209
+
210
+ Returns ``(garch or None, {"aic_constant", "aic_garch"})``; the GARCH model is returned
211
+ only if it beats constant variance by :data:`GARCH_MIN_AIC_GAIN` AIC points.
212
+ """
213
+ e = np.atleast_2d(np.asarray(e, dtype=np.float64))
214
+ ok = np.isfinite(e)
215
+ n = int(ok.sum())
216
+ if n < 100:
217
+ return None, {}
218
+ v = float(np.mean(e[ok] ** 2))
219
+ if v <= 0:
220
+ return None, {}
221
+ nll_c = 0.5 * n * (math.log(2 * math.pi * v) + 1.0)
222
+ e2 = np.where(ok, e ** 2, np.nan)
223
+ first = np.argmax(ok, axis=1)
224
+
225
+ def nll(x: np.ndarray) -> float:
226
+ om = v * math.exp(x[0])
227
+ pers = 0.999 / (1 + math.exp(-x[1]))
228
+ share = 1 / (1 + math.exp(-x[2]))
229
+ a, b = pers * share, pers * (1 - share)
230
+ s2 = np.full(e.shape[0], v)
231
+ tot = 0.0
232
+ for k in range(e.shape[1]):
233
+ col = e2[:, k]
234
+ m = np.isfinite(col)
235
+ if k > 0:
236
+ prev = e2[:, k - 1]
237
+ prev = np.where(np.isfinite(prev), prev, s2)
238
+ s2 = np.where(first < k, om + a * prev + b * s2, v)
239
+ if m.any():
240
+ ss = s2[m]
241
+ tot += float(np.sum(np.log(ss) + col[m] / ss))
242
+ return 0.5 * (tot + n * math.log(2 * math.pi))
243
+
244
+ x0 = np.array([math.log(0.05), math.log(0.95 / 0.049), math.log(0.05 / 0.95)])
245
+ res = optimize.minimize(nll, x0, method="L-BFGS-B",
246
+ bounds=[(-12, 3), (-6, 9), (-8, 6)],
247
+ options={"maxiter": 200})
248
+ pers = 0.999 / (1 + math.exp(-res.x[1]))
249
+ share = 1 / (1 + math.exp(-res.x[2]))
250
+ g = Garch(v * math.exp(res.x[0]), pers * share, pers * (1 - share))
251
+ aic_c, aic_g = 2 * nll_c + 2, 2 * float(res.fun) + 6
252
+ diag = {"aic_constant": aic_c, "aic_garch": aic_g}
253
+ return (g if aic_g < aic_c - GARCH_MIN_AIC_GAIN else None), diag
254
+
255
+
256
+ def garch_filter(e: np.ndarray, g: Garch) -> np.ndarray:
257
+ """Conditional standard deviations of ``e`` (rows = entities, NaN = missing)."""
258
+ e2 = e ** 2
259
+ s2 = np.full(e.shape[0], g.unconditional)
260
+ first = np.argmax(np.isfinite(e), axis=1)
261
+ out = np.empty_like(e)
262
+ for k in range(e.shape[1]):
263
+ if k > 0:
264
+ prev = np.where(np.isfinite(e2[:, k - 1]), e2[:, k - 1], s2)
265
+ s2 = np.where(first < k, g.omega + g.alpha * prev + g.beta * s2, g.unconditional)
266
+ out[:, k] = np.sqrt(s2)
267
+ return out
268
+
269
+
270
+ def _lagged(r: np.ndarray, k: int) -> np.ndarray:
271
+ out = np.full_like(r, np.nan)
272
+ out[:, k:] = r[:, : r.shape[1] - k]
273
+ return out
274
+
275
+
276
+ def fit_pooled_ar(r: np.ndarray, max_order: int = MAX_AR_ORDER) -> tuple[np.ndarray,
277
+ dict[str, float]]:
278
+ """AR(p) shared by all entities (rows of ``r``), ``p`` by AIC on a common sample."""
279
+ max_order = int(min(max_order, max(0, r.shape[1] // 4)))
280
+ lags = [_lagged(r, k) for k in range(1, max_order + 1)]
281
+ ok = np.isfinite(r)
282
+ for lg in lags:
283
+ ok &= np.isfinite(lg)
284
+ m = int(ok.sum())
285
+ if m < 20:
286
+ return np.zeros(0), {}
287
+ y = r[ok]
288
+ xl = np.column_stack([lg[ok] for lg in lags]) if lags else np.zeros((m, 0))
289
+ best: tuple[float, np.ndarray] | None = None
290
+ aic: dict[str, float] = {}
291
+ for p in range(0, max_order + 1):
292
+ if p == 0:
293
+ phi, sse = np.zeros(0), float(np.sum(y ** 2))
294
+ else:
295
+ phi, sse = _lstsq(xl[:, :p], y)
296
+ a = m * math.log(max(sse, 1e-300) / m) + 2 * p
297
+ aic[str(p)] = a
298
+ if best is None or a < best[0] - 1e-9:
299
+ best = (a, phi)
300
+ assert best is not None
301
+ return _stationary(best[1]), aic
302
+
303
+
304
+ def _ar_innovations(r: np.ndarray, phi: np.ndarray) -> np.ndarray:
305
+ out = r.copy()
306
+ for k, c in enumerate(phi, start=1):
307
+ out = out - c * _lagged(r, k)
308
+ return out
309
+
310
+
311
+ def _psd(c: np.ndarray, floor: float = 1e-12) -> np.ndarray:
312
+ c = 0.5 * (c + c.T)
313
+ w, v = np.linalg.eigh(c)
314
+ w = np.maximum(w, floor * max(1.0, float(np.max(np.abs(w))) if w.size else 1.0))
315
+ return (v * w) @ v.T
316
+
317
+
318
+ def _sqrtm(c: np.ndarray) -> np.ndarray:
319
+ w, v = np.linalg.eigh(0.5 * (c + c.T))
320
+ return v * np.sqrt(np.maximum(w, 0.0))
321
+
322
+
323
+ # ---------------------------------------------------------------------------------------------
324
+ # Model
325
+ # ---------------------------------------------------------------------------------------------
326
+
327
+
328
+ class PanelModel:
329
+ """Hierarchical panel: global trend/seasonality/regimes + entity-effect distribution."""
330
+
331
+ kind: ClassVar[str] = SECTION_KIND
332
+
333
+ def __init__(self) -> None:
334
+ self.time_col = ""
335
+ self.entity_col = ""
336
+ self.entity_dtype = "String"
337
+ self.value_cols: list[str] = []
338
+ self.clock = RegularSeriesModel() # used for its cadence/time-index helpers only
339
+ self.n_steps = 0
340
+ self.n_entities = 0
341
+ self.periods: list[float] = []
342
+ self.global_: dict[str, GlobalComponent] = {}
343
+ self.param_names: list[str] = []
344
+ self.effect_mean = np.zeros(0)
345
+ self.effect_cov = np.zeros((0, 0))
346
+ self.seasonal_scale = False
347
+ self.residual: dict[str, ResidualModel] = {}
348
+ self.copula: GaussianCopula | None = None
349
+ self.lifetime_levels = np.zeros(0)
350
+ self.start_q = np.zeros(0)
351
+ self.length_q = np.zeros(0)
352
+ self.lagged_xcorr: dict[str, list[float]] = {}
353
+ self.assumptions: list[str] = []
354
+ self.diagnostics: dict[str, Any] = {}
355
+ self.last_generation: dict[str, Any] = {}
356
+
357
+ # convenience accessors ---------------------------------------------------------------
358
+ @property
359
+ def cadence(self) -> str:
360
+ return self.clock.cadence
361
+
362
+ @property
363
+ def start(self) -> dt.date | dt.datetime | None:
364
+ return self.clock.start
365
+
366
+ @property
367
+ def end(self) -> dt.date | dt.datetime | None:
368
+ return self.clock.end
369
+
370
+ # -- fit -------------------------------------------------------------------------------
371
+ def fit(self, df: pl.DataFrame, time_col: str, entity_col: str, value_cols: list[str] | str,
372
+ policy: DisclosurePolicySpec | str | None = None, seed: int = 0, *,
373
+ periods: list[float] | None = None, max_periods: int = 2,
374
+ max_changepoints: int = MAX_REGIMES - 1, volatility: str = "auto") -> PanelModel:
375
+ """Fit on a long panel ``df``. ``volatility`` is ``"auto"`` (GARCH if it wins by AIC)
376
+ or ``"off"``."""
377
+ pol = resolve_policy(policy)
378
+ cols = [value_cols] if isinstance(value_cols, str) else list(value_cols)
379
+ for c, what in ((time_col, "time"), (entity_col, "entity")):
380
+ if c not in df.columns:
381
+ raise ProfilingError(f"{what} column {c!r} not found")
382
+ if not is_temporal_dtype(df.schema[time_col]):
383
+ raise ProfilingError(f"time column {time_col!r} must be pl.Date or pl.Datetime")
384
+ if not cols:
385
+ raise ProfilingError("at least one value column is required")
386
+ for c in cols:
387
+ if c not in df.columns or not df.schema[c].is_numeric():
388
+ raise ProfilingError(f"value column {c!r} must be an existing numeric column")
389
+ if volatility not in ("auto", "off"):
390
+ raise ProfilingError(f"unknown volatility option {volatility!r}")
391
+ self.time_col, self.entity_col, self.value_cols = time_col, entity_col, cols
392
+ self.entity_dtype = "Int64" if df.schema[entity_col].is_integer() else "String"
393
+
394
+ # ---- grid ----------------------------------------------------------------------
395
+ d0 = (df.select([entity_col, time_col, *cols])
396
+ .filter(pl.col(time_col).is_not_null() & pl.col(entity_col).is_not_null())
397
+ .group_by([entity_col, time_col])
398
+ .agg([pl.col(c).cast(pl.Float64).mean() for c in cols])
399
+ .sort([entity_col, time_col]))
400
+ tus = epoch_us(d0[time_col])
401
+ ent_codes = d0[entity_col].rank("dense").cast(pl.Int64).to_numpy() - 1
402
+ diffs = np.diff(tus)[np.diff(ent_codes) == 0]
403
+ diffs = diffs[diffs > 0]
404
+ if diffs.size < MIN_STEPS:
405
+ raise ProfilingError("too few within-entity time steps for a panel model")
406
+ step = float(np.median(diffs))
407
+ tdt = df.schema[time_col]
408
+ ck = self.clock
409
+ ck.time_kind = "date" if tdt == pl.Date else "datetime"
410
+ if isinstance(tdt, pl.Datetime):
411
+ ck.time_unit, ck.time_zone = tdt.time_unit or "us", tdt.time_zone
412
+ ck.cadence = _calendar_cadence(step) or format_duration(step)
413
+ ck.start, ck.end = (cast("dt.date | dt.datetime", d0[time_col].min()),
414
+ cast("dt.date | dt.datetime", d0[time_col].max()))
415
+ steps_f = ck._steps(d0[time_col])
416
+ steps = np.round(steps_f).astype(np.int64)
417
+ if np.max(np.abs(steps_f - steps)) > 0.1:
418
+ raise ProfilingError(f"timestamps are not aligned to the cadence {ck.cadence!r}")
419
+ n_ent = int(ent_codes.max()) + 1
420
+ T = int(np.max(steps)) + 1
421
+ if T < MIN_STEPS or n_ent < MIN_ENTITIES:
422
+ raise ProfilingError(f"panel too small: {T} steps, {n_ent} entities (need >= "
423
+ f"{MIN_STEPS} steps and >= {MIN_ENTITIES} entities)")
424
+ ck.n_steps = T
425
+ self.n_steps, self.n_entities = T, n_ent
426
+ Y = np.full((len(cols), n_ent, T), np.nan)
427
+ for j, c in enumerate(cols):
428
+ Y[j, ent_codes, steps] = d0[c].to_numpy()
429
+ present = np.isfinite(Y).any(axis=0)
430
+ first = np.argmax(present, axis=1)
431
+ last = T - 1 - np.argmax(present[:, ::-1], axis=1)
432
+ t = np.arange(T, dtype=np.float64)
433
+
434
+ # ---- global time effects (two-way fixed effects) -------------------------------
435
+ deltas = np.stack([_time_effects(Y[j]) for j in range(len(cols))])
436
+ if periods is not None:
437
+ per = sorted(float(p) for p in periods)
438
+ else:
439
+ found: set[float] = set()
440
+ for j in range(len(cols)):
441
+ found.update(detect_periods(deltas[j], cadence=ck.cadence,
442
+ max_periods=max_periods))
443
+ per = []
444
+ for p in sorted(found):
445
+ if not per or p > 1.05 * per[-1]:
446
+ per.append(p)
447
+ per = per[:max_periods]
448
+ per = [p for p in per if 2.0 <= p < T / 2.0]
449
+ self.periods = [coarsen(p, pol) for p in per]
450
+ for j, c in enumerate(cols):
451
+ w = np.maximum(np.isfinite(Y[j]).sum(axis=0), 0.5).astype(np.float64)
452
+ self.global_[c] = self._fit_global(t, deltas[j], self.periods, pol,
453
+ max_changepoints, w)
454
+
455
+ # ---- entity effects ------------------------------------------------------------
456
+ lengths = last - first + 1
457
+ self.seasonal_scale = bool(self.periods) and float(
458
+ np.mean(lengths >= max(self.periods))) >= 0.8
459
+ npar = 3 if self.seasonal_scale else 2
460
+ self.param_names = [f"{c}.{k}" for c in cols
461
+ for k in ("intercept", "slope", "seasonal_scale")[:npar]]
462
+ mids = 0.5 * (first + last)
463
+ thetas: list[np.ndarray] = []
464
+ covs: list[np.ndarray] = []
465
+ used: list[int] = []
466
+ resid = np.full_like(Y, np.nan)
467
+ g_vals = {c: self.global_[c](t) for c in cols}
468
+ s_vals = {c: self.global_[c].seasonal_part(t) for c in cols}
469
+ min_len = npar + 4
470
+ rho = 0.0
471
+ for _pass in range(2):
472
+ # pass 1: OLS; pass 2: prewhitened by the pooled lag-1 residual autocorrelation
473
+ # (Cochrane-Orcutt) so the per-entity sampling covariance is honest
474
+ thetas, covs, used = [], [], []
475
+ for i in range(n_ent):
476
+ th_i, cv_i, ok_i, r_i = [], [], True, []
477
+ for j, c in enumerate(cols):
478
+ m = np.isfinite(Y[j, i])
479
+ u = np.where(m, Y[j, i] - g_vals[c], np.nan)
480
+ x = [np.ones(T), t - mids[i]]
481
+ if npar == 3:
482
+ x.append(s_vals[c])
483
+ xm = np.column_stack(x)
484
+ if rho > 0:
485
+ uw = u[1:] - rho * u[:-1]
486
+ xw = xm[1:] - rho * xm[:-1]
487
+ else:
488
+ uw, xw = u, xm
489
+ ok = np.isfinite(uw)
490
+ if ok.sum() < min_len or np.linalg.matrix_rank(xw[ok]) < npar:
491
+ ok_i = False
492
+ break
493
+ b, sse = _lstsq(xw[ok], uw[ok])
494
+ r_i.append((j, m, u[m] - xm[m] @ b))
495
+ s2 = sse / max(1, ok.sum() - npar)
496
+ th_i.append(b + (np.array([0, 0, 1.0]) if npar == 3 else 0.0))
497
+ cv_i.append(s2 * np.linalg.inv(xw[ok].T @ xw[ok]))
498
+ if ok_i:
499
+ thetas.append(np.concatenate(th_i))
500
+ covs.append(_block_diag(cv_i))
501
+ used.append(i)
502
+ for j, m, r in r_i:
503
+ resid[j, i, m] = r
504
+ if len(used) < MIN_ENTITIES:
505
+ raise ProfilingError(f"only {len(used)} entities are long enough (>= "
506
+ f"{min_len} steps) to estimate entity effects")
507
+ if _pass == 0:
508
+ rho = _pooled_lag1(resid)
509
+ if rho < 0.05:
510
+ break
511
+ th = np.asarray(thetas)
512
+ samp = np.mean(np.asarray(covs), axis=0)
513
+ emp = np.cov(th, rowvar=False).reshape(th.shape[1], th.shape[1])
514
+ # method of moments: between-entity covariance = empirical - mean sampling covariance
515
+ cov = _psd(emp - samp, floor=0.0)
516
+ self.effect_mean = coarsen_array(th.mean(axis=0), pol)
517
+ self.effect_cov = coarsen_array(cov, pol)
518
+ # entities not used for the effects: residuals around the population-mean effects
519
+ for i in sorted(set(range(n_ent)) - set(used)):
520
+ for j, c in enumerate(cols):
521
+ yy = Y[j, i]
522
+ m = np.isfinite(yy)
523
+ resid[j, i, m] = yy[m] - self._entity_mean(c, t[m], mids[i], self.effect_mean)
524
+
525
+ # ---- residual process ----------------------------------------------------------
526
+ innov_std: dict[str, np.ndarray] = {}
527
+ for j, c in enumerate(cols):
528
+ phi, aic = fit_pooled_ar(resid[j])
529
+ phi = _stationary(coarsen_array(phi, pol)) if phi.size else phi
530
+ e = _ar_innovations(resid[j], phi)
531
+ g, gdiag = fit_garch(e) if volatility == "auto" else (None, {})
532
+ if g is not None:
533
+ g = Garch(coarsen(g.omega, pol), coarsen(g.alpha, pol), coarsen(g.beta, pol))
534
+ z = e / garch_filter(e, g)
535
+ else:
536
+ z = e
537
+ innov_std[c] = z
538
+ vals = z[np.isfinite(z)]
539
+ rng = stream(seed, "temporal", "panel", "innovation", c)
540
+ if vals.size > MAX_INNOVATION_SAMPLE:
541
+ vals = vals[np.sort(rng.choice(vals.size, MAX_INNOVATION_SAMPLE,
542
+ replace=False))]
543
+ col_schema = ColumnSchema(name=f"{c}__innovation",
544
+ logical_type=LogicalType.CONTINUOUS,
545
+ physical_dtype="Float64")
546
+ marg, mdiag = fit_marginal(vals, col_schema, pol, rng)
547
+ self.residual[c] = ResidualModel(
548
+ phi=phi, innovation=marg, garch=g, dtype=str(df.schema[c]),
549
+ diagnostics={"ar_aic": {k: coarsen(v, pol) for k, v in aic.items()},
550
+ "garch_aic": {k: coarsen(v, pol) for k, v in gdiag.items()},
551
+ "innovation_marginal": mdiag.get("chosen"),
552
+ "residual_std": coarsen(float(np.nanstd(resid[j])), pol)})
553
+
554
+ self.copula = None
555
+ self.lagged_xcorr = {}
556
+ if len(cols) > 1:
557
+ stack = np.stack([innov_std[c] for c in cols])
558
+ ok = np.isfinite(stack).all(axis=0)
559
+ if ok.sum() > 10 * len(cols):
560
+ z = np.column_stack([
561
+ special.ndtri(np.clip(self.residual[c].innovation.cdf(innov_std[c][ok]),
562
+ 1e-6, 1 - 1e-6)) for c in cols])
563
+ self.copula = GaussianCopula.fit(z, cols, policy=pol)
564
+ for ia in range(len(cols)):
565
+ for ib in range(len(cols)):
566
+ if ia == ib:
567
+ continue
568
+ xs = [_xcorr(resid[ia], resid[ib], k) for k in range(0, 4)]
569
+ self.lagged_xcorr[f"{cols[ia]}|{cols[ib]}"] = [coarsen(v, pol) for v in xs]
570
+
571
+ # ---- lifetimes -----------------------------------------------------------------
572
+ lev = quantile_levels(n_ent, pol)
573
+ self.lifetime_levels = lev
574
+ start_frac = first / T
575
+ len_frac = lengths / np.maximum(1, T - first)
576
+ self.start_q = coarsen_array(np.quantile(start_frac, lev), pol)
577
+ self.length_q = coarsen_array(np.quantile(len_frac, lev), pol)
578
+
579
+ self.diagnostics = {
580
+ "n_steps": T, "n_entities": n_ent, "n_entities_with_effects": len(used),
581
+ "residual_lag1_autocorrelation": coarsen(rho, pol),
582
+ "regimes": {c: len(g.regimes) for c, g in self.global_.items()},
583
+ "periods_source": "supplied" if periods is not None else "fft",
584
+ "balanced": bool(np.all(first == 0) and np.all(last == T - 1)),
585
+ }
586
+ self.assumptions = self._assumptions()
587
+ return self
588
+
589
+ def _fit_global(self, t: np.ndarray, d: np.ndarray, per: list[float],
590
+ pol: DisclosurePolicySpec, max_cp: int,
591
+ w: np.ndarray) -> GlobalComponent:
592
+ n = t.size
593
+ base = np.column_stack([np.ones(n), t])
594
+ four = []
595
+ ks = []
596
+ for j, p in enumerate(per):
597
+ others = [fourier_basis(t, q, 3) for i, q in enumerate(per) if i != j]
598
+ k = _choose_k(t, d, [p], np.column_stack([base, *others]) if others else base, j=0)
599
+ ks.append(k)
600
+ four.append(fourier_basis(t, p, k))
601
+ x = np.column_stack([base, *four]) if four else base
602
+ cps = detect_level_shifts(d, x, max_changepoints=max_cp, weights=w)
603
+ xs = np.column_stack([x, *[(t >= c).astype(np.float64) for c in cps]]) if cps else x
604
+ sw = np.sqrt(w / np.mean(w))
605
+ b, _ = _lstsq(xs * sw[:, None], d * sw)
606
+ seasonal, pos = [], 2
607
+ for p, k in zip(per, ks, strict=True):
608
+ seasonal.append((p, coarsen_array(b[pos: pos + 2 * k].reshape(k, 2), pol)))
609
+ pos += 2 * k
610
+ levels = np.cumsum(b[pos:]) if cps else np.zeros(0)
611
+ regimes = [Regime(0.0, 0.0)] + [Regime(float(c), coarsen(float(lv), pol))
612
+ for c, lv in zip(cps, levels, strict=True)]
613
+ return GlobalComponent(coarsen(float(b[0]), pol), coarsen(float(b[1]), pol), seasonal,
614
+ regimes)
615
+
616
+ def _entity_mean(self, c: str, t: np.ndarray, mid: float, theta: np.ndarray) -> np.ndarray:
617
+ """Deterministic part of column ``c`` for an entity with effects ``theta``."""
618
+ g = self.global_[c]
619
+ npar = 3 if self.seasonal_scale else 2
620
+ j = self.value_cols.index(c) * npar
621
+ out = g(t) + theta[j] + theta[j + 1] * (t - mid)
622
+ if npar == 3:
623
+ out = out + (theta[j + 2] - 1.0) * g.seasonal_part(t)
624
+ return out
625
+
626
+ def _assumptions(self) -> list[str]:
627
+ out = [f"new_period generation extrapolates the global linear trend and continues the "
628
+ f"last regime beyond the training window ({self.start} .. {self.end}); this is a "
629
+ f"modeling assumption, not a verified forecast",
630
+ "entity effects (intercept, slope" + (", seasonal scale" if self.seasonal_scale
631
+ else "") +
632
+ ") are assumed multivariate normal across entities; synthetic entities are new "
633
+ "draws, not copies of source entities",
634
+ "the pooled AR residual process is assumed stationary and shared by all "
635
+ "entities"]
636
+ if any(r.garch is not None for r in self.residual.values()):
637
+ out.append("residual volatility follows a GARCH(1,1) recursion")
638
+ if self.lagged_xcorr:
639
+ out.append("lagged cross-correlations between value columns are statistical "
640
+ "associations, not causal effects")
641
+ return out
642
+
643
+ # -- generate ----------------------------------------------------------------------------
644
+ def generate(self, request: TemporalRequest, seed: int) -> pl.DataFrame:
645
+ if not self.global_ or self.start is None or self.end is None:
646
+ raise GenerationError("model is not fitted")
647
+ # n_entities=None: as many (new) entities as the source panel had
648
+ request = request.with_entities(self.n_entities, model="this panel model")
649
+ if request.freq is not None and request.freq != self.cadence:
650
+ raise GenerationError(f"this model was fitted at cadence {self.cadence!r}; it cannot "
651
+ f"generate at freq {request.freq!r}")
652
+ ck = self.clock
653
+ if request.mode == "new_period":
654
+ start = request.start or ck._index(self.end, 2, None)[1]
655
+ idx = ck._index(start, None if request.end is not None
656
+ else request.n_periods(), request.end)
657
+ else:
658
+ start = request.start or self.start
659
+ n = request.n_periods()
660
+ if request.end is not None:
661
+ idx = ck._index(start, None, request.end)
662
+ elif n is not None:
663
+ idx = ck._index(start, n, None)
664
+ else:
665
+ idx = ck._index(start, None, self.end)
666
+ if idx.len() == 0:
667
+ raise GenerationError("the requested window contains no time steps")
668
+ steps = ck._steps(idx)
669
+ if not np.allclose(steps, np.round(steps)):
670
+ raise GenerationError(f"start {start} is not aligned with the fitted cadence "
671
+ f"{self.cadence!r} from {self.start}")
672
+ K, n_ent = idx.len(), int(request.n_entities or 1)
673
+
674
+ # lifetimes
675
+ if request.count_policy == "natural" and self.start_q.size:
676
+ rl = stream(seed, "temporal", "panel", "lifetimes")
677
+ u = rl.random((n_ent, 2))
678
+ sf = np.interp(u[:, 0], self.lifetime_levels, self.start_q)
679
+ lf = np.interp(u[:, 1], self.lifetime_levels, self.length_q)
680
+ first = np.clip(np.floor(sf * K), 0, K - 1).astype(np.int64)
681
+ length = np.clip(np.round(lf * (K - first)), 1, K - first).astype(np.int64)
682
+ else:
683
+ first = np.zeros(n_ent, dtype=np.int64)
684
+ length = np.full(n_ent, K, dtype=np.int64)
685
+ last = first + length - 1
686
+ mids = 0.5 * (steps[first] + steps[last])
687
+
688
+ # entity effects
689
+ re = stream(seed, "temporal", "panel", "entity_effects")
690
+ zz = special.ndtri(np.clip(re.random((n_ent, self.effect_mean.size)), 1e-12,
691
+ 1 - 1e-12))
692
+ theta = self.effect_mean + zz @ _sqrtm(self.effect_cov).T
693
+
694
+ # residuals
695
+ max_p = max(r.phi.size for r in self.residual.values())
696
+ burn = int(request.warmup_periods) + 10 * max_p + 50
697
+ total = burn + K
698
+ d = len(self.value_cols)
699
+ ri = stream(seed, "temporal", "panel", "innovations")
700
+ if self.copula is not None:
701
+ u = special.ndtr(self.copula.sample(n_ent * total, ri))
702
+ else:
703
+ u = ri.random((n_ent * total, d))
704
+ u = np.clip(u, 1e-12, 1 - 1e-12).reshape(n_ent, total, d)
705
+ out_vals: dict[str, np.ndarray] = {}
706
+ for j, c in enumerate(self.value_cols):
707
+ rm = self.residual[c]
708
+ z = rm.innovation.ppf(u[:, :, j].ravel()).reshape(n_ent, total)
709
+ e = _garch_simulate(z, rm.garch) if rm.garch is not None else z
710
+ r = signal.lfilter([1.0], np.r_[1.0, -rm.phi], e, axis=1) if rm.phi.size else e
711
+ y = np.empty((n_ent, K))
712
+ for i in range(n_ent):
713
+ y[i] = self._entity_mean(c, steps, mids[i], theta[i])
714
+ out_vals[c] = y + r[:, burn:]
715
+
716
+ # long frame within lifetimes
717
+ k_idx = np.arange(K)
718
+ alive = (k_idx[None, :] >= first[:, None]) & (k_idx[None, :] <= last[:, None])
719
+ ei, ki = np.nonzero(alive)
720
+ width = max(6, len(str(n_ent)))
721
+ if self.entity_dtype == "Int64":
722
+ ids = pl.Series(self.entity_col, ei + 1, dtype=pl.Int64)
723
+ else:
724
+ ids = pl.Series(self.entity_col, [f"entity_{i + 1:0{width}d}" for i in ei])
725
+ cols: dict[str, Any] = {self.entity_col: ids,
726
+ self.time_col: idx.gather(ki).alias(self.time_col)}
727
+ for c in self.value_cols:
728
+ cols[c] = _cast_values(out_vals[c][ei, ki], self.residual[c].dtype, c)
729
+ beyond = request.mode == "new_period" and float(steps.max()) > self.n_steps - 1
730
+ self.last_generation = {"mode": request.mode, "n_rows": int(ei.size),
731
+ "n_entities": n_ent, "burn_in": burn,
732
+ "trend_extrapolated": bool(beyond)}
733
+ return pl.DataFrame(cols)
734
+
735
+ # -- serialisation -----------------------------------------------------------------------
736
+ def to_section(self, store: ArrayStore, prefix: str = "temporal.") -> dict[str, Any]:
737
+ glob: dict[str, Any] = {}
738
+ for c, g in self.global_.items():
739
+ seas = []
740
+ for p, coef in g.seasonal:
741
+ ref = store.put(f"{prefix}{c}.global.seasonal.{p:g}", coef)
742
+ seas.append({"period": p, "harmonics": int(coef.shape[0]), "coefficients": ref})
743
+ glob[c] = {"intercept": g.intercept, "slope": g.slope, "seasonal": seas,
744
+ "regimes": [{"start_step": r.start_step, "level": r.level}
745
+ for r in g.regimes]}
746
+ res: dict[str, Any] = {}
747
+ for c, r in self.residual.items():
748
+ res[c] = {"dtype": r.dtype,
749
+ "ar": {"order": int(r.phi.size), "coef": [float(v) for v in r.phi]},
750
+ "garch": (None if r.garch is None else
751
+ {"omega": r.garch.omega, "alpha": r.garch.alpha,
752
+ "beta": r.garch.beta}),
753
+ "innovation": r.innovation.to_spec(store, f"{prefix}{c}.innovation.")
754
+ .model_dump(mode="json"),
755
+ "diagnostics": r.diagnostics}
756
+ ck = self.clock
757
+ return {
758
+ "kind": SECTION_KIND, "format": SECTION_FORMAT, "enabled": True,
759
+ "time_col": self.time_col, "entity_col": self.entity_col,
760
+ "entity_dtype": self.entity_dtype,
761
+ "time_dtype": {"kind": ck.time_kind, "time_unit": ck.time_unit,
762
+ "time_zone": ck.time_zone},
763
+ "cadence": ck.cadence, "start": _iso(ck.start), "end": _iso(ck.end),
764
+ "n_steps": self.n_steps, "n_entities": self.n_entities,
765
+ "value_cols": list(self.value_cols), "periods": list(self.periods),
766
+ "global": glob,
767
+ "entity_effects": {
768
+ "distribution": "multivariate_normal",
769
+ "params": list(self.param_names),
770
+ "seasonal_scale": self.seasonal_scale,
771
+ "mean": store.put(f"{prefix}entity_effects.mean", self.effect_mean),
772
+ "covariance": store.put(f"{prefix}entity_effects.covariance",
773
+ self.effect_cov)},
774
+ "lifetimes": {
775
+ "levels": store.put(f"{prefix}lifetimes.levels", self.lifetime_levels),
776
+ "start_fraction": store.put(f"{prefix}lifetimes.start_fraction", self.start_q),
777
+ "length_fraction": store.put(f"{prefix}lifetimes.length_fraction",
778
+ self.length_q)},
779
+ "residual": res,
780
+ "innovation_copula": (self.copula.to_spec(store, f"{prefix}innovation.")
781
+ .model_dump(mode="json") if self.copula is not None
782
+ else None),
783
+ "lagged_cross_correlation": dict(self.lagged_xcorr),
784
+ "assumptions": list(self.assumptions),
785
+ "diagnostics": dict(self.diagnostics),
786
+ }
787
+
788
+ @classmethod
789
+ def from_section(cls, section: dict[str, Any], store: ArrayStore) -> PanelModel:
790
+ if section.get("kind") != SECTION_KIND:
791
+ raise GenerationError(f"not a {SECTION_KIND} section: kind={section.get('kind')!r}")
792
+ if int(section.get("format", 0)) > SECTION_FORMAT:
793
+ raise GenerationError(f"unsupported {SECTION_KIND} section format "
794
+ f"{section.get('format')}")
795
+ m = cls()
796
+ ck = m.clock
797
+ m.time_col, m.entity_col = str(section["time_col"]), str(section["entity_col"])
798
+ m.entity_dtype = str(section.get("entity_dtype", "String"))
799
+ td = section["time_dtype"]
800
+ ck.time_kind, ck.time_unit, ck.time_zone = td["kind"], td["time_unit"], td["time_zone"]
801
+ ck.cadence = str(section["cadence"])
802
+ ck.start = _parse_time(section["start"], ck.time_kind)
803
+ ck.end = _parse_time(section["end"], ck.time_kind)
804
+ m.n_steps = ck.n_steps = int(section["n_steps"])
805
+ m.n_entities = int(section["n_entities"])
806
+ m.value_cols = [str(c) for c in section["value_cols"]]
807
+ m.periods = [float(p) for p in section.get("periods", [])]
808
+ for c in m.value_cols:
809
+ g = section["global"][c]
810
+ m.global_[c] = GlobalComponent(
811
+ float(g["intercept"]), float(g["slope"]),
812
+ [(float(s["period"]), np.asarray(store.get(s["coefficients"]),
813
+ dtype=np.float64).reshape(-1, 2))
814
+ for s in g["seasonal"]],
815
+ [Regime(float(r["start_step"]), float(r["level"])) for r in g["regimes"]])
816
+ r = section["residual"][c]
817
+ gs = r.get("garch")
818
+ m.residual[c] = ResidualModel(
819
+ phi=np.asarray(r["ar"]["coef"], dtype=np.float64),
820
+ innovation=marginal_from_spec(ModelSpec.model_validate(r["innovation"]), store),
821
+ garch=None if not gs else Garch(float(gs["omega"]), float(gs["alpha"]),
822
+ float(gs["beta"])),
823
+ dtype=str(r.get("dtype", "Float64")),
824
+ diagnostics=dict(r.get("diagnostics", {})))
825
+ ee = section["entity_effects"]
826
+ m.param_names = [str(p) for p in ee["params"]]
827
+ m.seasonal_scale = bool(ee["seasonal_scale"])
828
+ m.effect_mean = np.asarray(store.get(ee["mean"]), dtype=np.float64)
829
+ m.effect_cov = np.asarray(store.get(ee["covariance"]), dtype=np.float64).reshape(
830
+ m.effect_mean.size, m.effect_mean.size)
831
+ lt = section["lifetimes"]
832
+ m.lifetime_levels = np.asarray(store.get(lt["levels"]), dtype=np.float64)
833
+ m.start_q = np.asarray(store.get(lt["start_fraction"]), dtype=np.float64)
834
+ m.length_q = np.asarray(store.get(lt["length_fraction"]), dtype=np.float64)
835
+ cop = section.get("innovation_copula")
836
+ m.copula = GaussianCopula.from_spec(ModelSpec.model_validate(cop), store) if cop else None
837
+ m.lagged_xcorr = {str(k): [float(x) for x in v]
838
+ for k, v in section.get("lagged_cross_correlation", {}).items()}
839
+ m.assumptions = [str(a) for a in section.get("assumptions", [])]
840
+ m.diagnostics = dict(section.get("diagnostics", {}))
841
+ return m
842
+
843
+
844
+ # ---------------------------------------------------------------------------------------------
845
+ # helpers
846
+ # ---------------------------------------------------------------------------------------------
847
+
848
+
849
+ def _time_effects(y: np.ndarray, iters: int = 50) -> np.ndarray:
850
+ """``delta_t`` of ``y_it = alpha_i + b_i t + delta_t`` (entities x time, NaN = missing).
851
+
852
+ Entity intercepts *and* slopes are removed (normalised to mean zero), so ``delta`` is free
853
+ of the composition drift that heterogeneous slopes and staggered lifetimes would cause.
854
+ """
855
+ m = np.isfinite(y)
856
+ mf = m.astype(np.float64)
857
+ yz = np.where(m, y, 0.0)
858
+ t = np.arange(y.shape[1], dtype=np.float64)
859
+ cnt_t = m.sum(axis=0)
860
+ cnt_i = np.maximum(m.sum(axis=1), 1)
861
+ tbar = (mf * t).sum(axis=1) / cnt_i
862
+ tc = np.where(m, t[None, :] - tbar[:, None], 0.0)
863
+ stt = (tc ** 2).sum(axis=1)
864
+ slope_ok = stt > 0
865
+ alpha = np.zeros(y.shape[0])
866
+ slope = np.zeros(y.shape[0])
867
+ delta = np.zeros(y.shape[1])
868
+ for _ in range(iters):
869
+ fit = alpha[:, None] + slope[:, None] * tc
870
+ delta = np.where(cnt_t > 0, ((yz - fit) * mf).sum(axis=0) / np.maximum(cnt_t, 1),
871
+ np.nan)
872
+ dz = np.where(np.isfinite(delta), delta, 0.0)
873
+ v = (yz - dz[None, :]) * mf
874
+ a_new = v.sum(axis=1) / cnt_i
875
+ b_new = np.where(slope_ok, (v * tc).sum(axis=1) / np.where(slope_ok, stt, 1.0), 0.0)
876
+ a_new -= a_new.mean()
877
+ b_new -= b_new[slope_ok].mean() if slope_ok.any() else 0.0
878
+ b_new = np.where(slope_ok, b_new, 0.0)
879
+ done = max(np.max(np.abs(a_new - alpha)), np.max(np.abs(b_new - slope))) < 1e-9
880
+ alpha, slope = a_new, b_new
881
+ if done:
882
+ break
883
+ if not np.all(np.isfinite(delta)):
884
+ idx = np.arange(delta.size)
885
+ ok = np.isfinite(delta)
886
+ delta = np.interp(idx, idx[ok], delta[ok])
887
+ return delta
888
+
889
+
890
+ def _block_diag(blocks: list[np.ndarray]) -> np.ndarray:
891
+ n = sum(b.shape[0] for b in blocks)
892
+ out = np.zeros((n, n))
893
+ pos = 0
894
+ for b in blocks:
895
+ k = b.shape[0]
896
+ out[pos: pos + k, pos: pos + k] = b
897
+ pos += k
898
+ return out
899
+
900
+
901
+ def _pooled_lag1(resid: np.ndarray) -> float:
902
+ a, b = resid[..., 1:], resid[..., :-1]
903
+ ok = np.isfinite(a) & np.isfinite(b)
904
+ if ok.sum() < 10:
905
+ return 0.0
906
+ num = float(np.sum(a[ok] * b[ok]))
907
+ den = float(np.sqrt(np.sum(a[ok] ** 2) * np.sum(b[ok] ** 2)))
908
+ return float(np.clip(num / den if den > 0 else 0.0, 0.0, 0.95))
909
+
910
+
911
+ def _xcorr(a: np.ndarray, b: np.ndarray, k: int) -> float:
912
+ """corr(a_t, b_{t-k}) pooled over entities."""
913
+ bl = _lagged(b, k) if k else b
914
+ ok = np.isfinite(a) & np.isfinite(bl)
915
+ if ok.sum() < 10:
916
+ return 0.0
917
+ x, y = a[ok], bl[ok]
918
+ sx, sy = float(np.std(x)), float(np.std(y))
919
+ if sx <= 0 or sy <= 0:
920
+ return 0.0
921
+ return float(np.mean((x - x.mean()) * (y - y.mean())) / (sx * sy))
922
+
923
+
924
+ def _garch_simulate(z: np.ndarray, g: Garch) -> np.ndarray:
925
+ out = np.empty_like(z)
926
+ s2 = np.full(z.shape[0], g.unconditional)
927
+ prev = np.zeros(z.shape[0])
928
+ for k in range(z.shape[1]):
929
+ if k > 0:
930
+ s2 = g.omega + g.alpha * prev ** 2 + g.beta * s2
931
+ out[:, k] = np.sqrt(s2) * z[:, k]
932
+ prev = out[:, k]
933
+ return out
934
+
935
+
936
+ __all__ = ["GlobalComponent", "Garch", "PanelModel", "Regime", "detect_level_shifts",
937
+ "fit_garch", "fit_pooled_ar", "garch_filter"]