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,653 @@
1
+ """Mergeable streaming sketches for out-of-core profiling (M32).
2
+
3
+ Every sketch here has bounded memory, an ``update(array)`` that consumes one batch at a time,
4
+ and a ``merge(other)`` that combines two sketches built over disjoint parts of the data (in any
5
+ order, e.g. one per file, partition or worker). Together they let the coordinator profile a
6
+ source that does not fit in RAM:
7
+
8
+ * :class:`QuantileSketch` - a KLL sketch (Karnin, Lang & Liberty 2016) in numpy. Rank error is
9
+ about ``1.7 / k`` in the worst case and well under that typically (the default ``k=800``
10
+ gives about 0.2-0.35% on 1e6 values).
11
+ * :class:`HyperLogLog` - distinct counts, standard error ``1.04 / sqrt(2**p)`` (1.6% at p=12).
12
+ * :class:`Moments` - exact count, mean, variance, skewness and kurtosis (Welford / Pebay
13
+ pairwise update, mergeable), plus min/max.
14
+ * :class:`FrequencySketch` - count-min sketch plus a bounded heavy-hitter candidate set for
15
+ categorical top-k.
16
+
17
+ :func:`stream_profile` drives them over a Parquet/CSV file (pyarrow dataset batches, one pass)
18
+ or a polars ``LazyFrame`` and returns one :class:`ColumnSketch` per column.
19
+ :func:`empirical_spec_from_sketch` turns a numeric column sketch into a ``ModelSpec`` for the
20
+ registered ``"empirical"`` marginal, with exactly the levels, arrays and params that
21
+ ``EmpiricalMarginal.fit`` would store.
22
+
23
+ Larger-than-RAM sources
24
+ -----------------------
25
+ Memory use is ``O(batch_size * n_columns)`` for the batch in flight plus a few KB to a few
26
+ hundred KB per column for the sketches; it does not grow with the number of rows. A coordinator
27
+ can therefore (1) call ``stream_profile`` on the full source to get exact row/null counts,
28
+ moments, distinct counts, top-k categories and quantile grids; (2) build ``empirical``
29
+ marginals with :func:`empirical_spec_from_sketch`; and (3) fit the dependence structure
30
+ (joint model), which needs rows, on a bounded uniform sample (e.g. ``io.sql.read_sql(...,
31
+ sample_rows=...)``). Because sketches merge, a partitioned source can be profiled with one
32
+ ``stream_profile`` call per partition (in separate processes if wanted) and the per-column
33
+ sketches combined with ``ColumnSketch.merge``.
34
+
35
+ Determinism: the KLL compactor offsets come from ``rng.stream(seed, "kll")``, so the same input
36
+ batches in the same order give the same sketch. String hashing uses polars' ``Series.hash``
37
+ with fixed seeds; it is stable within a polars version, so only merge string sketches built
38
+ under the same engine environment (numeric hashing is pure numpy and fully stable).
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import math
44
+ from collections.abc import Iterator, Sequence
45
+ from dataclasses import dataclass, field
46
+ from pathlib import Path
47
+ from typing import Any
48
+
49
+ import numpy as np
50
+ import polars as pl
51
+
52
+ from ectype.fingerprint.core import ArrayStore
53
+ from ectype.fingerprint.disclosure import (
54
+ coarsen_array,
55
+ quantile_levels,
56
+ resolve_policy,
57
+ )
58
+ from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, ModelSpec
59
+ from ectype.rng import stream
60
+ from ectype.types import LogicalType
61
+
62
+ __all__ = [
63
+ "ColumnSketch",
64
+ "FrequencySketch",
65
+ "HyperLogLog",
66
+ "Moments",
67
+ "QuantileSketch",
68
+ "empirical_spec_from_sketch",
69
+ "hash64",
70
+ "stream_profile",
71
+ ]
72
+
73
+ _M64 = np.uint64(0xFFFFFFFFFFFFFFFF)
74
+
75
+
76
+ # ---------------------------------------------------------------------------------------------
77
+ # hashing
78
+ # ---------------------------------------------------------------------------------------------
79
+
80
+
81
+ def _splitmix64(x: np.ndarray) -> np.ndarray:
82
+ z = np.asarray(x, dtype=np.uint64)
83
+ with np.errstate(over="ignore"):
84
+ z = z + np.uint64(0x9E3779B97F4A7C15)
85
+ z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
86
+ z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
87
+ z = z ^ (z >> np.uint64(31))
88
+ return z
89
+
90
+
91
+ def hash64(values: Any) -> np.ndarray:
92
+ """64-bit hashes of the non-null values of ``values`` (numpy array or polars Series).
93
+
94
+ Numbers hash by their float64 bit pattern (so ``1`` and ``1.0`` collide, ``-0.0 == 0.0``);
95
+ everything else hashes by its string form via polars.
96
+ """
97
+ s = values if isinstance(values, pl.Series) else pl.Series("v", values)
98
+ s = s.drop_nulls()
99
+ if s.dtype.is_numeric() or s.dtype == pl.Boolean:
100
+ a = s.cast(pl.Float64).to_numpy().astype(np.float64)
101
+ a = a[~np.isnan(a)] + 0.0 # -0.0 -> 0.0
102
+ return _splitmix64(a.view(np.uint64))
103
+ h = s.cast(pl.String).hash(0x5EED)
104
+ return _splitmix64(h.to_numpy().astype(np.uint64))
105
+
106
+
107
+ # ---------------------------------------------------------------------------------------------
108
+ # quantiles: KLL
109
+ # ---------------------------------------------------------------------------------------------
110
+
111
+
112
+ class QuantileSketch:
113
+ """KLL quantile sketch over float64 values (non-finite values are ignored).
114
+
115
+ Level ``h`` holds items of weight ``2**h``. Level capacities decay geometrically by ``c``
116
+ from the top, so memory is ``O(k)`` items (about ``k / (1 - c)`` plus ``2`` per level).
117
+ """
118
+
119
+ def __init__(self, k: int = 800, *, c: float = 2.0 / 3.0, seed: int = 0) -> None:
120
+ if k < 8:
121
+ raise ValueError(f"k must be >= 8, got {k}")
122
+ self.k = int(k)
123
+ self.c = float(c)
124
+ self.seed = int(seed)
125
+ self.n = 0
126
+ self.min = math.inf
127
+ self.max = -math.inf
128
+ self.levels: list[np.ndarray] = [np.empty(0, dtype=np.float64)]
129
+ self._compactions = 0
130
+
131
+ def _capacity(self, h: int) -> int:
132
+ depth = len(self.levels) - 1 - h
133
+ return max(2, int(math.ceil(self.k * self.c ** depth)))
134
+
135
+ def _compact(self) -> None:
136
+ h = 0
137
+ while h < len(self.levels):
138
+ lv = self.levels[h]
139
+ if lv.size > self._capacity(h):
140
+ if h + 1 == len(self.levels):
141
+ self.levels.append(np.empty(0, dtype=np.float64))
142
+ lv = np.sort(lv, kind="stable")
143
+ keep = lv[:1] if lv.size % 2 else lv[:0]
144
+ body = lv[1:] if lv.size % 2 else lv
145
+ off = int(stream(self.seed, "kll", self._compactions).integers(0, 2))
146
+ self._compactions += 1
147
+ self.levels[h] = keep
148
+ self.levels[h + 1] = np.concatenate([self.levels[h + 1], body[off::2]])
149
+ h = 0 if h == 0 else h - 1 # capacities shift when a level is added
150
+ continue
151
+ h += 1
152
+
153
+ def update(self, values: Any) -> QuantileSketch:
154
+ a = np.asarray(values, dtype=np.float64).ravel()
155
+ a = a[np.isfinite(a)]
156
+ if a.size == 0:
157
+ return self
158
+ self.n += int(a.size)
159
+ self.min = min(self.min, float(a.min()))
160
+ self.max = max(self.max, float(a.max()))
161
+ self.levels[0] = np.concatenate([self.levels[0], a])
162
+ self._compact()
163
+ return self
164
+
165
+ def merge(self, other: QuantileSketch) -> QuantileSketch:
166
+ """Absorb ``other`` (in place); returns ``self``."""
167
+ while len(self.levels) < len(other.levels):
168
+ self.levels.append(np.empty(0, dtype=np.float64))
169
+ for h, lv in enumerate(other.levels):
170
+ self.levels[h] = np.concatenate([self.levels[h], lv])
171
+ self.n += other.n
172
+ self.min = min(self.min, other.min)
173
+ self.max = max(self.max, other.max)
174
+ self._compactions += other._compactions
175
+ self._compact()
176
+ return self
177
+
178
+ @property
179
+ def size(self) -> int:
180
+ """Number of stored items (the memory footprint in float64 values)."""
181
+ return int(sum(lv.size for lv in self.levels))
182
+
183
+ def _sorted(self) -> tuple[np.ndarray, np.ndarray]:
184
+ items = np.concatenate(self.levels)
185
+ weights = np.concatenate([np.full(lv.size, 2.0 ** h) for h, lv in enumerate(self.levels)])
186
+ order = np.argsort(items, kind="stable")
187
+ return items[order], np.cumsum(weights[order])
188
+
189
+ def quantile(self, q: Any) -> Any:
190
+ """Approximate quantile(s) at probability level(s) ``q`` (scalar or array)."""
191
+ qa = np.asarray(q, dtype=np.float64)
192
+ if self.n == 0:
193
+ out = np.full(qa.shape, np.nan)
194
+ return float(out) if out.ndim == 0 else out
195
+ items, cw = self._sorted()
196
+ total = cw[-1]
197
+ idx = np.searchsorted(cw, np.clip(qa, 0.0, 1.0) * total, side="left")
198
+ out = items[np.clip(idx, 0, items.size - 1)]
199
+ out = np.where(qa <= 0.0, self.min, np.where(qa >= 1.0, self.max, out))
200
+ return float(out) if out.ndim == 0 else out
201
+
202
+ def rank(self, x: Any) -> Any:
203
+ """Approximate normalised rank (CDF) of value(s) ``x``."""
204
+ xa = np.asarray(x, dtype=np.float64)
205
+ if self.n == 0:
206
+ return np.full(xa.shape, np.nan)
207
+ items, cw = self._sorted()
208
+ i = np.searchsorted(items, xa, side="right")
209
+ out = np.where(i > 0, cw[np.maximum(i - 1, 0)], 0.0) / cw[-1]
210
+ return float(out) if out.ndim == 0 else out
211
+
212
+
213
+ # ---------------------------------------------------------------------------------------------
214
+ # distinct counts: HyperLogLog
215
+ # ---------------------------------------------------------------------------------------------
216
+
217
+
218
+ def _leading_zeros64(w: np.ndarray) -> np.ndarray:
219
+ w = w.astype(np.uint64).copy()
220
+ n = np.zeros(w.shape, dtype=np.int64)
221
+ for shift in (32, 16, 8, 4, 2, 1):
222
+ mask = w < (np.uint64(1) << np.uint64(64 - shift))
223
+ n += np.where(mask, shift, 0)
224
+ w = np.where(mask, w << np.uint64(shift), w)
225
+ n += (w == 0).astype(np.int64) # all-zero word: 64 leading zeros
226
+ return n
227
+
228
+
229
+ class HyperLogLog:
230
+ """HyperLogLog distinct-count sketch with ``2**p`` 6-bit registers (stored as uint8)."""
231
+
232
+ def __init__(self, p: int = 12) -> None:
233
+ if not 4 <= p <= 18:
234
+ raise ValueError(f"p must be in [4, 18], got {p}")
235
+ self.p = int(p)
236
+ self.m = 1 << self.p
237
+ self.registers = np.zeros(self.m, dtype=np.uint8)
238
+
239
+ def update(self, values: Any) -> HyperLogLog:
240
+ return self.update_hashes(hash64(values))
241
+
242
+ def update_hashes(self, h: np.ndarray) -> HyperLogLog:
243
+ if h.size == 0:
244
+ return self
245
+ h = h.astype(np.uint64)
246
+ idx = (h >> np.uint64(64 - self.p)).astype(np.int64)
247
+ w = h << np.uint64(self.p)
248
+ rho = np.minimum(_leading_zeros64(w) + 1, 64 - self.p + 1).astype(np.uint8)
249
+ np.maximum.at(self.registers, idx, rho)
250
+ return self
251
+
252
+ def merge(self, other: HyperLogLog) -> HyperLogLog:
253
+ if other.p != self.p:
254
+ raise ValueError(f"cannot merge HyperLogLog with p={other.p} into p={self.p}")
255
+ np.maximum(self.registers, other.registers, out=self.registers)
256
+ return self
257
+
258
+ def estimate(self) -> float:
259
+ m = float(self.m)
260
+ alpha = {16: 0.673, 32: 0.697, 64: 0.709}.get(self.m, 0.7213 / (1 + 1.079 / m))
261
+ e = alpha * m * m / float(np.sum(np.ldexp(1.0, -self.registers.astype(np.int64))))
262
+ zeros = int(np.count_nonzero(self.registers == 0))
263
+ if e <= 2.5 * m and zeros:
264
+ e = m * math.log(m / zeros)
265
+ return float(e)
266
+
267
+
268
+ # ---------------------------------------------------------------------------------------------
269
+ # moments
270
+ # ---------------------------------------------------------------------------------------------
271
+
272
+
273
+ @dataclass
274
+ class Moments:
275
+ """Exact streaming central moments (count, mean, M2, M3, M4), min and max."""
276
+
277
+ n: int = 0
278
+ mean: float = 0.0
279
+ m2: float = 0.0
280
+ m3: float = 0.0
281
+ m4: float = 0.0
282
+ min: float = math.inf
283
+ max: float = -math.inf
284
+
285
+ def update(self, values: Any) -> Moments:
286
+ a = np.asarray(values, dtype=np.float64).ravel()
287
+ a = a[np.isfinite(a)]
288
+ if a.size == 0:
289
+ return self
290
+ mu = float(a.mean())
291
+ d = a - mu
292
+ d2 = d * d
293
+ other = Moments(int(a.size), mu, float(d2.sum()), float((d2 * d).sum()),
294
+ float((d2 * d2).sum()), float(a.min()), float(a.max()))
295
+ return self.merge(other)
296
+
297
+ def merge(self, o: Moments) -> Moments:
298
+ """Pebay (2008) pairwise combination; exact up to floating-point rounding."""
299
+ if o.n == 0:
300
+ return self
301
+ if self.n == 0:
302
+ self.n, self.mean, self.m2, self.m3, self.m4 = o.n, o.mean, o.m2, o.m3, o.m4
303
+ self.min, self.max = o.min, o.max
304
+ return self
305
+ na, nb = float(self.n), float(o.n)
306
+ n = na + nb
307
+ delta = o.mean - self.mean
308
+ d_n = delta / n
309
+ m2 = self.m2 + o.m2 + delta * d_n * na * nb
310
+ m3 = (self.m3 + o.m3 + delta * d_n * d_n * na * nb * (na - nb)
311
+ + 3.0 * d_n * (na * o.m2 - nb * self.m2))
312
+ m4 = (self.m4 + o.m4
313
+ + delta * d_n ** 3 * na * nb * (na * na - na * nb + nb * nb)
314
+ + 6.0 * d_n * d_n * (na * na * o.m2 + nb * nb * self.m2)
315
+ + 4.0 * d_n * (na * o.m3 - nb * self.m3))
316
+ self.mean = self.mean + d_n * nb
317
+ self.n, self.m2, self.m3, self.m4 = int(n), m2, m3, m4
318
+ self.min, self.max = min(self.min, o.min), max(self.max, o.max)
319
+ return self
320
+
321
+ @property
322
+ def variance(self) -> float:
323
+ """Sample variance (ddof=1)."""
324
+ return self.m2 / (self.n - 1) if self.n > 1 else float("nan")
325
+
326
+ @property
327
+ def std(self) -> float:
328
+ return math.sqrt(self.variance) if self.n > 1 else float("nan")
329
+
330
+ @property
331
+ def skewness(self) -> float:
332
+ """Population (biased) skewness, as ``scipy.stats.skew``."""
333
+ if self.n < 2 or self.m2 <= 0:
334
+ return float("nan")
335
+ return math.sqrt(self.n) * self.m3 / self.m2 ** 1.5
336
+
337
+ @property
338
+ def kurtosis(self) -> float:
339
+ """Excess (Fisher) kurtosis, biased, as ``scipy.stats.kurtosis``."""
340
+ if self.n < 2 or self.m2 <= 0:
341
+ return float("nan")
342
+ return self.n * self.m4 / (self.m2 * self.m2) - 3.0
343
+
344
+
345
+ # ---------------------------------------------------------------------------------------------
346
+ # frequencies: count-min + heavy hitters
347
+ # ---------------------------------------------------------------------------------------------
348
+
349
+
350
+ class FrequencySketch:
351
+ """Count-min sketch (``depth x width``) plus up to ``capacity`` heavy-hitter candidates.
352
+
353
+ Candidate labels are kept as strings; their counts are count-min estimates (upper bounds,
354
+ overestimating by at most ``e * n / width`` with probability ``1 - e**-depth``).
355
+ """
356
+
357
+ def __init__(self, width: int = 2048, depth: int = 5, capacity: int = 256) -> None:
358
+ self.width = int(width)
359
+ self.depth = int(depth)
360
+ self.capacity = int(capacity)
361
+ self.table = np.zeros((self.depth, self.width), dtype=np.int64)
362
+ self.n = 0
363
+ self.candidates: dict[str, np.uint64] = {} # label -> hash
364
+
365
+ def _cells(self, h: np.ndarray) -> np.ndarray:
366
+ h1 = h & np.uint64(0xFFFFFFFF)
367
+ h2 = (h >> np.uint64(32)) | np.uint64(1)
368
+ rows = np.arange(self.depth, dtype=np.uint64)[:, None]
369
+ with np.errstate(over="ignore"):
370
+ return ((h1[None, :] + rows * h2[None, :]) % np.uint64(self.width)).astype(np.int64)
371
+
372
+ def update(self, values: Any) -> FrequencySketch:
373
+ s = values if isinstance(values, pl.Series) else pl.Series("v", values)
374
+ s = s.drop_nulls()
375
+ if s.dtype.is_float():
376
+ s = s.filter(~s.is_nan())
377
+ if s.len() == 0:
378
+ return self
379
+ vc = s.value_counts(name="__count__")
380
+ keys = vc.get_column(vc.columns[0])
381
+ counts = vc.get_column("__count__").to_numpy().astype(np.int64)
382
+ h = hash64(keys)
383
+ cells = self._cells(h)
384
+ for d in range(self.depth):
385
+ np.add.at(self.table[d], cells[d], counts)
386
+ self.n += int(counts.sum())
387
+ order = np.argsort(-counts, kind="stable")[: self.capacity]
388
+ labels = keys.gather(order).cast(pl.String).to_list()
389
+ for lab, i in zip(labels, order, strict=True):
390
+ self.candidates.setdefault(str(lab), h[i])
391
+ self._prune()
392
+ return self
393
+
394
+ def _estimate_hashes(self, h: np.ndarray) -> np.ndarray:
395
+ if h.size == 0:
396
+ return np.zeros(0, dtype=np.int64)
397
+ cells = self._cells(h)
398
+ return np.min(self.table[np.arange(self.depth)[:, None], cells], axis=0)
399
+
400
+ def _prune(self) -> None:
401
+ if len(self.candidates) <= self.capacity:
402
+ return
403
+ labels = list(self.candidates)
404
+ est = self._estimate_hashes(np.array([self.candidates[x] for x in labels],
405
+ dtype=np.uint64))
406
+ order = sorted(range(len(labels)), key=lambda i: (-int(est[i]), labels[i]))
407
+ self.candidates = {labels[i]: self.candidates[labels[i]]
408
+ for i in order[: self.capacity]}
409
+
410
+ def merge(self, other: FrequencySketch) -> FrequencySketch:
411
+ if (other.width, other.depth) != (self.width, self.depth):
412
+ raise ValueError("cannot merge count-min sketches of different shapes")
413
+ self.table += other.table
414
+ self.n += other.n
415
+ for k, v in other.candidates.items():
416
+ self.candidates.setdefault(k, v)
417
+ self._prune()
418
+ return self
419
+
420
+ def estimate(self, values: Any) -> np.ndarray:
421
+ """Count-min estimates for ``values`` (an upper bound on each true count)."""
422
+ return self._estimate_hashes(hash64(values))
423
+
424
+ def top_k(self, k: int = 20) -> list[tuple[str, int]]:
425
+ """``k`` most frequent labels as ``(label, estimated_count)``, by count then label."""
426
+ labels = list(self.candidates)
427
+ est = self._estimate_hashes(np.array([self.candidates[x] for x in labels],
428
+ dtype=np.uint64))
429
+ order = sorted(range(len(labels)), key=lambda i: (-int(est[i]), labels[i]))
430
+ return [(labels[i], int(est[i])) for i in order[:k]]
431
+
432
+
433
+ # ---------------------------------------------------------------------------------------------
434
+ # per-column sketch + streaming driver
435
+ # ---------------------------------------------------------------------------------------------
436
+
437
+
438
+ def _is_numeric_dtype(dt: pl.DataType) -> bool:
439
+ return dt.is_numeric() or dt in (pl.Date,) or isinstance(dt, pl.Datetime)
440
+
441
+
442
+ def _numeric_values(s: pl.Series) -> np.ndarray:
443
+ """Engine value convention: Date -> days, Datetime -> epoch microseconds, else float64."""
444
+ if s.dtype == pl.Date:
445
+ s = s.cast(pl.Int32)
446
+ elif isinstance(s.dtype, pl.Datetime):
447
+ if (s.dtype.time_unit or "us") != "us":
448
+ s = s.dt.cast_time_unit("us")
449
+ s = s.cast(pl.Int64)
450
+ elif s.dtype == pl.Boolean:
451
+ s = s.cast(pl.Int8)
452
+ return s.cast(pl.Float64, strict=False).fill_null(np.nan).to_numpy().astype(np.float64)
453
+
454
+
455
+ @dataclass
456
+ class ColumnSketch:
457
+ """All sketches for one column. Numeric columns (incl. date/datetime) carry moments and a
458
+ quantile sketch; every column carries a distinct-count and a frequency sketch."""
459
+
460
+ name: str
461
+ dtype: str
462
+ numeric: bool
463
+ count: int = 0
464
+ null_count: int = 0
465
+ distinct: HyperLogLog = field(default_factory=HyperLogLog)
466
+ frequencies: FrequencySketch = field(default_factory=FrequencySketch)
467
+ moments: Moments | None = None
468
+ quantiles: QuantileSketch | None = None
469
+
470
+ @classmethod
471
+ def new(cls, name: str, dtype: pl.DataType, *, k: int = 800, hll_p: int = 12,
472
+ seed: int = 0) -> ColumnSketch:
473
+ numeric = _is_numeric_dtype(dtype)
474
+ return cls(name=name, dtype=str(dtype), numeric=numeric, distinct=HyperLogLog(hll_p),
475
+ moments=Moments() if numeric else None,
476
+ quantiles=QuantileSketch(k, seed=seed) if numeric else None)
477
+
478
+ def update(self, s: pl.Series) -> ColumnSketch:
479
+ self.count += s.len()
480
+ nulls = s.null_count()
481
+ if self.numeric:
482
+ v = _numeric_values(s)
483
+ finite = np.isfinite(v)
484
+ nulls = int((~finite).sum()) # nulls and NaN alike
485
+ v = v[finite]
486
+ assert self.moments is not None and self.quantiles is not None
487
+ self.moments.update(v)
488
+ self.quantiles.update(v)
489
+ h = _splitmix64((v + 0.0).view(np.uint64))
490
+ self.distinct.update_hashes(h)
491
+ self.frequencies.update(pl.Series(self.name, v))
492
+ else:
493
+ self.distinct.update(s)
494
+ self.frequencies.update(s)
495
+ self.null_count += int(nulls)
496
+ return self
497
+
498
+ def merge(self, other: ColumnSketch) -> ColumnSketch:
499
+ if other.numeric != self.numeric:
500
+ raise ValueError(f"cannot merge sketches of column {self.name!r}: numeric mismatch")
501
+ self.count += other.count
502
+ self.null_count += other.null_count
503
+ self.distinct.merge(other.distinct)
504
+ self.frequencies.merge(other.frequencies)
505
+ if self.moments is not None and other.moments is not None:
506
+ self.moments.merge(other.moments)
507
+ if self.quantiles is not None and other.quantiles is not None:
508
+ self.quantiles.merge(other.quantiles)
509
+ return self
510
+
511
+ @property
512
+ def non_null(self) -> int:
513
+ return self.count - self.null_count
514
+
515
+ def summary(self, policy: str | DisclosurePolicySpec | dict | None = "standard",
516
+ top_k: int = 20) -> dict[str, Any]:
517
+ """Plain-dict summary. Quantiles are taken at ``disclosure.quantile_levels`` for the
518
+ policy, so they can seed an ``empirical`` marginal directly."""
519
+ pol = resolve_policy(policy)
520
+ out: dict[str, Any] = {
521
+ "name": self.name, "dtype": self.dtype, "numeric": self.numeric,
522
+ "count": self.count, "null_count": self.null_count,
523
+ "null_fraction": (self.null_count / self.count) if self.count else 0.0,
524
+ "distinct_estimate": self.distinct.estimate(),
525
+ "top_k": self.frequencies.top_k(top_k),
526
+ }
527
+ if self.numeric and self.moments is not None and self.quantiles is not None:
528
+ m = self.moments
529
+ out.update(mean=m.mean, std=m.std, skewness=m.skewness, kurtosis=m.kurtosis,
530
+ min=m.min, max=m.max)
531
+ if self.non_null:
532
+ levels = quantile_levels(self.non_null, pol)
533
+ out["quantile_levels"] = levels
534
+ out["quantiles"] = np.asarray(self.quantiles.quantile(levels))
535
+ return out
536
+
537
+
538
+ def _iter_batches(source: Any, columns: list[str] | None, batch_size: int
539
+ ) -> Iterator[pl.DataFrame]:
540
+ if isinstance(source, pl.DataFrame):
541
+ df = source.select(columns) if columns else source
542
+ for off in range(0, df.height, batch_size):
543
+ yield df.slice(off, batch_size)
544
+ return
545
+ if isinstance(source, pl.LazyFrame):
546
+ lf = source.select(columns) if columns else source
547
+ if hasattr(lf, "collect_batches"):
548
+ yield from lf.collect_batches(chunk_size=batch_size)
549
+ return
550
+ n = int(lf.select(pl.len()).collect().item()) # pragma: no cover (older polars)
551
+ for off in range(0, n, batch_size): # pragma: no cover
552
+ yield lf.slice(off, batch_size).collect()
553
+ return
554
+ import pyarrow.dataset as ds
555
+
556
+ from ectype.io.adapters import infer_format
557
+
558
+ path = Path(source)
559
+ if not path.exists():
560
+ raise FileNotFoundError(f"no such table file: {str(path)!r}")
561
+ fmt = infer_format(path) if path.is_file() else "parquet"
562
+ if fmt not in ("parquet", "csv", "tsv", "ipc"):
563
+ raise ValueError(f"stream_profile supports parquet, csv, tsv and ipc, not {fmt!r}")
564
+ if fmt == "tsv":
565
+ import pyarrow.csv as pacsv
566
+
567
+ file_format: Any = ds.CsvFileFormat(parse_options=pacsv.ParseOptions(delimiter="\t"))
568
+ else:
569
+ file_format = {"ipc": "ipc", "csv": "csv"}.get(fmt, "parquet")
570
+ dataset = ds.dataset(str(path), format=file_format)
571
+ for rb in dataset.to_batches(columns=columns, batch_size=batch_size):
572
+ if rb.num_rows:
573
+ yield pl.from_arrow(rb) # type: ignore[misc]
574
+
575
+
576
+ def stream_profile(source: str | Path | pl.LazyFrame | pl.DataFrame,
577
+ columns: Sequence[str] | None = None, batch_size: int = 100_000, *,
578
+ k: int = 800, hll_p: int = 12, seed: int = 0) -> dict[str, ColumnSketch]:
579
+ """Profile ``source`` batch by batch with bounded memory.
580
+
581
+ ``source`` is a Parquet/CSV/TSV/IPC file (or a directory of Parquet files), read in
582
+ ``batch_size``-row record batches through ``pyarrow.dataset`` in a single pass, or a
583
+ polars ``LazyFrame`` (streamed with ``collect_batches``) or ``DataFrame``. Returns
584
+ ``{column: ColumnSketch}``; call ``.summary(policy)`` for a plain dict, or pass a numeric
585
+ sketch to :func:`empirical_spec_from_sketch`.
586
+ """
587
+ if batch_size < 1:
588
+ raise ValueError(f"batch_size must be >= 1, got {batch_size}")
589
+ cols = list(columns) if columns is not None else None
590
+ sketches: dict[str, ColumnSketch] = {}
591
+ for batch in _iter_batches(source, cols, int(batch_size)):
592
+ for name in batch.columns:
593
+ s = batch.get_column(name)
594
+ sk = sketches.get(name)
595
+ if sk is None:
596
+ sk = sketches[name] = ColumnSketch.new(name, s.dtype, k=k, hll_p=hll_p,
597
+ seed=int(stream(seed, "sketch", name)
598
+ .integers(0, 2**31)))
599
+ sk.update(s)
600
+ if cols is not None:
601
+ missing = [c for c in cols if c not in sketches]
602
+ if missing and sketches:
603
+ raise ValueError(f"column(s) {missing!r} not found in source")
604
+ return sketches
605
+
606
+
607
+ # ---------------------------------------------------------------------------------------------
608
+ # sketch -> empirical marginal spec
609
+ # ---------------------------------------------------------------------------------------------
610
+
611
+
612
+ def empirical_spec_from_sketch(sketch: ColumnSketch | QuantileSketch,
613
+ column: str | ColumnSchema,
614
+ policy: str | DisclosurePolicySpec | dict | None,
615
+ store: ArrayStore) -> ModelSpec:
616
+ """``ModelSpec`` for the registered ``"empirical"`` marginal, built from a sketch.
617
+
618
+ Mirrors ``EmpiricalMarginal.fit`` exactly (same quantile levels, coarsening, bound and
619
+ exponential-tail rules) with the exact quantiles replaced by sketch quantiles. The array
620
+ prefix is ``marginal.<column>``, the same one the profiler passes to ``to_spec``.
621
+ """
622
+ import math as _m
623
+
624
+ from ectype.models.marginals import EmpiricalMarginal, _c
625
+
626
+ qs = sketch.quantiles if isinstance(sketch, ColumnSketch) else sketch
627
+ if qs is None or qs.n == 0:
628
+ name = sketch.name if isinstance(sketch, ColumnSketch) else "?"
629
+ raise ValueError(f"column {name!r} has no numeric values to build an empirical marginal")
630
+ pol = resolve_policy(policy)
631
+ name = column.name if isinstance(column, ColumnSchema) else str(column)
632
+ col = column if isinstance(column, ColumnSchema) else None
633
+ levels = quantile_levels(qs.n, pol)
634
+ q = np.maximum.accumulate(coarsen_array(np.asarray(qs.quantile(levels)), pol))
635
+ lo_x, hi_x = qs.min, qs.max
636
+ lower, upper = -_m.inf, _m.inf
637
+ if col is not None:
638
+ if col.logical_type in (LogicalType.CONTINUOUS, LogicalType.DISCRETE) and lo_x >= 0.0:
639
+ lower = 0.0
640
+ if col.min_value is not None and lo_x >= col.min_value:
641
+ lower = max(lower, float(col.min_value))
642
+ if col.max_value is not None and hi_x <= col.max_value:
643
+ upper = float(col.max_value)
644
+ elif lo_x >= 0.0:
645
+ lower = 0.0
646
+ lower, upper = min(lower, q[0]), max(upper, q[-1])
647
+ b_lo = b_hi = 0.0
648
+ if levels[0] > 0 and q[1] > q[0] and q[0] > lower:
649
+ b_lo = (q[1] - q[0]) / _m.log(levels[1] / levels[0])
650
+ if levels[-1] < 1 and q[-1] > q[-2] and q[-1] < upper:
651
+ b_hi = (q[-1] - q[-2]) / _m.log((1 - levels[-2]) / (1 - levels[-1]))
652
+ model = EmpiricalMarginal(levels, q, _c(b_lo, pol), _c(b_hi, pol), lower, upper)
653
+ return model.to_spec(store, f"marginal.{name}")