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.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
ectype/models/copulas.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Joint models over latent standard-normal scores.
|
|
2
|
+
|
|
3
|
+
* ``GaussianCopula`` (kind ``"gaussian_copula"``): correlation of the latent normal scores
|
|
4
|
+
(Pearson on normal scores, i.e. a rank-based "normal-scores" estimate), Ledoit-Wolf shrinkage
|
|
5
|
+
toward the identity, nearest positive-definite correction (eigenvalue clipping, then rescale
|
|
6
|
+
to unit diagonal) and coarsening to the policy's significant digits. Sampling uses the
|
|
7
|
+
Cholesky factor and ``rng.standard_normal``.
|
|
8
|
+
* ``IndependentJoint`` (kind ``"independent"``): the independence baseline.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from ectype.fingerprint.core import ArrayStore
|
|
18
|
+
from ectype.fingerprint.disclosure import coarsen, coarsen_array
|
|
19
|
+
from ectype.fingerprint.schema import DisclosurePolicySpec, ModelSpec
|
|
20
|
+
from ectype.models.base import JOINTS, JointModel
|
|
21
|
+
|
|
22
|
+
MIN_EIGENVALUE = 1e-6
|
|
23
|
+
#: a latent column whose observed mid-rank variance, relative to a continuous column's 1/12,
|
|
24
|
+
#: times the row count (its effective sample size) is below this carries no estimable
|
|
25
|
+
#: correlation (constant, or fully determined by its CPT parent): its pairs get ``rho = 0``
|
|
26
|
+
MIN_EFFECTIVE_N = 10.0
|
|
27
|
+
#: without a row count, the relative mid-rank variance below which a column gets ``rho = 0``
|
|
28
|
+
MIN_RELATIVE_VARIANCE = 1e-3
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _check_z(z: np.ndarray, columns: list[str]) -> np.ndarray:
|
|
32
|
+
z = np.asarray(z, dtype=np.float64)
|
|
33
|
+
if z.ndim != 2 or z.shape[1] != len(columns):
|
|
34
|
+
raise ValueError(f"latent array shape {z.shape} does not match {len(columns)} columns")
|
|
35
|
+
if not np.all(np.isfinite(z)):
|
|
36
|
+
raise ValueError("latent array contains non-finite values")
|
|
37
|
+
return z
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _standardize(z: np.ndarray) -> np.ndarray:
|
|
41
|
+
x = z - z.mean(axis=0)
|
|
42
|
+
sd = x.std(axis=0)
|
|
43
|
+
ok = sd > 0
|
|
44
|
+
return np.where(ok, x / np.where(ok, sd, 1.0), 0.0)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def sample_correlation(z: np.ndarray) -> np.ndarray:
|
|
48
|
+
"""Pearson correlation of the columns of ``z``; constant columns get zero correlation."""
|
|
49
|
+
n, d = z.shape
|
|
50
|
+
x = _standardize(z)
|
|
51
|
+
s = x.T @ x / max(n, 1)
|
|
52
|
+
np.fill_diagonal(s, 1.0)
|
|
53
|
+
return s
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def ledoit_wolf_correlation(z: np.ndarray) -> tuple[np.ndarray, float]:
|
|
57
|
+
"""Ledoit-Wolf shrinkage of the sample correlation toward the identity.
|
|
58
|
+
|
|
59
|
+
Columns are standardised and the target is ``I``. Returns ``(R, shrinkage)``.
|
|
60
|
+
"""
|
|
61
|
+
n, d = z.shape
|
|
62
|
+
if d == 0:
|
|
63
|
+
return np.zeros((0, 0)), 0.0
|
|
64
|
+
if n < 2:
|
|
65
|
+
return np.eye(d), 1.0
|
|
66
|
+
x = _standardize(z)
|
|
67
|
+
s_raw = x.T @ x / n
|
|
68
|
+
s = s_raw.copy()
|
|
69
|
+
np.fill_diagonal(s, 1.0)
|
|
70
|
+
target = np.eye(d)
|
|
71
|
+
delta2 = float(np.sum((s - target) ** 2))
|
|
72
|
+
if delta2 <= 0:
|
|
73
|
+
return target, 0.0
|
|
74
|
+
# sum_k ||x_k x_k' - S||_F^2 = sum_k ||x_k||^4 - n ||S||_F^2
|
|
75
|
+
sq = np.sum(x * x, axis=1)
|
|
76
|
+
beta2 = float((np.sum(sq ** 2) - n * np.sum(s_raw ** 2)) / n ** 2)
|
|
77
|
+
beta2 = min(max(beta2, 0.0), delta2)
|
|
78
|
+
lam = beta2 / delta2
|
|
79
|
+
return (1.0 - lam) * s + lam * target, lam
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def nearest_correlation(r: np.ndarray, min_eig: float = MIN_EIGENVALUE) -> np.ndarray:
|
|
83
|
+
"""Clip eigenvalues at ``min_eig`` and rescale to unit diagonal (symmetric, PD)."""
|
|
84
|
+
r = 0.5 * (r + r.T)
|
|
85
|
+
w, v = np.linalg.eigh(r)
|
|
86
|
+
if w.min() < min_eig:
|
|
87
|
+
r = (v * np.maximum(w, min_eig)) @ v.T
|
|
88
|
+
dg = np.sqrt(np.clip(np.diag(r), 1e-300, None))
|
|
89
|
+
r = r / np.outer(dg, dg)
|
|
90
|
+
r = 0.5 * (r + r.T)
|
|
91
|
+
np.fill_diagonal(r, 1.0)
|
|
92
|
+
return r
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def rank_invert(target: np.ndarray, coef: np.ndarray, *, n: int | None = None,
|
|
96
|
+
bound: float = 0.999, iterations: int = 60) -> np.ndarray:
|
|
97
|
+
"""Per-pair latent correlations ``rho`` with ``sum_k coef_ik coef_jk rho^k = target_ij``.
|
|
98
|
+
|
|
99
|
+
``coef`` / ``target`` come from ``encoding.LatentMoments`` (mid-rank Hermite coefficients
|
|
100
|
+
and observed mid-rank covariances), so this is a tie-aware Spearman inversion: for two
|
|
101
|
+
continuous columns it reduces to ``rho = 2 sin(pi rho_S / 6)``, for discrete or
|
|
102
|
+
categorical pairs it is the moment form of the polychoric / polyserial correlation. Each
|
|
103
|
+
entry is solved by vectorised bisection on ``[0, +-bound]``; a target beyond the series'
|
|
104
|
+
reach clips to ``+-bound``. Pairs involving a column whose mid-rank variance is negligible
|
|
105
|
+
(constant, or fully determined by its CPT parent) get ``rho = 0``: its effective sample
|
|
106
|
+
size ``n * 12 * min(var_coef, var_observed)`` is below ``MIN_EFFECTIVE_N`` (``n`` = fit
|
|
107
|
+
rows), or without ``n`` its relative variance is below ``MIN_RELATIVE_VARIANCE``. Such a
|
|
108
|
+
column's covariances are noise divided by near-zero coefficients.
|
|
109
|
+
"""
|
|
110
|
+
b = np.asarray(coef, dtype=np.float64)
|
|
111
|
+
t = np.asarray(target, dtype=np.float64)
|
|
112
|
+
k = b.shape[1]
|
|
113
|
+
c = b[:, None, :] * b[None, :, :] # (d, d, K)
|
|
114
|
+
sign = np.where(t < 0, -1.0, 1.0)
|
|
115
|
+
goal = np.abs(t)
|
|
116
|
+
|
|
117
|
+
def series(rho: np.ndarray) -> np.ndarray:
|
|
118
|
+
x = sign * rho
|
|
119
|
+
acc = np.zeros_like(rho)
|
|
120
|
+
for j in range(k - 1, -1, -1): # Horner, powers 1..K
|
|
121
|
+
acc = (acc + c[:, :, j]) * x
|
|
122
|
+
return sign * acc
|
|
123
|
+
|
|
124
|
+
lo, hi = np.zeros_like(goal), np.full_like(goal, bound)
|
|
125
|
+
reach = series(hi)
|
|
126
|
+
for _ in range(iterations):
|
|
127
|
+
mid = 0.5 * (lo + hi)
|
|
128
|
+
below = series(mid) < goal
|
|
129
|
+
lo = np.where(below, mid, lo)
|
|
130
|
+
hi = np.where(below, hi, mid)
|
|
131
|
+
rho = np.where(reach <= goal, bound, 0.5 * (lo + hi)) * sign
|
|
132
|
+
rel = 12.0 * np.minimum(np.sum(b * b, axis=1), np.clip(np.diag(t), 0.0, None))
|
|
133
|
+
weak = rel * n < MIN_EFFECTIVE_N if n is not None else rel < MIN_RELATIVE_VARIANCE
|
|
134
|
+
rho = np.where(weak[:, None] | weak[None, :], 0.0, rho)
|
|
135
|
+
np.fill_diagonal(rho, 1.0)
|
|
136
|
+
return 0.5 * (rho + rho.T)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _safe_cholesky(r: np.ndarray) -> np.ndarray:
|
|
140
|
+
try:
|
|
141
|
+
return np.linalg.cholesky(r)
|
|
142
|
+
except np.linalg.LinAlgError:
|
|
143
|
+
return np.linalg.cholesky(nearest_correlation(r, 1e-4))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@JOINTS.register()
|
|
147
|
+
class GaussianCopula(JointModel):
|
|
148
|
+
kind = "gaussian_copula"
|
|
149
|
+
|
|
150
|
+
def __init__(self, columns: list[str], corr: np.ndarray, shrinkage: float = 0.0) -> None:
|
|
151
|
+
self.columns = list(columns)
|
|
152
|
+
self.corr = np.asarray(corr, dtype=np.float64)
|
|
153
|
+
if self.corr.shape != (len(self.columns), len(self.columns)):
|
|
154
|
+
raise ValueError("correlation matrix does not match columns")
|
|
155
|
+
self.shrinkage = float(shrinkage)
|
|
156
|
+
self._chol = _safe_cholesky(self.corr) if self.columns else np.zeros((0, 0))
|
|
157
|
+
|
|
158
|
+
@classmethod
|
|
159
|
+
def fit(cls, z: np.ndarray, columns: list[str], *, policy: DisclosurePolicySpec,
|
|
160
|
+
rng: np.random.Generator | None = None,
|
|
161
|
+
shrinkage: str | float = "ledoit_wolf",
|
|
162
|
+
attenuation: np.ndarray | None = None,
|
|
163
|
+
hermite: Any = None) -> GaussianCopula:
|
|
164
|
+
"""Fit to latent normal scores.
|
|
165
|
+
|
|
166
|
+
``shrinkage`` is ``"ledoit_wolf"`` (default), ``"dn"`` (``lambda = min(1, d/n)``) or a
|
|
167
|
+
fixed intensity in ``[0, 1]``. ``attenuation`` (one factor in ``(0, 1]`` per column,
|
|
168
|
+
e.g. ``MixedEncoder.latent_attenuation``) de-attenuates correlations involving
|
|
169
|
+
jittered discrete/categorical/missing-imputed scores as ``r_ij / (a_i * a_j)``, clipped
|
|
170
|
+
to ``[-0.999, 0.999]`` before the positive-definite correction.
|
|
171
|
+
|
|
172
|
+
When rank moments are available -- ``hermite`` is an ``encoding.LatentMoments``, or
|
|
173
|
+
``attenuation`` is ``MixedEncoder.latent_attenuation`` of a freshly fitted encoder,
|
|
174
|
+
which carries them -- the correlations are instead estimated per pair by
|
|
175
|
+
:func:`rank_invert` (tie-aware Spearman / polychoric-type moment matching) and then
|
|
176
|
+
shrunk with the same intensity. The first-order product over-corrects pairs of
|
|
177
|
+
heavily tied columns and divides noise by ~0 for near-deterministic CPT children.
|
|
178
|
+
"""
|
|
179
|
+
z = _check_z(z, columns)
|
|
180
|
+
n, d = z.shape
|
|
181
|
+
if shrinkage == "ledoit_wolf":
|
|
182
|
+
r, lam = ledoit_wolf_correlation(z)
|
|
183
|
+
else:
|
|
184
|
+
lam = min(1.0, d / max(n, 1)) if shrinkage == "dn" else float(shrinkage)
|
|
185
|
+
if not 0.0 <= lam <= 1.0:
|
|
186
|
+
raise ValueError("shrinkage intensity must be in [0, 1]")
|
|
187
|
+
r = (1.0 - lam) * sample_correlation(z) + lam * np.eye(d)
|
|
188
|
+
moments = hermite if hermite is not None else getattr(attenuation, "moments", None)
|
|
189
|
+
if moments is not None and d:
|
|
190
|
+
coef = np.asarray(moments.coef, dtype=np.float64)
|
|
191
|
+
target = np.asarray(moments.target, dtype=np.float64)
|
|
192
|
+
if coef.ndim != 2 or coef.shape[0] != d or target.shape != (d, d) or not (np.all(np.isfinite(coef)) and np.all(np.isfinite(target))):
|
|
193
|
+
raise ValueError("rank moments must be a finite (d, K) / (d, d) pair")
|
|
194
|
+
r = (1.0 - lam) * rank_invert(target, coef, n=n) + lam * np.eye(d)
|
|
195
|
+
elif attenuation is not None and d:
|
|
196
|
+
a = np.asarray(attenuation, dtype=np.float64)
|
|
197
|
+
if a.shape != (d,) or not np.all(np.isfinite(a)) or np.any(a <= 0):
|
|
198
|
+
raise ValueError("attenuation must be d positive finite factors")
|
|
199
|
+
a = np.minimum(a, 1.0)
|
|
200
|
+
r = np.clip(r / np.outer(a, a), -0.999, 0.999)
|
|
201
|
+
np.fill_diagonal(r, 1.0)
|
|
202
|
+
if d:
|
|
203
|
+
r = nearest_correlation(r)
|
|
204
|
+
r = coarsen_array(r, policy)
|
|
205
|
+
np.fill_diagonal(r, 1.0)
|
|
206
|
+
r = 0.5 * (r + r.T)
|
|
207
|
+
if np.linalg.eigvalsh(r).min() < MIN_EIGENVALUE * 0.5:
|
|
208
|
+
r = nearest_correlation(r)
|
|
209
|
+
return cls(columns, r, coarsen(float(lam), policy) if lam else 0.0)
|
|
210
|
+
|
|
211
|
+
def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
|
|
212
|
+
d = len(self.columns)
|
|
213
|
+
e = rng.standard_normal((n, d))
|
|
214
|
+
return e @ self._chol.T if d else e
|
|
215
|
+
|
|
216
|
+
@property
|
|
217
|
+
def n_parameters(self) -> int:
|
|
218
|
+
d = len(self.columns)
|
|
219
|
+
return d * (d - 1) // 2
|
|
220
|
+
|
|
221
|
+
def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
|
|
222
|
+
ref = store.put(f"{prefix}correlation", self.corr)
|
|
223
|
+
params: dict[str, Any] = {"columns": list(self.columns), "shrinkage": self.shrinkage}
|
|
224
|
+
return ModelSpec(kind=self.kind, params=params, arrays={"correlation": ref})
|
|
225
|
+
|
|
226
|
+
@classmethod
|
|
227
|
+
def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> GaussianCopula:
|
|
228
|
+
cols = [str(c) for c in spec.params.get("columns", [])] # type: ignore[union-attr]
|
|
229
|
+
corr = np.asarray(store.get(spec.arrays["correlation"]), dtype=np.float64)
|
|
230
|
+
return cls(cols, corr, float(spec.params.get("shrinkage", 0.0))) # type: ignore[arg-type]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@JOINTS.register()
|
|
234
|
+
class IndependentJoint(JointModel):
|
|
235
|
+
kind = "independent"
|
|
236
|
+
|
|
237
|
+
def __init__(self, columns: list[str]) -> None:
|
|
238
|
+
self.columns = list(columns)
|
|
239
|
+
|
|
240
|
+
@classmethod
|
|
241
|
+
def fit(cls, z: np.ndarray, columns: list[str], *, policy: DisclosurePolicySpec,
|
|
242
|
+
rng: np.random.Generator | None = None) -> IndependentJoint:
|
|
243
|
+
_check_z(z, columns)
|
|
244
|
+
return cls(columns)
|
|
245
|
+
|
|
246
|
+
def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
|
|
247
|
+
return rng.standard_normal((n, len(self.columns)))
|
|
248
|
+
|
|
249
|
+
def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
|
|
250
|
+
return ModelSpec(kind=self.kind, params={"columns": list(self.columns)})
|
|
251
|
+
|
|
252
|
+
@classmethod
|
|
253
|
+
def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> IndependentJoint:
|
|
254
|
+
return cls([str(c) for c in spec.params.get("columns", [])]) # type: ignore[union-attr]
|