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,596 @@
|
|
|
1
|
+
"""Temporal metrics (M19): autocorrelation, seasonal profile, spectrum and trend.
|
|
2
|
+
|
|
3
|
+
All four are arity-1 metrics on a numeric value column that need the **time ordering**:
|
|
4
|
+
|
|
5
|
+
* Construct them with ``time_col=...`` (``METRICS.get("temporal.acf")(time_col="date")``). The
|
|
6
|
+
frame passed to ``measure`` must then contain that column; rows are sorted by it and values
|
|
7
|
+
sharing a timestamp are averaged (so a panel collapses to its cross-entity mean series).
|
|
8
|
+
* With ``time_col=None`` (the registry's no-argument construction) the metric uses the single
|
|
9
|
+
Date/Datetime column in the frame if there is exactly one, else the row order.
|
|
10
|
+
* ``applies_to`` is **False unless ``time_col`` is set**, so the generic target builder (which
|
|
11
|
+
bootstraps rows and would destroy the ordering) skips these metrics. The targets engine must
|
|
12
|
+
build temporal targets explicitly: instantiate with ``time_col``, call ``measure`` on the
|
|
13
|
+
time-ordered table and use :meth:`noise_floor`, which is overridden with a moving-block
|
|
14
|
+
bootstrap that keeps the timestamps in place.
|
|
15
|
+
|
|
16
|
+
Summaries are JSON-safe and policy-coarsened (significant digits); they hold aggregate
|
|
17
|
+
statistics only, never raw points:
|
|
18
|
+
|
|
19
|
+
* ``temporal.acf``: ``{"acf": [r_1..r_k]}`` of the linearly detrended series;
|
|
20
|
+
distance = L2 norm of the difference over the common lags.
|
|
21
|
+
* ``temporal.seasonal_profile``: ``{"scale": sd, "periods": [{"period", "amplitude",
|
|
22
|
+
"phase"}]}``. Periods (in cadence steps) come from the constructor or FFT detection; amplitude
|
|
23
|
+
and phase (peak position in steps, measured from the Unix epoch when a time column is used, so
|
|
24
|
+
different windows are comparable) are of the first harmonic. Distance = mean over reference
|
|
25
|
+
periods of ``0.5 * (relative amplitude error + circular phase error / (P/2))``, both capped at 1;
|
|
26
|
+
an unmatched reference period counts 1.
|
|
27
|
+
* ``temporal.spectrum``: ``{"bands": [log10 power share | null] * n_bands}`` over fixed
|
|
28
|
+
log-spaced frequency bands (cycles per step) of the detrended, Hann-windowed periodogram;
|
|
29
|
+
distance = RMS difference over bands present in both.
|
|
30
|
+
* ``temporal.trend``: ``{"slope", "unit": "per_day" | "per_step", "span", "scale"}``; distance
|
|
31
|
+
= ``|slope_ref - slope_cand| * span_ref / scale_ref`` (trend difference accumulated over the
|
|
32
|
+
reference window, in units of the reference standard deviation).
|
|
33
|
+
|
|
34
|
+
Event metrics (M21) are measured on the **time column itself** (``columns = [time column]``),
|
|
35
|
+
with an optional ``entity_col`` (gaps and transitions are taken within each entity). They also
|
|
36
|
+
apply only when ``time_col`` is set, and their noise floors resample gaps / sequences in blocks
|
|
37
|
+
(or whole entities) instead of rows:
|
|
38
|
+
|
|
39
|
+
* ``temporal.interarrival``: ``{"levels", "quantiles", "mean"}`` of the gaps in seconds at fixed
|
|
40
|
+
levels (5%..95%); distance = mean absolute quantile difference / reference mean gap.
|
|
41
|
+
* ``temporal.burstiness``: ``{"B": (sigma - mu) / (sigma + mu)}`` of the gaps; distance =
|
|
42
|
+
``|B_ref - B_cand|``.
|
|
43
|
+
* ``temporal.transition`` (on a categorical column, ordered by ``time_col``):
|
|
44
|
+
``{"labels", "matrix", "weights"}``, a first-order transition matrix over categories pooled by
|
|
45
|
+
``min_category_support``, with cells below ``rare_cell_min`` suppressed; distance = mean
|
|
46
|
+
total-variation distance between matching rows, weighted by the reference row shares.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
import copy
|
|
52
|
+
import math
|
|
53
|
+
from typing import Any, ClassVar, Literal
|
|
54
|
+
|
|
55
|
+
import numpy as np
|
|
56
|
+
import polars as pl
|
|
57
|
+
|
|
58
|
+
from ectype.fingerprint.disclosure import coarsen, pool_categories
|
|
59
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
|
|
60
|
+
from ectype.temporal.detect import (
|
|
61
|
+
DAY_US,
|
|
62
|
+
detect_periods,
|
|
63
|
+
epoch_us,
|
|
64
|
+
infer_cadence,
|
|
65
|
+
is_temporal_dtype,
|
|
66
|
+
)
|
|
67
|
+
from ectype.types import LogicalType
|
|
68
|
+
from ectype.validation.metrics.base import METRICS, Metric
|
|
69
|
+
from ectype.validation.metrics.univariate import (
|
|
70
|
+
is_category,
|
|
71
|
+
is_numeric,
|
|
72
|
+
numeric_values,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
MIN_POINTS = 16
|
|
76
|
+
N_BANDS = 16
|
|
77
|
+
F_MIN = 1.0 / 2048.0 # cycles per step; lowest band edge
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _Ordered:
|
|
81
|
+
"""Time-ordered values of one column."""
|
|
82
|
+
|
|
83
|
+
def __init__(self, y: np.ndarray, t_us: np.ndarray | None) -> None:
|
|
84
|
+
self.y = y
|
|
85
|
+
self.t_us = t_us
|
|
86
|
+
if t_us is not None and t_us.size >= 3:
|
|
87
|
+
cad = infer_cadence(t_us)
|
|
88
|
+
step = float(np.median(np.diff(np.unique(t_us))))
|
|
89
|
+
self.step_us = step if step > 0 else float("nan")
|
|
90
|
+
self.cadence = cad.cadence
|
|
91
|
+
else:
|
|
92
|
+
self.step_us = float("nan")
|
|
93
|
+
self.cadence = None
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def n(self) -> int:
|
|
97
|
+
return int(self.y.size)
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def has_time(self) -> bool:
|
|
101
|
+
return self.t_us is not None and math.isfinite(self.step_us)
|
|
102
|
+
|
|
103
|
+
def steps(self, absolute: bool = False) -> np.ndarray:
|
|
104
|
+
"""Time in cadence steps: from the first point, or from the Unix epoch."""
|
|
105
|
+
if not self.has_time:
|
|
106
|
+
return np.arange(self.n, dtype=np.float64)
|
|
107
|
+
assert self.t_us is not None
|
|
108
|
+
base = 0 if absolute else int(self.t_us[0])
|
|
109
|
+
return (self.t_us - base).astype(np.float64) / self.step_us
|
|
110
|
+
|
|
111
|
+
def detrended(self) -> np.ndarray:
|
|
112
|
+
s = self.steps()
|
|
113
|
+
if self.n < 3:
|
|
114
|
+
return self.y - self.y.mean() if self.n else self.y
|
|
115
|
+
return self.y - np.polyval(np.polyfit(s, self.y, 1), s)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class TemporalMetric(Metric):
|
|
119
|
+
arity: ClassVar[Literal[1, 2, "all"]] = 1
|
|
120
|
+
default_tolerance: ClassVar[float] = 0.2
|
|
121
|
+
|
|
122
|
+
def __init__(self, time_col: str | None = None) -> None:
|
|
123
|
+
self.time_col = time_col
|
|
124
|
+
|
|
125
|
+
def applies_to(self, columns: tuple[ColumnSchema, ...]) -> bool: # type: ignore[override]
|
|
126
|
+
return (self.time_col is not None and len(columns) == 1 and is_numeric(columns[0])
|
|
127
|
+
and columns[0].name != self.time_col)
|
|
128
|
+
|
|
129
|
+
# -- data access -----------------------------------------------------------------------
|
|
130
|
+
def _time_col(self, df: pl.DataFrame, value: str) -> str | None:
|
|
131
|
+
if self.time_col is not None:
|
|
132
|
+
if self.time_col not in df.columns:
|
|
133
|
+
raise ValueError(f"time column {self.time_col!r} not in the frame; pass it "
|
|
134
|
+
f"alongside the value column")
|
|
135
|
+
return self.time_col
|
|
136
|
+
cands = [c for c in df.columns if c != value and is_temporal_dtype(df.schema[c])]
|
|
137
|
+
return cands[0] if len(cands) == 1 else None
|
|
138
|
+
|
|
139
|
+
def ordered(self, df: pl.DataFrame, columns: list[ColumnSchema]) -> _Ordered:
|
|
140
|
+
col = columns[0]
|
|
141
|
+
tc = self._time_col(df, col.name)
|
|
142
|
+
y = numeric_values(df[col.name], col)
|
|
143
|
+
if tc is None:
|
|
144
|
+
return _Ordered(y[np.isfinite(y)], None)
|
|
145
|
+
d = pl.DataFrame({"t": df[tc], "y": y}).filter(pl.col("t").is_not_null()
|
|
146
|
+
& pl.col("y").is_not_nan())
|
|
147
|
+
d = d.group_by("t").agg(pl.col("y").mean()).sort("t")
|
|
148
|
+
return _Ordered(d["y"].to_numpy().astype(np.float64), epoch_us(d["t"]))
|
|
149
|
+
|
|
150
|
+
# -- block bootstrap noise floor ----------------------------------------------------------
|
|
151
|
+
def noise_floor(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
152
|
+
policy: DisclosurePolicySpec, rng: np.random.Generator,
|
|
153
|
+
n_boot: int = 20, sample_size: int | None = None) -> float:
|
|
154
|
+
"""Moving-block bootstrap of the detrended values, timestamps kept in place."""
|
|
155
|
+
ref = self.measure(df, columns, policy)
|
|
156
|
+
o = self.ordered(df, columns)
|
|
157
|
+
if o.n < MIN_POINTS:
|
|
158
|
+
return 0.0
|
|
159
|
+
s = o.steps()
|
|
160
|
+
fit = np.polyval(np.polyfit(s, o.y, 1), s)
|
|
161
|
+
resid = o.y - fit
|
|
162
|
+
blk = int(max(5, round(o.n ** (1 / 3) * 2)))
|
|
163
|
+
name = columns[0].name
|
|
164
|
+
times = (pl.Series("t", o.t_us).cast(pl.Datetime("us")) if o.t_us is not None
|
|
165
|
+
else None)
|
|
166
|
+
ds = []
|
|
167
|
+
for _ in range(n_boot):
|
|
168
|
+
starts = rng.integers(0, o.n - blk + 1, size=o.n // blk + 1)
|
|
169
|
+
idx = np.concatenate([np.arange(a, a + blk) for a in starts])[: o.n]
|
|
170
|
+
yb = fit + resid[idx]
|
|
171
|
+
frame = pl.DataFrame({name: yb})
|
|
172
|
+
if times is not None:
|
|
173
|
+
frame = frame.with_columns(times.alias(self.time_col or "__time__"))
|
|
174
|
+
m = copy.copy(self)
|
|
175
|
+
m.time_col = (self.time_col or "__time__") if times is not None else None
|
|
176
|
+
ds.append(self.distance(ref, m.measure(frame, [_float_schema(columns[0])], policy)))
|
|
177
|
+
return float(np.quantile(ds, 0.95)) if ds else 0.0
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _float_schema(col: ColumnSchema) -> ColumnSchema:
|
|
181
|
+
return col.model_copy(update={"logical_type": LogicalType.CONTINUOUS,
|
|
182
|
+
"physical_dtype": "Float64", "datetime_unit": None})
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _c(x: float, policy: DisclosurePolicySpec) -> float:
|
|
186
|
+
return coarsen(float(x), policy)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# ---------------------------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def acf(y: np.ndarray, max_lag: int) -> np.ndarray:
|
|
193
|
+
x = np.asarray(y, dtype=np.float64) - np.mean(y)
|
|
194
|
+
den = float(np.dot(x, x))
|
|
195
|
+
if den <= 0:
|
|
196
|
+
return np.zeros(max_lag)
|
|
197
|
+
return np.array([float(np.dot(x[:-k], x[k:])) / den for k in range(1, max_lag + 1)])
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@METRICS.register()
|
|
201
|
+
class ACFMetric(TemporalMetric):
|
|
202
|
+
kind = "temporal.acf"
|
|
203
|
+
family = "temporal.acf"
|
|
204
|
+
default_tolerance = 0.2
|
|
205
|
+
|
|
206
|
+
def __init__(self, time_col: str | None = None, max_lag: int = 10) -> None:
|
|
207
|
+
super().__init__(time_col)
|
|
208
|
+
self.max_lag = int(max_lag)
|
|
209
|
+
|
|
210
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
211
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
212
|
+
o = self.ordered(df, columns)
|
|
213
|
+
if o.n < MIN_POINTS:
|
|
214
|
+
return {"acf": []}
|
|
215
|
+
k = min(self.max_lag, o.n // 4)
|
|
216
|
+
return {"acf": [_c(v, policy) for v in acf(o.detrended(), k)]}
|
|
217
|
+
|
|
218
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
219
|
+
a, b = reference.get("acf", []), candidate.get("acf", [])
|
|
220
|
+
k = min(len(a), len(b))
|
|
221
|
+
if k == 0:
|
|
222
|
+
return 0.0 if len(a) == len(b) else 1.0
|
|
223
|
+
return float(np.linalg.norm(np.asarray(a[:k]) - np.asarray(b[:k])))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def harmonic_fit(y: np.ndarray, tau: np.ndarray, period: float) -> tuple[float, float]:
|
|
227
|
+
"""Amplitude and peak phase (steps in ``[0, P)``) of the first harmonic at ``period``."""
|
|
228
|
+
w = 2 * np.pi * tau / period
|
|
229
|
+
x = np.column_stack([np.ones(y.size), np.cos(w), np.sin(w)])
|
|
230
|
+
b, *_ = np.linalg.lstsq(x, y, rcond=None)
|
|
231
|
+
amp = float(np.hypot(b[1], b[2]))
|
|
232
|
+
phase = float((math.atan2(b[2], b[1]) * period / (2 * np.pi)) % period)
|
|
233
|
+
return amp, phase
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@METRICS.register()
|
|
237
|
+
class SeasonalProfileMetric(TemporalMetric):
|
|
238
|
+
kind = "temporal.seasonal_profile"
|
|
239
|
+
family = "temporal.seasonal_profile"
|
|
240
|
+
default_tolerance = 0.15
|
|
241
|
+
|
|
242
|
+
def __init__(self, time_col: str | None = None, periods: list[float] | None = None,
|
|
243
|
+
max_periods: int = 3) -> None:
|
|
244
|
+
super().__init__(time_col)
|
|
245
|
+
self.periods = None if periods is None else [float(p) for p in periods]
|
|
246
|
+
self.max_periods = int(max_periods)
|
|
247
|
+
|
|
248
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
249
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
250
|
+
o = self.ordered(df, columns)
|
|
251
|
+
if o.n < MIN_POINTS:
|
|
252
|
+
return {"scale": 0.0, "periods": []}
|
|
253
|
+
y = o.detrended()
|
|
254
|
+
per = self.periods if self.periods is not None else detect_periods(
|
|
255
|
+
y, cadence=o.cadence, max_periods=self.max_periods)
|
|
256
|
+
tau = o.steps(absolute=True)
|
|
257
|
+
out = []
|
|
258
|
+
for p in per:
|
|
259
|
+
if not 2.0 <= p <= o.n / 1.5:
|
|
260
|
+
continue
|
|
261
|
+
amp, ph = harmonic_fit(y, tau, p)
|
|
262
|
+
out.append({"period": _c(p, policy), "amplitude": _c(amp, policy),
|
|
263
|
+
"phase": _c(ph, policy)})
|
|
264
|
+
return {"scale": _c(float(np.std(y)), policy), "periods": out}
|
|
265
|
+
|
|
266
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
267
|
+
ref, cand = reference.get("periods", []), candidate.get("periods", [])
|
|
268
|
+
if not ref:
|
|
269
|
+
return 0.0
|
|
270
|
+
scale = float(reference.get("scale") or 0.0)
|
|
271
|
+
errs = []
|
|
272
|
+
for r in ref:
|
|
273
|
+
p = float(r["period"])
|
|
274
|
+
match = [c for c in cand if abs(float(c["period"]) - p) <= 0.05 * p]
|
|
275
|
+
if not match:
|
|
276
|
+
errs.append(1.0)
|
|
277
|
+
continue
|
|
278
|
+
c = min(match, key=lambda m: abs(float(m["period"]) - p))
|
|
279
|
+
ar, ac = float(r["amplitude"]), float(c["amplitude"])
|
|
280
|
+
amp_err = min(1.0, abs(ar - ac) / max(ar, 1e-3 * scale, 1e-12))
|
|
281
|
+
dph = abs(float(r["phase"]) - float(c["phase"])) % p
|
|
282
|
+
ph_err = min(dph, p - dph) / (p / 2.0)
|
|
283
|
+
errs.append(0.5 * (amp_err + ph_err))
|
|
284
|
+
return float(np.mean(errs))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@METRICS.register()
|
|
288
|
+
class SpectrumMetric(TemporalMetric):
|
|
289
|
+
kind = "temporal.spectrum"
|
|
290
|
+
family = "temporal.spectrum"
|
|
291
|
+
default_tolerance = 0.3
|
|
292
|
+
|
|
293
|
+
def __init__(self, time_col: str | None = None, n_bands: int = N_BANDS) -> None:
|
|
294
|
+
super().__init__(time_col)
|
|
295
|
+
self.n_bands = int(n_bands)
|
|
296
|
+
|
|
297
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
298
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
299
|
+
o = self.ordered(df, columns)
|
|
300
|
+
if o.n < MIN_POINTS:
|
|
301
|
+
return {"bands": []}
|
|
302
|
+
y = o.detrended()
|
|
303
|
+
sd = float(np.std(y))
|
|
304
|
+
if sd <= 0:
|
|
305
|
+
return {"bands": [None] * self.n_bands}
|
|
306
|
+
p = np.abs(np.fft.rfft((y / sd) * np.hanning(o.n))) ** 2
|
|
307
|
+
f = np.arange(p.size) / o.n
|
|
308
|
+
p, f = p[1:], f[1:]
|
|
309
|
+
edges = np.logspace(math.log10(F_MIN), math.log10(0.5), self.n_bands + 1)
|
|
310
|
+
edges[-1] = 0.5 + 1e-12
|
|
311
|
+
total = float(p.sum()) or 1.0
|
|
312
|
+
bands: list[float | None] = []
|
|
313
|
+
for lo, hi in zip(edges[:-1], edges[1:], strict=True):
|
|
314
|
+
m = (f >= lo) & (f < hi)
|
|
315
|
+
bands.append(_c(math.log10(float(p[m].sum()) / total + 1e-8), policy)
|
|
316
|
+
if m.any() else None)
|
|
317
|
+
return {"bands": bands}
|
|
318
|
+
|
|
319
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
320
|
+
a, b = reference.get("bands", []), candidate.get("bands", [])
|
|
321
|
+
diffs = [float(x) - float(y) for x, y in zip(a, b, strict=False)
|
|
322
|
+
if x is not None and y is not None]
|
|
323
|
+
if not diffs:
|
|
324
|
+
return 0.0 if not a and not b else 1.0
|
|
325
|
+
return float(np.sqrt(np.mean(np.square(diffs))))
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
@METRICS.register()
|
|
329
|
+
class TrendMetric(TemporalMetric):
|
|
330
|
+
kind = "temporal.trend"
|
|
331
|
+
family = "temporal.trend"
|
|
332
|
+
default_tolerance = 0.25
|
|
333
|
+
|
|
334
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
335
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
336
|
+
o = self.ordered(df, columns)
|
|
337
|
+
if o.n < 3:
|
|
338
|
+
return {"slope": 0.0, "unit": "per_step", "span": 0.0, "scale": 0.0}
|
|
339
|
+
if o.has_time:
|
|
340
|
+
assert o.t_us is not None
|
|
341
|
+
x = (o.t_us - o.t_us[0]).astype(np.float64) / DAY_US
|
|
342
|
+
unit = "per_day"
|
|
343
|
+
else:
|
|
344
|
+
x = np.arange(o.n, dtype=np.float64)
|
|
345
|
+
unit = "per_step"
|
|
346
|
+
slope = float(np.polyfit(x, o.y, 1)[0])
|
|
347
|
+
return {"slope": _c(slope, policy), "unit": unit, "span": _c(float(x[-1] - x[0]), policy),
|
|
348
|
+
"scale": _c(float(np.std(o.y)), policy)}
|
|
349
|
+
|
|
350
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
351
|
+
if reference.get("unit") != candidate.get("unit"):
|
|
352
|
+
return math.inf
|
|
353
|
+
scale = float(reference.get("scale") or 0.0)
|
|
354
|
+
span = float(reference.get("span") or 0.0)
|
|
355
|
+
diff = abs(float(reference["slope"]) - float(candidate["slope"])) * span
|
|
356
|
+
if scale <= 0:
|
|
357
|
+
return 0.0 if diff == 0 else math.inf
|
|
358
|
+
return float(diff / scale)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# ---------------------------------------------------------------------------------------------
|
|
362
|
+
# Event metrics (M21)
|
|
363
|
+
# ---------------------------------------------------------------------------------------------
|
|
364
|
+
|
|
365
|
+
GAP_LEVELS = (0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
class EventMetric(Metric):
|
|
369
|
+
"""Base for metrics on event timestamps, optionally within entities."""
|
|
370
|
+
|
|
371
|
+
arity: ClassVar[Literal[1, 2, "all"]] = 1
|
|
372
|
+
default_tolerance: ClassVar[float] = 0.1
|
|
373
|
+
|
|
374
|
+
def __init__(self, time_col: str | None = None, entity_col: str | None = None) -> None:
|
|
375
|
+
self.time_col = time_col
|
|
376
|
+
self.entity_col = entity_col
|
|
377
|
+
|
|
378
|
+
def applies_to(self, columns: tuple[ColumnSchema, ...]) -> bool: # type: ignore[override]
|
|
379
|
+
return (self.time_col is not None and len(columns) == 1
|
|
380
|
+
and columns[0].name == self.time_col)
|
|
381
|
+
|
|
382
|
+
def _time(self, df: pl.DataFrame, columns: list[ColumnSchema]) -> str:
|
|
383
|
+
tc = self.time_col or columns[0].name
|
|
384
|
+
if tc not in df.columns or not is_temporal_dtype(df.schema[tc]):
|
|
385
|
+
raise ValueError(f"time column {tc!r} must be a Date/Datetime column of the frame")
|
|
386
|
+
return tc
|
|
387
|
+
|
|
388
|
+
def sequences(self, df: pl.DataFrame, columns: list[ColumnSchema]) -> list[np.ndarray]:
|
|
389
|
+
"""Sorted event times (seconds) per entity."""
|
|
390
|
+
tc = self._time(df, columns)
|
|
391
|
+
ec = self.entity_col if self.entity_col in df.columns else None
|
|
392
|
+
d = df.select([c for c in (ec, tc) if c is not None]).drop_nulls()
|
|
393
|
+
t = epoch_us(d[tc]).astype(np.float64) / 1e6
|
|
394
|
+
if ec is None:
|
|
395
|
+
return [np.sort(t)]
|
|
396
|
+
e = d[ec].rank("dense").cast(pl.Int64).to_numpy()
|
|
397
|
+
o = np.lexsort((t, e))
|
|
398
|
+
t, e = t[o], e[o]
|
|
399
|
+
cuts = np.flatnonzero(np.diff(e)) + 1
|
|
400
|
+
return np.split(t, cuts)
|
|
401
|
+
|
|
402
|
+
def gaps(self, df: pl.DataFrame, columns: list[ColumnSchema]) -> np.ndarray:
|
|
403
|
+
g = [np.diff(s) for s in self.sequences(df, columns) if s.size > 1]
|
|
404
|
+
return np.concatenate(g) if g else np.zeros(0)
|
|
405
|
+
|
|
406
|
+
def from_gaps(self, g: np.ndarray, policy: DisclosurePolicySpec) -> Any:
|
|
407
|
+
raise NotImplementedError
|
|
408
|
+
|
|
409
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
410
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
411
|
+
return self.from_gaps(self.gaps(df, columns), policy)
|
|
412
|
+
|
|
413
|
+
def noise_floor(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
414
|
+
policy: DisclosurePolicySpec, rng: np.random.Generator,
|
|
415
|
+
n_boot: int = 20, sample_size: int | None = None) -> float:
|
|
416
|
+
"""Moving-block bootstrap of the gap sequence (keeps bursts together)."""
|
|
417
|
+
g = self.gaps(df, columns)
|
|
418
|
+
if g.size < MIN_POINTS:
|
|
419
|
+
return 0.0
|
|
420
|
+
ref = self.from_gaps(g, policy)
|
|
421
|
+
blk = int(max(5, round(g.size ** (1 / 3) * 2)))
|
|
422
|
+
ds = []
|
|
423
|
+
for _ in range(n_boot):
|
|
424
|
+
starts = rng.integers(0, g.size - blk + 1, size=g.size // blk + 1)
|
|
425
|
+
idx = np.concatenate([np.arange(a, a + blk) for a in starts])[: g.size]
|
|
426
|
+
ds.append(self.distance(ref, self.from_gaps(g[idx], policy)))
|
|
427
|
+
return float(np.quantile(ds, 0.95))
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
@METRICS.register()
|
|
431
|
+
class InterarrivalMetric(EventMetric):
|
|
432
|
+
kind = "temporal.interarrival"
|
|
433
|
+
family = "temporal.interarrival"
|
|
434
|
+
default_tolerance = 0.15
|
|
435
|
+
|
|
436
|
+
def from_gaps(self, g: np.ndarray, policy: DisclosurePolicySpec) -> Any:
|
|
437
|
+
if g.size < MIN_POINTS:
|
|
438
|
+
return {"levels": list(GAP_LEVELS), "quantiles": [], "mean": 0.0}
|
|
439
|
+
q = np.quantile(g, GAP_LEVELS)
|
|
440
|
+
return {"levels": list(GAP_LEVELS), "quantiles": [_c(v, policy) for v in q],
|
|
441
|
+
"mean": _c(float(g.mean()), policy)}
|
|
442
|
+
|
|
443
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
444
|
+
a, b = reference.get("quantiles", []), candidate.get("quantiles", [])
|
|
445
|
+
if not a or not b:
|
|
446
|
+
return 0.0 if not a and not b else 1.0
|
|
447
|
+
scale = float(reference.get("mean") or 0.0)
|
|
448
|
+
diff = float(np.mean(np.abs(np.asarray(a, dtype=float) - np.asarray(b, dtype=float))))
|
|
449
|
+
if scale <= 0:
|
|
450
|
+
return 0.0 if diff == 0 else math.inf
|
|
451
|
+
return diff / scale
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def burstiness(g: np.ndarray) -> float:
|
|
455
|
+
"""Goh-Barabasi burstiness ``(sigma - mu) / (sigma + mu)`` of the gaps (0 = Poisson)."""
|
|
456
|
+
g = np.asarray(g, dtype=np.float64)
|
|
457
|
+
if g.size < 2:
|
|
458
|
+
return 0.0
|
|
459
|
+
mu, sd = float(g.mean()), float(g.std())
|
|
460
|
+
return (sd - mu) / (sd + mu) if sd + mu > 0 else 0.0
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
@METRICS.register()
|
|
464
|
+
class BurstinessMetric(EventMetric):
|
|
465
|
+
kind = "temporal.burstiness"
|
|
466
|
+
family = "temporal.burstiness"
|
|
467
|
+
default_tolerance = 0.05
|
|
468
|
+
|
|
469
|
+
def from_gaps(self, g: np.ndarray, policy: DisclosurePolicySpec) -> Any:
|
|
470
|
+
if g.size < MIN_POINTS:
|
|
471
|
+
return {"B": None}
|
|
472
|
+
return {"B": _c(burstiness(g), policy)}
|
|
473
|
+
|
|
474
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
475
|
+
a, b = reference.get("B"), candidate.get("B")
|
|
476
|
+
if a is None or b is None:
|
|
477
|
+
return 0.0 if a is None and b is None else 1.0
|
|
478
|
+
return abs(float(a) - float(b))
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
@METRICS.register()
|
|
482
|
+
class TransitionMetric(Metric):
|
|
483
|
+
"""First-order transition matrix of a categorical column ordered by ``time_col``."""
|
|
484
|
+
|
|
485
|
+
kind = "temporal.transition"
|
|
486
|
+
family = "temporal.transition"
|
|
487
|
+
arity: ClassVar[Literal[1, 2, "all"]] = 1
|
|
488
|
+
default_tolerance = 0.05
|
|
489
|
+
|
|
490
|
+
def __init__(self, time_col: str | None = None, entity_col: str | None = None) -> None:
|
|
491
|
+
self.time_col = time_col
|
|
492
|
+
self.entity_col = entity_col
|
|
493
|
+
|
|
494
|
+
def applies_to(self, columns: tuple[ColumnSchema, ...]) -> bool: # type: ignore[override]
|
|
495
|
+
return (self.time_col is not None and len(columns) == 1 and is_category(columns[0])
|
|
496
|
+
and columns[0].name != self.time_col)
|
|
497
|
+
|
|
498
|
+
def sequences(self, df: pl.DataFrame, columns: list[ColumnSchema]) -> list[list[str]]:
|
|
499
|
+
col = columns[0].name
|
|
500
|
+
tc = self.time_col
|
|
501
|
+
if tc is None:
|
|
502
|
+
cands = [c for c in df.columns if c != col and is_temporal_dtype(df.schema[c])]
|
|
503
|
+
tc = cands[0] if len(cands) == 1 else None
|
|
504
|
+
ec = self.entity_col if self.entity_col in df.columns else None
|
|
505
|
+
d = df.select([c for c in (ec, tc) if c is not None]
|
|
506
|
+
+ [pl.col(col).cast(pl.String).alias("__state__")]).drop_nulls()
|
|
507
|
+
keys = [c for c in (ec, tc) if c is not None]
|
|
508
|
+
if keys:
|
|
509
|
+
d = d.sort(keys, maintain_order=True)
|
|
510
|
+
states = d["__state__"].to_list()
|
|
511
|
+
if ec is None:
|
|
512
|
+
return [states]
|
|
513
|
+
e = d[ec].to_list()
|
|
514
|
+
out: list[list[str]] = []
|
|
515
|
+
for i, s in enumerate(states):
|
|
516
|
+
if i == 0 or e[i] != e[i - 1]:
|
|
517
|
+
out.append([])
|
|
518
|
+
out[-1].append(s)
|
|
519
|
+
return out
|
|
520
|
+
|
|
521
|
+
def from_sequences(self, seqs: list[list[str]], policy: DisclosurePolicySpec) -> Any:
|
|
522
|
+
flat = [s for q in seqs for s in q]
|
|
523
|
+
if len(flat) < MIN_POINTS:
|
|
524
|
+
return {"labels": [], "matrix": [], "weights": []}
|
|
525
|
+
lab, cnt = np.unique(np.asarray(flat, dtype=str), return_counts=True)
|
|
526
|
+
labels, _, _ = pool_categories(lab, cnt, policy)
|
|
527
|
+
index = {v: i for i, v in enumerate(labels.tolist())}
|
|
528
|
+
other = index.get("__other__", -1)
|
|
529
|
+
k = labels.size
|
|
530
|
+
c = np.zeros((k, k))
|
|
531
|
+
for q in seqs:
|
|
532
|
+
codes = np.array([index.get(s, other) for s in q], dtype=np.int64)
|
|
533
|
+
if codes.size > 1 and (codes >= 0).all():
|
|
534
|
+
np.add.at(c, (codes[:-1], codes[1:]), 1.0)
|
|
535
|
+
c[c < policy.rare_cell_min] = 0.0
|
|
536
|
+
tot = c.sum(axis=1)
|
|
537
|
+
mat = [[_c(v, policy) for v in (c[i] / tot[i])] if tot[i] > 0 else None
|
|
538
|
+
for i in range(k)]
|
|
539
|
+
w = tot / tot.sum() if tot.sum() > 0 else tot
|
|
540
|
+
return {"labels": labels.tolist(), "matrix": mat,
|
|
541
|
+
"weights": [_c(float(v), policy) for v in w]}
|
|
542
|
+
|
|
543
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
544
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
545
|
+
return self.from_sequences(self.sequences(df, columns), policy)
|
|
546
|
+
|
|
547
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
548
|
+
rl, cl = reference.get("labels", []), candidate.get("labels", [])
|
|
549
|
+
if not rl:
|
|
550
|
+
return 0.0 if not cl else 1.0
|
|
551
|
+
cidx = {v: i for i, v in enumerate(cl)}
|
|
552
|
+
labels = list(dict.fromkeys([*rl, *cl]))
|
|
553
|
+
tot, wsum = 0.0, 0.0
|
|
554
|
+
for i, lab in enumerate(rl):
|
|
555
|
+
row = reference["matrix"][i]
|
|
556
|
+
w = float(reference["weights"][i])
|
|
557
|
+
if row is None or w <= 0:
|
|
558
|
+
continue
|
|
559
|
+
p = {rl[j]: float(v) for j, v in enumerate(row)}
|
|
560
|
+
ci = cidx.get(lab)
|
|
561
|
+
crow = candidate["matrix"][ci] if ci is not None else None
|
|
562
|
+
if crow is None:
|
|
563
|
+
tvd = 1.0
|
|
564
|
+
else:
|
|
565
|
+
q = {cl[j]: float(v) for j, v in enumerate(crow)}
|
|
566
|
+
tvd = 0.5 * sum(abs(p.get(x, 0.0) - q.get(x, 0.0)) for x in labels)
|
|
567
|
+
tot += w * tvd
|
|
568
|
+
wsum += w
|
|
569
|
+
return float(tot / wsum) if wsum > 0 else 0.0
|
|
570
|
+
|
|
571
|
+
def noise_floor(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
572
|
+
policy: DisclosurePolicySpec, rng: np.random.Generator,
|
|
573
|
+
n_boot: int = 20, sample_size: int | None = None) -> float:
|
|
574
|
+
"""Resample whole entities, or blocks of a single sequence."""
|
|
575
|
+
seqs = self.sequences(df, columns)
|
|
576
|
+
ref = self.from_sequences(seqs, policy)
|
|
577
|
+
ds = []
|
|
578
|
+
for _ in range(n_boot):
|
|
579
|
+
if len(seqs) > 1:
|
|
580
|
+
pick = rng.integers(0, len(seqs), size=len(seqs))
|
|
581
|
+
bs = [seqs[i] for i in pick]
|
|
582
|
+
else:
|
|
583
|
+
s = seqs[0] if seqs else []
|
|
584
|
+
n = len(s)
|
|
585
|
+
if n < MIN_POINTS:
|
|
586
|
+
return 0.0
|
|
587
|
+
blk = int(max(5, round(n ** (1 / 3) * 2)))
|
|
588
|
+
starts = rng.integers(0, n - blk + 1, size=n // blk + 1)
|
|
589
|
+
bs = [s[a: a + blk] for a in starts]
|
|
590
|
+
ds.append(self.distance(ref, self.from_sequences(bs, policy)))
|
|
591
|
+
return float(np.quantile(ds, 0.95)) if ds else 0.0
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
__all__ = ["ACFMetric", "BurstinessMetric", "EventMetric", "InterarrivalMetric",
|
|
595
|
+
"SeasonalProfileMetric", "SpectrumMetric", "TemporalMetric", "TransitionMetric",
|
|
596
|
+
"TrendMetric", "acf", "burstiness", "harmonic_fit"]
|