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
ectype/privacy/dp.py ADDED
@@ -0,0 +1,313 @@
1
+ """Differential-privacy building blocks for marginals and the copula (M29, optional DP mode).
2
+
3
+ .. important::
4
+ **Full-pipeline DP fitting is NOT wired into the Profiler in this release.** The functions
5
+ here are tested building blocks only. A fingerprint fitted by :class:`~ectype.
6
+ profiler.Profiler` under the ``strict``/``standard``/``research`` disclosure policies is not
7
+ differentially private and never claims to be. The coordinator will integrate these
8
+ mechanisms behind a separate ``"dp"`` policy type later; that integration must route every
9
+ data-dependent fitting step (structural stats, marginals, correlation, targets) through one
10
+ :class:`PrivacyAccountant` and record ε, δ and the accountant log in the manifest.
11
+
12
+ Adjacency model
13
+ ---------------
14
+ All mechanisms assume **add/remove-one-row** adjacency, with the row count ``n`` treated as
15
+ public (it is recorded in every manifest). Per-mechanism sensitivities:
16
+
17
+ * :func:`dp_categorical`: histogram counts, L1 sensitivity 1 -> Laplace(1/ε).
18
+ * :func:`dp_quantiles`: histogram over fixed, data-independent ``bounds``; L1 sensitivity 1
19
+ -> Laplace(1/ε). Values outside ``bounds`` are clipped first (the bounds must be public).
20
+ * :func:`dp_correlation`: rows are clipped to L2 norm ``clip``; the unnormalized second-moment
21
+ matrix ``sum x x^T`` then has L2 (Frobenius) sensitivity ``clip**2`` -> Gaussian mechanism
22
+ with σ calibrated by the analytic Gaussian mechanism (Balle & Wang 2018): the smallest σ
23
+ whose exact privacy curve meets the target δ at ε, valid for every ε > 0.
24
+
25
+ Everything after the noise (clipping counts at zero, normalizing, inverting the CDF,
26
+ projecting to the nearest positive-definite correlation) is post-processing and costs no
27
+ budget. Budgets compose by **basic sequential composition** (ε and δ add up) in
28
+ :class:`PrivacyAccountant`.
29
+
30
+ Sampling uses in-engine inverse CDFs on ``rng.random`` draws (no global RNG state).
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import math
36
+ from dataclasses import dataclass, field
37
+ from typing import Any
38
+
39
+ import numpy as np
40
+ from scipy import special
41
+
42
+ from ectype.errors import PolicyError
43
+ from ectype.models.copulas import nearest_correlation
44
+
45
+ ADJACENCY = "add/remove one row; row count n treated as public"
46
+
47
+ __all__ = [
48
+ "ADJACENCY",
49
+ "BudgetExceededError",
50
+ "PrivacyAccountant",
51
+ "dp_categorical",
52
+ "dp_correlation",
53
+ "dp_quantiles",
54
+ "gaussian_delta",
55
+ "gaussian_sigma",
56
+ "laplace_noise",
57
+ ]
58
+
59
+
60
+ class BudgetExceededError(PolicyError):
61
+ """A spend would exceed the accountant's ε or δ budget."""
62
+
63
+
64
+ # ---------------------------------------------------------------------------------------------
65
+ # Accountant
66
+ # ---------------------------------------------------------------------------------------------
67
+
68
+
69
+ @dataclass
70
+ class PrivacyAccountant:
71
+ """Basic sequential composition: total ε = Σ ε_i, total δ = Σ δ_i.
72
+
73
+ :meth:`spend` checks the budget *before* recording, so a mechanism that would overspend
74
+ raises :class:`BudgetExceededError` and must not release its output.
75
+ """
76
+
77
+ epsilon: float
78
+ delta: float = 0.0
79
+ log: list[dict[str, Any]] = field(default_factory=list)
80
+ adjacency: str = ADJACENCY
81
+ _tol: float = 1e-12
82
+
83
+ def __post_init__(self) -> None:
84
+ if not (self.epsilon > 0 and math.isfinite(self.epsilon)):
85
+ raise ValueError("epsilon budget must be a positive finite number")
86
+ if not (0.0 <= self.delta < 1.0):
87
+ raise ValueError("delta budget must be in [0, 1)")
88
+
89
+ @property
90
+ def spent_epsilon(self) -> float:
91
+ return float(sum(e["epsilon"] for e in self.log))
92
+
93
+ @property
94
+ def spent_delta(self) -> float:
95
+ return float(sum(e["delta"] for e in self.log))
96
+
97
+ @property
98
+ def remaining_epsilon(self) -> float:
99
+ return max(0.0, self.epsilon - self.spent_epsilon)
100
+
101
+ @property
102
+ def remaining_delta(self) -> float:
103
+ return max(0.0, self.delta - self.spent_delta)
104
+
105
+ def can_spend(self, epsilon: float, delta: float = 0.0) -> bool:
106
+ return (self.spent_epsilon + epsilon <= self.epsilon + self._tol
107
+ and self.spent_delta + delta <= self.delta + self._tol)
108
+
109
+ def spend(self, epsilon: float, delta: float = 0.0, *, label: str = "",
110
+ mechanism: str = "") -> None:
111
+ _check_eps(epsilon)
112
+ if delta < 0:
113
+ raise ValueError("delta must be >= 0")
114
+ if not self.can_spend(epsilon, delta):
115
+ raise BudgetExceededError(
116
+ f"privacy budget exceeded by {label or mechanism or 'operation'!r}: "
117
+ f"spent ε={self.spent_epsilon:.6g}, δ={self.spent_delta:.3g}; requested "
118
+ f"ε={epsilon:.6g}, δ={delta:.3g}; budget ε={self.epsilon:.6g}, "
119
+ f"δ={self.delta:.3g}")
120
+ self.log.append({"label": label, "mechanism": mechanism, "epsilon": float(epsilon),
121
+ "delta": float(delta)})
122
+
123
+ def to_dict(self) -> dict[str, Any]:
124
+ return {"composition": "basic_sequential", "adjacency": self.adjacency,
125
+ "epsilon_budget": self.epsilon, "delta_budget": self.delta,
126
+ "epsilon_spent": self.spent_epsilon, "delta_spent": self.spent_delta,
127
+ "log": [dict(e) for e in self.log]}
128
+
129
+
130
+ def _check_eps(epsilon: float) -> None:
131
+ if not (isinstance(epsilon, int | float) and epsilon > 0 and math.isfinite(epsilon)):
132
+ raise ValueError(f"epsilon must be a positive finite number, got {epsilon!r}")
133
+
134
+
135
+ def _charge(acc: PrivacyAccountant | None, eps: float, delta: float, label: str | None,
136
+ mechanism: str) -> None:
137
+ if acc is not None:
138
+ acc.spend(eps, delta, label=label or mechanism, mechanism=mechanism)
139
+
140
+
141
+ # ---------------------------------------------------------------------------------------------
142
+ # Noise
143
+ # ---------------------------------------------------------------------------------------------
144
+
145
+
146
+ def laplace_noise(scale: float, size: int | tuple[int, ...], rng: np.random.Generator
147
+ ) -> np.ndarray:
148
+ """Laplace(0, scale) by inverse CDF."""
149
+ u = rng.random(size) - 0.5
150
+ return -scale * np.sign(u) * np.log1p(-2.0 * np.abs(u))
151
+
152
+
153
+ def gaussian_delta(sensitivity: float, sigma: float, epsilon: float) -> float:
154
+ """Exact δ(ε) of the Gaussian mechanism with L2 sensitivity Δ and noise scale σ
155
+ (Balle & Wang 2018, Theorem 8)::
156
+
157
+ δ = Φ(Δ/(2σ) - εσ/Δ) - e^ε Φ(-Δ/(2σ) - εσ/Δ)
158
+
159
+ The second term is evaluated in log space (``log_ndtr``) so large ε does not overflow.
160
+ """
161
+ a = sensitivity / (2.0 * sigma)
162
+ b = epsilon * sigma / sensitivity
163
+ first = float(special.ndtr(a - b))
164
+ second = math.exp(min(epsilon + float(special.log_ndtr(-a - b)), 700.0))
165
+ return max(0.0, first - second)
166
+
167
+
168
+ def gaussian_sigma(sensitivity: float, epsilon: float, delta: float) -> float:
169
+ """Noise scale of the **analytic Gaussian mechanism** (Balle & Wang 2018).
170
+
171
+ Returns (up to bisection tolerance, rounded up) the smallest σ whose exact privacy curve
172
+ satisfies ``gaussian_delta(Δ, σ, ε) <= δ``. Unlike the classical bound
173
+ ``Δ sqrt(2 ln(1.25/δ)) / ε``, this is valid for every ε > 0 (including ε > 1) and is
174
+ never larger than the classical scale where that one applies.
175
+ """
176
+ _check_eps(epsilon)
177
+ if not (0.0 < delta < 1.0):
178
+ raise ValueError("the Gaussian mechanism needs 0 < delta < 1")
179
+ if not (sensitivity > 0 and math.isfinite(sensitivity)):
180
+ raise ValueError("sensitivity must be a positive finite number")
181
+ # δ(σ) decreases monotonically in σ; bracket then bisect (in log σ)
182
+ hi = sensitivity
183
+ while gaussian_delta(sensitivity, hi, epsilon) > delta:
184
+ hi *= 2.0
185
+ lo = hi / 2.0
186
+ while lo > 1e-300 and gaussian_delta(sensitivity, lo, epsilon) <= delta:
187
+ hi, lo = lo, lo / 2.0
188
+ for _ in range(200):
189
+ mid = math.sqrt(lo * hi)
190
+ if mid <= lo or mid >= hi:
191
+ break
192
+ if gaussian_delta(sensitivity, mid, epsilon) <= delta:
193
+ hi = mid
194
+ else:
195
+ lo = mid
196
+ return hi # the upper end always satisfies the δ condition
197
+
198
+
199
+ # ---------------------------------------------------------------------------------------------
200
+ # Mechanisms
201
+ # ---------------------------------------------------------------------------------------------
202
+
203
+
204
+ def dp_categorical(counts: np.ndarray, epsilon: float, rng: np.random.Generator, *,
205
+ accountant: PrivacyAccountant | None = None, label: str | None = None
206
+ ) -> np.ndarray:
207
+ """ε-DP category probabilities from histogram counts.
208
+
209
+ Adds Laplace(1/ε) noise to each count (L1 sensitivity 1 under add/remove-one), clips at
210
+ zero and normalizes. If every noisy count is zero the result is uniform. The *category
211
+ list* must be public (e.g. a declared domain); releasing data-derived labels is not
212
+ covered by this mechanism.
213
+ """
214
+ _check_eps(epsilon)
215
+ c = np.asarray(counts, dtype=np.float64)
216
+ if c.ndim != 1 or c.size == 0:
217
+ raise ValueError("counts must be a non-empty 1-D array")
218
+ if np.any(c < 0) or not np.all(np.isfinite(c)):
219
+ raise ValueError("counts must be finite and non-negative")
220
+ _charge(accountant, epsilon, 0.0, label, "laplace_histogram")
221
+ noisy = np.maximum(c + laplace_noise(1.0 / epsilon, c.size, rng), 0.0)
222
+ tot = noisy.sum()
223
+ return noisy / tot if tot > 0 else np.full(c.size, 1.0 / c.size)
224
+
225
+
226
+ def dp_quantiles(x: np.ndarray, levels: np.ndarray, epsilon: float,
227
+ bounds: tuple[float, float], rng: np.random.Generator, *, n_bins: int = 64,
228
+ accountant: PrivacyAccountant | None = None, label: str | None = None
229
+ ) -> np.ndarray:
230
+ """ε-DP quantiles at probability ``levels`` via a noisy histogram over public ``bounds``.
231
+
232
+ Values are clipped to ``bounds`` and binned into ``n_bins`` equal-width bins; Laplace(1/ε)
233
+ noise is added to the counts (one row changes one count by 1), which are clipped at zero,
234
+ and the piecewise-linear CDF is inverted. Output is non-decreasing and inside ``bounds``.
235
+ NaNs are dropped (their count is not released). Resolution is at best one bin width.
236
+ """
237
+ _check_eps(epsilon)
238
+ lo, hi = float(bounds[0]), float(bounds[1])
239
+ if not (math.isfinite(lo) and math.isfinite(hi) and lo < hi):
240
+ raise ValueError("bounds must be finite with lo < hi")
241
+ if n_bins < 1:
242
+ raise ValueError("n_bins must be >= 1")
243
+ q = np.asarray(levels, dtype=np.float64)
244
+ if np.any((q < 0) | (q > 1)) or not np.all(np.isfinite(q)):
245
+ raise ValueError("levels must lie in [0, 1]")
246
+ _charge(accountant, epsilon, 0.0, label, "laplace_histogram_quantiles")
247
+ v = np.asarray(x, dtype=np.float64)
248
+ v = np.clip(v[np.isfinite(v)], lo, hi)
249
+ edges = np.linspace(lo, hi, n_bins + 1)
250
+ counts, _ = np.histogram(v, bins=edges)
251
+ noisy = np.maximum(counts + laplace_noise(1.0 / epsilon, n_bins, rng), 0.0)
252
+ tot = noisy.sum()
253
+ if tot <= 0:
254
+ noisy, tot = np.ones(n_bins), float(n_bins)
255
+ cdf = np.concatenate([[0.0], np.cumsum(noisy) / tot])
256
+ cdf[-1] = 1.0
257
+ # invert: for empty bins the CDF is flat; take the leftmost edge reaching level q
258
+ # (np.interp needs strictly increasing xp, so search explicitly)
259
+ j = np.clip(np.searchsorted(cdf, q, side="left"), 1, n_bins)
260
+ c0, c1 = cdf[j - 1], cdf[j]
261
+ w = np.where(c1 > c0, (q - c0) / np.where(c1 > c0, c1 - c0, 1.0), 0.0)
262
+ out = edges[j - 1] + np.clip(w, 0.0, 1.0) * (edges[j] - edges[j - 1])
263
+ out = np.clip(out, lo, hi)
264
+ order = np.argsort(q, kind="stable")
265
+ out[order] = np.maximum.accumulate(out[order]) # monotone in the level
266
+ return out
267
+
268
+
269
+ def dp_correlation(z: np.ndarray, epsilon: float, rng: np.random.Generator, *,
270
+ delta: float = 1e-6, clip: float | None = None,
271
+ accountant: PrivacyAccountant | None = None, label: str | None = None
272
+ ) -> np.ndarray:
273
+ """(ε, δ)-DP correlation matrix of latent scores ``z`` (n x d).
274
+
275
+ Each row is scaled down to L2 norm at most ``clip`` (default ``2 sqrt(d)``, which leaves
276
+ most standard-normal rows intact; scaling keeps a row's direction). The second-moment
277
+ matrix ``S = sum x x^T`` then has Frobenius sensitivity ``clip**2``; symmetric Gaussian
278
+ noise (upper triangle incl. diagonal, mirrored) with :func:`gaussian_sigma` is added.
279
+ Post-processing: divide by the public ``n``, convert covariance to correlation and project
280
+ to the nearest positive-definite correlation matrix.
281
+ """
282
+ _check_eps(epsilon)
283
+ a = np.asarray(z, dtype=np.float64)
284
+ if a.ndim != 2 or a.shape[0] < 1:
285
+ raise ValueError("z must be a 2-D array with at least one row")
286
+ if not np.all(np.isfinite(a)):
287
+ raise ValueError("z must be finite")
288
+ n, d = a.shape
289
+ if d == 0:
290
+ return np.zeros((0, 0))
291
+ c = float(clip) if clip is not None else 2.0 * math.sqrt(d)
292
+ if c <= 0:
293
+ raise ValueError("clip must be positive")
294
+ sigma = gaussian_sigma(c * c, epsilon, delta)
295
+ _charge(accountant, epsilon, delta, label, "gaussian_second_moment")
296
+ norms = np.linalg.norm(a, axis=1)
297
+ a = a * np.minimum(1.0, c / np.maximum(norms, 1e-300))[:, None]
298
+ s = a.T @ a
299
+ iu = np.triu_indices(d)
300
+ noise = np.zeros((d, d))
301
+ noise[iu] = sigma * special.ndtri(_open_unit(rng, len(iu[0])))
302
+ noise = noise + np.triu(noise, 1).T
303
+ cov = (s + noise) / n
304
+ dg = np.sqrt(np.maximum(np.diag(cov), 1e-12))
305
+ r = cov / np.outer(dg, dg)
306
+ r = np.clip(r, -1.0, 1.0)
307
+ np.fill_diagonal(r, 1.0)
308
+ return nearest_correlation(r)
309
+
310
+
311
+ def _open_unit(rng: np.random.Generator, n: int) -> np.ndarray:
312
+ u = rng.random(n)
313
+ return np.clip(u, np.finfo(float).tiny, 1.0 - np.finfo(float).eps)
@@ -0,0 +1,364 @@
1
+ """Privacy attack results and the :class:`PrivacyReport`.
2
+
3
+ Every number in this report is an **empirical attack result**: the measured success of a
4
+ specific set of attacks (distance-to-closest-record, distance-based membership inference and
5
+ nearest-neighbour attribute inference) against one synthetic sample. These are evidence about
6
+ disclosure risk, **not formal privacy guarantees**. A "low" risk level means these particular
7
+ attacks did not succeed; stronger attacks may. Formal guarantees require differential privacy
8
+ with a stated adjacency model, mechanism and budget (see :mod:`ectype.privacy.dp`).
9
+
10
+ Risk levels
11
+ -----------
12
+ :data:`RISK_THRESHOLDS` holds the documented cut-offs. The overall level is the worst level
13
+ triggered by any single indicator:
14
+
15
+ ====================================== ============== ==========
16
+ indicator elevated if high if
17
+ ====================================== ============== ==========
18
+ MIA AUC (and its 95% CI low > 0.5) >= 0.60 >= 0.70
19
+ MIA advantage (max TPR - FPR) >= 0.15 >= 0.30
20
+ excess exact-match rate (train-holdout) >= 0.01 >= 0.05
21
+ DCR closer-to-train share >= 0.60 >= 0.75
22
+ DCR median ratio (train / holdout) <= 0.85 <= 0.50
23
+ attribute-inference accuracy gap >= 0.10 >= 0.25
24
+ ====================================== ============== ==========
25
+
26
+ Each of the four MIA/DCR indicators only triggers when it lies beyond the ``NULL_QUANTILE``
27
+ (``1 - 0.05 / 4``, a Bonferroni split of 5% over the four) of a permutation null: the MIA AUC
28
+ and advantage under shuffled member labels (the AUC also needs its bootstrap CI to exclude
29
+ 0.5), the closer-to-train share and the DCR median ratio under random re-splits of the pooled
30
+ train and holdout rows. Small-sample noise on tiny leak-free tables therefore raises the level
31
+ in about 5% of draws at most, not in every fourth. Exact-match rates are measured against
32
+ size-matched train and holdout references; when the sizes differ, the excess only counts
33
+ when it exceeds the subsampling noise bound.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from dataclasses import dataclass, field
39
+ from typing import Any
40
+
41
+ from ectype.validation.report import (
42
+ ReportShell,
43
+ _fmt,
44
+ esc,
45
+ html_table,
46
+ meta_list,
47
+ stats_row,
48
+ )
49
+
50
+ DISCLAIMER = ("These are empirical attack results against one synthetic sample, not formal "
51
+ "privacy guarantees. A low risk level means these specific attacks did not "
52
+ "succeed; it does not prove the data is anonymous. Only a differential-privacy "
53
+ "mechanism with stated adjacency, budget and accounting gives a formal guarantee.")
54
+
55
+ RISK_LEVELS = ("low", "elevated", "high")
56
+
57
+ #: indicator -> (elevated threshold, high threshold, direction). ``">="`` means larger values
58
+ #: are riskier; ``"<="`` means smaller values are riskier.
59
+ RISK_THRESHOLDS: dict[str, tuple[float, float, str]] = {
60
+ "mia_auc": (0.60, 0.70, ">="),
61
+ "mia_advantage": (0.15, 0.30, ">="),
62
+ "excess_exact_match_rate": (0.01, 0.05, ">="),
63
+ "closer_to_train_share": (0.60, 0.75, ">="),
64
+ "dcr_median_ratio": (0.85, 0.50, "<="),
65
+ "attribute_gap": (0.10, 0.25, ">="),
66
+ }
67
+
68
+
69
+ #: one-sided quantile of the permutation nulls gating the MIA AUC, MIA advantage, DCR
70
+ #: closer-to-train share and DCR median ratio: each test at 5% / 4 keeps the chance that *any*
71
+ #: of the four fires on leak-free data at about 5% or less.
72
+ NULL_QUANTILE = 1.0 - 0.05 / 4
73
+
74
+
75
+ def _level(name: str, value: float | None) -> str:
76
+ if value is None:
77
+ return "low"
78
+ elevated, high, direction = RISK_THRESHOLDS[name]
79
+ if direction == ">=":
80
+ return "high" if value >= high else "elevated" if value >= elevated else "low"
81
+ return "high" if value <= high else "elevated" if value <= elevated else "low"
82
+
83
+
84
+ # ---------------------------------------------------------------------------------------------
85
+ # Attack results
86
+ # ---------------------------------------------------------------------------------------------
87
+
88
+
89
+ @dataclass
90
+ class DCRResult:
91
+ """Distance to closest record from synthetic rows to train versus to holdout."""
92
+
93
+ median_ratio: float # median of DCR_train / DCR_holdout (1 = no leakage)
94
+ closer_to_train_share: float # share with DCR_train < DCR_holdout (ties count 1/2)
95
+ exact_match_rate: float # synthetic rows identical to some train row
96
+ holdout_exact_match_rate: float # same against holdout: the "natural" duplicate rate
97
+ median_dcr_train: float
98
+ median_dcr_holdout: float
99
+ n_reference: int # rows per side (train and holdout, equal)
100
+ n_synthetic: int
101
+ #: one-sided 95% noise bound of the excess exact-match rate when train and holdout sizes
102
+ #: differ (0 when they are equal and no subsampling noise exists)
103
+ exact_match_noise: float = 0.0
104
+ #: ``NULL_QUANTILE`` upper quantile of the closer-to-train share and lower quantile of the
105
+ #: median ratio under the permutation null (None: not computed)
106
+ closer_share_null: float | None = None
107
+ median_ratio_null: float | None = None
108
+
109
+ @property
110
+ def closer_share_significant(self) -> bool:
111
+ """The closer-to-train share exceeds its permutation null (True when not computed)."""
112
+ return self.closer_share_null is None or self.closer_to_train_share > self.closer_share_null
113
+
114
+ @property
115
+ def median_ratio_significant(self) -> bool:
116
+ """The median ratio lies below its permutation null (True when not computed)."""
117
+ return self.median_ratio_null is None or self.median_ratio < self.median_ratio_null
118
+
119
+ @property
120
+ def excess_exact_match_rate(self) -> float:
121
+ return max(0.0, self.exact_match_rate - self.holdout_exact_match_rate)
122
+
123
+ def to_dict(self) -> dict[str, Any]:
124
+ return {
125
+ "median_ratio": self.median_ratio,
126
+ "closer_to_train_share": self.closer_to_train_share,
127
+ "exact_match_rate": self.exact_match_rate,
128
+ "holdout_exact_match_rate": self.holdout_exact_match_rate,
129
+ "excess_exact_match_rate": self.excess_exact_match_rate,
130
+ "exact_match_noise": self.exact_match_noise,
131
+ "closer_share_null": self.closer_share_null,
132
+ "median_ratio_null": self.median_ratio_null,
133
+ "median_dcr_train": self.median_dcr_train,
134
+ "median_dcr_holdout": self.median_dcr_holdout,
135
+ "n_reference": self.n_reference,
136
+ "n_synthetic": self.n_synthetic,
137
+ }
138
+
139
+
140
+ @dataclass
141
+ class MIAResult:
142
+ """Distance-based membership inference: score = -DCR(candidate, synthetic)."""
143
+
144
+ auc: float
145
+ advantage: float # max over thresholds of TPR - FPR
146
+ auc_ci: tuple[float, float] # bootstrap 95% percentile interval
147
+ n_members: int
148
+ n_nonmembers: int
149
+ n_bootstrap: int
150
+ #: 95th percentile of the advantage under a label-permutation null (None: not computed)
151
+ advantage_null_q95: float | None = None
152
+ #: ``NULL_QUANTILE`` quantiles of the advantage and the AUC under the same null; these
153
+ #: gate the indicators (None: not computed)
154
+ advantage_null: float | None = None
155
+ auc_null: float | None = None
156
+
157
+ @property
158
+ def advantage_significant(self) -> bool:
159
+ """The advantage exceeds what label noise alone produces (always True when the
160
+ permutation null was not computed)."""
161
+ gate = self.advantage_null if self.advantage_null is not None else self.advantage_null_q95
162
+ return gate is None or self.advantage > gate
163
+
164
+ @property
165
+ def auc_significant(self) -> bool:
166
+ """The bootstrap CI excludes 0.5 and the AUC exceeds its permutation null (the latter
167
+ always holds when the null was not computed)."""
168
+ return self.auc_ci[0] > 0.5 and (self.auc_null is None or self.auc > self.auc_null)
169
+
170
+ def to_dict(self) -> dict[str, Any]:
171
+ return {"auc": self.auc, "advantage": self.advantage, "auc_ci": list(self.auc_ci),
172
+ "advantage_null_q95": self.advantage_null_q95,
173
+ "advantage_null": self.advantage_null, "auc_null": self.auc_null,
174
+ "n_members": self.n_members, "n_nonmembers": self.n_nonmembers,
175
+ "n_bootstrap": self.n_bootstrap}
176
+
177
+
178
+ @dataclass
179
+ class AttributeResult:
180
+ """Nearest-neighbour attribute inference of one sensitive column."""
181
+
182
+ column: str
183
+ kind: str # "categorical" or "numeric"
184
+ quasi_ids: list[str]
185
+ member_accuracy: float
186
+ nonmember_accuracy: float
187
+ baseline_accuracy: float # majority class / synthetic mean, on non-members
188
+ n_members: int
189
+ n_nonmembers: int
190
+ tolerance: float | None = None # numeric hit tolerance (0.1 x train std)
191
+
192
+ @property
193
+ def gap(self) -> float:
194
+ return self.member_accuracy - self.nonmember_accuracy
195
+
196
+ def to_dict(self) -> dict[str, Any]:
197
+ return {"column": self.column, "kind": self.kind, "quasi_ids": list(self.quasi_ids),
198
+ "member_accuracy": self.member_accuracy,
199
+ "nonmember_accuracy": self.nonmember_accuracy,
200
+ "baseline_accuracy": self.baseline_accuracy, "gap": self.gap,
201
+ "tolerance": self.tolerance, "n_members": self.n_members,
202
+ "n_nonmembers": self.n_nonmembers}
203
+
204
+
205
+ @dataclass
206
+ class AttributeInferenceResult:
207
+ results: list[AttributeResult] = field(default_factory=list)
208
+ skipped: dict[str, str] = field(default_factory=dict)
209
+
210
+ @property
211
+ def max_gap(self) -> float | None:
212
+ return max((r.gap for r in self.results), default=None)
213
+
214
+ def to_dict(self) -> dict[str, Any]:
215
+ return {"max_gap": self.max_gap, "columns": [r.to_dict() for r in self.results],
216
+ "skipped": dict(self.skipped)}
217
+
218
+
219
+ # ---------------------------------------------------------------------------------------------
220
+ # Report
221
+ # ---------------------------------------------------------------------------------------------
222
+
223
+
224
+ @dataclass
225
+ class PrivacyReport(ReportShell):
226
+ """Results of :func:`ectype.privacy.attacks.run_privacy_suite`."""
227
+
228
+ dcr: DCRResult
229
+ mia: MIAResult
230
+ attribute: AttributeInferenceResult | None = None
231
+ seed: int = 0
232
+ n_train: int = 0
233
+ n_holdout: int = 0
234
+ n_synthetic: int = 0
235
+ columns: list[str] = field(default_factory=list)
236
+ notes: list[str] = field(default_factory=list)
237
+ title: str = "Privacy attack report"
238
+
239
+ # -- risk ------------------------------------------------------------------------------
240
+ def indicators(self) -> dict[str, float | None]:
241
+ auc = self.mia.auc if self.mia.auc_significant else None
242
+ adv = self.mia.advantage if self.mia.advantage_significant else None
243
+ excess = self.dcr.excess_exact_match_rate
244
+ exact = excess if excess > self.dcr.exact_match_noise or excess == 0 else None
245
+ return {
246
+ "mia_auc": auc,
247
+ "mia_advantage": adv,
248
+ "excess_exact_match_rate": exact,
249
+ "closer_to_train_share": (self.dcr.closer_to_train_share
250
+ if self.dcr.closer_share_significant else None),
251
+ "dcr_median_ratio": (self.dcr.median_ratio
252
+ if self.dcr.median_ratio_significant else None),
253
+ "attribute_gap": self.attribute.max_gap if self.attribute else None,
254
+ }
255
+
256
+ def indicator_levels(self) -> dict[str, str]:
257
+ return {k: _level(k, v) for k, v in self.indicators().items()}
258
+
259
+ @property
260
+ def risk_level(self) -> str:
261
+ levels = self.indicator_levels().values()
262
+ return max(levels, key=RISK_LEVELS.index, default="low")
263
+
264
+ @property
265
+ def risk_reasons(self) -> list[str]:
266
+ """One line per indicator above ``low``: its value, the threshold it crossed, its level."""
267
+ out = []
268
+ ind = self.indicators()
269
+ for k, lvl in self.indicator_levels().items():
270
+ if lvl != "low":
271
+ elevated, high, direction = RISK_THRESHOLDS[k]
272
+ thr = high if lvl == "high" else elevated
273
+ out.append(f"{k} = {_fmt(ind[k])} ({direction} {thr}: {lvl})")
274
+ return out
275
+
276
+ # -- serialization ---------------------------------------------------------------------
277
+ def to_dict(self, verbose: bool = False) -> dict[str, Any]:
278
+ d: dict[str, Any] = {
279
+ "kind": "privacy_report",
280
+ "disclaimer": DISCLAIMER,
281
+ "formal_guarantee": False,
282
+ "risk_level": self.risk_level,
283
+ "risk_reasons": self.risk_reasons,
284
+ "thresholds": {k: {"elevated": e, "high": h, "direction": dr}
285
+ for k, (e, h, dr) in RISK_THRESHOLDS.items()},
286
+ "seed": self.seed,
287
+ "n_train": self.n_train,
288
+ "n_holdout": self.n_holdout,
289
+ "n_synthetic": self.n_synthetic,
290
+ "columns": list(self.columns),
291
+ "nn_distance_ratio": self.dcr.to_dict(),
292
+ "membership_inference": self.mia.to_dict(),
293
+ "attribute_inference": self.attribute.to_dict() if self.attribute else None,
294
+ "notes": list(self.notes),
295
+ }
296
+ if verbose:
297
+ d["indicators"] = self.indicators()
298
+ d["indicator_levels"] = self.indicator_levels()
299
+ return d
300
+
301
+ def summary(self) -> str:
302
+ m, c = self.mia, self.dcr
303
+ lines = [
304
+ f"Privacy attack report: risk {self.risk_level.upper()} "
305
+ f"(train={self.n_train}, holdout={self.n_holdout}, synthetic={self.n_synthetic})",
306
+ f" membership inference: AUC {m.auc:.3f} [{m.auc_ci[0]:.3f}, {m.auc_ci[1]:.3f}], "
307
+ f"advantage {m.advantage:.3f}",
308
+ f" DCR: median train/holdout ratio {c.median_ratio:.3f}, closer-to-train share "
309
+ f"{c.closer_to_train_share:.3f}, exact matches {c.exact_match_rate:.2%} "
310
+ f"(holdout baseline {c.holdout_exact_match_rate:.2%})",
311
+ ]
312
+ if self.attribute is not None:
313
+ for r in self.attribute.results:
314
+ lines.append(f" attribute '{r.column}': member acc {r.member_accuracy:.3f}, "
315
+ f"non-member {r.nonmember_accuracy:.3f}, baseline "
316
+ f"{r.baseline_accuracy:.3f}, gap {r.gap:+.3f}")
317
+ for col, why in self.attribute.skipped.items():
318
+ lines.append(f" attribute '{col}': skipped ({why})")
319
+ for reason in self.risk_reasons:
320
+ lines.append(f" ! {reason}")
321
+ lines.append(f" Note: {DISCLAIMER}")
322
+ return "\n".join(lines)
323
+
324
+ def _html_body(self) -> tuple[str, str]:
325
+ lvl = self.risk_level
326
+ cls = {"low": "ok", "elevated": "warn", "high": "bad"}[lvl]
327
+ m, c = self.mia, self.dcr
328
+ parts = [
329
+ f'<p><span class="pill {cls}">risk: {esc(lvl)}</span></p>',
330
+ f'<p class="muted"><strong>{esc(DISCLAIMER)}</strong></p>',
331
+ stats_row({"MIA AUC": f"{m.auc:.3f}", "MIA advantage": f"{m.advantage:.3f}",
332
+ "exact matches": f"{c.exact_match_rate:.2%}",
333
+ "DCR ratio": f"{c.median_ratio:.3f}"}),
334
+ "<h2>Risk indicators</h2>",
335
+ ]
336
+ ind, levels = self.indicators(), self.indicator_levels()
337
+ rows = []
338
+ for k, (e, h, dr) in RISK_THRESHOLDS.items():
339
+ lc = {"low": "ok", "elevated": "warn", "high": "bad"}[levels[k]]
340
+ rows.append([f"<code>{esc(k)}</code>", _fmt(ind[k]), esc(f"{dr} {e}"),
341
+ esc(f"{dr} {h}"), f'<span class="pill {lc}">{esc(levels[k])}</span>'])
342
+ parts.append(html_table(["indicator", "value", "elevated", "high", "level"], rows,
343
+ numeric={1}))
344
+ parts.append("<h2>Membership inference (distance-based)</h2>")
345
+ parts.append(meta_list({k: v for k, v in m.to_dict().items()}))
346
+ parts.append("<h2>Distance to closest record</h2>")
347
+ parts.append(meta_list({k: _fmt(v) if isinstance(v, float) else v
348
+ for k, v in c.to_dict().items()}))
349
+ if self.attribute is not None:
350
+ parts.append("<h2>Attribute inference (nearest neighbour)</h2>")
351
+ arows = [[esc(r.column), esc(r.kind), _fmt(r.member_accuracy),
352
+ _fmt(r.nonmember_accuracy), _fmt(r.baseline_accuracy), _fmt(r.gap)]
353
+ for r in self.attribute.results]
354
+ parts.append(html_table(["column", "kind", "member acc", "non-member acc",
355
+ "baseline", "gap"], arows, numeric={2, 3, 4, 5},
356
+ empty="No sensitive columns evaluated."))
357
+ for col, why in self.attribute.skipped.items():
358
+ parts.append(f'<p class="muted">{esc(col)}: skipped ({esc(why)})</p>')
359
+ if self.notes:
360
+ parts.append("<h2>Notes</h2><ul>" + "".join(f"<li>{esc(n)}</li>"
361
+ for n in self.notes) + "</ul>")
362
+ sub = (f"seed {self.seed} · train {self.n_train} · holdout {self.n_holdout} · "
363
+ f"synthetic {self.n_synthetic} · empirical attacks, not a formal guarantee")
364
+ return sub, "".join(parts)