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,492 @@
1
+ """Multivariate profiling: higher-order interaction screening and joint-model escalation.
2
+
3
+ * :func:`screen_interactions` looks for three-way interactions that pairwise dependence does
4
+ not explain. Each column is quantile-binned (columns with few distinct values keep their
5
+ values; missing values get their own bin) and the *interaction information*
6
+
7
+ II(a; b; c) = I(a; b | c) - I(a; b)
8
+ = H(ab) + H(ac) + H(bc) - H(a) - H(b) - H(c) - H(abc)
9
+
10
+ is estimated with Miller-Madow corrected plug-in entropies (nats). It is symmetric in
11
+ ``(a, b, c)``; a positive value means synergy (e.g. ``c = a XOR b``: every pair is
12
+ independent but ``I(a; b | c) = log 2``). Two references are used:
13
+
14
+ - a **permutation null** (``c`` permuted ``n_permutations`` times), giving a z-score and an
15
+ empirical p-value for ``II != 0``;
16
+ - the **pairwise-implied value**: II of data simulated from a Gaussian copula fitted to the
17
+ triple's normal scores and re-binned to the same marginal frequencies. Synergy that a
18
+ pairwise (copula) model already produces, such as a collider ``c = a + b``, is subtracted.
19
+
20
+ A triple is reported when its z-score exceeds the Bonferroni-corrected normal critical value
21
+ and its excess over the pairwise-implied II is at least ``min_effect`` nats. Triples are
22
+ pre-ranked by raw II (cheap) so at most ``max_triples`` get the permutation test.
23
+
24
+ * :func:`recommend_joint` is the escalation rule for the joint model: Gaussian copula,
25
+ Gaussian mixture copula and vine copula are fitted on a training split of the latent scores
26
+ and compared by held-out mean log-likelihood per row minus a BIC-style complexity penalty
27
+ ``k * log(n_train) / (2 * n_train)``. A richer model is recommended only if its penalised
28
+ score beats the Gaussian copula by more than ``max(margin, 2 * SE)``, where SE is the standard
29
+ error of the paired per-row log-likelihood difference on the held-out rows. (The forest
30
+ copula has a ``logpdf`` and may be passed explicitly, but its thousands of leaf parameters
31
+ never clear that penalty, so it is not a default candidate here.)
32
+
33
+ * :func:`select_joint_by_targets` is what ``Profiler(joint="auto")`` uses. Held-out latent
34
+ likelihood stopped tracking generated-data fidelity once the Gaussian copula's correlation
35
+ was estimated by rank-moment matching (that estimate is not the latent likelihood maximiser,
36
+ so the copula loses on likelihood while generating better data: on UCI credit the mixture
37
+ copula won the likelihood comparison yet passed 303/543 sealed targets against 385). The
38
+ selection therefore fits every candidate exactly as the profiler would, decodes a common
39
+ sample of ``min(n, 5000)`` rows from each, counts the **calibration** targets it passes
40
+ (sealed targets are never looked at) and measures its energy distance to the source rows
41
+ (which sees joint shape, such as mixture modes, that pairwise targets miss). It starts from
42
+ the *baseline*, the default joint model (``models.base.DEFAULT_JOINT``, the chain copula;
43
+ ADR-0015), and another model replaces it only if it is no worse on both and clearly better
44
+ on one. The candidates are :func:`auto_candidates`: the chain, Gaussian, mixture, vine and
45
+ forest copulas, as far as their modules are built-in plug-ins.
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import math
51
+ from collections.abc import Callable, Mapping
52
+ from itertools import combinations
53
+ from typing import Any
54
+
55
+ import numpy as np
56
+ import polars as pl
57
+ from scipy import special, stats
58
+
59
+ from ectype.fingerprint.disclosure import coarsen, resolve_policy
60
+ from ectype.fingerprint.schema import DisclosurePolicySpec
61
+ from ectype.models.base import DEFAULT_JOINT, JointModel
62
+ from ectype.models.chain import ChainCopula
63
+ from ectype.models.copulas import GaussianCopula, nearest_correlation
64
+ from ectype.models.forest import ForestCopula
65
+ from ectype.models.mixtures import GaussianMixtureCopula
66
+ from ectype.models.vines import VineCopula
67
+ from ectype.rng import stream
68
+
69
+ MAX_SCREEN_ROWS = 20_000
70
+
71
+
72
+ # ---------------------------------------------------------------------------------------------
73
+ # Interaction screening
74
+ # ---------------------------------------------------------------------------------------------
75
+
76
+ def _n_bins(n: int, policy: DisclosurePolicySpec) -> int:
77
+ per_cell = max(int(policy.rare_cell_min), 5)
78
+ return int(np.clip(math.floor((n / per_cell) ** (1.0 / 3.0)), 2, 5))
79
+
80
+
81
+ def _bin_column(x: np.ndarray, n_bins: int) -> np.ndarray:
82
+ x = np.asarray(x, dtype=np.float64)
83
+ finite = np.isfinite(x)
84
+ codes = np.zeros(len(x), dtype=np.int64)
85
+ if finite.any():
86
+ xf = x[finite]
87
+ uniq = np.unique(xf)
88
+ if len(uniq) <= n_bins:
89
+ codes[finite] = np.searchsorted(uniq, xf)
90
+ else:
91
+ cuts = np.unique(np.quantile(xf, np.linspace(0, 1, n_bins + 1)[1:-1]))
92
+ codes[finite] = np.searchsorted(cuts, xf, side="right")
93
+ if not finite.all():
94
+ codes[~finite] = np.max(codes[finite]) + 1 if finite.any() else 0
95
+ # re-index to 0..k-1
96
+ _, codes = np.unique(codes, return_inverse=True)
97
+ return codes.astype(np.int64)
98
+
99
+
100
+ def _entropy(codes: np.ndarray, n: int) -> float:
101
+ """Miller-Madow corrected plug-in entropy (nats) of integer codes."""
102
+ counts = np.bincount(codes)
103
+ counts = counts[counts > 0]
104
+ p = counts / n
105
+ return float(-np.sum(p * np.log(p)) + (len(counts) - 1) / (2.0 * n))
106
+
107
+
108
+ class _Triple:
109
+ """Entropy bookkeeping for one triple of binned columns."""
110
+
111
+ def __init__(self, a: np.ndarray, b: np.ndarray, c: np.ndarray) -> None:
112
+ self.n = len(a)
113
+ self.ka, self.kb, self.kc = int(a.max()) + 1, int(b.max()) + 1, int(c.max()) + 1
114
+ self.a, self.b = a, b
115
+ self.ab = a * self.kb + b
116
+ self.h_a, self.h_b = _entropy(a, self.n), _entropy(b, self.n)
117
+ self.h_ab = _entropy(self.ab, self.n)
118
+
119
+ def terms(self, c: np.ndarray) -> dict[str, float]:
120
+ n, kc = self.n, self.kc
121
+ h_c = _entropy(c, n)
122
+ h_ac = _entropy(self.a * kc + c, n)
123
+ h_bc = _entropy(self.b * kc + c, n)
124
+ h_abc = _entropy(self.ab * kc + c, n)
125
+ i_ab = self.h_a + self.h_b - self.h_ab
126
+ i_ac = self.h_a + h_c - h_ac
127
+ i_bc = self.h_b + h_c - h_bc
128
+ i_ab_c = h_ac + h_bc - h_abc - h_c
129
+ return {"I_ab": i_ab, "I_ac": i_ac, "I_bc": i_bc, "I_ab|c": i_ab_c,
130
+ "II": i_ab_c - i_ab}
131
+
132
+ def ii(self, c: np.ndarray) -> float:
133
+ return self.terms(c)["II"]
134
+
135
+
136
+ def _normal_scores(x: np.ndarray) -> np.ndarray:
137
+ x = np.asarray(x, dtype=np.float64)
138
+ out = np.zeros(len(x))
139
+ ok = np.isfinite(x)
140
+ if ok.sum() > 1:
141
+ r = stats.rankdata(x[ok])
142
+ out[ok] = special.ndtri((r - 0.5) / ok.sum())
143
+ return out
144
+
145
+
146
+ def _rebin_like(sim: np.ndarray, codes: np.ndarray) -> np.ndarray:
147
+ """Bin standard-normal draws so the bin frequencies match ``codes``'s."""
148
+ p = np.bincount(codes) / len(codes)
149
+ cuts = special.ndtri(np.clip(np.cumsum(p)[:-1], 1e-12, 1 - 1e-12))
150
+ return np.searchsorted(cuts, sim).astype(np.int64)
151
+
152
+
153
+ def _gaussian_implied_ii(scores: np.ndarray, codes: list[np.ndarray],
154
+ rng: np.random.Generator, reps: int = 2) -> float:
155
+ r = nearest_correlation(np.corrcoef(scores.T))
156
+ chol = np.linalg.cholesky(r)
157
+ n = scores.shape[0]
158
+ vals = []
159
+ for _ in range(reps):
160
+ sim = rng.standard_normal((n, 3)) @ chol.T
161
+ binned = [_rebin_like(sim[:, j], codes[j]) for j in range(3)]
162
+ vals.append(_Triple(binned[0], binned[1], binned[2]).ii(binned[2]))
163
+ return float(np.mean(vals))
164
+
165
+
166
+ def screen_interactions(df_values: np.ndarray, columns: list[str],
167
+ policy: DisclosurePolicySpec | str | None = None, seed: int = 0,
168
+ max_triples: int = 500, *, n_permutations: int = 49,
169
+ alpha: float = 0.05, min_effect: float = 0.01,
170
+ n_bins: int | None = None) -> list[dict[str, Any]]:
171
+ """Detect three-way interactions not explained by pairwise dependence.
172
+
173
+ ``df_values`` is an ``(n, p)`` numeric array (categoricals as integer codes, NaN for
174
+ missing). Returns one dict per detected triple, sorted by decreasing excess interaction
175
+ information::
176
+
177
+ {"columns": [a, b, c], "interaction_information": II, "pairwise_implied": II_gauss,
178
+ "excess": II - II_gauss, "z": z, "p_value": p, "n_bins": [ka, kb, kc],
179
+ "mutual_information": {"a|b": .., "a|c": .., "b|c": ..},
180
+ "conditional_mutual_information": {"a,b|c": .., "a,c|b": .., "b,c|a": ..}}
181
+
182
+ Values are in nats and coarsened by the policy.
183
+ """
184
+ policy = resolve_policy(policy)
185
+ x = np.asarray(df_values, dtype=np.float64)
186
+ if x.ndim != 2 or x.shape[1] != len(columns):
187
+ raise ValueError("df_values shape does not match columns")
188
+ n, p = x.shape
189
+ if p < 3 or n < 20:
190
+ return []
191
+ rng = stream(seed, "screen_interactions")
192
+ if n > MAX_SCREEN_ROWS:
193
+ x = x[np.sort(rng.choice(n, MAX_SCREEN_ROWS, replace=False))]
194
+ n = MAX_SCREEN_ROWS
195
+ k = n_bins or _n_bins(n, policy)
196
+ codes = [_bin_column(x[:, j], k) for j in range(p)]
197
+ usable = [j for j in range(p) if codes[j].max() >= 1]
198
+
199
+ # candidate triples (all, or a seeded random subset when there are too many)
200
+ n_cand = math.comb(len(usable), 3)
201
+ cap = 20 * max_triples
202
+ if n_cand <= cap:
203
+ triples = list(combinations(usable, 3))
204
+ else:
205
+ seen: set[tuple[int, int, int]] = set()
206
+ while len(seen) < cap:
207
+ t = tuple(sorted(int(v) for v in rng.choice(usable, 3, replace=False)))
208
+ seen.add(t) # type: ignore[arg-type]
209
+ triples = sorted(seen)
210
+
211
+ raw = []
212
+ for t in triples:
213
+ tr = _Triple(codes[t[0]], codes[t[1]], codes[t[2]])
214
+ ii = tr.ii(codes[t[2]])
215
+ if ii > min_effect:
216
+ raw.append((ii, t))
217
+ raw.sort(key=lambda r: (-r[0], r[1]))
218
+ raw = raw[:max_triples]
219
+ if not raw:
220
+ return []
221
+
222
+ z_crit = float(special.ndtri(1.0 - alpha / max(len(raw), 1)))
223
+ scores: dict[int, np.ndarray] = {}
224
+ found: list[dict[str, Any]] = []
225
+ for _, (ia, ib, ic) in raw:
226
+ tr = _Triple(codes[ia], codes[ib], codes[ic])
227
+ terms = tr.terms(codes[ic])
228
+ ii = terms["II"]
229
+ trng = stream(seed, "screen_interactions", "perm", ia, ib, ic)
230
+ null = np.array([tr.ii(codes[ic][trng.permutation(n)])
231
+ for _ in range(n_permutations)])
232
+ sd = float(null.std(ddof=1)) if n_permutations > 1 else 0.0
233
+ z = (ii - float(null.mean())) / max(sd, 1e-12)
234
+ p_val = (1.0 + float(np.sum(null >= ii))) / (n_permutations + 1.0)
235
+ for j in (ia, ib, ic):
236
+ if j not in scores:
237
+ scores[j] = _normal_scores(x[:, j])
238
+ implied = _gaussian_implied_ii(np.column_stack([scores[ia], scores[ib], scores[ic]]),
239
+ [codes[ia], codes[ib], codes[ic]],
240
+ stream(seed, "screen_interactions", "gauss", ia, ib, ic))
241
+ excess = ii - implied
242
+ if z < z_crit or excess < min_effect:
243
+ continue
244
+ # the other two conditional MIs follow from II's symmetry
245
+ i_ac_b = ii + terms["I_ac"]
246
+ i_bc_a = ii + terms["I_bc"]
247
+ a, b, c = columns[ia], columns[ib], columns[ic]
248
+
249
+ def _c(v: float) -> float:
250
+ return coarsen(float(v), policy)
251
+
252
+ found.append({
253
+ "columns": [a, b, c],
254
+ "interaction_information": _c(ii),
255
+ "pairwise_implied": _c(implied),
256
+ "excess": _c(excess),
257
+ "z": _c(min(z, 1e6)),
258
+ "p_value": _c(p_val),
259
+ "n_bins": [tr.ka, tr.kb, tr.kc],
260
+ "mutual_information": {f"{a}|{b}": _c(terms["I_ab"]), f"{a}|{c}": _c(terms["I_ac"]),
261
+ f"{b}|{c}": _c(terms["I_bc"])},
262
+ "conditional_mutual_information": {f"{a},{b}|{c}": _c(terms["I_ab|c"]),
263
+ f"{a},{c}|{b}": _c(i_ac_b),
264
+ f"{b},{c}|{a}": _c(i_bc_a)},
265
+ })
266
+ found.sort(key=lambda r: -r["excess"])
267
+ return found
268
+
269
+
270
+ # ---------------------------------------------------------------------------------------------
271
+ # Joint-model escalation
272
+ # ---------------------------------------------------------------------------------------------
273
+
274
+ def gaussian_copula_logpdf(model: GaussianCopula, z: np.ndarray) -> np.ndarray:
275
+ """Log density of latent scores under a Gaussian copula with N(0, 1) margins."""
276
+ d = z.shape[1]
277
+ chol = np.linalg.cholesky(model.corr)
278
+ sol = np.linalg.solve(chol, z.T)
279
+ return (-0.5 * np.sum(sol * sol, axis=0) - np.sum(np.log(np.diag(chol)))
280
+ - 0.5 * d * math.log(2 * math.pi))
281
+
282
+
283
+ def _logpdf(model: Any, z: np.ndarray) -> np.ndarray:
284
+ if isinstance(model, GaussianCopula):
285
+ return gaussian_copula_logpdf(model, z)
286
+ return np.asarray(model.logpdf(z), dtype=np.float64)
287
+
288
+
289
+ CANDIDATES: dict[str, type[JointModel]] = {"gaussian_copula": GaussianCopula,
290
+ "gaussian_mixture_copula": GaussianMixtureCopula,
291
+ "vine_copula": VineCopula,
292
+ "forest_copula": ForestCopula,
293
+ "chain_copula": ChainCopula}
294
+
295
+ #: Joint kinds :func:`select_joint_by_targets` fits only when ``candidates`` names them. None
296
+ #: at present: the chain copula was here until it became the default joint model and the
297
+ #: baseline of ``joint="auto"`` (ADR-0015).
298
+ OPT_IN_CANDIDATES: dict[str, type[JointModel]] = {}
299
+
300
+ #: ``recommend_joint`` ranks models by held-out likelihood minus a BIC-style penalty
301
+ #: ``k log(n) / (2 n)``. The forest copula stores thousands of leaf parameters and can never
302
+ #: clear that penalty, so by default only the parametric models are compared.
303
+ LIKELIHOOD_CANDIDATES: tuple[str, ...] = ("gaussian_copula", "gaussian_mixture_copula",
304
+ "vine_copula")
305
+
306
+
307
+ def auto_candidates() -> tuple[str, ...]:
308
+ """The joint kinds ``Profiler(joint="auto")`` compares (the default candidates of
309
+ :func:`select_joint_by_targets`): every entry of ``CANDIDATES`` whose module is a
310
+ built-in plug-in (``ectype.plugins``). A fresh process compiles a fingerprint only if
311
+ ``load_builtin_plugins`` registers its joint kind, so auto never chooses a model that
312
+ could not be loaded again; registering a module there makes its model a candidate."""
313
+ from ectype.plugins import _BUILTIN
314
+
315
+ return tuple(kind for kind, cls in CANDIDATES.items() if cls.__module__ in _BUILTIN)
316
+
317
+
318
+ def recommend_joint(z: np.ndarray, columns: list[str], seed: int = 0, *,
319
+ policy: DisclosurePolicySpec | str | None = None, margin: float = 0.01,
320
+ test_frac: float = 0.3, max_rows: int = 20_000,
321
+ candidates: tuple[str, ...] = LIKELIHOOD_CANDIDATES
322
+ ) -> tuple[str, dict[str, Any]]:
323
+ """Recommend a joint-model kind for latent scores ``z`` (n, d).
324
+
325
+ Returns ``(kind, diagnostics)``. ``diagnostics["models"][kind]`` holds the held-out mean
326
+ log-likelihood per row, the complexity penalty, the penalised score, the parameter count,
327
+ the improvement over the Gaussian copula, its standard error and whether it cleared the
328
+ escalation threshold.
329
+ """
330
+ policy = resolve_policy(policy)
331
+ z = np.asarray(z, dtype=np.float64)
332
+ n, d = z.shape if z.ndim == 2 else (0, 0)
333
+ base = "gaussian_copula"
334
+ diags: dict[str, Any] = {"baseline": base, "margin": margin, "models": {}}
335
+ if d < 2 or n < 50:
336
+ diags["reason"] = "too few rows or columns to compare"
337
+ return base, diags
338
+ rng = stream(seed, "recommend_joint")
339
+ if n > max_rows:
340
+ z = z[np.sort(rng.choice(n, max_rows, replace=False))]
341
+ n = max_rows
342
+ perm = rng.permutation(n)
343
+ n_test = max(int(round(n * test_frac)), 10)
344
+ test, train = z[perm[:n_test]], z[perm[n_test:]]
345
+ n_train = len(train)
346
+ kinds = [base] + [k for k in candidates if k != base and k in CANDIDATES]
347
+ ll: dict[str, np.ndarray] = {}
348
+ for kind in kinds:
349
+ model = CANDIDATES[kind].fit(train, list(columns), policy=policy,
350
+ rng=stream(seed, "recommend_joint", kind))
351
+ ll[kind] = _logpdf(model, test)
352
+ k = int(model.n_parameters)
353
+ penalty = k * math.log(n_train) / (2.0 * n_train)
354
+ mean_ll = float(np.mean(ll[kind]))
355
+ diags["models"][kind] = {"heldout_loglik": mean_ll, "penalty": penalty,
356
+ "score": mean_ll - penalty, "n_parameters": k}
357
+ best, best_score = base, diags["models"][base]["score"]
358
+ for kind in kinds[1:]:
359
+ info = diags["models"][kind]
360
+ diff = ll[kind] - ll[base]
361
+ se = float(diff.std(ddof=1) / math.sqrt(len(diff)))
362
+ gain = info["score"] - diags["models"][base]["score"]
363
+ threshold = max(margin, 2.0 * se)
364
+ info.update({"improvement": gain, "se": se, "threshold": threshold,
365
+ "eligible": bool(gain > threshold)})
366
+ if info["eligible"] and info["score"] > best_score:
367
+ best, best_score = kind, info["score"]
368
+ diags["chosen"] = best
369
+ return best, diags
370
+
371
+
372
+ def select_joint_by_targets(
373
+ z: np.ndarray, columns: list[str], decode: Callable[[np.ndarray], pl.DataFrame],
374
+ targets: list[Any], schemas: Mapping[str, Any], *, seed: int = 0,
375
+ policy: DisclosurePolicySpec | str | None = None,
376
+ reference: pl.DataFrame | None = None,
377
+ fit_rng: Callable[[str], np.random.Generator] | None = None,
378
+ fit_kwargs: Mapping[str, Mapping[str, Any]] | None = None,
379
+ candidates: tuple[str, ...] | None = None, n_sample: int = 5000,
380
+ min_gain: int = 3, rel_margin: float = 0.02, energy_gain: float = 0.25,
381
+ energy_abs: float = 0.002, baseline: str | None = None,
382
+ energy_slack: float = 0.0) -> tuple[str, JointModel, dict[str, Any]]:
383
+ """Choose the joint model by the fidelity of its generated sample.
384
+
385
+ ``candidates`` defaults to :func:`auto_candidates` (the chain copula takes the encoder's
386
+ ``atoms`` and ``values`` through ``fit_kwargs["chain_copula"]``). ``baseline`` is the
387
+ model that is kept unless another one clearly beats it, and is always fitted: by default
388
+ the default joint model (``DEFAULT_JOINT``; the Gaussian copula if that one's module is
389
+ not a built-in plug-in). Every candidate is fitted on all of
390
+ ``z`` with ``fit_rng(kind)`` and ``fit_kwargs[kind]`` (the forest copula, unless given its
391
+ own, gets the encoder moments in ``fit_kwargs["gaussian_copula"]``)
392
+ (so the returned model is the one an explicit ``joint=kind`` would fit), sampled with a
393
+ common random stream (``min(n, n_sample)`` rows), decoded by ``decode`` and scored on
394
+
395
+ * the number of calibration ``targets`` it passes (sealed targets are never used), and
396
+ * when ``reference`` (the source feature columns) is given, the energy distance of the
397
+ sample to it (``multivariate.energy``: the joint shape that pairwise targets miss, such
398
+ as the modes of a mixture). Nothing about it is stored.
399
+
400
+ With ``margin = max(min_gain, rel_margin * len(targets))``, a candidate beats the
401
+ baseline when it is no worse on either criterion (at most ``margin`` fewer targets passed;
402
+ energy not higher, give or take ``energy_slack``) and clearly better on one: more than
403
+ ``margin`` extra targets passed, or energy lower by a factor ``1 - energy_gain`` and by
404
+ more than ``energy_abs``. Among winners the most targets passed, then the lowest energy,
405
+ wins; otherwise the baseline is kept. Returns ``(kind, fitted model, diagnostics)``.
406
+
407
+ Both scores are noisy on a sample of this size: the energy distance of one model varies
408
+ by 0.00007 to 0.00015 (standard deviation over 8 samples of 5,000 rows on two benchmark
409
+ tables, where the distance itself is 0.0004 to 0.0013), and the count of targets passed
410
+ by a few. So the default is replaced only when the two agree: a model that passes more
411
+ targets must not be farther from the source in energy at all. (While the baseline was
412
+ the Gaussian copula, "no worse" allowed 10% + 0.001. Next to the chain copula's energies
413
+ that let the forest copula through on two of nine benchmark tables with an energy a
414
+ third to a half higher, and its data was easier to tell from real rows; ADR-0015.)
415
+ """
416
+ from ectype.fingerprint.targets import evaluate_target
417
+ from ectype.validation.metrics.multivariate import Energy
418
+
419
+ pol = resolve_policy(policy)
420
+ z = np.asarray(z, dtype=np.float64)
421
+ n = len(z)
422
+ pool = auto_candidates() if candidates is None else candidates
423
+ known = {**CANDIDATES, **OPT_IN_CANDIDATES}
424
+ if baseline is None:
425
+ baseline = DEFAULT_JOINT if DEFAULT_JOINT in auto_candidates() else "gaussian_copula"
426
+ if baseline not in known:
427
+ raise ValueError(f"unknown baseline joint model {baseline!r}")
428
+ base = baseline
429
+ kinds = [base] + [k for k in pool if k != base and k in known]
430
+ kw = dict(fit_kwargs or {})
431
+ # the forest copula mixes its draws back with the rank-moment correlation when it gets
432
+ # the encoder moments the Gaussian copula is fitted with
433
+ if "forest_copula" in kinds and "forest_copula" not in kw:
434
+ kw["forest_copula"] = {k: v for k, v in dict(kw.get("gaussian_copula", {})).items()
435
+ if k in ("attenuation", "hermite")}
436
+ m = int(max(1, min(n, n_sample)))
437
+ margin = float(max(min_gain, rel_margin * len(targets)))
438
+ diags: dict[str, Any] = {"method": "calibration_targets+energy", "baseline": base,
439
+ "n_sample": m, "n_targets": len(targets), "margin": margin,
440
+ "energy_slack": energy_slack, "models": {}}
441
+ ref_cols = ([schemas[c] for c in reference.columns if c in schemas]
442
+ if reference is not None else [])
443
+ fitted: dict[str, JointModel] = {}
444
+ passed: dict[str, int] = {}
445
+ energy: dict[str, float | None] = {}
446
+ for kind in kinds:
447
+ rng = fit_rng(kind) if fit_rng is not None else stream(seed, "joint", kind)
448
+ try:
449
+ model = known[kind].fit(z, list(columns), policy=pol, rng=rng,
450
+ **dict(kw.get(kind, {})))
451
+ sample = decode(model.sample(m, stream(seed, "joint_selection", "sample")))
452
+ except Exception as exc: # noqa: BLE001 - a candidate that fails is not chosen
453
+ if kind == base:
454
+ raise
455
+ diags["models"][kind] = {"error": f"{type(exc).__name__}: {exc}"}
456
+ continue
457
+ ok = 0
458
+ for t in targets:
459
+ try:
460
+ ok += int(evaluate_target(t, sample, dict(schemas), pol)[1])
461
+ except Exception: # noqa: BLE001 - an unmeasurable target counts as failed
462
+ pass
463
+ e: float | None = None
464
+ if reference is not None and ref_cols:
465
+ try:
466
+ e = float(Energy().compare_samples(
467
+ reference, sample, ref_cols, stream(seed, "joint_selection", "energy"),
468
+ pol))
469
+ except Exception: # noqa: BLE001 - no energy score: judged on targets alone
470
+ e = None
471
+ fitted[kind], passed[kind], energy[kind] = model, ok, e
472
+ diags["models"][kind] = {"calibration_passed": ok, "energy": e,
473
+ "n_parameters": int(model.n_parameters)}
474
+ best = base
475
+ e0 = energy[base]
476
+ for kind in kinds[1:]:
477
+ if kind not in passed:
478
+ continue
479
+ gain = passed[kind] - passed[base]
480
+ ek = energy[kind]
481
+ e_better, e_ok = False, True
482
+ if e0 is not None and ek is not None:
483
+ e_better = ek < (1.0 - energy_gain) * e0 and e0 - ek > energy_abs
484
+ e_ok = ek <= e0 + energy_slack
485
+ wins = gain >= -margin and e_ok and (gain > margin or e_better)
486
+ diags["models"][kind].update({"gain": gain, "energy_better": bool(e_better),
487
+ "eligible": bool(wins)})
488
+ if wins and (best == base or (passed[kind], -(ek or 0.0))
489
+ > (passed[best], -(energy[best] or 0.0))):
490
+ best = kind
491
+ diags["chosen"] = best
492
+ return best, fitted[best], diags