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,265 @@
1
+ """Multivariate (data-requiring) metrics.
2
+
3
+ Design choice: ``multivariate.energy`` and ``multivariate.c2st`` are ``requires_data = True``.
4
+ A policy-safe *stored* summary that still supports these tests is not feasible (they need
5
+ row-level samples), so they are **excluded from stored targets** (``build_targets`` skips them)
6
+ and are used only when the validator has raw reference data (row-level holdout). Use
7
+ ``compare_samples(ref_df, syn_df, columns, rng) -> float`` instead of ``measure``/``distance``.
8
+
9
+ * ``multivariate.energy``: energy distance on numeric-like features standardized by the
10
+ reference (nulls -> 0 after standardization, plus missing indicators), each side subsampled
11
+ to at most 2000 rows; reported as the normalized energy coefficient
12
+ ``E / (2 E|X-Y|)`` in [0, 1]. Falls back to one-hot categoricals if there is no numeric column.
13
+ * ``multivariate.c2st``: classifier two-sample test. L2 logistic regression (numpy Newton/IRLS)
14
+ on standardized numeric and one-hot categorical features (categories from the reference,
15
+ policy pooled) **plus quadratic terms of the numeric features** (squares and pairwise
16
+ products of the first ``C2ST_MAX_QUADRATIC_BASE`` standardized numerics, clipped and
17
+ re-standardized), so the classifier sees variance and dependence differences and not only
18
+ mean shifts; 2-fold cross-validation, distance = max(0, AUC - 0.5) * 2.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from typing import Any, ClassVar, Literal
24
+
25
+ import numpy as np
26
+ import polars as pl
27
+ from scipy import stats
28
+ from scipy.spatial.distance import cdist
29
+
30
+ from ectype.fingerprint.disclosure import OTHER, POLICIES
31
+ from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
32
+ from ectype.validation.metrics.base import METRICS, Metric
33
+ from ectype.validation.metrics.missingness import null_mask
34
+ from ectype.validation.metrics.univariate import (
35
+ category_codes_from_data,
36
+ is_category,
37
+ is_numeric_like,
38
+ label_series,
39
+ numeric_values,
40
+ )
41
+
42
+ ENERGY_MAX_ROWS = 2000
43
+ C2ST_MAX_ROWS = 5000
44
+ MAX_ONE_HOT = 20
45
+ #: numeric base features expanded into squares and pairwise products for the C2ST classifier
46
+ C2ST_MAX_QUADRATIC_BASE = 30
47
+ #: standardized values are clipped to this before squaring, so outliers cannot dominate
48
+ _QUAD_CLIP = 6.0
49
+ #: extra L2 weight on the quadratic terms (many weak features: limit overfitting noise)
50
+ QUAD_PENALTY = 10.0
51
+
52
+
53
+ class _Featurizer:
54
+ """Reference-fitted feature map: standardized numerics (+ null flags), one-hot categoricals."""
55
+
56
+ def __init__(self, ref: pl.DataFrame, columns: list[ColumnSchema], *, numeric: bool,
57
+ categorical: bool, policy: DisclosurePolicySpec) -> None:
58
+ self.num: list[tuple[ColumnSchema, float, float, bool]] = []
59
+ self.cat: list[tuple[ColumnSchema, list[str], bool]] = []
60
+ for c in columns:
61
+ if numeric and is_numeric_like(c):
62
+ v = numeric_values(ref[c.name], c)
63
+ f = v[np.isfinite(v)]
64
+ mu = float(f.mean()) if f.size else 0.0
65
+ sd = float(f.std()) if f.size else 1.0
66
+ self.num.append((c, mu, sd if sd > 0 else 1.0, bool(np.isnan(v).any())))
67
+ elif categorical and is_category(c):
68
+ labels, _, _ = category_codes_from_data(ref[c.name], policy)
69
+ labels = labels[:MAX_ONE_HOT]
70
+ self.cat.append((c, labels, bool(null_mask(ref[c.name]).any())))
71
+
72
+ @property
73
+ def n_features(self) -> int:
74
+ return (sum(1 + int(h) for *_, h in self.num)
75
+ + sum(len(lb) + int(h) for _, lb, h in self.cat))
76
+
77
+ def numeric_positions(self) -> list[int]:
78
+ """Column positions of the standardized numeric values in :meth:`transform`."""
79
+ pos, i = [], 0
80
+ for *_, has_null in self.num:
81
+ pos.append(i)
82
+ i += 1 + int(has_null)
83
+ return pos
84
+
85
+ def transform(self, df: pl.DataFrame) -> np.ndarray:
86
+ cols: list[np.ndarray] = []
87
+ for c, mu, sd, has_null in self.num:
88
+ v = numeric_values(df[c.name], c)
89
+ nan = ~np.isfinite(v)
90
+ z = np.where(nan, 0.0, (v - mu) / sd)
91
+ cols.append(z)
92
+ if has_null:
93
+ cols.append(nan.astype(float))
94
+ for c, labels, has_null in self.cat:
95
+ lab = label_series(df[c.name]).to_numpy()
96
+ known = set(labels)
97
+ for lb in labels:
98
+ if lb == OTHER:
99
+ cols.append(np.array([x is not None and x not in known for x in lab],
100
+ dtype=float))
101
+ else:
102
+ cols.append((lab == lb).astype(float))
103
+ if has_null:
104
+ cols.append(np.array([x is None for x in lab], dtype=float))
105
+ if not cols:
106
+ return np.zeros((df.height, 0))
107
+ return np.column_stack(cols)
108
+
109
+
110
+ def _subsample(df: pl.DataFrame, m: int, rng: np.random.Generator) -> pl.DataFrame:
111
+ if df.height <= m:
112
+ return df
113
+ return df[np.sort(rng.choice(df.height, m, replace=False))]
114
+
115
+
116
+ class _DataMetric(Metric):
117
+ arity: ClassVar[Literal[1, 2, "all"]] = "all"
118
+ requires_data: ClassVar[bool] = True
119
+
120
+ @classmethod
121
+ def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
122
+ return any(is_numeric_like(c) or is_category(c) for c in columns)
123
+
124
+ def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
125
+ policy: DisclosurePolicySpec) -> Any:
126
+ raise NotImplementedError(
127
+ f"{self.kind} requires row-level data and has no stored summary; "
128
+ "use compare_samples(ref_df, syn_df, columns, rng)")
129
+
130
+ def distance(self, reference: Any, candidate: Any) -> float:
131
+ # values produced by compare_samples are already distances
132
+ return abs(float(candidate) - float(reference))
133
+
134
+ def noise_floor(self, df: pl.DataFrame, columns: list[ColumnSchema],
135
+ policy: DisclosurePolicySpec, rng: np.random.Generator,
136
+ n_boot: int = 20, sample_size: int | None = None) -> float:
137
+ """Distance between two disjoint random halves of ``df`` (median over a few splits)."""
138
+ ds = []
139
+ for _ in range(max(1, min(n_boot, 5))):
140
+ perm = rng.permutation(df.height)
141
+ h = df.height // 2
142
+ if sample_size is not None:
143
+ h = min(h, sample_size)
144
+ ds.append(self.compare_samples(df[perm[:h]], df[perm[h:2 * h]], columns, rng))
145
+ return float(np.median(ds))
146
+
147
+ def compare_samples(self, ref_df: pl.DataFrame, syn_df: pl.DataFrame,
148
+ columns: list[ColumnSchema], rng: np.random.Generator,
149
+ policy: DisclosurePolicySpec | None = None) -> float:
150
+ raise NotImplementedError
151
+
152
+
153
+ @METRICS.register()
154
+ class Energy(_DataMetric):
155
+ kind = "multivariate.energy"
156
+ family = "multivariate.energy"
157
+ default_tolerance = 0.02
158
+
159
+ def compare_samples(self, ref_df: pl.DataFrame, syn_df: pl.DataFrame,
160
+ columns: list[ColumnSchema], rng: np.random.Generator,
161
+ policy: DisclosurePolicySpec | None = None) -> float:
162
+ policy = policy or POLICIES["standard"]
163
+ a = _subsample(ref_df, ENERGY_MAX_ROWS, rng)
164
+ b = _subsample(syn_df, ENERGY_MAX_ROWS, rng)
165
+ feat = _Featurizer(a, columns, numeric=True, categorical=False, policy=policy)
166
+ if feat.n_features == 0:
167
+ feat = _Featurizer(a, columns, numeric=False, categorical=True, policy=policy)
168
+ x, y = feat.transform(a), feat.transform(b)
169
+ if x.shape[1] == 0 or x.shape[0] == 0 or y.shape[0] == 0:
170
+ return 0.0
171
+ exy = float(cdist(x, y).mean())
172
+ exx = float(cdist(x, x).mean())
173
+ eyy = float(cdist(y, y).mean())
174
+ if exy <= 0:
175
+ return 0.0
176
+ return float(max(0.0, (2 * exy - exx - eyy) / (2 * exy)))
177
+
178
+
179
+ def _fit_logistic(x: np.ndarray, y: np.ndarray, lam: float = 1e-2, iters: int = 25,
180
+ penalty: np.ndarray | None = None) -> np.ndarray:
181
+ """L2-penalised logistic regression via Newton's method; intercept in column 0.
182
+ ``penalty`` optionally multiplies the L2 weight per feature column."""
183
+ xb = np.column_stack([np.ones(len(x)), x])
184
+ w = np.zeros(xb.shape[1])
185
+ reg = np.full(xb.shape[1], lam * len(x) / 100.0 + 1e-6)
186
+ if penalty is not None:
187
+ reg[1:] *= penalty
188
+ reg[0] = 1e-8
189
+ for _ in range(iters):
190
+ z = np.clip(xb @ w, -30, 30)
191
+ p = 1.0 / (1.0 + np.exp(-z))
192
+ g = xb.T @ (p - y) + reg * w
193
+ h = (xb * (p * (1 - p))[:, None]).T @ xb + np.diag(reg)
194
+ try:
195
+ step = np.linalg.solve(h, g)
196
+ except np.linalg.LinAlgError:
197
+ step = np.linalg.lstsq(h, g, rcond=None)[0]
198
+ w -= step
199
+ if np.max(np.abs(step)) < 1e-6:
200
+ break
201
+ return w
202
+
203
+
204
+ def _quadratic(x: np.ndarray, positions: list[int]) -> np.ndarray:
205
+ """Append squares and pairwise products of the numeric columns at ``positions`` (at most
206
+ ``C2ST_MAX_QUADRATIC_BASE``), each centred and scaled over the pooled sample (label-blind)."""
207
+ pos = positions[:C2ST_MAX_QUADRATIC_BASE]
208
+ if not pos:
209
+ return x
210
+ z = np.clip(x[:, pos], -_QUAD_CLIP, _QUAD_CLIP)
211
+ k = z.shape[1]
212
+ iu, ju = np.triu_indices(k)
213
+ q = z[:, iu] * z[:, ju]
214
+ sd = q.std(axis=0)
215
+ keep = sd > 1e-12
216
+ q = (q[:, keep] - q[:, keep].mean(axis=0)) / sd[keep]
217
+ return np.hstack([x, q])
218
+
219
+
220
+ def _auc(score: np.ndarray, label: np.ndarray) -> float:
221
+ pos = label == 1
222
+ n1, n0 = int(pos.sum()), int((~pos).sum())
223
+ if n1 == 0 or n0 == 0:
224
+ return 0.5
225
+ r = stats.rankdata(score)
226
+ return float((r[pos].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))
227
+
228
+
229
+ @METRICS.register()
230
+ class C2ST(_DataMetric):
231
+ kind = "multivariate.c2st"
232
+ family = "multivariate.c2st"
233
+ default_tolerance = 0.05
234
+
235
+ def compare_samples(self, ref_df: pl.DataFrame, syn_df: pl.DataFrame,
236
+ columns: list[ColumnSchema], rng: np.random.Generator,
237
+ policy: DisclosurePolicySpec | None = None) -> float:
238
+ policy = policy or POLICIES["standard"]
239
+ m = min(ref_df.height, syn_df.height, C2ST_MAX_ROWS)
240
+ if m < 10:
241
+ return 0.0
242
+ a = _subsample(ref_df, m, rng)
243
+ b = _subsample(syn_df, m, rng)
244
+ feat = _Featurizer(a, columns, numeric=True, categorical=True, policy=policy)
245
+ if feat.n_features == 0:
246
+ return 0.0
247
+ x = np.vstack([feat.transform(a), feat.transform(b)])
248
+ n_lin = x.shape[1]
249
+ x = _quadratic(x, feat.numeric_positions())
250
+ penalty = np.ones(x.shape[1])
251
+ penalty[n_lin:] = QUAD_PENALTY
252
+ y = np.concatenate([np.zeros(a.height), np.ones(b.height)])
253
+ fold = np.zeros(len(y), dtype=int)
254
+ # stratified 2-fold split
255
+ for cls in (0, 1):
256
+ idx = np.flatnonzero(y == cls)
257
+ idx = rng.permutation(idx)
258
+ fold[idx[: len(idx) // 2]] = 1
259
+ score = np.zeros(len(y))
260
+ for k in (0, 1):
261
+ tr, te = fold != k, fold == k
262
+ w = _fit_logistic(x[tr], y[tr], penalty=penalty)
263
+ score[te] = np.column_stack([np.ones(int(te.sum())), x[te]]) @ w
264
+ auc = _auc(score, y)
265
+ return float(max(0.0, auc - 0.5) * 2.0)