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,49 @@
1
+ """Privacy evaluation (empirical attacks) and differential-privacy building blocks (M29).
2
+
3
+ The attack suite measures disclosure risk empirically; it is not a formal guarantee. The DP
4
+ functions in :mod:`.dp` are building blocks and are not yet wired into the Profiler.
5
+ """
6
+
7
+ from ectype.privacy.attacks import (
8
+ RowEncoder,
9
+ attribute_inference,
10
+ membership_inference,
11
+ nn_distance_ratio,
12
+ run_privacy_suite,
13
+ )
14
+ from ectype.privacy.dp import (
15
+ BudgetExceededError,
16
+ PrivacyAccountant,
17
+ dp_categorical,
18
+ dp_correlation,
19
+ dp_quantiles,
20
+ )
21
+ from ectype.privacy.report import (
22
+ DISCLAIMER,
23
+ RISK_THRESHOLDS,
24
+ AttributeInferenceResult,
25
+ AttributeResult,
26
+ DCRResult,
27
+ MIAResult,
28
+ PrivacyReport,
29
+ )
30
+
31
+ __all__ = [
32
+ "DISCLAIMER",
33
+ "RISK_THRESHOLDS",
34
+ "AttributeInferenceResult",
35
+ "AttributeResult",
36
+ "BudgetExceededError",
37
+ "DCRResult",
38
+ "MIAResult",
39
+ "PrivacyAccountant",
40
+ "PrivacyReport",
41
+ "RowEncoder",
42
+ "attribute_inference",
43
+ "dp_categorical",
44
+ "dp_correlation",
45
+ "dp_quantiles",
46
+ "membership_inference",
47
+ "nn_distance_ratio",
48
+ "run_privacy_suite",
49
+ ]
@@ -0,0 +1,599 @@
1
+ """Empirical privacy attacks on synthetic tables (M29).
2
+
3
+ All attacks take Polars frames with mixed column types and share one preprocessing step
4
+ (:class:`RowEncoder`), fitted on the **train** frame only:
5
+
6
+ * numeric, boolean and temporal columns are standardized with train mean / std;
7
+ * other columns are one-hot encoded for the top-``k`` train levels that occur at least twice
8
+ (singleton levels such as identifiers are not encoded, so they cannot act as row keys);
9
+ one-hot entries are scaled by ``1/sqrt(2)`` so a category mismatch costs distance 1;
10
+ * nulls (and NaN) get an indicator column and the numeric value is imputed at the train mean.
11
+
12
+ Distances are Euclidean in that space, computed by chunked brute force in numpy. Every side
13
+ is subsampled to at most ``max_rows`` (default 5000) rows with a seeded stream.
14
+
15
+ The attacks are:
16
+
17
+ * :func:`nn_distance_ratio`: distance to closest record (DCR) of each synthetic row to train
18
+ versus to an equally sized holdout sample, plus exact-match rates.
19
+ * :func:`membership_inference`: members (train) and non-members (holdout) are scored by their
20
+ negative DCR to the synthetic sample; AUC, attacker advantage and a bootstrap CI.
21
+ * :func:`attribute_inference`: a kNN model fitted on synthetic data predicts sensitive columns
22
+ of members and non-members from quasi-identifiers; leakage is the accuracy gap.
23
+
24
+ These are empirical attack results, not formal privacy guarantees (see :mod:`.report`).
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from collections.abc import Sequence
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ import numpy as np
34
+ import polars as pl
35
+ from scipy.stats import rankdata
36
+
37
+ from ectype.privacy.report import (
38
+ NULL_QUANTILE,
39
+ AttributeInferenceResult,
40
+ AttributeResult,
41
+ DCRResult,
42
+ MIAResult,
43
+ PrivacyReport,
44
+ )
45
+ from ectype.rng import stream
46
+
47
+ MAX_ROWS = 5000
48
+ TOP_K = 20
49
+ CHUNK = 512
50
+ _ZERO = 1e-9
51
+ _EXACT_REPEATS = 20
52
+ _ONEHOT_SCALE = 1.0 / np.sqrt(2.0)
53
+
54
+ __all__ = [
55
+ "RowEncoder",
56
+ "attribute_inference",
57
+ "membership_inference",
58
+ "nn_distance_ratio",
59
+ "run_privacy_suite",
60
+ ]
61
+
62
+
63
+ # ---------------------------------------------------------------------------------------------
64
+ # Preprocessing
65
+ # ---------------------------------------------------------------------------------------------
66
+
67
+
68
+ def _is_numeric(dtype: pl.DataType) -> bool:
69
+ return dtype.is_numeric() or dtype == pl.Boolean or dtype.is_temporal()
70
+
71
+
72
+ def _as_float(s: pl.Series) -> np.ndarray:
73
+ if s.dtype.is_temporal():
74
+ s = s.to_physical()
75
+ x = s.cast(pl.Float64).to_numpy().astype(np.float64, copy=False)
76
+ return np.where(np.isfinite(x), x, np.nan)
77
+
78
+
79
+ def _as_str(s: pl.Series) -> np.ndarray:
80
+ try:
81
+ s = s.cast(pl.Utf8)
82
+ except Exception: # nested or exotic types
83
+ s = pl.Series(s.name, [None if v is None else str(v) for v in s.to_list()],
84
+ dtype=pl.Utf8)
85
+ return s.to_numpy()
86
+
87
+
88
+ class RowEncoder:
89
+ """Mixed-type rows -> float matrix, fitted on train statistics (see module docstring)."""
90
+
91
+ def __init__(self, columns: Sequence[str], top_k: int = TOP_K) -> None:
92
+ self.columns = list(columns)
93
+ self.top_k = int(top_k)
94
+ self.kinds: dict[str, str] = {}
95
+ self.stats: dict[str, tuple[float, float]] = {}
96
+ self.levels: dict[str, np.ndarray] = {}
97
+ self.null_indicator: dict[str, bool] = {}
98
+
99
+ def fit(self, train: pl.DataFrame, others: Sequence[pl.DataFrame] = ()) -> RowEncoder:
100
+ for c in self.columns:
101
+ s = train[c]
102
+ has_null = any(_null_mask(f[c]).any() for f in (train, *others) if c in f.columns)
103
+ self.null_indicator[c] = bool(has_null)
104
+ if _is_numeric(s.dtype):
105
+ self.kinds[c] = "numeric"
106
+ x = _as_float(s)
107
+ x = x[~np.isnan(x)]
108
+ mu = float(x.mean()) if x.size else 0.0
109
+ sd = float(x.std()) if x.size > 1 else 0.0
110
+ self.stats[c] = (mu, sd if sd > 0 else 1.0)
111
+ else:
112
+ self.kinds[c] = "categorical"
113
+ v = _as_str(s)
114
+ v = v[v != None] # noqa: E711 (object array comparison)
115
+ if v.size:
116
+ labels, counts = np.unique(v.astype(str), return_counts=True)
117
+ order = np.lexsort((labels, -counts))
118
+ keep = order[counts[order] >= 2][: self.top_k]
119
+ self.levels[c] = labels[keep]
120
+ else:
121
+ self.levels[c] = np.array([], dtype=str)
122
+ return self
123
+
124
+ @property
125
+ def width(self) -> int:
126
+ w = 0
127
+ for c in self.columns:
128
+ w += 1 if self.kinds[c] == "numeric" else len(self.levels[c])
129
+ w += int(self.null_indicator[c])
130
+ return w
131
+
132
+ def transform(self, df: pl.DataFrame) -> np.ndarray:
133
+ n = df.height
134
+ blocks: list[np.ndarray] = []
135
+ for c in self.columns:
136
+ s = df[c]
137
+ null = _null_mask(s)
138
+ if self.kinds[c] == "numeric":
139
+ mu, sd = self.stats[c]
140
+ x = (_as_float(s) - mu) / sd
141
+ x = np.where(np.isnan(x), 0.0, x)
142
+ blocks.append(x[:, None])
143
+ else:
144
+ lv = self.levels[c]
145
+ if lv.size:
146
+ v = _as_str(s)
147
+ v = np.where(null, "", v).astype(str)
148
+ blocks.append((v[:, None] == lv[None, :]).astype(np.float64)
149
+ * _ONEHOT_SCALE)
150
+ if self.null_indicator[c]:
151
+ blocks.append(null.astype(np.float64)[:, None])
152
+ if not blocks:
153
+ return np.zeros((n, 0))
154
+ return np.hstack(blocks)
155
+
156
+
157
+ def _null_mask(s: pl.Series) -> np.ndarray:
158
+ m = s.is_null().to_numpy()
159
+ if s.dtype.is_float():
160
+ m = m | s.is_nan().fill_null(False).to_numpy()
161
+ return np.asarray(m, dtype=bool)
162
+
163
+
164
+ def _common_columns(train: pl.DataFrame, *others: pl.DataFrame,
165
+ exclude: Sequence[str] = ()) -> list[str]:
166
+ cols = [c for c in train.columns if all(c in o.columns for o in others)
167
+ and c not in set(exclude)]
168
+ if not cols:
169
+ raise ValueError("train, holdout and synthetic share no columns to attack")
170
+ return cols
171
+
172
+
173
+ def _check_nonempty(**frames: pl.DataFrame) -> None:
174
+ for name, f in frames.items():
175
+ if not isinstance(f, pl.DataFrame):
176
+ raise TypeError(f"{name} must be a polars DataFrame, not {type(f).__name__}")
177
+ if f.height == 0:
178
+ raise ValueError(f"{name} has no rows")
179
+
180
+
181
+ def _subsample(df: pl.DataFrame, m: int, rng: np.random.Generator) -> pl.DataFrame:
182
+ if df.height <= m:
183
+ return df
184
+ idx = np.sort(rng.choice(df.height, size=m, replace=False))
185
+ return df[idx]
186
+
187
+
188
+ # ---------------------------------------------------------------------------------------------
189
+ # Nearest neighbours (chunked brute force)
190
+ # ---------------------------------------------------------------------------------------------
191
+
192
+
193
+ def _knn(a: np.ndarray, b: np.ndarray, k: int = 1, chunk: int = CHUNK
194
+ ) -> tuple[np.ndarray, np.ndarray]:
195
+ """k nearest rows of ``b`` for each row of ``a``: (distances, indices), sorted ascending.
196
+
197
+ Ties are broken by the lower index in ``b`` (stable), so results are deterministic.
198
+ """
199
+ k = min(int(k), b.shape[0])
200
+ na = a.shape[0]
201
+ dist = np.empty((na, k))
202
+ idx = np.empty((na, k), dtype=np.int64)
203
+ if b.shape[1] == 0:
204
+ dist[:] = 0.0
205
+ idx[:] = np.arange(k)[None, :]
206
+ return dist, idx
207
+ bn = np.einsum("ij,ij->i", b, b)
208
+ for i in range(0, na, chunk):
209
+ x = a[i:i + chunk]
210
+ d2 = np.einsum("ij,ij->i", x, x)[:, None] + bn[None, :] - 2.0 * (x @ b.T)
211
+ np.maximum(d2, 0.0, out=d2)
212
+ if k == 1:
213
+ j = np.argmin(d2, axis=1)[:, None]
214
+ else:
215
+ j = np.argsort(d2, axis=1, kind="stable")[:, :k]
216
+ dd = np.sqrt(np.take_along_axis(d2, j, axis=1))
217
+ dd[dd < 1e-6] = 0.0 # float cancellation on exact duplicates
218
+ dist[i:i + chunk], idx[i:i + chunk] = dd, j
219
+ return dist, idx
220
+
221
+
222
+ def _min_dist(a: np.ndarray, b: np.ndarray) -> np.ndarray:
223
+ return _knn(a, b, 1)[0][:, 0]
224
+
225
+
226
+ def _row_hashes(df: pl.DataFrame, cols: list[str]) -> np.ndarray:
227
+ exprs = [pl.col(c).cast(pl.Utf8, strict=False).fill_null("\x00<null>") for c in cols]
228
+ return df.select(exprs).hash_rows(seed=0).to_numpy()
229
+
230
+
231
+ # ---------------------------------------------------------------------------------------------
232
+ # Attacks
233
+ # ---------------------------------------------------------------------------------------------
234
+
235
+
236
+ def nn_distance_ratio(train: pl.DataFrame, holdout: pl.DataFrame, synthetic: pl.DataFrame,
237
+ seed: int = 0, *, max_rows: int = MAX_ROWS,
238
+ exclude: Sequence[str] = (), n_permutations: int = 200) -> DCRResult:
239
+ """Distance to closest record of synthetic rows: train versus holdout.
240
+
241
+ Train and holdout are subsampled to the same size so their DCRs are comparable. For a
242
+ generator that does not memorize, a synthetic row is as close to holdout as to train:
243
+ the median ratio ``DCR_train / DCR_holdout`` is about 1 and the closer-to-train share is
244
+ about 0.5 (ties count one half). The exact-match rate compares raw values (all shared
245
+ columns, cast to strings) of the full synthetic frame against size-matched train and
246
+ holdout references of ``min(len(train), len(holdout))`` rows each (no ``max_rows`` cap; the
247
+ larger side is averaged over repeated subsamples); the holdout rate is the natural
248
+ baseline, and ``exact_match_noise`` is the one-sided 95% spread of their difference under
249
+ no memorization.
250
+
251
+ The closer-to-train share and the median ratio also get a permutation null
252
+ (``n_permutations`` random re-splits of the pooled train + holdout reference rows into
253
+ two halves; see ``_dcr_null``): on small tables both drift far from 0.5 / 1 by chance, and
254
+ the report only counts them when they are beyond the null's ``NULL_QUANTILE``.
255
+ """
256
+ _check_nonempty(train=train, holdout=holdout, synthetic=synthetic)
257
+ cols = _common_columns(train, holdout, synthetic, exclude=exclude)
258
+ m = min(train.height, holdout.height, max_rows)
259
+ tr = _subsample(train, m, stream(seed, "privacy", "dcr", "train"))
260
+ ho = _subsample(holdout, m, stream(seed, "privacy", "dcr", "holdout"))
261
+ sy = _subsample(synthetic, max_rows, stream(seed, "privacy", "dcr", "synthetic"))
262
+ enc = RowEncoder(cols).fit(train, (holdout, synthetic))
263
+ xs = enc.transform(sy)
264
+ x_tr, x_ho = enc.transform(tr), enc.transform(ho)
265
+ d_tr = _min_dist(xs, x_tr)
266
+ d_ho = _min_dist(xs, x_ho)
267
+ closer_share, med_ratio = _dcr_stats(d_tr, d_ho)
268
+ null_share, null_ratio = _dcr_null(xs, x_tr, x_ho, n_permutations,
269
+ stream(seed, "privacy", "dcr", "perm"))
270
+
271
+ # exact matches: train and holdout reference sets of the SAME size, so the holdout rate
272
+ # is a fair baseline (a larger reference set covers more of a discrete domain by chance)
273
+ m_exact = min(train.height, holdout.height)
274
+ h_syn = _row_hashes(synthetic, cols)
275
+ exact, sd_tr = _exact_match_rate(h_syn, _row_hashes(train, cols), m_exact,
276
+ stream(seed, "privacy", "exact", "train"))
277
+ exact_ho, sd_ho = _exact_match_rate(h_syn, _row_hashes(holdout, cols), m_exact,
278
+ stream(seed, "privacy", "exact", "holdout"))
279
+ # one size-m reference draw varies by about sd; the averaged side by sd / sqrt(R)
280
+ sd = max(sd_tr, sd_ho)
281
+ noise = 1.645 * sd * float(np.sqrt(1.0 + 1.0 / _EXACT_REPEATS)) if sd > 0 else 0.0
282
+ return DCRResult(
283
+ median_ratio=med_ratio,
284
+ closer_to_train_share=closer_share,
285
+ exact_match_rate=exact,
286
+ holdout_exact_match_rate=exact_ho,
287
+ exact_match_noise=noise,
288
+ median_dcr_train=float(np.median(d_tr)),
289
+ median_dcr_holdout=float(np.median(d_ho)),
290
+ n_reference=m,
291
+ n_synthetic=sy.height,
292
+ closer_share_null=null_share,
293
+ median_ratio_null=null_ratio,
294
+ )
295
+
296
+
297
+ def _dcr_stats(d_tr: np.ndarray, d_ho: np.ndarray) -> tuple[float, float]:
298
+ """(closer-to-train share with ties as one half, median of DCR_train / DCR_holdout)."""
299
+ both_zero = (d_tr == 0) & (d_ho == 0)
300
+ ratio = np.where(both_zero, 1.0, d_tr / np.maximum(d_ho, _ZERO))
301
+ closer = np.where(d_tr < d_ho, 1.0, np.where(d_tr == d_ho, 0.5, 0.0))
302
+ return float(closer.mean()), float(np.median(np.minimum(ratio, 1e6)))
303
+
304
+
305
+ #: nearest pooled reference rows kept per synthetic row for the DCR permutation null
306
+ _NULL_K = 32
307
+
308
+
309
+ def _dcr_null(xs: np.ndarray, x_tr: np.ndarray, x_ho: np.ndarray, n_perm: int,
310
+ rng: np.random.Generator) -> tuple[float | None, float | None]:
311
+ """Null quantiles of the DCR indicators: ``(q of closer share, 1 - q of median ratio)`` at
312
+ ``q = NULL_QUANTILE``.
313
+
314
+ Without memorization train and holdout rows are exchangeable, so the indicators'
315
+ distribution is obtained by re-splitting the pooled reference rows at random into two
316
+ halves of the original sizes. Each synthetic row keeps its ``_NULL_K`` nearest pooled rows;
317
+ its DCR to a half is the first of those in that half (the farthest kept distance when none
318
+ is, which only happens with probability about ``2**-_NULL_K``).
319
+ """
320
+ if n_perm <= 0 or len(x_tr) == 0 or len(x_ho) == 0 or len(xs) == 0:
321
+ return None, None
322
+ pooled = np.vstack([x_tr, x_ho])
323
+ dist, idx = _knn(xs, pooled, _NULL_K)
324
+ n_tr = len(x_tr)
325
+ base = np.r_[np.ones(n_tr, dtype=bool), np.zeros(len(x_ho), dtype=bool)]
326
+ rows = np.arange(len(xs))
327
+ shares, ratios = np.empty(n_perm), np.empty(n_perm)
328
+ for b in range(n_perm):
329
+ lab = rng.permutation(base)[idx] # True: neighbour falls in the "train" half
330
+ has_t, has_h = lab.any(axis=1), (~lab).any(axis=1)
331
+ d_t = np.where(has_t, dist[rows, np.argmax(lab, axis=1)], dist[:, -1])
332
+ d_h = np.where(has_h, dist[rows, np.argmax(~lab, axis=1)], dist[:, -1])
333
+ shares[b], ratios[b] = _dcr_stats(d_t, d_h)
334
+ return (float(np.quantile(shares, NULL_QUANTILE)),
335
+ float(np.quantile(ratios, 1.0 - NULL_QUANTILE)))
336
+
337
+
338
+ def _exact_match_rate(h_syn: np.ndarray, h_ref: np.ndarray, m: int,
339
+ rng: np.random.Generator) -> tuple[float, float]:
340
+ """Share of synthetic row hashes found among ``m`` reference rows: (mean, sd).
341
+
342
+ A reference set larger than ``m`` is subsampled ``_EXACT_REPEATS`` times without
343
+ replacement; the mean rate and its spread across subsamples are returned. A reference
344
+ set of exactly ``m`` rows is used whole (sd 0).
345
+ """
346
+ if len(h_ref) <= m:
347
+ return float(np.isin(h_syn, h_ref).mean()), 0.0
348
+ rates = np.array([np.isin(h_syn, h_ref[rng.choice(len(h_ref), size=m, replace=False)]).mean()
349
+ for _ in range(_EXACT_REPEATS)])
350
+ return float(rates.mean()), float(rates.std(ddof=1))
351
+
352
+
353
+ def _auc(pos: np.ndarray, neg: np.ndarray) -> float:
354
+ """Mann-Whitney AUC = P(score_pos > score_neg) + 1/2 P(tie)."""
355
+ r = rankdata(np.concatenate([pos, neg]))
356
+ n1, n0 = len(pos), len(neg)
357
+ return float((r[:n1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0))
358
+
359
+
360
+ def _advantage(pos: np.ndarray, neg: np.ndarray) -> float:
361
+ """max over thresholds of TPR - FPR (the attacker's membership advantage)."""
362
+ s = np.concatenate([pos, neg])
363
+ y = np.concatenate([np.ones(len(pos)), np.zeros(len(neg))])
364
+ order = np.argsort(-s, kind="stable")
365
+ s, y = s[order], y[order]
366
+ last = np.r_[np.diff(s) != 0, True] # cut only between distinct scores
367
+ tpr = np.cumsum(y)[last] / len(pos)
368
+ fpr = np.cumsum(1.0 - y)[last] / len(neg)
369
+ return float(max(0.0, np.max(tpr - fpr)))
370
+
371
+
372
+ def membership_inference(train: pl.DataFrame, holdout: pl.DataFrame, synthetic: pl.DataFrame,
373
+ seed: int = 0, *, max_rows: int = MAX_ROWS, n_bootstrap: int = 200,
374
+ exclude: Sequence[str] = ()) -> MIAResult:
375
+ """Distance-based membership inference.
376
+
377
+ Candidates are an equal number of train records (members) and holdout records
378
+ (non-members); each is scored by ``-DCR`` to the synthetic sample (closer = more likely a
379
+ member). Reports the ROC AUC (0.5 = no better than chance), the advantage
380
+ ``max(TPR - FPR)``, a stratified bootstrap 95% CI of the AUC and the 95th percentile of
381
+ the advantage under a label-permutation null (``n_bootstrap`` permutations).
382
+ """
383
+ _check_nonempty(train=train, holdout=holdout, synthetic=synthetic)
384
+ cols = _common_columns(train, holdout, synthetic, exclude=exclude)
385
+ m = min(train.height, holdout.height, max_rows)
386
+ tr = _subsample(train, m, stream(seed, "privacy", "mia", "train"))
387
+ ho = _subsample(holdout, m, stream(seed, "privacy", "mia", "holdout"))
388
+ sy = _subsample(synthetic, max_rows, stream(seed, "privacy", "mia", "synthetic"))
389
+ enc = RowEncoder(cols).fit(train, (holdout, synthetic))
390
+ xs = enc.transform(sy)
391
+ pos = -_min_dist(enc.transform(tr), xs)
392
+ neg = -_min_dist(enc.transform(ho), xs)
393
+ auc = _auc(pos, neg)
394
+ rng = stream(seed, "privacy", "mia", "bootstrap")
395
+ boots = np.empty(n_bootstrap)
396
+ for b in range(n_bootstrap):
397
+ ip = rng.integers(0, len(pos), len(pos))
398
+ ineg = rng.integers(0, len(neg), len(neg))
399
+ boots[b] = _auc(pos[ip], neg[ineg])
400
+ ci = ((float(np.quantile(boots, 0.025)), float(np.quantile(boots, 0.975)))
401
+ if n_bootstrap > 0 else (auc, auc))
402
+ null = _mia_null(pos, neg, n_bootstrap, stream(seed, "privacy", "mia", "perm"))
403
+ return MIAResult(auc=auc, advantage=_advantage(pos, neg), auc_ci=ci, n_members=len(pos),
404
+ n_nonmembers=len(neg), n_bootstrap=int(n_bootstrap),
405
+ advantage_null_q95=null[0], advantage_null=null[1], auc_null=null[2])
406
+
407
+
408
+ def _mia_null(pos: np.ndarray, neg: np.ndarray, n_perm: int, rng: np.random.Generator
409
+ ) -> tuple[float | None, float | None, float | None]:
410
+ """Label-permutation null of the MIA indicators (member labels shuffled):
411
+ ``(advantage q95, advantage q, AUC q)`` at ``q = NULL_QUANTILE``.
412
+
413
+ The maximum of ``TPR - FPR`` over thresholds is biased upward on small samples (about
414
+ ``1.36 / sqrt(n/2)`` for two samples of ``n/2`` even without any leakage), so the advantage
415
+ indicator is only meaningful when it exceeds its null quantile; likewise the AUC.
416
+ """
417
+ if n_perm <= 0 or len(pos) == 0 or len(neg) == 0:
418
+ return None, None, None
419
+ s = np.concatenate([pos, neg])
420
+ y = np.concatenate([np.ones(len(pos)), np.zeros(len(neg))])
421
+ order = np.argsort(-s, kind="stable")
422
+ last = np.r_[np.diff(s[order]) != 0, True]
423
+ r = rankdata(s)
424
+ n1, n0 = len(pos), len(neg)
425
+ adv, auc = np.empty(n_perm), np.empty(n_perm)
426
+ for b in range(n_perm):
427
+ yp = rng.permutation(y)
428
+ ys = yp[order]
429
+ tpr = np.cumsum(ys)[last] / n1
430
+ fpr = np.cumsum(1.0 - ys)[last] / n0
431
+ adv[b] = max(0.0, float(np.max(tpr - fpr)))
432
+ auc[b] = (r[yp == 1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0)
433
+ return (float(np.quantile(adv, 0.95)), float(np.quantile(adv, NULL_QUANTILE)),
434
+ float(np.quantile(auc, NULL_QUANTILE)))
435
+
436
+
437
+ def _attribute_one(train: pl.DataFrame, tr: pl.DataFrame, ho: pl.DataFrame, sy: pl.DataFrame,
438
+ target: str, qids: list[str], k: int) -> AttributeResult | str:
439
+ sy = sy.filter(~pl.Series(_null_mask(sy[target])))
440
+ tr = tr.filter(~pl.Series(_null_mask(tr[target])))
441
+ ho = ho.filter(~pl.Series(_null_mask(ho[target])))
442
+ if sy.height == 0 or tr.height == 0 or ho.height == 0:
443
+ return "no non-null values"
444
+ enc = RowEncoder(qids).fit(train, (sy, ho))
445
+ xs = enc.transform(sy)
446
+ _, i_tr = _knn(enc.transform(tr), xs, k)
447
+ _, i_ho = _knn(enc.transform(ho), xs, k)
448
+ numeric = _is_numeric(train[target].dtype) and train[target].dtype != pl.Boolean
449
+ if numeric:
450
+ y_sy, y_tr, y_ho = (_as_float(f[target]) for f in (sy, tr, ho))
451
+ ref = _as_float(train[target])
452
+ sd = float(np.nanstd(ref)) if np.isfinite(ref).sum() > 1 else 0.0
453
+ tol = 0.1 * sd if sd > 0 else _ZERO
454
+
455
+ def hits(idx: np.ndarray, y: np.ndarray) -> float:
456
+ return float((np.abs(y_sy[idx].mean(axis=1) - y) <= tol).mean())
457
+
458
+ base = float((np.abs(np.nanmean(y_sy) - y_ho) <= tol).mean())
459
+ return AttributeResult(target, "numeric", qids, hits(i_tr, y_tr), hits(i_ho, y_ho),
460
+ base, tr.height, ho.height, tolerance=tol)
461
+ y_sy, y_tr, y_ho = (_as_str(f[target]).astype(str) for f in (sy, tr, ho))
462
+
463
+ def vote(idx: np.ndarray) -> np.ndarray:
464
+ if idx.shape[1] == 1:
465
+ return y_sy[idx[:, 0]]
466
+ out = np.empty(idx.shape[0], dtype=object)
467
+ for r, row in enumerate(idx):
468
+ labels = y_sy[row]
469
+ uniq, first, cnt = np.unique(labels, return_index=True, return_counts=True)
470
+ best = np.lexsort((first, -cnt))[0] # most votes, then nearest
471
+ out[r] = uniq[best]
472
+ return out.astype(str)
473
+
474
+ lab, cnt = np.unique(y_sy, return_counts=True)
475
+ majority = lab[np.lexsort((lab, -cnt))[0]]
476
+ return AttributeResult(target, "categorical", qids, float((vote(i_tr) == y_tr).mean()),
477
+ float((vote(i_ho) == y_ho).mean()), float((y_ho == majority).mean()),
478
+ tr.height, ho.height)
479
+
480
+
481
+ def attribute_inference(train: pl.DataFrame, holdout: pl.DataFrame, synthetic: pl.DataFrame,
482
+ sensitive: list[str], quasi_ids: list[str] | None = None,
483
+ seed: int = 0, *, k: int = 1, max_rows: int = MAX_ROWS,
484
+ exclude: Sequence[str] = ()) -> AttributeInferenceResult:
485
+ """Nearest-neighbour attribute inference of each ``sensitive`` column.
486
+
487
+ The attacker fits a kNN classifier (categorical/boolean target, majority vote) or regressor
488
+ (numeric/temporal target, neighbour mean) on the synthetic rows, mapping quasi-identifiers
489
+ (default: every other shared column) to the sensitive column, and predicts it for train
490
+ members and holdout non-members. Numeric "accuracy" is the share of predictions within
491
+ ``0.1 x train std`` of the truth. Leakage is ``member - non-member`` accuracy; the
492
+ baseline is the synthetic majority class / mean evaluated on non-members.
493
+ """
494
+ _check_nonempty(train=train, holdout=holdout, synthetic=synthetic)
495
+ cols = _common_columns(train, holdout, synthetic, exclude=exclude)
496
+ m = min(train.height, holdout.height, max_rows)
497
+ tr = _subsample(train, m, stream(seed, "privacy", "attr", "train"))
498
+ ho = _subsample(holdout, m, stream(seed, "privacy", "attr", "holdout"))
499
+ sy = _subsample(synthetic, max_rows, stream(seed, "privacy", "attr", "synthetic"))
500
+ out = AttributeInferenceResult()
501
+ for target in sensitive:
502
+ if target not in cols:
503
+ out.skipped[target] = "column not present in all frames"
504
+ continue
505
+ qids = ([q for q in quasi_ids if q in cols and q != target] if quasi_ids is not None
506
+ else [c for c in cols if c != target])
507
+ if not qids:
508
+ out.skipped[target] = "no quasi-identifiers"
509
+ continue
510
+ r = _attribute_one(train, tr, ho, sy, target, qids, k)
511
+ if isinstance(r, str):
512
+ out.skipped[target] = r
513
+ else:
514
+ out.results.append(r)
515
+ return out
516
+
517
+
518
+ # ---------------------------------------------------------------------------------------------
519
+ # Suite
520
+ # ---------------------------------------------------------------------------------------------
521
+
522
+
523
+ def _resolve_synthetic(src: Any, n: int, seed: int
524
+ ) -> tuple[pl.DataFrame, list[str], list[str], list[str]]:
525
+ """(synthetic frame, columns to exclude, notes, pseudonymised columns among the excluded)
526
+ from a frame, Generator or fingerprint."""
527
+ if isinstance(src, pl.DataFrame):
528
+ return src, [], ["synthetic data supplied directly"], []
529
+ from ectype.fingerprint.core import Fingerprint
530
+ from ectype.generation.generator import Generator
531
+ from ectype.types import Role
532
+
533
+ if isinstance(src, Generator):
534
+ gen = src
535
+ elif isinstance(src, Fingerprint | str | Path):
536
+ gen = Generator.from_fingerprint(src)
537
+ else:
538
+ raise TypeError("run_privacy_suite needs a Fingerprint, Generator, path or a polars "
539
+ f"DataFrame of synthetic rows, not {type(src).__name__}")
540
+ syn = gen.generate(n, seed=seed)
541
+ cols = gen.fingerprint.manifest.columns
542
+ exclude = [c.name for c in cols
543
+ if c.role in (Role.IDENTIFIER, Role.EXCLUDED, Role.REFERENCE)]
544
+ notes = [f"generated {n} synthetic rows with seed {seed}"]
545
+ if exclude:
546
+ notes.append(f"identifier, reference-key and excluded columns not attacked "
547
+ f"(regenerated): {exclude}")
548
+ pseudonyms = [c.name for c in cols if c.role == Role.PSEUDONYM]
549
+ if pseudonyms:
550
+ # tokens never equal a source label: leaving the column in would add the same
551
+ # mismatch to every train and holdout distance and dilute the other columns' signal
552
+ notes.append(f"pseudonymised columns not attacked (synthetic rows carry stand-in "
553
+ f"tokens, never source values): {pseudonyms}")
554
+ return syn, exclude + pseudonyms, notes, pseudonyms
555
+
556
+
557
+ def run_privacy_suite(fp_or_generator: Any, train: pl.DataFrame, holdout: pl.DataFrame, *,
558
+ sensitive: list[str] | None = None, quasi_ids: list[str] | None = None,
559
+ n_synthetic: int | None = None, seed: int = 0,
560
+ max_rows: int = MAX_ROWS, n_bootstrap: int = 200,
561
+ exclude: Sequence[str] = ()) -> PrivacyReport:
562
+ """Run every attack and return a :class:`PrivacyReport`.
563
+
564
+ ``fp_or_generator`` is a Fingerprint, a path to a ``.dfp``, a Generator, or an already
565
+ generated synthetic DataFrame. When synthetic data has to be generated, ``n_synthetic``
566
+ defaults to ``train.height``. Attribute inference runs only when ``sensitive`` is given.
567
+ ``train`` must be the data the fingerprint was fitted on and ``holdout`` rows drawn from
568
+ the same population but never seen by the fit.
569
+
570
+ Identifier and excluded columns are left out (they are regenerated or absent), and so are
571
+ pseudonymised columns: their synthetic values are stand-in tokens that never equal a source
572
+ value, so they cannot match a real row and would only dilute the distances. The report's
573
+ notes list the columns left out. When synthetic rows are passed directly, name such columns
574
+ in ``exclude``.
575
+ """
576
+ _check_nonempty(train=train, holdout=holdout)
577
+ n = int(n_synthetic) if n_synthetic is not None else train.height
578
+ syn, auto_excl, notes, pseudonyms = _resolve_synthetic(fp_or_generator, n, seed)
579
+ excl = [*exclude, *auto_excl]
580
+ cols = _common_columns(train, holdout, syn, exclude=excl)
581
+ dcr = nn_distance_ratio(train, holdout, syn, seed, max_rows=max_rows, exclude=excl,
582
+ n_permutations=n_bootstrap)
583
+ mia = membership_inference(train, holdout, syn, seed, max_rows=max_rows,
584
+ n_bootstrap=n_bootstrap, exclude=excl)
585
+ attr = None
586
+ if sensitive:
587
+ attr = attribute_inference(train, holdout, syn, list(sensitive), quasi_ids, seed,
588
+ max_rows=max_rows, exclude=excl)
589
+ for col in pseudonyms:
590
+ if col in attr.skipped:
591
+ attr.skipped[col] = ("pseudonymised column: synthetic rows carry stand-in "
592
+ "tokens, so no source value can be inferred from them")
593
+ else:
594
+ notes.append("attribute inference not run: no sensitive columns given")
595
+ if train.height > max_rows or holdout.height > max_rows or syn.height > max_rows:
596
+ notes.append(f"frames subsampled to at most {max_rows} rows per side")
597
+ return PrivacyReport(dcr=dcr, mia=mia, attribute=attr, seed=seed, n_train=train.height,
598
+ n_holdout=holdout.height, n_synthetic=syn.height, columns=cols,
599
+ notes=notes)