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,431 @@
1
+ """Temporal shape detection (M18).
2
+
3
+ ``detect_temporal_shape`` classifies a table as one of:
4
+
5
+ * ``"series"``: one regular ordered series (unique timestamps on a regular cadence).
6
+ * ``"panel"``: repeated regular series, one per entity (timestamps repeat across entities but
7
+ not within one).
8
+ * ``"events"``: irregular timestamps in time order (transactions, logs).
9
+ * ``"cross_sectional"``: no usable time column, or dates that carry no ordering (rows are not
10
+ in time order and the timestamps are irregular).
11
+
12
+ It also reports the cadence as a polars duration string (``"1d"``, ``"1h"``, ``"1mo"``...), a
13
+ regularity score (the fraction of consecutive distinct timestamps one cadence apart), gaps,
14
+ duplicates and a confidence. Users can override the time and entity columns.
15
+
16
+ ``detect_periods`` (FFT period detection) and ``infer_cadence`` are shared helpers used by the
17
+ regular-series model and the temporal metrics.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ from dataclasses import asdict, dataclass, field
24
+ from typing import Any, Literal, cast
25
+
26
+ import numpy as np
27
+ import polars as pl
28
+
29
+ from ectype.errors import ProfilingError
30
+
31
+ Shape = Literal["series", "panel", "events", "cross_sectional"]
32
+
33
+ US_PER: dict[str, int] = {
34
+ "w": 7 * 86_400_000_000,
35
+ "d": 86_400_000_000,
36
+ "h": 3_600_000_000,
37
+ "m": 60_000_000,
38
+ "s": 1_000_000,
39
+ "ms": 1_000,
40
+ "us": 1,
41
+ }
42
+ DAY_US = US_PER["d"]
43
+
44
+ #: relative tolerance for "one cadence apart" (covers 28-31 day months)
45
+ CADENCE_TOL = 0.1
46
+ #: thresholds for classification
47
+ SERIES_REGULARITY = 0.7
48
+ SERIES_MAX_DUP_FRACTION = 0.01
49
+ PANEL_MIN_SCORE = 0.7
50
+ #: a peak at period P/h (h <= this) of a stronger period P is treated as its harmonic
51
+ MAX_HARMONIC = 12
52
+ EVENTS_MIN_MONOTONICITY = 0.9
53
+
54
+ #: well-known seasonal periods (in steps) per cadence, used to snap FFT estimates
55
+ KNOWN_PERIODS: dict[str, tuple[float, ...]] = {
56
+ "1d": (7.0, 30.4375, 365.25),
57
+ "1h": (24.0, 168.0),
58
+ "30m": (48.0, 336.0),
59
+ "15m": (96.0, 672.0),
60
+ "1m": (60.0, 1440.0),
61
+ "7d": (52.1775,),
62
+ "1w": (52.1775,),
63
+ "1mo": (12.0,),
64
+ "3mo": (4.0,),
65
+ }
66
+
67
+
68
+ @dataclass
69
+ class TemporalShape:
70
+ shape: Shape
71
+ time_col: str | None = None
72
+ entity_col: str | None = None
73
+ cadence: str | None = None # polars duration string, e.g. "1d"
74
+ regularity: float = 0.0 # fraction of distinct-time steps == cadence
75
+ n_gaps: int = 0 # steps longer than 1.5 x cadence
76
+ n_duplicate_timestamps: int = 0 # rows sharing a timestamp (within entity for panels)
77
+ monotonicity: float = 0.0 # fraction of non-decreasing consecutive rows
78
+ confidence: float = 0.0
79
+ n_entities: int | None = None
80
+ candidates: dict[str, dict[str, float]] = field(default_factory=dict)
81
+ notes: list[str] = field(default_factory=list)
82
+
83
+ def to_dict(self) -> dict[str, Any]:
84
+ return asdict(self)
85
+
86
+
87
+ # ---------------------------------------------------------------------------------------------
88
+ # Time helpers
89
+ # ---------------------------------------------------------------------------------------------
90
+
91
+
92
+ def is_temporal_dtype(dtype: pl.DataType) -> bool:
93
+ return dtype == pl.Date or isinstance(dtype, pl.Datetime)
94
+
95
+
96
+ def epoch_us(s: pl.Series) -> np.ndarray:
97
+ """Microseconds since the Unix epoch as int64 (nulls dropped by the caller)."""
98
+ if s.dtype == pl.Date:
99
+ return s.cast(pl.Int64).to_numpy().astype(np.int64) * DAY_US
100
+ if isinstance(s.dtype, pl.Datetime):
101
+ return s.dt.epoch("us").to_numpy().astype(np.int64)
102
+ raise ProfilingError(f"column {s.name!r} is not a Date/Datetime column (dtype {s.dtype})")
103
+
104
+
105
+ def format_duration(us: float) -> str:
106
+ """Fixed-length duration (microseconds) as the coarsest exact polars duration string."""
107
+ v = int(round(us))
108
+ if v <= 0:
109
+ raise ValueError("duration must be positive")
110
+ for unit in ("d", "h", "m", "s", "ms", "us"):
111
+ if v % US_PER[unit] == 0:
112
+ return f"{v // US_PER[unit]}{unit}"
113
+ return f"{v}us" # pragma: no cover
114
+
115
+
116
+ def _calendar_cadence(med_us: float) -> str | None:
117
+ days = med_us / DAY_US
118
+ if 27.5 <= days <= 31.5:
119
+ return "1mo"
120
+ if 88.5 <= days <= 92.5:
121
+ return "3mo"
122
+ if 180.5 <= days <= 184.5:
123
+ return "6mo"
124
+ if 364.5 <= days <= 366.5:
125
+ return "1y"
126
+ return None
127
+
128
+
129
+ @dataclass
130
+ class Cadence:
131
+ cadence: str | None
132
+ step_us: float # nominal step (median distinct-time difference)
133
+ regularity: float
134
+ n_gaps: int
135
+ n_duplicates: int
136
+
137
+
138
+ def infer_cadence(t_us: np.ndarray) -> Cadence:
139
+ """Cadence of the *distinct* sorted timestamps ``t_us`` (int64 microseconds)."""
140
+ t = np.asarray(t_us, dtype=np.int64)
141
+ u = np.unique(t)
142
+ dups = int(t.size - u.size)
143
+ if u.size < 3:
144
+ return Cadence(None, float("nan"), 0.0, 0, dups)
145
+ d = np.diff(u).astype(np.float64)
146
+ med = float(np.median(d))
147
+ on = np.abs(d - med) <= CADENCE_TOL * med
148
+ regularity = float(on.mean())
149
+ gaps = int((d > 1.5 * med).sum())
150
+ cal = _calendar_cadence(med)
151
+ cadence: str | None
152
+ if cal is not None:
153
+ cadence = cal
154
+ else:
155
+ # the modal exact step if most steps share it, else the median
156
+ vals, counts = np.unique(d[on], return_counts=True) if on.any() else (np.array([med]),
157
+ np.array([1]))
158
+ cadence = format_duration(float(vals[np.argmax(counts)]))
159
+ if regularity < 0.5:
160
+ cadence = None # no meaningful cadence for irregular timestamps
161
+ return Cadence(cadence, med, regularity, gaps, dups)
162
+
163
+
164
+ def parse_duration(freq: str) -> list[tuple[int, str]]:
165
+ """Parse a polars duration string (``"1d"``, ``"2h30m"``, ``"1mo"``) into parts."""
166
+
167
+
168
+ s = freq.strip()
169
+ parts = re.findall(r"(\d+)(mo|ms|us|ns|y|q|w|d|h|m|s)", s)
170
+ if not parts or "".join(f"{n}{u}" for n, u in parts) != s:
171
+ raise ValueError(f"invalid duration string {freq!r}; use polars syntax such as "
172
+ f"'1d', '1h', '15m', '1w', '1mo', '1q' or '1y'")
173
+ out = [(int(n), u) for n, u in parts]
174
+ if all(n == 0 for n, _ in out):
175
+ raise ValueError(f"duration {freq!r} must be positive")
176
+ return out
177
+
178
+
179
+ def is_calendar(freq: str) -> bool:
180
+ return any(u in ("mo", "q", "y") for _, u in parse_duration(freq))
181
+
182
+
183
+ def duration_us(freq: str) -> int:
184
+ """Fixed length of a non-calendar duration in microseconds."""
185
+ total = 0
186
+ for n, u in parse_duration(freq):
187
+ if u in ("mo", "q", "y"):
188
+ raise ValueError(f"duration {freq!r} has no fixed length (calendar units)")
189
+ total += n // 1000 if u == "ns" else n * US_PER[u]
190
+ return total
191
+
192
+
193
+ def months_of(freq: str) -> int:
194
+ """Number of months in a pure calendar duration (``"1mo"``, ``"1q"``, ``"1y"``)."""
195
+ total = 0
196
+ for n, u in parse_duration(freq):
197
+ if u == "mo":
198
+ total += n
199
+ elif u == "q":
200
+ total += 3 * n
201
+ elif u == "y":
202
+ total += 12 * n
203
+ else:
204
+ raise ValueError(f"duration {freq!r} mixes calendar and fixed units")
205
+ return total
206
+
207
+
208
+ # ---------------------------------------------------------------------------------------------
209
+ # Periods
210
+ # ---------------------------------------------------------------------------------------------
211
+
212
+
213
+ def detect_periods(y: np.ndarray, *, max_periods: int = 3, cadence: str | None = None,
214
+ min_cycles: float = 2.0, threshold: float = 25.0) -> list[float]:
215
+ """Dominant seasonal periods (in steps) by FFT of the linearly detrended series.
216
+
217
+ A peak must be a local maximum with power above ``threshold`` x the median power of the
218
+ neighbouring frequency bins (a local background, robust to red AR noise) and span
219
+ at least ``min_cycles`` cycles. Harmonics (integer fractions) of a stronger period are
220
+ dropped. Estimates within 3% of a well-known period for ``cadence`` (7 and 365.25 for daily
221
+ data, 24 and 168 for hourly...) are snapped to it.
222
+ """
223
+ x = np.asarray(y, dtype=np.float64)
224
+ x = x[np.isfinite(x)]
225
+ n = x.size
226
+ if n < 8:
227
+ return []
228
+ tt = np.arange(n, dtype=np.float64)
229
+ x = x - np.polyval(np.polyfit(tt, x, 1), tt)
230
+ p = np.abs(np.fft.rfft(x * np.hanning(n))) ** 2
231
+ k = np.arange(p.size)
232
+ ok = (k >= min_cycles) & (k >= 1)
233
+ if p.size < 4 or not ok.any():
234
+ return []
235
+ peaks = []
236
+ for i in range(1, p.size - 1):
237
+ if not (ok[i] and p[i] >= p[i - 1] and p[i] >= p[i + 1]):
238
+ continue
239
+ # local background (red noise is not flat): neighbouring bins outside the peak lobe
240
+ w = max(8, i // 2)
241
+ nb = np.r_[p[max(1, i - w): max(1, i - 2)], p[i + 3: i + w + 1]]
242
+ bg = float(np.median(nb)) if nb.size else float(np.median(p[1:]))
243
+ if p[i] > threshold * max(bg, 1e-300):
244
+ # parabolic interpolation on log power for a sub-bin frequency estimate
245
+ a, b, c = np.log(p[i - 1] + 1e-300), np.log(p[i]), np.log(p[i + 1] + 1e-300)
246
+ den = a - 2 * b + c
247
+ off = 0.5 * (a - c) / den if den != 0 else 0.0
248
+ freq = (i + float(np.clip(off, -0.5, 0.5))) / n
249
+ peaks.append((float(p[i]), n / (i * 1.0) if freq <= 0 else 1.0 / freq))
250
+ peaks.sort(reverse=True)
251
+ known = KNOWN_PERIODS.get(cadence or "", ())
252
+ chosen: list[float] = []
253
+ for _, per in peaks:
254
+ if per < 2.0:
255
+ continue
256
+ for kp in known:
257
+ if abs(per - kp) <= 0.03 * kp:
258
+ per = kp
259
+ break
260
+ harmonic = False
261
+ for c in chosen:
262
+ h = round(c / per)
263
+ if abs(per - c) <= 0.05 * c or (2 <= h <= MAX_HARMONIC
264
+ and abs(per * h - c) <= 0.02 * c):
265
+ harmonic = True
266
+ break
267
+ if not harmonic:
268
+ chosen.append(float(per))
269
+ if len(chosen) >= max_periods:
270
+ break
271
+ return sorted(chosen)
272
+
273
+
274
+ # ---------------------------------------------------------------------------------------------
275
+ # Detection
276
+ # ---------------------------------------------------------------------------------------------
277
+
278
+
279
+ def _monotonicity(t_us: np.ndarray) -> float:
280
+ if t_us.size < 2:
281
+ return 1.0
282
+ d = np.diff(t_us)
283
+ return float((d >= 0).mean())
284
+
285
+
286
+ def _time_candidates(df: pl.DataFrame) -> list[str]:
287
+ return [c for c in df.columns if is_temporal_dtype(df.schema[c])]
288
+
289
+
290
+ def _entity_candidates(df: pl.DataFrame, exclude: set[str]) -> list[str]:
291
+ out = []
292
+ n = df.height
293
+ for c in df.columns:
294
+ if c in exclude:
295
+ continue
296
+ dt = df.schema[c]
297
+ if not (dt in (pl.String, pl.Categorical) or isinstance(dt, pl.Enum)
298
+ or dt.is_integer()):
299
+ continue
300
+ k = df[c].n_unique()
301
+ if 2 <= k <= max(2, n // 3):
302
+ out.append(c)
303
+ return out
304
+
305
+
306
+ def _entity_stats(df: pl.DataFrame, time_col: str, entity_col: str) -> dict[str, float]:
307
+ """Within-entity duplicate fraction, mean within-entity regularity and the cadence."""
308
+ sub = df.select(pl.col(entity_col).alias("e"), pl.col(time_col).alias("traw")).drop_nulls()
309
+ d = pl.DataFrame({"e": sub["e"], "t": epoch_us(sub["traw"])}).sort(["e", "t"])
310
+ d = d.with_columns(dt=pl.col("t").diff().over("e"))
311
+ g = d.group_by("e").agg(n=pl.len(), nu=pl.col("t").n_unique(),
312
+ med=pl.col("dt").filter(pl.col("dt") > 0).median())
313
+ d = d.join(g.select("e", "med"), on="e", how="left").filter(pl.col("dt") > 0)
314
+ d = d.with_columns(on=((pl.col("dt") - pl.col("med")).abs()
315
+ <= CADENCE_TOL * pl.col("med")).cast(pl.Float64),
316
+ gap=(pl.col("dt") > 1.5 * pl.col("med")).cast(pl.Int64))
317
+ per = d.group_by("e").agg(reg=pl.col("on").mean(), gaps=pl.col("gap").sum())
318
+ n = float(g["n"].sum())
319
+ dups = float((g["n"] - g["nu"]).sum())
320
+ reg = float(cast(float, per["reg"].mean())) if per.height else 0.0
321
+ med = float(cast(float, g["med"].drop_nulls().median())) if g["med"].drop_nulls().len() else float("nan")
322
+ multi = float(cast(float, (g["n"] >= 3).mean()))
323
+ return {"dup_fraction": dups / n if n else 1.0, "regularity": reg,
324
+ "n_duplicates": dups, "n_gaps": float(per["gaps"].sum()) if per.height else 0.0,
325
+ "step_us": med, "n_entities": float(g.height), "multi_row_fraction": multi,
326
+ "score": (1.0 - dups / n if n else 0.0) * reg * multi}
327
+
328
+
329
+ def detect_temporal_shape(df: pl.DataFrame, time_col: str | None = None,
330
+ entity_col: str | None = None) -> TemporalShape:
331
+ """Classify the temporal shape of ``df``; ``time_col`` / ``entity_col`` override detection."""
332
+ for name, what in ((time_col, "time"), (entity_col, "entity")):
333
+ if name is not None and name not in df.columns:
334
+ raise ProfilingError(f"{what} column {name!r} not found; columns are "
335
+ f"{df.columns[:20]}")
336
+ if time_col is not None and not is_temporal_dtype(df.schema[time_col]):
337
+ raise ProfilingError(f"time column {time_col!r} has dtype {df.schema[time_col]}; "
338
+ f"cast it to pl.Date or pl.Datetime first")
339
+
340
+ cands = [time_col] if time_col is not None else _time_candidates(df)
341
+ if not cands or df.height < 3:
342
+ return TemporalShape("cross_sectional", confidence=1.0 if not cands else 0.5,
343
+ notes=["no Date/Datetime column" if not cands
344
+ else "too few rows for temporal analysis"])
345
+
346
+ scored: dict[str, dict[str, float]] = {}
347
+ for c in cands:
348
+ s = df[c].drop_nulls()
349
+ if s.len() < 3:
350
+ scored[c] = {"score": -1.0, "monotonicity": 0.0, "regularity": 0.0}
351
+ continue
352
+ t = epoch_us(s)
353
+ cad = infer_cadence(t)
354
+ mono = _monotonicity(t)
355
+ null_frac = 1.0 - s.len() / df.height
356
+ scored[c] = {"score": mono + cad.regularity - null_frac, "monotonicity": mono,
357
+ "regularity": cad.regularity}
358
+ tc = max(scored, key=lambda c: (scored[c]["score"], -cands.index(c)))
359
+ notes: list[str] = []
360
+ if len(cands) > 1:
361
+ notes.append(f"time column {tc!r} chosen among {cands} by monotonicity + regularity")
362
+
363
+ s = df[tc].drop_nulls()
364
+ if s.len() < 3:
365
+ return TemporalShape("cross_sectional", time_col=tc, confidence=0.5, candidates=scored,
366
+ notes=[*notes, "time column has fewer than 3 non-null values"])
367
+ t = epoch_us(s)
368
+ cad = infer_cadence(t)
369
+ mono = _monotonicity(t)
370
+ dup_frac = cad.n_duplicates / t.size
371
+ base = dict(time_col=tc, cadence=cad.cadence, regularity=cad.regularity,
372
+ n_gaps=cad.n_gaps, n_duplicate_timestamps=cad.n_duplicates, monotonicity=mono,
373
+ candidates=scored)
374
+
375
+ # ---- panel: an entity column whose groups each form a regular series ----------------
376
+ ent_cands = ([entity_col] if entity_col is not None
377
+ else (_entity_candidates(df, {tc}) if dup_frac > SERIES_MAX_DUP_FRACTION
378
+ else []))
379
+ best: tuple[str, dict[str, float]] | None = None
380
+ for e in ent_cands:
381
+ st = _entity_stats(df, tc, e)
382
+ scored[f"entity:{e}"] = st
383
+ if best is None or st["score"] > best[1]["score"]:
384
+ best = (e, st)
385
+ # An explicit entity column still needs per-entity regularity (duplicate timestamps
386
+ # within an entity are tolerated: the user chose the grouping); otherwise it is events.
387
+ if best is not None and (best[1]["score"] >= PANEL_MIN_SCORE
388
+ or (entity_col is not None
389
+ and best[1]["regularity"] >= SERIES_REGULARITY)):
390
+ e, st = best
391
+ step = st["step_us"]
392
+ cadence = (_calendar_cadence(step) or format_duration(step)) if np.isfinite(step) \
393
+ else None
394
+ if entity_col is None:
395
+ notes.append(f"entity column {e!r} detected (score {st['score']:.2f})")
396
+ return TemporalShape("panel", time_col=tc, entity_col=e, cadence=cadence,
397
+ regularity=st["regularity"], n_gaps=int(st["n_gaps"]),
398
+ n_duplicate_timestamps=int(st["n_duplicates"]),
399
+ monotonicity=mono, confidence=float(np.clip(st["score"], 0, 1)),
400
+ n_entities=int(st["n_entities"]), candidates=scored, notes=notes)
401
+
402
+ if entity_col is not None and best is not None:
403
+ # An explicit entity column whose groups are not regular series: events per entity.
404
+ st = best[1]
405
+ notes.append(f"entity column {entity_col!r} given but its groups are not regular "
406
+ f"series (per-entity regularity {st['regularity']:.2f} < "
407
+ f"{SERIES_REGULARITY}); treated as events with entities")
408
+ return TemporalShape("events", time_col=tc, entity_col=entity_col, cadence=None,
409
+ regularity=st["regularity"], n_gaps=cad.n_gaps,
410
+ n_duplicate_timestamps=cad.n_duplicates, monotonicity=mono,
411
+ confidence=float(np.clip(1.0 - st["score"], 0, 1)),
412
+ n_entities=int(st["n_entities"]), candidates=scored, notes=notes)
413
+
414
+ # ---- single regular series -------------------------------------------------------------
415
+ if dup_frac <= SERIES_MAX_DUP_FRACTION and cad.regularity >= SERIES_REGULARITY:
416
+ conf = float(np.clip(cad.regularity * (1.0 - dup_frac), 0.0, 1.0))
417
+ if mono < 0.99:
418
+ notes.append("rows are not in time order; sort by the time column before modeling")
419
+ return TemporalShape("series", confidence=conf, notes=notes, **base) # type: ignore[arg-type]
420
+
421
+ # ---- irregular: events if ordered, otherwise cross-sectional with dates ------------------
422
+ if mono >= EVENTS_MIN_MONOTONICITY:
423
+ if cad.regularity >= SERIES_REGULARITY:
424
+ notes.append("regular cadence with repeated timestamps and no entity key: treated "
425
+ "as events (consider aggregating, or pass entity_col)")
426
+ return TemporalShape("events", confidence=float(np.clip(mono, 0, 1)), notes=notes,
427
+ **base) # type: ignore[arg-type]
428
+ conf = float(np.clip(1.0 - max(0.0, mono - 0.5) * 2.5, 0.3, 1.0))
429
+ notes.append("timestamps are irregular and rows are not in time order: dates are treated "
430
+ "as an ordinary column")
431
+ return TemporalShape("cross_sectional", confidence=conf, notes=notes, **base) # type: ignore[arg-type]