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,514 @@
1
+ """Univariate metrics plus the value helpers shared by every metric module.
2
+
3
+ Summary formats (all JSON-safe, policy-coarsened):
4
+
5
+ * ``univariate.wasserstein`` / ``univariate.ks``: ``{"levels": [...], "quantiles": [...],
6
+ "iqr": float, "std": float}`` - quantiles at ``disclosure.quantile_levels`` (each stored
7
+ quantile summarises at least ``min_category_support`` rows, inside the tail clip).
8
+ * ``univariate.mean_std``: ``{"mean": float, "std": float}``.
9
+ * ``univariate.tail``: ``{"levels": [lo, hi], "q_lo": float, "q_hi": float, "scale": float}``.
10
+ * ``univariate.frequencies``: ``{"labels": [...], "probs": [...]}`` keyed on labels; labels
11
+ with support below ``min_category_support`` are pooled into ``"__other__"``.
12
+ * ``univariate.missing_rate``: a float (null fraction).
13
+ * ``univariate.granularity``: ``{"sizes": [...], "distinct": [...], "atoms": [...],
14
+ "atom_shares": [...], "atom_mass": float, "exponents": [...], "round": [...]}`` - how the
15
+ values repeat (ADR-0007): the expected share of distinct values among ``sizes[i]`` random
16
+ rows; the most frequent values held by at least ``min_category_support`` rows with their
17
+ shares, and the pooled share of all such values; and the share of non-zero values that are
18
+ multiples of ``10^exponents[i]``.
19
+
20
+ Categorical summaries key on *labels*, never codes, so datasets with different category sets
21
+ compare correctly (labels unseen by the reference count as zero reference mass).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from typing import Any, ClassVar, Literal
27
+
28
+ import numpy as np
29
+ import polars as pl
30
+ from scipy import special
31
+
32
+ from ectype.fingerprint.disclosure import (
33
+ OTHER,
34
+ coarsen,
35
+ pool_categories,
36
+ quantile_levels,
37
+ )
38
+ from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
39
+ from ectype.io.values import category_labels, column_to_values
40
+ from ectype.types import LogicalType
41
+ from ectype.validation.metrics.base import (
42
+ CATEGORY_TYPES,
43
+ METRICS,
44
+ NUMERIC_TYPES,
45
+ Metric,
46
+ )
47
+
48
+ #: types that have a meaningful numeric value (boolean as 0/1)
49
+ NUMERIC_LIKE = (*NUMERIC_TYPES, LogicalType.BOOLEAN)
50
+
51
+ # ---------------------------------------------------------------------------------------------
52
+ # Shared helpers
53
+ # ---------------------------------------------------------------------------------------------
54
+
55
+
56
+ def is_numeric(col: ColumnSchema) -> bool:
57
+ return col.logical_type in NUMERIC_TYPES
58
+
59
+
60
+ def is_numeric_like(col: ColumnSchema) -> bool:
61
+ return col.logical_type in NUMERIC_LIKE
62
+
63
+
64
+ def is_category(col: ColumnSchema) -> bool:
65
+ return col.logical_type in CATEGORY_TYPES
66
+
67
+
68
+ def label_series(s: pl.Series) -> pl.Series:
69
+ """Canonical string labels (``io.values.category_labels``)."""
70
+ return category_labels(s)
71
+
72
+
73
+ def numeric_values(s: pl.Series, col: ColumnSchema) -> np.ndarray:
74
+ """float64 values (NaN for null) for numeric-like columns."""
75
+ if col.logical_type == LogicalType.BOOLEAN and s.dtype != pl.Boolean:
76
+ lab = label_series(s)
77
+ cats = np.array(sorted(x for x in lab.unique().to_list() if x is not None))
78
+ if cats.size == 2 and set(cats.tolist()) <= {"0", "1", "False", "True", "false",
79
+ "true"}:
80
+ cats = np.array(sorted(cats.tolist(), key=lambda v: v.lower() in ("1", "true")))
81
+ mapping = {c: float(i) for i, c in enumerate(cats.tolist())}
82
+ return lab.replace_strict(mapping, default=None, return_dtype=pl.Float64) \
83
+ .fill_null(np.nan).to_numpy().astype(np.float64)
84
+ v = column_to_values(s, col)
85
+ v = np.array(v, dtype=np.float64, copy=True)
86
+ v[~np.isfinite(v)] = np.nan
87
+ return v
88
+
89
+
90
+ def category_codes_from_data(s: pl.Series, policy: DisclosurePolicySpec
91
+ ) -> tuple[list[str], np.ndarray, np.ndarray]:
92
+ """Derive categories from the data with policy pooling.
93
+
94
+ Returns ``(labels, codes, counts)``: labels kept (support >= ``min_category_support``) plus
95
+ ``"__other__"`` last if anything was pooled; codes as float64 (NaN for null); counts per
96
+ label.
97
+ """
98
+ lab = label_series(s)
99
+ vc = lab.drop_nulls().value_counts(name="__n__")
100
+ if vc.height == 0:
101
+ return [], np.full(len(s), np.nan), np.zeros(0, dtype=np.int64)
102
+ names = vc[vc.columns[0]].to_numpy().astype(str)
103
+ cnts = vc[vc.columns[1]].to_numpy().astype(np.int64)
104
+ labels, counts, _ = pool_categories(names, cnts, policy)
105
+ labels_l = [str(x) for x in labels.tolist()]
106
+ mapping = {lb: float(i) for i, lb in enumerate(labels_l)}
107
+ other = mapping.get(OTHER)
108
+ codes = lab.replace_strict(mapping, default=other, return_dtype=pl.Float64) \
109
+ .fill_null(np.nan).to_numpy().astype(np.float64)
110
+ return labels_l, codes, counts
111
+
112
+
113
+ def safe_float(x: float, policy: DisclosurePolicySpec) -> float:
114
+ x = float(x)
115
+ if not np.isfinite(x):
116
+ return 0.0
117
+ return coarsen(x, policy)
118
+
119
+
120
+ def coarsen_list(a: np.ndarray, policy: DisclosurePolicySpec) -> list[float]:
121
+ return [safe_float(v, policy) for v in np.asarray(a, dtype=float).ravel()]
122
+
123
+
124
+ def aligned_tvd(ref: dict[str, float], cand: dict[str, float], residual: str | None) -> float:
125
+ """Total variation distance between label->prob maps.
126
+
127
+ Candidate keys unknown to the reference are moved into the reference's ``residual`` bucket
128
+ (e.g. ``"__other__"``) when the reference has one; otherwise they are compared to zero mass.
129
+ """
130
+ c2: dict[str, float] = {}
131
+ for k, v in cand.items():
132
+ key = k if k in ref else (residual if residual is not None and residual in ref else k)
133
+ c2[key] = c2.get(key, 0.0) + float(v)
134
+ keys = set(ref) | set(c2)
135
+ return 0.5 * float(sum(abs(ref.get(k, 0.0) - c2.get(k, 0.0)) for k in keys))
136
+
137
+
138
+ def rank_profiles(a: Any, b: Any) -> tuple[dict[str, Any], dict[str, Any]]:
139
+ """Label-free forms of two ``univariate.frequencies`` summaries (ADR-0010).
140
+
141
+ Used where the labels of the two sides cannot be matched: a pseudonymised column carries
142
+ tokens in synthetic data and in its fingerprint, source labels in real data, and different
143
+ tokens in every fingerprint. Each side's levels are renamed ``#1``, ``#2``, ... by
144
+ descending frequency, up to the number of levels both sides resolve; everything below that
145
+ rank joins the pooled ``__other__`` bucket. ``Frequencies.distance`` of the two results is
146
+ the total variation distance between the sorted level-frequency profiles: it sees how
147
+ concentrated the column is and how much of it is pooled, but not which level is which.
148
+ """
149
+ def split(v: Any) -> tuple[list[float], float]:
150
+ pairs = list(zip(v.get("labels", []), map(float, v.get("probs", []))))
151
+ other = sum(p for lb, p in pairs if lb == OTHER)
152
+ return sorted((p for lb, p in pairs if lb != OTHER), reverse=True), other
153
+
154
+ (pa, oa), (pb, ob) = split(a), split(b)
155
+ r = min(len(pa), len(pb))
156
+ labels = [f"#{i + 1}" for i in range(r)] + [OTHER]
157
+
158
+ def profile(p: list[float], other: float) -> dict[str, Any]:
159
+ return {"labels": labels, "probs": [*p[:r], other + sum(p[r:])]}
160
+
161
+ return profile(pa, oa), profile(pb, ob)
162
+
163
+
164
+ def _finite(v: np.ndarray) -> np.ndarray:
165
+ return v[np.isfinite(v)]
166
+
167
+
168
+ def _quantile_summary(x: np.ndarray, policy: DisclosurePolicySpec) -> dict[str, Any]:
169
+ if x.size == 0:
170
+ return {"levels": [], "quantiles": [], "iqr": 0.0, "std": 0.0}
171
+ levels = quantile_levels(int(x.size), policy)
172
+ q = np.quantile(x, levels)
173
+ iqr = float(np.subtract(*np.quantile(x, [0.75, 0.25])))
174
+ return {"levels": [float(round(v, 10)) for v in levels], "quantiles": coarsen_list(q, policy),
175
+ "iqr": safe_float(iqr, policy), "std": safe_float(float(np.std(x)), policy)}
176
+
177
+
178
+ def _scale(summary: dict[str, Any]) -> float:
179
+ iqr, std = float(summary.get("iqr") or 0.0), float(summary.get("std") or 0.0)
180
+ if iqr > 0:
181
+ return iqr
182
+ if std > 0:
183
+ return std
184
+ return 1.0
185
+
186
+
187
+ class _Univariate(Metric):
188
+ arity: ClassVar[Literal[1, 2, "all"]] = 1
189
+
190
+ @staticmethod
191
+ def _numeric(df: pl.DataFrame, columns: list[ColumnSchema]) -> np.ndarray:
192
+ col = columns[0]
193
+ return _finite(numeric_values(df[col.name], col))
194
+
195
+
196
+ # ---------------------------------------------------------------------------------------------
197
+ # Metrics
198
+ # ---------------------------------------------------------------------------------------------
199
+
200
+
201
+ @METRICS.register()
202
+ class Wasserstein(_Univariate):
203
+ """W1 between quantile functions, divided by the reference IQR (std fallback)."""
204
+
205
+ kind = "univariate.wasserstein"
206
+ family = "univariate.wasserstein"
207
+ default_tolerance = 0.05
208
+
209
+ @classmethod
210
+ def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
211
+ return len(columns) == 1 and is_numeric(columns[0])
212
+
213
+ def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
214
+ policy: DisclosurePolicySpec) -> Any:
215
+ return _quantile_summary(self._numeric(df, columns), policy)
216
+
217
+ def distance(self, reference: Any, candidate: Any) -> float:
218
+ la, qa = np.asarray(reference["levels"], float), np.asarray(reference["quantiles"], float)
219
+ lb, qb = np.asarray(candidate["levels"], float), np.asarray(candidate["quantiles"], float)
220
+ if la.size == 0 or lb.size == 0:
221
+ return 0.0 if la.size == lb.size else 1.0
222
+ qb_on_a = np.interp(la, lb, qb)
223
+ diff = np.abs(qa - qb_on_a)
224
+ w1 = float(np.trapezoid(diff, la) / (la[-1] - la[0])) if la[-1] > la[0] else float(
225
+ diff.mean())
226
+ return w1 / _scale(reference)
227
+
228
+
229
+ @METRICS.register()
230
+ class KS(_Univariate):
231
+ """Kolmogorov-Smirnov statistic between the stored quantile grids."""
232
+
233
+ kind = "univariate.ks"
234
+ family = "univariate.ks"
235
+ default_tolerance = 0.05
236
+
237
+ @classmethod
238
+ def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
239
+ return len(columns) == 1 and is_numeric(columns[0])
240
+
241
+ def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
242
+ policy: DisclosurePolicySpec) -> Any:
243
+ return _quantile_summary(self._numeric(df, columns), policy)
244
+
245
+ @staticmethod
246
+ def _cdf(x: np.ndarray, levels: np.ndarray, q: np.ndarray) -> np.ndarray:
247
+ # right-continuous CDF from a (possibly tied) quantile grid
248
+ idx = np.searchsorted(q, x, side="right")
249
+ out = np.where(idx == 0, 0.0, levels[np.clip(idx - 1, 0, len(levels) - 1)])
250
+ inner = (idx > 0) & (idx < len(q))
251
+ if inner.any():
252
+ lo, hi = q[idx[inner] - 1], q[idx[inner]]
253
+ llo, lhi = levels[idx[inner] - 1], levels[idx[inner]]
254
+ w = np.where(hi > lo, (x[inner] - lo) / np.where(hi > lo, hi - lo, 1.0), 1.0)
255
+ out[inner] = llo + w * (lhi - llo)
256
+ out[idx >= len(q)] = 1.0
257
+ return out
258
+
259
+ def distance(self, reference: Any, candidate: Any) -> float:
260
+ la, qa = np.asarray(reference["levels"], float), np.asarray(reference["quantiles"], float)
261
+ lb, qb = np.asarray(candidate["levels"], float), np.asarray(candidate["quantiles"], float)
262
+ if la.size == 0 or lb.size == 0:
263
+ return 0.0 if la.size == lb.size else 1.0
264
+ # evaluate both CDFs on the union grid
265
+ grid = np.union1d(qa, qb)
266
+ fa = self._cdf(grid, la, qa)
267
+ fb = self._cdf(grid, lb, qb)
268
+ return float(np.max(np.abs(fa - fb)))
269
+
270
+
271
+ @METRICS.register()
272
+ class MeanStd(_Univariate):
273
+ """max(|d mean| / std_ref, |d std| / std_ref)."""
274
+
275
+ kind = "univariate.mean_std"
276
+ family = "univariate.mean_std"
277
+ default_tolerance = 0.05
278
+
279
+ @classmethod
280
+ def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
281
+ return len(columns) == 1 and is_numeric(columns[0])
282
+
283
+ def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
284
+ policy: DisclosurePolicySpec) -> Any:
285
+ x = self._numeric(df, columns)
286
+ if x.size == 0:
287
+ return {"mean": 0.0, "std": 0.0}
288
+ return {"mean": safe_float(x.mean(), policy), "std": safe_float(x.std(), policy)}
289
+
290
+ def distance(self, reference: Any, candidate: Any) -> float:
291
+ s = float(reference["std"]) or 1.0
292
+ return max(abs(float(reference["mean"]) - float(candidate["mean"])) / s,
293
+ abs(float(reference["std"]) - float(candidate["std"])) / s)
294
+
295
+
296
+ @METRICS.register()
297
+ class Tail(_Univariate):
298
+ """q01/q99 error relative to the reference q01..q99 span (levels clipped to the policy)."""
299
+
300
+ kind = "univariate.tail"
301
+ family = "univariate.tail"
302
+ default_tolerance = 0.05
303
+
304
+ @classmethod
305
+ def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
306
+ return len(columns) == 1 and is_numeric(columns[0])
307
+
308
+ def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
309
+ policy: DisclosurePolicySpec) -> Any:
310
+ x = self._numeric(df, columns)
311
+ lo, hi = max(0.01, policy.tail_clip[0]), min(0.99, policy.tail_clip[1])
312
+ if x.size == 0:
313
+ return {"levels": [lo, hi], "q_lo": 0.0, "q_hi": 0.0, "scale": 0.0}
314
+ qlo, qhi = np.quantile(x, [lo, hi])
315
+ scale = qhi - qlo
316
+ if scale <= 0:
317
+ scale = float(np.std(x))
318
+ return {"levels": [lo, hi], "q_lo": safe_float(qlo, policy),
319
+ "q_hi": safe_float(qhi, policy), "scale": safe_float(scale, policy)}
320
+
321
+ def distance(self, reference: Any, candidate: Any) -> float:
322
+ s = float(reference["scale"]) or 1.0
323
+ return max(abs(float(reference["q_lo"]) - float(candidate["q_lo"])),
324
+ abs(float(reference["q_hi"]) - float(candidate["q_hi"]))) / s
325
+
326
+
327
+ @METRICS.register()
328
+ class Frequencies(_Univariate):
329
+ """Total variation distance between label frequencies (rare labels pooled)."""
330
+
331
+ kind = "univariate.frequencies"
332
+ family = "univariate.frequencies"
333
+ default_tolerance = 0.05
334
+
335
+ @classmethod
336
+ def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
337
+ return len(columns) == 1 and is_category(columns[0])
338
+
339
+ def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
340
+ policy: DisclosurePolicySpec) -> Any:
341
+ labels, _, counts = category_codes_from_data(df[columns[0].name], policy)
342
+ total = float(counts.sum())
343
+ probs = counts / total if total > 0 else counts.astype(float)
344
+ return {"labels": labels, "probs": coarsen_list(probs, policy)}
345
+
346
+ def distance(self, reference: Any, candidate: Any) -> float:
347
+ ref = dict(zip(reference["labels"], map(float, reference["probs"])))
348
+ cand = dict(zip(candidate["labels"], map(float, candidate["probs"])))
349
+ return aligned_tvd(ref, cand, OTHER)
350
+
351
+
352
+ @METRICS.register()
353
+ class MissingRate(_Univariate):
354
+ """Absolute difference in null fraction."""
355
+
356
+ kind = "univariate.missing_rate"
357
+ family = "univariate.missing_rate"
358
+ default_tolerance = 0.02
359
+
360
+ def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
361
+ policy: DisclosurePolicySpec) -> Any:
362
+ s = df[columns[0].name]
363
+ if len(s) == 0:
364
+ return 0.0
365
+ nulls = s.null_count()
366
+ if s.dtype.is_float():
367
+ nulls = int(s.is_null().sum()) + int(s.is_nan().fill_null(False).sum())
368
+ return safe_float(nulls / len(s), policy)
369
+
370
+ def distance(self, reference: Any, candidate: Any) -> float:
371
+ return abs(float(reference) - float(candidate))
372
+
373
+
374
+ # ---------------------------------------------------------------------------------------------
375
+ # Granularity (ADR-0007)
376
+ # ---------------------------------------------------------------------------------------------
377
+
378
+ #: sample sizes at which the share of distinct values is reported ...
379
+ GRANULARITY_SIZES = (10, 100, 1_000, 10_000, 100_000, 1_000_000)
380
+ #: ... those of at most this share of the rows (a larger subsample of a bootstrap resample is
381
+ #: dominated by the ties the resampling itself creates)
382
+ GRANULARITY_SIZE_FRACTION = 0.1
383
+ #: point masses compared (the most frequent supported values of either side) and stored
384
+ GRANULARITY_TOP_ATOMS = 20
385
+ GRANULARITY_STORED_ATOMS = 40
386
+ #: powers of ten whose multiples are counted
387
+ GRANULARITY_EXPONENTS = tuple(range(-6, 13))
388
+ #: largest ``|x| / 10^e`` at which "is a multiple" can still be told in float64
389
+ _ROUND_MAX_RATIO = 1e11
390
+
391
+
392
+ def rarefied_distinct(counts: np.ndarray, m: int) -> float:
393
+ """Expected number of distinct values among ``m`` rows drawn without replacement from a
394
+ column whose values occur ``counts`` times (the rarefaction formula:
395
+ ``sum_v 1 - C(n - c_v, m) / C(n, m)``)."""
396
+ c, mult = np.unique(np.asarray(counts, dtype=np.float64), return_counts=True)
397
+ n = float(np.sum(c * mult))
398
+ if m >= n:
399
+ return float(mult.sum())
400
+ lg = special.gammaln
401
+ rest = np.maximum(n - c - m, 0.0)
402
+ log_absent = lg(n - c + 1.0) - lg(rest + 1.0) - lg(n + 1.0) + lg(n - m + 1.0)
403
+ absent = np.where(c > n - m, 0.0, np.exp(np.minimum(log_absent, 0.0)))
404
+ return float(np.sum(mult * (1.0 - absent)))
405
+
406
+
407
+ def round_shares(values: np.ndarray, counts: np.ndarray, min_support: int
408
+ ) -> tuple[list[int], list[float]]:
409
+ """For each power of ten ``10^e`` in ``GRANULARITY_EXPONENTS``: the share of the non-zero
410
+ rows whose value is a multiple of it (0 is a multiple of everything, so it says nothing
411
+ about rounding). A share standing for fewer than ``min_support`` rows is reported as 0, and
412
+ one that leaves out fewer than ``min_support`` rows as 1, so a handful of exceptional rows
413
+ never shows."""
414
+ nz = values != 0
415
+ v, c = np.abs(values[nz]), counts[nz].astype(np.float64)
416
+ total = float(c.sum())
417
+ shares = []
418
+ for e in GRANULARITY_EXPONENTS:
419
+ if total < max(min_support, 1):
420
+ shares.append(0.0)
421
+ continue
422
+ ratio = v / (10.0 ** e)
423
+ nearest = np.rint(ratio) # 0 for a value smaller than the step
424
+ whole = (nearest >= 1) & (ratio <= _ROUND_MAX_RATIO) \
425
+ & (np.abs(ratio - nearest) <= 1e-6 + 1e-12 * ratio)
426
+ hit = float(c[whole].sum())
427
+ if hit < min_support:
428
+ hit = 0.0
429
+ elif total - hit < min_support:
430
+ hit = total
431
+ shares.append(hit / total)
432
+ return list(GRANULARITY_EXPONENTS), shares
433
+
434
+
435
+ @METRICS.register()
436
+ class Granularity(_Univariate):
437
+ """How the values of a numeric column repeat: a marginal can match every quantile and
438
+ still be told from the source at a glance when it has too few distinct values, misses a
439
+ spike or ignores that the source is rounded (ADR-0007). The distance is the largest of
440
+
441
+ * the difference in the share of distinct values among ``m`` random rows (``m`` the
442
+ largest reported size both summaries have);
443
+ * the total absolute difference in the shares of the ``GRANULARITY_TOP_ATOMS`` most
444
+ frequent supported values of either summary (a value the other summary does not list
445
+ counts as share 0 there);
446
+ * the largest difference, over the powers of ten, in the share of round values.
447
+
448
+ Nothing in the summary is a rare value: values below ``min_category_support`` rows only
449
+ enter through the distinct-value share (rounded to three decimals) and the pooled
450
+ ``atom_mass``.
451
+ """
452
+
453
+ kind = "univariate.granularity"
454
+ family = "univariate.granularity"
455
+ default_tolerance = 0.05
456
+
457
+ @classmethod
458
+ def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
459
+ return len(columns) == 1 and columns[0].logical_type in (LogicalType.CONTINUOUS,
460
+ LogicalType.DISCRETE)
461
+
462
+ def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
463
+ policy: DisclosurePolicySpec) -> Any:
464
+ x = self._numeric(df, columns)
465
+ n = int(x.size)
466
+ if n == 0:
467
+ return {"sizes": [], "distinct": [], "atoms": [], "atom_shares": [],
468
+ "atom_mass": 0.0, "exponents": [], "round": []}
469
+ vals, counts = np.unique(x, return_counts=True)
470
+ sizes = [m for m in GRANULARITY_SIZES if m <= GRANULARITY_SIZE_FRACTION * n]
471
+ distinct = [round(rarefied_distinct(counts, m) / m, 3) for m in sizes]
472
+ k = max(int(policy.min_category_support), 1)
473
+ sup = np.flatnonzero(counts >= k)
474
+ top = sup[np.argsort(-counts[sup], kind="stable")[:GRANULARITY_STORED_ATOMS]]
475
+ exponents, shares = round_shares(vals, counts, k)
476
+ return {
477
+ "sizes": [int(m) for m in sizes],
478
+ "distinct": [float(d) for d in distinct],
479
+ "atoms": [float(v) for v in vals[top]],
480
+ "atom_shares": coarsen_list(counts[top] / n, policy),
481
+ "atom_mass": safe_float(float(counts[sup].sum()) / n, policy),
482
+ "exponents": exponents,
483
+ "round": coarsen_list(np.asarray(shares), policy),
484
+ }
485
+
486
+ @staticmethod
487
+ def _distinct_distance(reference: Any, candidate: Any) -> float:
488
+ ref = dict(zip(reference.get("sizes", []), reference.get("distinct", [])))
489
+ cand = dict(zip(candidate.get("sizes", []), candidate.get("distinct", [])))
490
+ common = sorted(set(ref) & set(cand))
491
+ if not common:
492
+ return 0.0
493
+ return abs(float(ref[common[-1]]) - float(cand[common[-1]]))
494
+
495
+ @staticmethod
496
+ def _atom_distance(reference: Any, candidate: Any) -> float:
497
+ ref = dict(zip(map(float, reference.get("atoms", [])),
498
+ map(float, reference.get("atom_shares", []))))
499
+ cand = dict(zip(map(float, candidate.get("atoms", [])),
500
+ map(float, candidate.get("atom_shares", []))))
501
+ top = set(list(ref)[:GRANULARITY_TOP_ATOMS]) | set(list(cand)[:GRANULARITY_TOP_ATOMS])
502
+ return float(sum(abs(ref.get(v, 0.0) - cand.get(v, 0.0)) for v in top))
503
+
504
+ @staticmethod
505
+ def _round_distance(reference: Any, candidate: Any) -> float:
506
+ ref = dict(zip(reference.get("exponents", []), reference.get("round", [])))
507
+ cand = dict(zip(candidate.get("exponents", []), candidate.get("round", [])))
508
+ common = set(ref) & set(cand)
509
+ return max((abs(float(ref[e]) - float(cand[e])) for e in common), default=0.0)
510
+
511
+ def distance(self, reference: Any, candidate: Any) -> float:
512
+ return max(self._distinct_distance(reference, candidate),
513
+ self._atom_distance(reference, candidate),
514
+ self._round_distance(reference, candidate))