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,946 @@
|
|
|
1
|
+
"""Irregular event model (M21): timestamps, optional entities, categorical and numeric marks.
|
|
2
|
+
|
|
3
|
+
* **Calendar modulation**: an hour-of-day (24) and day-of-week (7) intensity profile, each kept
|
|
4
|
+
only when a quasi-Poisson test (dispersion estimated from hourly / daily counts, so clustered
|
|
5
|
+
processes do not trigger it) rejects a flat profile at ``p < 1e-4``. Profiles are shrunk
|
|
6
|
+
towards 1 by ``policy.rare_cell_min`` pseudo-counts and rounded to 3 decimals. Event times are
|
|
7
|
+
mapped to *operational time* ``tau(t) = int c(s) ds`` (``c`` = the profile, mean 1 over a
|
|
8
|
+
week) before the interarrival model is fitted, and mapped back after simulation.
|
|
9
|
+
* **Interarrival process** (in operational time, chosen by AIC on the conditional likelihood of
|
|
10
|
+
events 2..n): ``"poisson"`` (exponential gaps), ``"gamma"`` (gamma renewal) or ``"hawkes"``
|
|
11
|
+
(univariate, exponential kernel ``alpha beta exp(-beta s)``: ``alpha`` is the branching
|
|
12
|
+
ratio; MLE with an analytic gradient).
|
|
13
|
+
* **Entities** (optional): independent copies of the process; per-entity rate heterogeneity is a
|
|
14
|
+
lognormal multiplier (log-rate SD by method of moments, Poisson noise subtracted); entity
|
|
15
|
+
activity windows are stored as policy-coarsened quantiles (start offset and length fractions).
|
|
16
|
+
* **Marks**: every categorical mark gets a first-order transition matrix (categories pooled by
|
|
17
|
+
``min_category_support``; cells with fewer than ``rare_cell_min`` transitions are backed off
|
|
18
|
+
to the marginal). Numeric marks get a marginal (``profiling.univariate.fit_marginal``) per
|
|
19
|
+
state of the first categorical mark (the event type), pooled for rare states.
|
|
20
|
+
|
|
21
|
+
Generation (``TemporalRequest``): ``count_policy="natural"`` samples the count from the
|
|
22
|
+
intensity; ``"fixed"`` produces exactly ``n_rows`` events: the process is simulated until
|
|
23
|
+
``n_rows + 1`` events exist and the first ``n_rows`` are rescaled in time so the ``(n+1)``-th
|
|
24
|
+
lands on the window end (time rescaling). Output is deterministic for a given seed.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import datetime as dt
|
|
30
|
+
import math
|
|
31
|
+
from dataclasses import dataclass, field
|
|
32
|
+
from typing import Any, ClassVar, cast
|
|
33
|
+
|
|
34
|
+
import numpy as np
|
|
35
|
+
import polars as pl
|
|
36
|
+
from scipy import optimize, special, stats
|
|
37
|
+
|
|
38
|
+
from ectype.errors import GenerationError, ProfilingError
|
|
39
|
+
from ectype.fingerprint.core import ArrayStore
|
|
40
|
+
from ectype.fingerprint.disclosure import (
|
|
41
|
+
coarsen,
|
|
42
|
+
coarsen_array,
|
|
43
|
+
pool_categories,
|
|
44
|
+
quantile_levels,
|
|
45
|
+
resolve_policy,
|
|
46
|
+
)
|
|
47
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, ModelSpec
|
|
48
|
+
from ectype.models.base import MarginalModel, marginal_from_spec
|
|
49
|
+
from ectype.profiling.univariate import fit_marginal
|
|
50
|
+
from ectype.rng import stream
|
|
51
|
+
from ectype.temporal.contract import TemporalRequest, TimeUnit, time_index
|
|
52
|
+
from ectype.temporal.detect import DAY_US, epoch_us, is_temporal_dtype
|
|
53
|
+
from ectype.temporal.regular import _cast_values, _iso, _parse_time
|
|
54
|
+
from ectype.types import LogicalType
|
|
55
|
+
|
|
56
|
+
SECTION_KIND = "events"
|
|
57
|
+
SECTION_FORMAT = 1
|
|
58
|
+
HOUR_US = 3_600_000_000
|
|
59
|
+
MIN_EVENTS = 20
|
|
60
|
+
CALENDAR_P = 1e-4
|
|
61
|
+
PROCESSES = ("poisson", "gamma", "hawkes")
|
|
62
|
+
#: a numeric mark gets its own marginal per event type only with at least this many events
|
|
63
|
+
MIN_STATE_EVENTS = 30
|
|
64
|
+
MAX_MARK_SAMPLE = 20_000
|
|
65
|
+
_EPOCH_MONDAY_OFFSET = 3 # 1970-01-01 was a Thursday (weekday 3 with Monday = 0)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ---------------------------------------------------------------------------------------------
|
|
69
|
+
# Interarrival processes (times in normalised operational units)
|
|
70
|
+
# ---------------------------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Process:
|
|
75
|
+
kind: str # "poisson" | "gamma" | "hawkes"
|
|
76
|
+
params: dict[str, float]
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def rate(self) -> float:
|
|
80
|
+
"""Stationary event rate (per normalised unit)."""
|
|
81
|
+
p = self.params
|
|
82
|
+
if self.kind == "poisson":
|
|
83
|
+
return p["rate"]
|
|
84
|
+
if self.kind == "gamma":
|
|
85
|
+
return 1.0 / (p["shape"] * p["scale"])
|
|
86
|
+
return p["mu"] / max(1e-9, 1.0 - p["alpha"])
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def n_params(self) -> int:
|
|
90
|
+
return {"poisson": 1, "gamma": 2, "hawkes": 3}[self.kind]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _gaps(seqs: list[np.ndarray]) -> np.ndarray:
|
|
94
|
+
g = [np.diff(s) for s in seqs if s.size > 1]
|
|
95
|
+
return np.concatenate(g) if g else np.zeros(0)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def fit_poisson(seqs: list[np.ndarray]) -> tuple[Process, float]:
|
|
99
|
+
g = _gaps(seqs)
|
|
100
|
+
lam = g.size / max(float(g.sum()), 1e-300)
|
|
101
|
+
ll = g.size * math.log(lam) - lam * float(g.sum())
|
|
102
|
+
return Process("poisson", {"rate": lam}), ll
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def fit_gamma(seqs: list[np.ndarray]) -> tuple[Process, float]:
|
|
106
|
+
g = _gaps(seqs)
|
|
107
|
+
g = g[g > 0]
|
|
108
|
+
n, mean, mlog = g.size, float(g.mean()), float(np.mean(np.log(g)))
|
|
109
|
+
|
|
110
|
+
def nll(lk: float) -> float:
|
|
111
|
+
k = math.exp(lk)
|
|
112
|
+
th = mean / k
|
|
113
|
+
return -n * ((k - 1) * mlog - k * math.log(th) - special.gammaln(k) - k)
|
|
114
|
+
|
|
115
|
+
res = optimize.minimize_scalar(nll, bounds=(-6.0, 6.0), method="bounded")
|
|
116
|
+
k = math.exp(float(res.x))
|
|
117
|
+
return Process("gamma", {"shape": k, "scale": mean / k}), -float(res.fun)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def hawkes_loglik(seqs: list[np.ndarray], mu: float, alpha: float, beta: float,
|
|
121
|
+
grad: bool = False) -> tuple[float, np.ndarray]:
|
|
122
|
+
"""Log-likelihood of events 2..n of each sequence given the first, on ``(t_1, t_n]``,
|
|
123
|
+
and its gradient in ``(mu, alpha, beta)``."""
|
|
124
|
+
ll, g_mu, g_a, g_b = 0.0, 0.0, 0.0, 0.0
|
|
125
|
+
ab = alpha * beta
|
|
126
|
+
exp = math.exp
|
|
127
|
+
log = math.log
|
|
128
|
+
for s in seqs:
|
|
129
|
+
if s.size < 2:
|
|
130
|
+
continue
|
|
131
|
+
ts = s.tolist()
|
|
132
|
+
t0, tn = ts[0], ts[-1]
|
|
133
|
+
a_prev, b_prev = 0.0, 0.0 # A_i = sum_j e^{-beta dt}, B_i = sum_j dt e^{-beta dt}
|
|
134
|
+
for i in range(1, len(ts)):
|
|
135
|
+
d = ts[i] - ts[i - 1]
|
|
136
|
+
e = exp(-beta * d)
|
|
137
|
+
a_i = e * (1.0 + a_prev)
|
|
138
|
+
b_i = e * (b_prev + d * (1.0 + a_prev))
|
|
139
|
+
lam = mu + ab * a_i
|
|
140
|
+
ll += log(lam)
|
|
141
|
+
if grad:
|
|
142
|
+
g_mu += 1.0 / lam
|
|
143
|
+
g_a += beta * a_i / lam
|
|
144
|
+
g_b += (alpha * a_i - ab * b_i) / lam
|
|
145
|
+
a_prev, b_prev = a_i, b_i
|
|
146
|
+
# compensator: mu (t_n - t_1) + alpha sum_j (1 - e^{-beta (t_n - t_j)})
|
|
147
|
+
r = tn - s[:-1]
|
|
148
|
+
er = np.exp(-beta * r)
|
|
149
|
+
ll -= mu * (tn - t0) + alpha * float(np.sum(1.0 - er))
|
|
150
|
+
if grad:
|
|
151
|
+
g_mu -= tn - t0
|
|
152
|
+
g_a -= float(np.sum(1.0 - er))
|
|
153
|
+
g_b -= alpha * float(np.sum(r * er))
|
|
154
|
+
return ll, np.array([g_mu, g_a, g_b])
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def fit_hawkes(seqs: list[np.ndarray]) -> tuple[Process, float]:
|
|
158
|
+
"""MLE over ``(log mu, logit alpha, log beta)`` with L-BFGS-B."""
|
|
159
|
+
g = _gaps(seqs)
|
|
160
|
+
lam = g.size / max(float(g.sum()), 1e-300)
|
|
161
|
+
|
|
162
|
+
def unpack(x: np.ndarray) -> tuple[float, float, float]:
|
|
163
|
+
return math.exp(x[0]), 0.98 / (1 + math.exp(-x[1])), math.exp(x[2])
|
|
164
|
+
|
|
165
|
+
def f(x: np.ndarray) -> tuple[float, np.ndarray]:
|
|
166
|
+
mu, a, b = unpack(x)
|
|
167
|
+
ll, gr = hawkes_loglik(seqs, mu, a, b, grad=True)
|
|
168
|
+
da = a * (1 - a / 0.98)
|
|
169
|
+
return -ll, -np.array([gr[0] * mu, gr[1] * da, gr[2] * b])
|
|
170
|
+
|
|
171
|
+
best = None
|
|
172
|
+
for a0, b0 in ((0.5, 5.0 * lam), (0.2, 1.0 * lam)):
|
|
173
|
+
x0 = np.array([math.log(lam * (1 - a0)), math.log(a0 / (0.98 - a0)), math.log(b0)])
|
|
174
|
+
res = optimize.minimize(f, x0, jac=True, method="L-BFGS-B",
|
|
175
|
+
bounds=[(math.log(lam) - 12, math.log(lam) + 3), (-9, 9),
|
|
176
|
+
(math.log(lam) - 8, math.log(lam) + 9)],
|
|
177
|
+
options={"maxiter": 200})
|
|
178
|
+
if best is None or res.fun < best.fun:
|
|
179
|
+
best = res
|
|
180
|
+
assert best is not None
|
|
181
|
+
mu, a, b = unpack(best.x)
|
|
182
|
+
return Process("hawkes", {"mu": mu, "alpha": a, "beta": b}), -float(best.fun)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
_FITTERS = {"poisson": fit_poisson, "gamma": fit_gamma, "hawkes": fit_hawkes}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def select_process(seqs: list[np.ndarray], processes: tuple[str, ...] = PROCESSES
|
|
189
|
+
) -> tuple[Process, dict[str, float]]:
|
|
190
|
+
"""Fit each candidate and keep the lowest AIC."""
|
|
191
|
+
aic: dict[str, float] = {}
|
|
192
|
+
best: tuple[float, Process] | None = None
|
|
193
|
+
for k in processes:
|
|
194
|
+
proc, ll = _FITTERS[k](seqs)
|
|
195
|
+
a = 2 * proc.n_params - 2 * ll
|
|
196
|
+
aic[k] = a
|
|
197
|
+
if best is None or a < best[0]:
|
|
198
|
+
best = (a, proc)
|
|
199
|
+
assert best is not None
|
|
200
|
+
return best[1], aic
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def simulate_process(proc: Process, u0: float, u1: float, rng: np.random.Generator) -> np.ndarray:
|
|
204
|
+
"""Event times of ``proc`` in ``[u0, u1)``, simulated from a burn-in before ``u0``."""
|
|
205
|
+
p = proc.params
|
|
206
|
+
span = max(0.0, u1 - u0)
|
|
207
|
+
if proc.kind == "hawkes":
|
|
208
|
+
mu, a, b = p["mu"], p["alpha"], p["beta"]
|
|
209
|
+
burn = 20.0 / b / max(1e-3, 1 - a)
|
|
210
|
+
lo = u0 - burn
|
|
211
|
+
n_imm = int(stats.poisson.ppf(rng.random(), mu * (u1 - lo)))
|
|
212
|
+
gen = np.sort(lo + (u1 - lo) * rng.random(n_imm))
|
|
213
|
+
out = [gen]
|
|
214
|
+
while gen.size:
|
|
215
|
+
k = stats.poisson.ppf(rng.random(gen.size), a).astype(np.int64)
|
|
216
|
+
if k.sum() == 0:
|
|
217
|
+
break
|
|
218
|
+
parents = np.repeat(gen, k)
|
|
219
|
+
child = parents - np.log1p(-rng.random(parents.size)) / b
|
|
220
|
+
gen = child[child < u1]
|
|
221
|
+
out.append(gen)
|
|
222
|
+
t = np.sort(np.concatenate(out))
|
|
223
|
+
return t[t >= u0]
|
|
224
|
+
mean = 1.0 / proc.rate
|
|
225
|
+
burn = 20.0 * mean
|
|
226
|
+
chunks: list[np.ndarray] = []
|
|
227
|
+
pos = u0 - burn
|
|
228
|
+
while pos < u1:
|
|
229
|
+
m = int(1.2 * (u1 - pos) / mean) + 16
|
|
230
|
+
uu = rng.random(m)
|
|
231
|
+
if proc.kind == "poisson":
|
|
232
|
+
g = -np.log1p(-uu) / p["rate"]
|
|
233
|
+
else:
|
|
234
|
+
g = stats.gamma.ppf(uu, p["shape"], scale=p["scale"])
|
|
235
|
+
c = pos + np.cumsum(g)
|
|
236
|
+
chunks.append(c)
|
|
237
|
+
pos = float(c[-1])
|
|
238
|
+
allt = np.concatenate(chunks) if chunks else np.zeros(0)
|
|
239
|
+
return allt[(allt >= u0) & (allt < u0 + span)]
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def simulate_fixed(proc: Process, u0: float, n: int, rng: np.random.Generator
|
|
243
|
+
) -> tuple[np.ndarray, float]:
|
|
244
|
+
"""The first ``n`` events after ``u0`` and the time of the ``(n+1)``-th."""
|
|
245
|
+
horizon = (n + 1) / proc.rate * 1.3 + 10.0 / proc.rate
|
|
246
|
+
for _ in range(30):
|
|
247
|
+
t = simulate_process(proc, u0, u0 + horizon, rng)
|
|
248
|
+
if t.size >= n + 1:
|
|
249
|
+
return t[:n], float(t[n])
|
|
250
|
+
horizon *= 2.0
|
|
251
|
+
raise GenerationError(f"could not simulate {n} events") # pragma: no cover
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
# ---------------------------------------------------------------------------------------------
|
|
255
|
+
# Calendar profiles and operational time
|
|
256
|
+
# ---------------------------------------------------------------------------------------------
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@dataclass
|
|
260
|
+
class Calendar:
|
|
261
|
+
hour: np.ndarray | None = None # (24,) relative intensity, mean 1
|
|
262
|
+
dow: np.ndarray | None = None # (7,) relative intensity (Monday = 0), mean 1
|
|
263
|
+
time_zone: str | None = None
|
|
264
|
+
norm: float = 1.0 # makes the weekly mean of hour x dow equal 1
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def active(self) -> bool:
|
|
268
|
+
return self.hour is not None or self.dow is not None
|
|
269
|
+
|
|
270
|
+
def _hod_dow(self, us: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
271
|
+
s = pl.Series(us.astype(np.int64)).cast(pl.Datetime("us", "UTC"))
|
|
272
|
+
if self.time_zone:
|
|
273
|
+
s = s.dt.convert_time_zone(self.time_zone)
|
|
274
|
+
return s.dt.hour().to_numpy().astype(np.int64), \
|
|
275
|
+
(s.dt.weekday().to_numpy().astype(np.int64) - 1)
|
|
276
|
+
|
|
277
|
+
def factor(self, us: np.ndarray) -> np.ndarray:
|
|
278
|
+
h, d = self._hod_dow(us)
|
|
279
|
+
out = np.ones(us.size)
|
|
280
|
+
if self.hour is not None:
|
|
281
|
+
out = out * self.hour[h]
|
|
282
|
+
if self.dow is not None:
|
|
283
|
+
out = out * self.dow[d]
|
|
284
|
+
return out / self.norm
|
|
285
|
+
|
|
286
|
+
def finalize(self) -> None:
|
|
287
|
+
hh = self.hour if self.hour is not None else np.ones(24)
|
|
288
|
+
dd = self.dow if self.dow is not None else np.ones(7)
|
|
289
|
+
self.norm = float(np.mean(np.outer(dd, hh)))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
class OpClock:
|
|
293
|
+
"""Piecewise-linear map between seconds since ``origin_us`` and operational seconds."""
|
|
294
|
+
|
|
295
|
+
def __init__(self, cal: Calendar, origin_us: int, lo_s: float, hi_s: float) -> None:
|
|
296
|
+
self.cal = cal
|
|
297
|
+
self.origin = int(origin_us)
|
|
298
|
+
if not cal.active:
|
|
299
|
+
self.grid = None
|
|
300
|
+
return
|
|
301
|
+
h0 = (self.origin + int(math.floor(lo_s)) * 1_000_000) // HOUR_US - 1
|
|
302
|
+
h1 = (self.origin + int(math.ceil(hi_s)) * 1_000_000) // HOUR_US + 2
|
|
303
|
+
hours = np.arange(h0, h1 + 1, dtype=np.int64) * HOUR_US
|
|
304
|
+
f = cal.factor(hours[:-1])
|
|
305
|
+
self.grid = (hours - self.origin) / 1e6
|
|
306
|
+
self.cum = np.concatenate([[0.0], np.cumsum(f * 3600.0)])
|
|
307
|
+
self.cum -= np.interp(0.0, self.grid, self.cum)
|
|
308
|
+
|
|
309
|
+
def to_op(self, s: np.ndarray) -> np.ndarray:
|
|
310
|
+
if self.grid is None:
|
|
311
|
+
return np.asarray(s, dtype=np.float64)
|
|
312
|
+
return _interp_ext(s, self.grid, self.cum)
|
|
313
|
+
|
|
314
|
+
def from_op(self, tau: np.ndarray) -> np.ndarray:
|
|
315
|
+
if self.grid is None:
|
|
316
|
+
return np.asarray(tau, dtype=np.float64)
|
|
317
|
+
return _interp_ext(tau, self.cum, self.grid)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _interp_ext(x: np.ndarray, xp: np.ndarray, fp: np.ndarray) -> np.ndarray:
|
|
321
|
+
"""``np.interp`` with slope-1 extrapolation outside ``xp``."""
|
|
322
|
+
x = np.asarray(x, dtype=np.float64)
|
|
323
|
+
y = np.interp(x, xp, fp)
|
|
324
|
+
y = np.where(x < xp[0], fp[0] + (x - xp[0]), y)
|
|
325
|
+
return np.where(x > xp[-1], fp[-1] + (x - xp[-1]), y)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def fit_calendar(t_us: np.ndarray, lo_us: int, hi_us: int, *, hourly: bool,
|
|
329
|
+
policy: DisclosurePolicySpec, time_zone: str | None = None) -> tuple[
|
|
330
|
+
Calendar, dict[str, Any]]:
|
|
331
|
+
"""Hour-of-day / day-of-week profiles, kept only when significant (quasi-Poisson test)."""
|
|
332
|
+
cal = Calendar(time_zone=time_zone)
|
|
333
|
+
diag: dict[str, Any] = {}
|
|
334
|
+
span_h = (hi_us - lo_us) / HOUR_US
|
|
335
|
+
if t_us.size < 24 * policy.rare_cell_min or span_h < 48:
|
|
336
|
+
cal.finalize()
|
|
337
|
+
return cal, {"reason": "too few events or too short a window"}
|
|
338
|
+
h0, h1 = lo_us // HOUR_US, hi_us // HOUR_US + 1
|
|
339
|
+
slots = np.arange(h0, h1, dtype=np.int64)
|
|
340
|
+
counts = np.bincount((t_us // HOUR_US - h0).astype(np.int64), minlength=slots.size)
|
|
341
|
+
hod, dow = cal._hod_dow(slots * HOUR_US)
|
|
342
|
+
for name, key, k, enabled in (("hour", hod, 24, hourly), ("dow", dow, 7, span_h >= 14 * 24)):
|
|
343
|
+
if not enabled:
|
|
344
|
+
continue
|
|
345
|
+
c = np.bincount(key, weights=counts, minlength=k)
|
|
346
|
+
e = np.bincount(key, minlength=k).astype(np.float64) # exposure in slots
|
|
347
|
+
rate = counts.sum() / slots.size
|
|
348
|
+
exp_c = e * rate
|
|
349
|
+
x2 = float(np.sum((c - exp_c) ** 2 / np.maximum(exp_c, 1e-12)))
|
|
350
|
+
# dispersion of slot counts (hourly for the hour profile, daily for the weekday one)
|
|
351
|
+
if name == "hour":
|
|
352
|
+
unit = counts.astype(np.float64)
|
|
353
|
+
else:
|
|
354
|
+
day_idx = (slots - slots[0]) // 24
|
|
355
|
+
unit = np.bincount(day_idx, weights=counts).astype(np.float64)
|
|
356
|
+
prof_raw = np.where(e > 0, c / np.maximum(exp_c, 1e-12), 1.0)
|
|
357
|
+
fitted = prof_raw[key] * rate if name == "hour" else None
|
|
358
|
+
if fitted is not None:
|
|
359
|
+
phi = float(np.sum((unit - fitted) ** 2 / np.maximum(fitted, 1e-12))
|
|
360
|
+
/ max(1, unit.size - k))
|
|
361
|
+
else:
|
|
362
|
+
dw = np.bincount(day_idx, weights=prof_raw[key] * rate)
|
|
363
|
+
phi = float(np.sum((unit - dw) ** 2 / np.maximum(dw, 1e-12))
|
|
364
|
+
/ max(1, unit.size - k))
|
|
365
|
+
phi = max(phi, 1.0)
|
|
366
|
+
thr = float(stats.chi2.ppf(1 - CALENDAR_P, k - 1))
|
|
367
|
+
sig = x2 / phi > thr
|
|
368
|
+
diag[name] = {"chi2": coarsen(x2, policy), "dispersion": coarsen(phi, policy),
|
|
369
|
+
"threshold": coarsen(thr, policy), "significant": bool(sig)}
|
|
370
|
+
if sig:
|
|
371
|
+
# shrink towards flat with rare_cell_min pseudo-counts per bin
|
|
372
|
+
m = (c + policy.rare_cell_min) / (exp_c + policy.rare_cell_min)
|
|
373
|
+
m = m / (np.sum(m * e) / np.sum(e))
|
|
374
|
+
prof = np.round(np.maximum(m, 1e-3), 3)
|
|
375
|
+
setattr(cal, name, prof)
|
|
376
|
+
cal.finalize()
|
|
377
|
+
return cal, diag
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
# ---------------------------------------------------------------------------------------------
|
|
381
|
+
# Marks
|
|
382
|
+
# ---------------------------------------------------------------------------------------------
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
@dataclass
|
|
386
|
+
class CategoricalMark:
|
|
387
|
+
labels: np.ndarray # str labels; "__other__" last if pooled
|
|
388
|
+
marginal: np.ndarray # (k,)
|
|
389
|
+
transition: np.ndarray # (k, k) rows sum to 1
|
|
390
|
+
dtype: str = "String"
|
|
391
|
+
|
|
392
|
+
def simulate(self, seq_lengths: list[int], rng: np.random.Generator) -> list[np.ndarray]:
|
|
393
|
+
k = self.labels.size
|
|
394
|
+
cm = np.cumsum(self.marginal)
|
|
395
|
+
ct = np.cumsum(self.transition, axis=1)
|
|
396
|
+
n_seq = len(seq_lengths)
|
|
397
|
+
lmax = max(seq_lengths) if seq_lengths else 0
|
|
398
|
+
u = rng.random((n_seq, max(lmax, 1)))
|
|
399
|
+
states = np.zeros((n_seq, max(lmax, 1)), dtype=np.int64)
|
|
400
|
+
if lmax:
|
|
401
|
+
states[:, 0] = np.minimum(np.searchsorted(cm, u[:, 0] * cm[-1], side="right"),
|
|
402
|
+
k - 1)
|
|
403
|
+
for j in range(1, lmax):
|
|
404
|
+
rows = ct[states[:, j - 1]]
|
|
405
|
+
states[:, j] = np.minimum((rows < (u[:, j] * rows[:, -1])[:, None]).sum(axis=1),
|
|
406
|
+
k - 1)
|
|
407
|
+
return [states[i, :n] for i, n in enumerate(seq_lengths)]
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
@dataclass
|
|
411
|
+
class NumericMark:
|
|
412
|
+
by: str | None # categorical mark that selects the marginal
|
|
413
|
+
pooled: MarginalModel
|
|
414
|
+
per_state: dict[int, MarginalModel] = field(default_factory=dict)
|
|
415
|
+
dtype: str = "Float64"
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def transition_matrix(seqs: list[np.ndarray], k: int, marginal: np.ndarray,
|
|
419
|
+
rare_cell_min: int) -> tuple[np.ndarray, np.ndarray]:
|
|
420
|
+
"""Row-normalised transition probabilities with rare cells backed off to the marginal.
|
|
421
|
+
|
|
422
|
+
Cells with fewer than ``rare_cell_min`` transitions keep no own probability: the row mass
|
|
423
|
+
they held is redistributed over them in proportion to the marginal. Rows with fewer than
|
|
424
|
+
``rare_cell_min`` transitions in total become the marginal. Returns ``(P, counts)``.
|
|
425
|
+
"""
|
|
426
|
+
cnt = np.zeros((k, k))
|
|
427
|
+
for s in seqs:
|
|
428
|
+
if s.size > 1:
|
|
429
|
+
np.add.at(cnt, (s[:-1], s[1:]), 1.0)
|
|
430
|
+
p = np.empty((k, k))
|
|
431
|
+
for i in range(k):
|
|
432
|
+
row = cnt[i]
|
|
433
|
+
n = row.sum()
|
|
434
|
+
if n < rare_cell_min or n == 0:
|
|
435
|
+
p[i] = marginal
|
|
436
|
+
continue
|
|
437
|
+
keep = row >= rare_cell_min
|
|
438
|
+
rest = n - row[keep].sum()
|
|
439
|
+
out = np.where(keep, row, 0.0)
|
|
440
|
+
if (~keep).any() and rest > 0:
|
|
441
|
+
w = np.where(~keep, marginal, 0.0)
|
|
442
|
+
out = out + (rest * w / w.sum() if w.sum() > 0 else 0.0)
|
|
443
|
+
p[i] = out / out.sum()
|
|
444
|
+
return p, cnt
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
# ---------------------------------------------------------------------------------------------
|
|
448
|
+
# Model
|
|
449
|
+
# ---------------------------------------------------------------------------------------------
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
class EventModel:
|
|
453
|
+
"""Irregular events: calendar-modulated point process + entities + marks."""
|
|
454
|
+
|
|
455
|
+
kind: ClassVar[str] = SECTION_KIND
|
|
456
|
+
|
|
457
|
+
def __init__(self) -> None:
|
|
458
|
+
self.time_col = ""
|
|
459
|
+
self.entity_col: str | None = None
|
|
460
|
+
self.entity_dtype = "String"
|
|
461
|
+
self.mark_cols: list[str] = []
|
|
462
|
+
self.time_kind = "datetime"
|
|
463
|
+
self.time_unit: TimeUnit = "us"
|
|
464
|
+
self.time_zone: str | None = None
|
|
465
|
+
self.start: dt.date | dt.datetime | None = None
|
|
466
|
+
self.end: dt.date | dt.datetime | None = None
|
|
467
|
+
self.start_us = 0
|
|
468
|
+
self.end_us = 0
|
|
469
|
+
self.n_events = 0
|
|
470
|
+
self.n_entities = 1
|
|
471
|
+
self.scale_s = 1.0 # normalised unit in operational seconds
|
|
472
|
+
self.process = Process("poisson", {"rate": 1.0})
|
|
473
|
+
self.calendar = Calendar()
|
|
474
|
+
self.log_rate_sd = 0.0
|
|
475
|
+
self.lifetime_levels = np.zeros(0)
|
|
476
|
+
self.start_q = np.zeros(0)
|
|
477
|
+
self.length_q = np.zeros(0)
|
|
478
|
+
self.categorical: dict[str, CategoricalMark] = {}
|
|
479
|
+
self.numeric: dict[str, NumericMark] = {}
|
|
480
|
+
self.assumptions: list[str] = []
|
|
481
|
+
self.diagnostics: dict[str, Any] = {}
|
|
482
|
+
self.last_generation: dict[str, Any] = {}
|
|
483
|
+
|
|
484
|
+
# -- fit -------------------------------------------------------------------------------
|
|
485
|
+
def fit(self, df: pl.DataFrame, time_col: str, entity_col: str | None = None,
|
|
486
|
+
mark_cols: list[str] | str | None = None,
|
|
487
|
+
policy: DisclosurePolicySpec | str | None = None, seed: int = 0, *,
|
|
488
|
+
processes: tuple[str, ...] = PROCESSES, calendar: str = "auto") -> EventModel:
|
|
489
|
+
"""Fit on ``df``. ``calendar`` is ``"auto"`` (significance-tested profiles) or
|
|
490
|
+
``"off"``; ``processes`` restricts the interarrival candidates."""
|
|
491
|
+
pol = resolve_policy(policy)
|
|
492
|
+
marks = [] if mark_cols is None else ([mark_cols] if isinstance(mark_cols, str)
|
|
493
|
+
else list(mark_cols))
|
|
494
|
+
if time_col not in df.columns:
|
|
495
|
+
raise ProfilingError(f"time column {time_col!r} not found")
|
|
496
|
+
if not is_temporal_dtype(df.schema[time_col]):
|
|
497
|
+
raise ProfilingError(f"time column {time_col!r} must be pl.Date or pl.Datetime")
|
|
498
|
+
if entity_col is not None and entity_col not in df.columns:
|
|
499
|
+
raise ProfilingError(f"entity column {entity_col!r} not found")
|
|
500
|
+
for c in marks:
|
|
501
|
+
if c not in df.columns or c in (time_col, entity_col):
|
|
502
|
+
raise ProfilingError(f"mark column {c!r} must be an existing non-key column")
|
|
503
|
+
bad = [p for p in processes if p not in _FITTERS]
|
|
504
|
+
if bad or not processes:
|
|
505
|
+
raise ProfilingError(f"unknown interarrival processes {bad}; use {PROCESSES}")
|
|
506
|
+
if calendar not in ("auto", "off"):
|
|
507
|
+
raise ProfilingError(f"unknown calendar option {calendar!r}")
|
|
508
|
+
self.time_col, self.entity_col, self.mark_cols = time_col, entity_col, marks
|
|
509
|
+
tdt = df.schema[time_col]
|
|
510
|
+
self.time_kind = "date" if tdt == pl.Date else "datetime"
|
|
511
|
+
if isinstance(tdt, pl.Datetime):
|
|
512
|
+
self.time_unit, self.time_zone = tdt.time_unit or "us", tdt.time_zone
|
|
513
|
+
if entity_col is not None:
|
|
514
|
+
self.entity_dtype = "Int64" if df.schema[entity_col].is_integer() else "String"
|
|
515
|
+
|
|
516
|
+
d = df.filter(pl.col(time_col).is_not_null())
|
|
517
|
+
if entity_col is not None:
|
|
518
|
+
d = d.filter(pl.col(entity_col).is_not_null())
|
|
519
|
+
if d.height < MIN_EVENTS:
|
|
520
|
+
raise ProfilingError(f"too few events ({d.height} < {MIN_EVENTS})")
|
|
521
|
+
t_us = epoch_us(d[time_col]).astype(np.float64)
|
|
522
|
+
rng_j = stream(seed, "temporal", "events", "jitter")
|
|
523
|
+
if self.time_kind == "date":
|
|
524
|
+
t_us = t_us + rng_j.random(t_us.size) * DAY_US # spread within the day
|
|
525
|
+
ent = (d[entity_col].rank("dense").cast(pl.Int64).to_numpy() - 1
|
|
526
|
+
if entity_col is not None else np.zeros(d.height, dtype=np.int64))
|
|
527
|
+
order = np.lexsort((t_us, ent))
|
|
528
|
+
t_us, ent = t_us[order], ent[order]
|
|
529
|
+
d = d[order]
|
|
530
|
+
# break exact ties (equal timestamps within an entity) inside the time resolution
|
|
531
|
+
same = np.r_[False, (np.diff(t_us) == 0) & (np.diff(ent) == 0)]
|
|
532
|
+
if same.any():
|
|
533
|
+
pos = np.diff(t_us)[np.diff(t_us) > 0]
|
|
534
|
+
res = float(np.min(pos)) if pos.size else 1e6
|
|
535
|
+
t_us = t_us + np.where(same, rng_j.random(t_us.size) * min(res, 1e6) * 0.5, 0.0)
|
|
536
|
+
order2 = np.lexsort((t_us, ent))
|
|
537
|
+
t_us, ent, d = t_us[order2], ent[order2], d[order2]
|
|
538
|
+
self.start, self.end = (cast("dt.date | dt.datetime", d[time_col].min()),
|
|
539
|
+
cast("dt.date | dt.datetime", d[time_col].max()))
|
|
540
|
+
lo_us = int(np.floor(np.min(t_us)))
|
|
541
|
+
hi_us = int(np.ceil(np.max(t_us)))
|
|
542
|
+
if self.time_kind == "date":
|
|
543
|
+
hi_us = int(epoch_us(pl.Series([self.end]))[0]) + DAY_US
|
|
544
|
+
self.start_us, self.end_us = lo_us, hi_us
|
|
545
|
+
self.n_events = int(t_us.size)
|
|
546
|
+
|
|
547
|
+
# ---- calendar ------------------------------------------------------------------
|
|
548
|
+
if calendar == "auto":
|
|
549
|
+
self.calendar, cal_diag = fit_calendar(
|
|
550
|
+
t_us.astype(np.int64), lo_us, hi_us, hourly=self.time_kind == "datetime",
|
|
551
|
+
policy=pol, time_zone=self.time_zone)
|
|
552
|
+
else:
|
|
553
|
+
self.calendar, cal_diag = Calendar(), {"reason": "disabled"}
|
|
554
|
+
self.calendar.finalize()
|
|
555
|
+
clock = OpClock(self.calendar, lo_us, 0.0, (hi_us - lo_us) / 1e6)
|
|
556
|
+
op = clock.to_op((t_us - lo_us) / 1e6)
|
|
557
|
+
window_op = float(clock.to_op(np.array([(hi_us - lo_us) / 1e6]))[0])
|
|
558
|
+
|
|
559
|
+
# ---- entities: activity windows and rate heterogeneity ------------------------
|
|
560
|
+
n_ent = int(np.max(ent)) + 1
|
|
561
|
+
self.n_entities = n_ent
|
|
562
|
+
bounds = np.searchsorted(ent, np.arange(n_ent + 1))
|
|
563
|
+
seqs = [op[bounds[i]: bounds[i + 1]] for i in range(n_ent)]
|
|
564
|
+
mult = np.ones(n_ent)
|
|
565
|
+
self.log_rate_sd = 0.0
|
|
566
|
+
if entity_col is not None and n_ent >= 3:
|
|
567
|
+
ok = np.array([s.size >= 3 and s[-1] > s[0] for s in seqs])
|
|
568
|
+
if ok.sum() >= 3:
|
|
569
|
+
nn = np.array([s.size - 1 for s in seqs], dtype=np.float64)
|
|
570
|
+
lr = np.array([math.log(s.size - 1) - math.log(s[-1] - s[0]) if o else 0.0
|
|
571
|
+
for s, o in zip(seqs, ok, strict=True)])
|
|
572
|
+
c = lr[ok].mean()
|
|
573
|
+
var = float(np.var(lr[ok], ddof=1) - np.mean(1.0 / nn[ok]))
|
|
574
|
+
if var > 0.01:
|
|
575
|
+
self.log_rate_sd = math.sqrt(var)
|
|
576
|
+
shrink = np.where(ok, var / (var + 1.0 / np.maximum(nn, 1)), 0.0)
|
|
577
|
+
mult = np.exp(shrink * (lr - c))
|
|
578
|
+
firsts = np.array([s[0] for s in seqs]) / max(window_op, 1e-12)
|
|
579
|
+
lens = np.array([s[-1] - s[0] for s in seqs]) / np.maximum(
|
|
580
|
+
window_op - np.array([s[0] for s in seqs]), 1e-12)
|
|
581
|
+
lev = quantile_levels(n_ent, pol)
|
|
582
|
+
self.lifetime_levels = lev
|
|
583
|
+
self.start_q = coarsen_array(np.quantile(np.clip(firsts, 0, 1), lev), pol)
|
|
584
|
+
self.length_q = coarsen_array(np.quantile(np.clip(lens, 0, 1), lev), pol)
|
|
585
|
+
# normalise: operational seconds per unit = mean gap (after rate multipliers)
|
|
586
|
+
scaled = [s * m for s, m in zip(seqs, mult, strict=True)]
|
|
587
|
+
g = _gaps(scaled)
|
|
588
|
+
if g.size < MIN_EVENTS - 1:
|
|
589
|
+
raise ProfilingError("too few within-entity interarrival gaps")
|
|
590
|
+
self.scale_s = coarsen(float(g.mean()), pol)
|
|
591
|
+
useqs = [s / self.scale_s for s in scaled]
|
|
592
|
+
proc, aic = select_process(useqs, tuple(processes))
|
|
593
|
+
self.process = Process(proc.kind, {k: coarsen(v, pol) for k, v in proc.params.items()})
|
|
594
|
+
|
|
595
|
+
# ---- marks -----------------------------------------------------------------------
|
|
596
|
+
self.categorical, self.numeric = {}, {}
|
|
597
|
+
type_col: str | None = None
|
|
598
|
+
type_codes: np.ndarray | None = None
|
|
599
|
+
for c in marks:
|
|
600
|
+
if _is_categorical(d.schema[c]):
|
|
601
|
+
cm, codes = _fit_categorical(d[c], bounds, pol)
|
|
602
|
+
self.categorical[c] = cm
|
|
603
|
+
if type_col is None:
|
|
604
|
+
type_col, type_codes = c, codes
|
|
605
|
+
for c in marks:
|
|
606
|
+
if c in self.categorical:
|
|
607
|
+
continue
|
|
608
|
+
if not d.schema[c].is_numeric():
|
|
609
|
+
raise ProfilingError(f"mark column {c!r} has unsupported dtype {d.schema[c]}")
|
|
610
|
+
v = d[c].cast(pl.Float64).to_numpy()
|
|
611
|
+
self.numeric[c] = self._fit_numeric(c, v, type_col, type_codes, str(d.schema[c]),
|
|
612
|
+
pol, seed)
|
|
613
|
+
|
|
614
|
+
lam_s = self.process.rate / self.scale_s
|
|
615
|
+
self.diagnostics = {
|
|
616
|
+
"n_events": self.n_events, "n_entities": n_ent,
|
|
617
|
+
"process_aic": {k: coarsen(v, pol) for k, v in aic.items()},
|
|
618
|
+
"rate_per_second": coarsen(lam_s, pol),
|
|
619
|
+
"calendar": cal_diag,
|
|
620
|
+
"window_seconds": coarsen((hi_us - lo_us) / 1e6, pol),
|
|
621
|
+
}
|
|
622
|
+
self.assumptions = self._assumptions()
|
|
623
|
+
return self
|
|
624
|
+
|
|
625
|
+
def _fit_numeric(self, c: str, v: np.ndarray, type_col: str | None,
|
|
626
|
+
codes: np.ndarray | None, dtype: str, pol: DisclosurePolicySpec,
|
|
627
|
+
seed: int) -> NumericMark:
|
|
628
|
+
schema = ColumnSchema(name=c, logical_type=LogicalType.CONTINUOUS,
|
|
629
|
+
physical_dtype="Float64")
|
|
630
|
+
|
|
631
|
+
def fit(x: np.ndarray, name: str | int) -> MarginalModel:
|
|
632
|
+
r = stream(seed, "temporal", "events", "mark", c, name)
|
|
633
|
+
x = x[np.isfinite(x)]
|
|
634
|
+
if x.size > MAX_MARK_SAMPLE:
|
|
635
|
+
x = x[np.sort(r.choice(x.size, MAX_MARK_SAMPLE, replace=False))]
|
|
636
|
+
return fit_marginal(x, schema, pol, r)[0]
|
|
637
|
+
|
|
638
|
+
if not np.isfinite(v).any():
|
|
639
|
+
raise ProfilingError(f"mark column {c!r} has no non-null values")
|
|
640
|
+
pooled = fit(v, "pooled")
|
|
641
|
+
per: dict[int, MarginalModel] = {}
|
|
642
|
+
if type_col is not None and codes is not None:
|
|
643
|
+
need = max(MIN_STATE_EVENTS, 2 * pol.min_category_support)
|
|
644
|
+
for k in range(self.categorical[type_col].labels.size):
|
|
645
|
+
x = v[(codes == k) & np.isfinite(v)]
|
|
646
|
+
if x.size >= need:
|
|
647
|
+
per[k] = fit(x, k)
|
|
648
|
+
return NumericMark(type_col if per else None, pooled, per, dtype)
|
|
649
|
+
|
|
650
|
+
def _assumptions(self) -> list[str]:
|
|
651
|
+
out = [f"event arrivals follow a stationary {self.process.kind} process in calendar-"
|
|
652
|
+
f"adjusted operational time"]
|
|
653
|
+
if self.calendar.active:
|
|
654
|
+
out.append("hour-of-day / day-of-week intensity profiles are assumed stable")
|
|
655
|
+
if self.categorical:
|
|
656
|
+
out.append("categorical marks follow first-order Markov chains within each "
|
|
657
|
+
"sequence")
|
|
658
|
+
if self.n_entities > 1:
|
|
659
|
+
out.append("entities are independent copies of the process with lognormal rate "
|
|
660
|
+
"multipliers; synthetic entities are new, not copies of source entities")
|
|
661
|
+
return out
|
|
662
|
+
|
|
663
|
+
# -- generate ----------------------------------------------------------------------------
|
|
664
|
+
def _window(self, request: TemporalRequest) -> tuple[int, int | None]:
|
|
665
|
+
"""Window start and (optional) end in epoch microseconds."""
|
|
666
|
+
def us(x: dt.date | dt.datetime) -> int:
|
|
667
|
+
if isinstance(x, dt.datetime):
|
|
668
|
+
s = pl.Series([x])
|
|
669
|
+
if self.time_zone and x.tzinfo is None:
|
|
670
|
+
s = s.dt.replace_time_zone(self.time_zone)
|
|
671
|
+
return int(epoch_us(s)[0])
|
|
672
|
+
return int(epoch_us(pl.Series([x]))[0])
|
|
673
|
+
|
|
674
|
+
def end_of(x: dt.date | dt.datetime) -> int:
|
|
675
|
+
return us(x) + (DAY_US if self.time_kind == "date" or not isinstance(
|
|
676
|
+
x, dt.datetime) else 0)
|
|
677
|
+
|
|
678
|
+
if request.mode == "resample":
|
|
679
|
+
s0 = us(request.start) if request.start is not None else self.start_us
|
|
680
|
+
else:
|
|
681
|
+
s0 = us(request.start) if request.start is not None else self.end_us
|
|
682
|
+
if request.end is not None:
|
|
683
|
+
return s0, end_of(request.end)
|
|
684
|
+
if request.periods is not None:
|
|
685
|
+
if request.freq is None:
|
|
686
|
+
if request.mode == "resample":
|
|
687
|
+
return s0, s0 + (self.end_us - self.start_us)
|
|
688
|
+
raise GenerationError("event generation with 'periods' needs 'freq' (or give "
|
|
689
|
+
"'end')")
|
|
690
|
+
base = dt.datetime(1970, 1, 1) + dt.timedelta(microseconds=s0)
|
|
691
|
+
idx = time_index(base, request.freq, periods=request.periods + 1)
|
|
692
|
+
return s0, int(epoch_us(idx)[-1])
|
|
693
|
+
if request.mode == "resample":
|
|
694
|
+
return s0, s0 + (self.end_us - self.start_us)
|
|
695
|
+
if request.n_rows is not None:
|
|
696
|
+
return s0, None
|
|
697
|
+
raise GenerationError("new_period event generation needs 'end', 'periods' with "
|
|
698
|
+
"'freq', or a fixed 'n_rows'") # pragma: no cover
|
|
699
|
+
|
|
700
|
+
def generate(self, request: TemporalRequest, seed: int) -> pl.DataFrame:
|
|
701
|
+
if self.n_events == 0:
|
|
702
|
+
raise GenerationError("model is not fitted")
|
|
703
|
+
# n_entities=None: as many entities as the source; without an entity column, one stream
|
|
704
|
+
request = request.with_entities(
|
|
705
|
+
self.n_entities if self.entity_col is not None else None,
|
|
706
|
+
model="this event model")
|
|
707
|
+
s0, s1 = self._window(request)
|
|
708
|
+
if s1 is not None and s1 <= s0:
|
|
709
|
+
raise GenerationError("the requested window is empty")
|
|
710
|
+
fixed = request.count_policy == "fixed" and request.n_rows is not None
|
|
711
|
+
if request.count_policy == "fixed" and request.n_rows is None and s1 is None:
|
|
712
|
+
raise GenerationError("fixed event counts need n_rows") # pragma: no cover
|
|
713
|
+
# Without an entity column the fitted process is the aggregate stream of the whole table
|
|
714
|
+
# (its rate already covers every source entity) and the output has no column to label
|
|
715
|
+
# copies with: simulate that one stream. Superimposing ``n_entities`` copies of it
|
|
716
|
+
# multiplied the natural event count by ``n_entities``.
|
|
717
|
+
n_ent = int(request.n_entities or 1) if self.entity_col is not None else 1
|
|
718
|
+
span_s = None if s1 is None else (s1 - s0) / 1e6
|
|
719
|
+
# operational clock over a generous range around the window
|
|
720
|
+
hi = span_s if span_s is not None else (request.n_rows or 1) * self.scale_s * 4.0 / max(
|
|
721
|
+
self.process.rate, 1e-12) / n_ent + 86400.0
|
|
722
|
+
clock = OpClock(self.calendar, s0, -86400.0 * 8, hi + 86400.0 * 8)
|
|
723
|
+
w_op = None if span_s is None else float(clock.to_op(np.array([span_s]))[0])
|
|
724
|
+
|
|
725
|
+
rs = stream(seed, "temporal", "events", "entities")
|
|
726
|
+
z = special.ndtri(np.clip(rs.random(n_ent), 1e-12, 1 - 1e-12))
|
|
727
|
+
sd = self.log_rate_sd
|
|
728
|
+
mult = np.exp(sd * z - 0.5 * sd * sd) if sd > 0 else np.ones(n_ent)
|
|
729
|
+
if not fixed and request.count_policy == "natural" and self.start_q.size \
|
|
730
|
+
and n_ent > 1 and w_op is not None:
|
|
731
|
+
ul = rs.random((n_ent, 2))
|
|
732
|
+
sf = np.interp(ul[:, 0], self.lifetime_levels, self.start_q)
|
|
733
|
+
lf = np.interp(ul[:, 1], self.lifetime_levels, self.length_q)
|
|
734
|
+
a0 = sf * w_op
|
|
735
|
+
a1 = a0 + lf * (w_op - a0)
|
|
736
|
+
else:
|
|
737
|
+
a0 = np.zeros(n_ent)
|
|
738
|
+
a1 = np.full(n_ent, np.nan if w_op is None else w_op)
|
|
739
|
+
# ``fixed`` implies ``request.n_rows is not None``; restated for the type checker
|
|
740
|
+
per_ent = (request.n_rows // n_ent) if fixed and request.n_rows is not None else 0
|
|
741
|
+
|
|
742
|
+
times: list[np.ndarray] = []
|
|
743
|
+
for i in range(n_ent):
|
|
744
|
+
rp = stream(seed, "temporal", "events", "process", i)
|
|
745
|
+
m = mult[i]
|
|
746
|
+
if fixed:
|
|
747
|
+
u, u_next = simulate_fixed(self.process, 0.0, per_ent, rp)
|
|
748
|
+
if w_op is not None:
|
|
749
|
+
u = u * ((w_op * m / self.scale_s) / u_next if u_next > 0 else 1.0)
|
|
750
|
+
op = u * self.scale_s / m
|
|
751
|
+
else:
|
|
752
|
+
u = simulate_process(self.process, a0[i] * m / self.scale_s,
|
|
753
|
+
a1[i] * m / self.scale_s, rp)
|
|
754
|
+
op = u * self.scale_s / m
|
|
755
|
+
times.append(clock.from_op(op))
|
|
756
|
+
lengths = [t.size for t in times]
|
|
757
|
+
n_tot = int(sum(lengths))
|
|
758
|
+
sec = np.concatenate(times) if times else np.zeros(0)
|
|
759
|
+
out_us = (s0 + np.round(sec * 1e6)).astype(np.int64)
|
|
760
|
+
if s1 is not None:
|
|
761
|
+
out_us = np.minimum(out_us, s1 - 1)
|
|
762
|
+
cols: dict[str, Any] = {}
|
|
763
|
+
ent_idx = np.repeat(np.arange(n_ent), lengths)
|
|
764
|
+
if self.entity_col is not None:
|
|
765
|
+
width = max(6, len(str(n_ent)))
|
|
766
|
+
cols[self.entity_col] = (pl.Series(self.entity_col, ent_idx + 1, dtype=pl.Int64)
|
|
767
|
+
if self.entity_dtype == "Int64" else
|
|
768
|
+
pl.Series(self.entity_col,
|
|
769
|
+
[f"entity_{k + 1:0{width}d}" for k in ent_idx],
|
|
770
|
+
dtype=pl.String))
|
|
771
|
+
ts = pl.Series(self.time_col, out_us).cast(pl.Datetime("us", "UTC" if self.time_zone
|
|
772
|
+
else None))
|
|
773
|
+
if self.time_zone:
|
|
774
|
+
ts = ts.dt.convert_time_zone(self.time_zone)
|
|
775
|
+
if self.time_kind == "date":
|
|
776
|
+
ts = ts.dt.date()
|
|
777
|
+
else:
|
|
778
|
+
ts = ts.dt.cast_time_unit(self.time_unit)
|
|
779
|
+
cols[self.time_col] = ts
|
|
780
|
+
|
|
781
|
+
states: dict[str, np.ndarray] = {}
|
|
782
|
+
for c, cm in self.categorical.items():
|
|
783
|
+
seqs = cm.simulate(lengths, stream(seed, "temporal", "events", "mark", c))
|
|
784
|
+
codes = np.concatenate(seqs) if seqs else np.zeros(0, dtype=np.int64)
|
|
785
|
+
states[c] = codes
|
|
786
|
+
cols[c] = _labels_to_series(c, cm.labels[codes] if codes.size else
|
|
787
|
+
np.zeros(0, dtype=str), cm.dtype)
|
|
788
|
+
for c, nm in self.numeric.items():
|
|
789
|
+
u = np.clip(stream(seed, "temporal", "events", "mark", c).random(n_tot), 1e-12,
|
|
790
|
+
1 - 1e-12)
|
|
791
|
+
v = nm.pooled.ppf(u) if n_tot else np.zeros(0)
|
|
792
|
+
if nm.by is not None and n_tot:
|
|
793
|
+
st = states[nm.by]
|
|
794
|
+
for k, mm in nm.per_state.items():
|
|
795
|
+
sel = st == k
|
|
796
|
+
if sel.any():
|
|
797
|
+
v[sel] = mm.ppf(u[sel])
|
|
798
|
+
cols[c] = _cast_values(v, nm.dtype, c)
|
|
799
|
+
order = [c for c in ([self.entity_col] if self.entity_col else []) + [self.time_col]
|
|
800
|
+
+ self.mark_cols if c in cols]
|
|
801
|
+
self.last_generation = {"mode": request.mode, "n_rows": n_tot, "n_entities": n_ent,
|
|
802
|
+
"requested_entities": request.n_entities,
|
|
803
|
+
"count_policy": "fixed" if fixed else "natural",
|
|
804
|
+
"window_seconds": span_s}
|
|
805
|
+
return pl.DataFrame({c: cols[c] for c in order})
|
|
806
|
+
|
|
807
|
+
# -- serialisation -----------------------------------------------------------------------
|
|
808
|
+
def to_section(self, store: ArrayStore, prefix: str = "temporal.") -> dict[str, Any]:
|
|
809
|
+
cat = {}
|
|
810
|
+
for c, cm in self.categorical.items():
|
|
811
|
+
cat[c] = {"dtype": cm.dtype,
|
|
812
|
+
"labels": store.put(f"{prefix}{c}.labels", cm.labels.astype(str)),
|
|
813
|
+
"marginal": store.put(f"{prefix}{c}.marginal", cm.marginal),
|
|
814
|
+
"transition": store.put(f"{prefix}{c}.transition", cm.transition)}
|
|
815
|
+
num = {}
|
|
816
|
+
for c, nm in self.numeric.items():
|
|
817
|
+
num[c] = {"dtype": nm.dtype, "by": nm.by,
|
|
818
|
+
"pooled": nm.pooled.to_spec(store, f"{prefix}{c}.pooled.")
|
|
819
|
+
.model_dump(mode="json"),
|
|
820
|
+
"per_state": {str(k): m.to_spec(store, f"{prefix}{c}.state{k}.")
|
|
821
|
+
.model_dump(mode="json") for k, m in nm.per_state.items()}}
|
|
822
|
+
cal = self.calendar
|
|
823
|
+
return {
|
|
824
|
+
"kind": SECTION_KIND, "format": SECTION_FORMAT, "enabled": True,
|
|
825
|
+
"time_col": self.time_col, "entity_col": self.entity_col,
|
|
826
|
+
"entity_dtype": self.entity_dtype,
|
|
827
|
+
"time_dtype": {"kind": self.time_kind, "time_unit": self.time_unit,
|
|
828
|
+
"time_zone": self.time_zone},
|
|
829
|
+
"start": _iso(self.start), "end": _iso(self.end),
|
|
830
|
+
"window_us": [int(self.start_us), int(self.end_us)],
|
|
831
|
+
"n_events": self.n_events, "n_entities": self.n_entities,
|
|
832
|
+
"mark_cols": list(self.mark_cols),
|
|
833
|
+
"process": {"kind": self.process.kind, "params": dict(self.process.params),
|
|
834
|
+
"unit_seconds": self.scale_s},
|
|
835
|
+
"calendar": {"hour": None if cal.hour is None else [float(x) for x in cal.hour],
|
|
836
|
+
"dow": None if cal.dow is None else [float(x) for x in cal.dow]},
|
|
837
|
+
"entities": {"log_rate_sd": self.log_rate_sd,
|
|
838
|
+
"lifetimes": None if not self.start_q.size else {
|
|
839
|
+
"levels": store.put(f"{prefix}lifetimes.levels",
|
|
840
|
+
self.lifetime_levels),
|
|
841
|
+
"start_fraction": store.put(f"{prefix}lifetimes.start_fraction",
|
|
842
|
+
self.start_q),
|
|
843
|
+
"length_fraction": store.put(
|
|
844
|
+
f"{prefix}lifetimes.length_fraction", self.length_q)}},
|
|
845
|
+
"marks": {"categorical": cat, "numeric": num},
|
|
846
|
+
"assumptions": list(self.assumptions),
|
|
847
|
+
"diagnostics": dict(self.diagnostics),
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
@classmethod
|
|
851
|
+
def from_section(cls, section: dict[str, Any], store: ArrayStore) -> EventModel:
|
|
852
|
+
if section.get("kind") != SECTION_KIND:
|
|
853
|
+
raise GenerationError(f"not a {SECTION_KIND} section: kind={section.get('kind')!r}")
|
|
854
|
+
if int(section.get("format", 0)) > SECTION_FORMAT:
|
|
855
|
+
raise GenerationError(f"unsupported {SECTION_KIND} section format "
|
|
856
|
+
f"{section.get('format')}")
|
|
857
|
+
m = cls()
|
|
858
|
+
m.time_col = str(section["time_col"])
|
|
859
|
+
m.entity_col = section.get("entity_col")
|
|
860
|
+
m.entity_dtype = str(section.get("entity_dtype", "String"))
|
|
861
|
+
td = section["time_dtype"]
|
|
862
|
+
m.time_kind, m.time_unit, m.time_zone = td["kind"], td["time_unit"], td["time_zone"]
|
|
863
|
+
m.start = _parse_time(section["start"], m.time_kind)
|
|
864
|
+
m.end = _parse_time(section["end"], m.time_kind)
|
|
865
|
+
m.start_us, m.end_us = (int(x) for x in section["window_us"])
|
|
866
|
+
m.n_events, m.n_entities = int(section["n_events"]), int(section["n_entities"])
|
|
867
|
+
m.mark_cols = [str(c) for c in section.get("mark_cols", [])]
|
|
868
|
+
pr = section["process"]
|
|
869
|
+
m.process = Process(str(pr["kind"]), {k: float(v) for k, v in pr["params"].items()})
|
|
870
|
+
m.scale_s = float(pr["unit_seconds"])
|
|
871
|
+
cal = section.get("calendar") or {}
|
|
872
|
+
m.calendar = Calendar(
|
|
873
|
+
hour=None if cal.get("hour") is None else np.asarray(cal["hour"], dtype=float),
|
|
874
|
+
dow=None if cal.get("dow") is None else np.asarray(cal["dow"], dtype=float),
|
|
875
|
+
time_zone=m.time_zone)
|
|
876
|
+
m.calendar.finalize()
|
|
877
|
+
en = section.get("entities") or {}
|
|
878
|
+
m.log_rate_sd = float(en.get("log_rate_sd", 0.0))
|
|
879
|
+
lt = en.get("lifetimes")
|
|
880
|
+
if lt:
|
|
881
|
+
m.lifetime_levels = np.asarray(store.get(lt["levels"]), dtype=np.float64)
|
|
882
|
+
m.start_q = np.asarray(store.get(lt["start_fraction"]), dtype=np.float64)
|
|
883
|
+
m.length_q = np.asarray(store.get(lt["length_fraction"]), dtype=np.float64)
|
|
884
|
+
mk = section.get("marks") or {}
|
|
885
|
+
for c, cs in (mk.get("categorical") or {}).items():
|
|
886
|
+
labels = np.asarray(store.get(cs["labels"])).astype(str)
|
|
887
|
+
m.categorical[c] = CategoricalMark(
|
|
888
|
+
labels, np.asarray(store.get(cs["marginal"]), dtype=np.float64),
|
|
889
|
+
np.asarray(store.get(cs["transition"]), dtype=np.float64).reshape(
|
|
890
|
+
labels.size, labels.size), str(cs.get("dtype", "String")))
|
|
891
|
+
for c, ns in (mk.get("numeric") or {}).items():
|
|
892
|
+
m.numeric[c] = NumericMark(
|
|
893
|
+
ns.get("by"), marginal_from_spec(ModelSpec.model_validate(ns["pooled"]), store),
|
|
894
|
+
{int(k): marginal_from_spec(ModelSpec.model_validate(v), store)
|
|
895
|
+
for k, v in (ns.get("per_state") or {}).items()},
|
|
896
|
+
str(ns.get("dtype", "Float64")))
|
|
897
|
+
m.assumptions = [str(a) for a in section.get("assumptions", [])]
|
|
898
|
+
m.diagnostics = dict(section.get("diagnostics", {}))
|
|
899
|
+
return m
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
# ---------------------------------------------------------------------------------------------
|
|
903
|
+
# helpers
|
|
904
|
+
# ---------------------------------------------------------------------------------------------
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def _is_categorical(dtype: pl.DataType) -> bool:
|
|
908
|
+
return dtype in (pl.String, pl.Categorical, pl.Boolean) or isinstance(dtype, pl.Enum)
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
def _fit_categorical(s: pl.Series, bounds: np.ndarray, pol: DisclosurePolicySpec
|
|
912
|
+
) -> tuple[CategoricalMark, np.ndarray]:
|
|
913
|
+
dtype = "Boolean" if s.dtype == pl.Boolean else (
|
|
914
|
+
"Categorical" if s.dtype == pl.Categorical or isinstance(s.dtype, pl.Enum)
|
|
915
|
+
else "String")
|
|
916
|
+
lab = s.cast(pl.String).fill_null("__null__")
|
|
917
|
+
vc = lab.value_counts(sort=True, name="__n__")
|
|
918
|
+
labels, counts, _ = pool_categories(vc[lab.name].to_numpy().astype(str),
|
|
919
|
+
vc["__n__"].to_numpy(), pol)
|
|
920
|
+
index = {str(v): i for i, v in enumerate(labels.tolist())}
|
|
921
|
+
other = index.get("__other__", -1)
|
|
922
|
+
codes = np.array([index.get(x, other) for x in lab.to_list()], dtype=np.int64)
|
|
923
|
+
k = labels.size
|
|
924
|
+
raw = np.bincount(codes, minlength=k).astype(np.float64)
|
|
925
|
+
marginal = raw / raw.sum()
|
|
926
|
+
seqs = [codes[bounds[i]: bounds[i + 1]] for i in range(bounds.size - 1)]
|
|
927
|
+
p, _ = transition_matrix(seqs, k, marginal, pol.rare_cell_min)
|
|
928
|
+
p = coarsen_array(p, pol)
|
|
929
|
+
p = p / p.sum(axis=1, keepdims=True)
|
|
930
|
+
marginal = coarsen_array(marginal, pol)
|
|
931
|
+
return CategoricalMark(labels, marginal / marginal.sum(), p, dtype), codes
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
def _labels_to_series(name: str, labels: np.ndarray, dtype: str) -> pl.Series:
|
|
935
|
+
s = pl.Series(name, labels.astype(str).tolist(), dtype=pl.String)
|
|
936
|
+
s = s.set(s == "__null__", None) if s.len() else s
|
|
937
|
+
if dtype == "Boolean":
|
|
938
|
+
return (s == "true").alias(name)
|
|
939
|
+
if dtype == "Categorical":
|
|
940
|
+
return s.cast(pl.Categorical)
|
|
941
|
+
return s
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
__all__ = ["Calendar", "CategoricalMark", "EventModel", "NumericMark", "OpClock", "Process",
|
|
945
|
+
"fit_calendar", "fit_gamma", "fit_hawkes", "fit_poisson", "hawkes_loglik",
|
|
946
|
+
"select_process", "simulate_fixed", "simulate_process", "transition_matrix"]
|