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
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""Gaussian mixture copula (kind ``"gaussian_mixture_copula"``).
|
|
2
|
+
|
|
3
|
+
A K-component, full-covariance Gaussian mixture is fitted to the latent standard-normal scores
|
|
4
|
+
with EM written in numpy (diagonal regularisation ``reg_covar``). K is chosen from
|
|
5
|
+
``1..max_k`` by a held-out BIC: each candidate is fitted on a training split and scored as
|
|
6
|
+
``-2 * (n_train / n_test) * LL_test + p_K * log(n_train)``. The chosen K is refitted on all
|
|
7
|
+
rows. Components whose support (``weight * n``) is below ``policy.min_category_support`` are a
|
|
8
|
+
disclosure risk: they are dropped and EM is re-run on the survivors, which absorb their mass.
|
|
9
|
+
|
|
10
|
+
Sampling picks a component, draws from its Gaussian and then **re-standardises** every latent
|
|
11
|
+
dimension through the mixture's marginal CDF (a mixture of normals) and ``Phi^-1``. The output
|
|
12
|
+
marginals are therefore exactly N(0, 1): the model is the *copula* of the mixture. Stored
|
|
13
|
+
weights, means and covariances are coarsened to the policy's significant digits.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
from scipy import special
|
|
23
|
+
|
|
24
|
+
from ectype.fingerprint.core import ArrayStore
|
|
25
|
+
from ectype.fingerprint.disclosure import coarsen_array
|
|
26
|
+
from ectype.fingerprint.schema import DisclosurePolicySpec, ModelSpec
|
|
27
|
+
from ectype.models.base import JOINTS, JointModel
|
|
28
|
+
from ectype.models.copulas import _check_z
|
|
29
|
+
|
|
30
|
+
LOG_2PI = math.log(2.0 * math.pi)
|
|
31
|
+
MAX_FIT_ROWS = 20_000
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ---------------------------------------------------------------------------------------------
|
|
35
|
+
# EM for full-covariance Gaussian mixtures
|
|
36
|
+
# ---------------------------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
def _component_logpdf(x: np.ndarray, mean: np.ndarray, cov: np.ndarray) -> np.ndarray:
|
|
39
|
+
d = x.shape[1]
|
|
40
|
+
try:
|
|
41
|
+
chol = np.linalg.cholesky(cov)
|
|
42
|
+
except np.linalg.LinAlgError:
|
|
43
|
+
w, v = np.linalg.eigh(0.5 * (cov + cov.T))
|
|
44
|
+
chol = np.linalg.cholesky((v * np.maximum(w, 1e-6)) @ v.T)
|
|
45
|
+
sol = np.linalg.solve(chol, (x - mean).T)
|
|
46
|
+
maha = np.sum(sol * sol, axis=0)
|
|
47
|
+
logdet = 2.0 * np.sum(np.log(np.diag(chol)))
|
|
48
|
+
return -0.5 * (d * LOG_2PI + logdet + maha)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _weighted_logpdf(x: np.ndarray, weights: np.ndarray, means: np.ndarray,
|
|
52
|
+
covs: np.ndarray) -> np.ndarray:
|
|
53
|
+
"""(n, K) matrix of ``log w_k + log N(x | mu_k, S_k)``."""
|
|
54
|
+
return np.column_stack([np.log(weights[k]) + _component_logpdf(x, means[k], covs[k])
|
|
55
|
+
for k in range(len(weights))])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def mixture_loglik(x: np.ndarray, weights: np.ndarray, means: np.ndarray,
|
|
59
|
+
covs: np.ndarray) -> np.ndarray:
|
|
60
|
+
"""Per-row log density of the raw mixture."""
|
|
61
|
+
return special.logsumexp(_weighted_logpdf(x, weights, means, covs), axis=1)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _kmeanspp(x: np.ndarray, k: int, rng: np.random.Generator) -> np.ndarray:
|
|
65
|
+
n = x.shape[0]
|
|
66
|
+
centers = [x[int(rng.integers(n))]]
|
|
67
|
+
d2 = np.sum((x - centers[0]) ** 2, axis=1)
|
|
68
|
+
for _ in range(1, k):
|
|
69
|
+
tot = d2.sum()
|
|
70
|
+
idx = int(rng.integers(n)) if tot <= 0 else int(
|
|
71
|
+
min(np.searchsorted(np.cumsum(d2) / tot, rng.random()), n - 1))
|
|
72
|
+
centers.append(x[idx])
|
|
73
|
+
d2 = np.minimum(d2, np.sum((x - x[idx]) ** 2, axis=1))
|
|
74
|
+
return np.asarray(centers)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _m_step(x: np.ndarray, resp: np.ndarray, reg_covar: float
|
|
78
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
79
|
+
n, d = x.shape
|
|
80
|
+
nk = resp.sum(axis=0) + 1e-12
|
|
81
|
+
weights = nk / n
|
|
82
|
+
means = (resp.T @ x) / nk[:, None]
|
|
83
|
+
covs = np.empty((len(nk), d, d))
|
|
84
|
+
for k in range(len(nk)):
|
|
85
|
+
diff = x - means[k]
|
|
86
|
+
covs[k] = (resp[:, k:k + 1] * diff).T @ diff / nk[k]
|
|
87
|
+
covs[k] = 0.5 * (covs[k] + covs[k].T) + reg_covar * np.eye(d)
|
|
88
|
+
return weights, means, covs
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def fit_gmm(x: np.ndarray, k: int, rng: np.random.Generator, *, reg_covar: float = 1e-3,
|
|
92
|
+
max_iter: int = 200, tol: float = 1e-6,
|
|
93
|
+
init: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None,
|
|
94
|
+
min_weight: float = 0.0) -> tuple[np.ndarray, np.ndarray, np.ndarray, float]:
|
|
95
|
+
"""EM for a full-covariance mixture. Returns ``(weights, means, covs, mean_loglik)``.
|
|
96
|
+
|
|
97
|
+
Components whose weight falls below ``min_weight`` during EM are removed.
|
|
98
|
+
"""
|
|
99
|
+
n, d = x.shape
|
|
100
|
+
if init is None:
|
|
101
|
+
centers = _kmeanspp(x, k, rng)
|
|
102
|
+
lab = np.argmin(((x[:, None, :] - centers[None, :, :]) ** 2).sum(axis=2), axis=1)
|
|
103
|
+
resp = np.zeros((n, k))
|
|
104
|
+
resp[np.arange(n), lab] = 1.0
|
|
105
|
+
weights, means, covs = _m_step(x, resp, reg_covar)
|
|
106
|
+
keep = weights * n >= d + 1
|
|
107
|
+
if not keep.all() and keep.any():
|
|
108
|
+
weights, means, covs = weights[keep] / weights[keep].sum(), means[keep], covs[keep]
|
|
109
|
+
else:
|
|
110
|
+
weights, means, covs = (np.array(a, dtype=np.float64) for a in init)
|
|
111
|
+
prev = -np.inf
|
|
112
|
+
ll = -np.inf
|
|
113
|
+
for _ in range(max_iter):
|
|
114
|
+
lp = _weighted_logpdf(x, weights, means, covs)
|
|
115
|
+
norm = special.logsumexp(lp, axis=1)
|
|
116
|
+
ll = float(norm.mean())
|
|
117
|
+
resp = np.exp(lp - norm[:, None])
|
|
118
|
+
weights, means, covs = _m_step(x, resp, reg_covar)
|
|
119
|
+
keep = (weights >= min_weight) & (weights * n >= min(d + 1, n))
|
|
120
|
+
if not keep.all() and keep.any():
|
|
121
|
+
weights, means, covs = weights[keep] / weights[keep].sum(), means[keep], covs[keep]
|
|
122
|
+
if abs(ll - prev) < tol * max(1.0, abs(ll)):
|
|
123
|
+
break
|
|
124
|
+
prev = ll
|
|
125
|
+
ll = float(mixture_loglik(x, weights, means, covs).mean())
|
|
126
|
+
return weights, means, covs, ll
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _n_params(k: int, d: int) -> int:
|
|
130
|
+
return (k - 1) + k * d + k * d * (d + 1) // 2
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def select_k(x: np.ndarray, max_k: int, rng: np.random.Generator, *, reg_covar: float,
|
|
134
|
+
min_support: int, test_frac: float = 0.25) -> tuple[int, list[dict[str, float]]]:
|
|
135
|
+
"""Choose K by held-out BIC. Returns ``(K, diagnostics)``."""
|
|
136
|
+
n, d = x.shape
|
|
137
|
+
perm = rng.permutation(n)
|
|
138
|
+
n_test = max(int(round(n * test_frac)), 1)
|
|
139
|
+
if n - n_test < 2 * (d + 1):
|
|
140
|
+
return 1, []
|
|
141
|
+
test, train = x[perm[:n_test]], x[perm[n_test:]]
|
|
142
|
+
n_train = len(train)
|
|
143
|
+
diags: list[dict[str, float]] = []
|
|
144
|
+
best_k, best_crit, worse = 1, np.inf, 0
|
|
145
|
+
for k in range(1, max_k + 1):
|
|
146
|
+
if k * max(min_support, d + 1) > n_train:
|
|
147
|
+
break
|
|
148
|
+
w, m, c, _ = fit_gmm(train, k, rng, reg_covar=reg_covar)
|
|
149
|
+
ll_test = float(mixture_loglik(test, w, m, c).sum())
|
|
150
|
+
crit = -2.0 * (n_train / n_test) * ll_test + _n_params(len(w), d) * math.log(n_train)
|
|
151
|
+
diags.append({"k": k, "heldout_bic": crit, "heldout_mean_loglik": ll_test / n_test})
|
|
152
|
+
if crit < best_crit:
|
|
153
|
+
best_k, best_crit, worse = k, crit, 0
|
|
154
|
+
else:
|
|
155
|
+
worse += 1
|
|
156
|
+
if worse >= 2:
|
|
157
|
+
break
|
|
158
|
+
return best_k, diags
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _nearest_pd(c: np.ndarray, min_eig: float = 1e-6) -> np.ndarray:
|
|
162
|
+
c = 0.5 * (c + c.T)
|
|
163
|
+
w, v = np.linalg.eigh(c)
|
|
164
|
+
if w.min() < min_eig:
|
|
165
|
+
c = (v * np.maximum(w, min_eig)) @ v.T
|
|
166
|
+
c = 0.5 * (c + c.T)
|
|
167
|
+
return c
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# ---------------------------------------------------------------------------------------------
|
|
171
|
+
# The joint model
|
|
172
|
+
# ---------------------------------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
@JOINTS.register()
|
|
175
|
+
class GaussianMixtureCopula(JointModel):
|
|
176
|
+
kind = "gaussian_mixture_copula"
|
|
177
|
+
|
|
178
|
+
def __init__(self, columns: list[str], weights: np.ndarray, means: np.ndarray,
|
|
179
|
+
covs: np.ndarray, *, reg_covar: float = 1e-3) -> None:
|
|
180
|
+
self.columns = list(columns)
|
|
181
|
+
d = len(self.columns)
|
|
182
|
+
self.weights = np.asarray(weights, dtype=np.float64).ravel()
|
|
183
|
+
k = len(self.weights)
|
|
184
|
+
self.means = np.asarray(means, dtype=np.float64).reshape(k, d)
|
|
185
|
+
self.covs = np.asarray(covs, dtype=np.float64).reshape(k, d, d)
|
|
186
|
+
if k < 1 or np.any(self.weights <= 0):
|
|
187
|
+
raise ValueError("mixture needs at least one component with positive weight")
|
|
188
|
+
self.weights = self.weights / self.weights.sum()
|
|
189
|
+
self.reg_covar = float(reg_covar)
|
|
190
|
+
self.selection: list[dict[str, float]] = []
|
|
191
|
+
self._chols = np.stack([np.linalg.cholesky(_nearest_pd(c)) for c in self.covs]) \
|
|
192
|
+
if d else np.zeros((k, 0, 0))
|
|
193
|
+
self._sd = np.sqrt(np.stack([np.diag(c) for c in self.covs])) if d else \
|
|
194
|
+
np.zeros((k, 0))
|
|
195
|
+
|
|
196
|
+
# -- fitting ------------------------------------------------------------------------------
|
|
197
|
+
@classmethod
|
|
198
|
+
def fit(cls, z: np.ndarray, columns: list[str], *, policy: DisclosurePolicySpec,
|
|
199
|
+
rng: np.random.Generator | None = None, max_k: int = 6,
|
|
200
|
+
reg_covar: float = 1e-3, n_components: int | None = None,
|
|
201
|
+
**kwargs: Any) -> GaussianMixtureCopula:
|
|
202
|
+
"""Fit to latent normal scores.
|
|
203
|
+
|
|
204
|
+
``n_components`` fixes K (skipping the held-out BIC search). Extra keywords such as
|
|
205
|
+
``attenuation`` are accepted for interface compatibility; attenuation has no
|
|
206
|
+
well-defined analogue for mixture covariances and is ignored.
|
|
207
|
+
"""
|
|
208
|
+
z = _check_z(z, columns)
|
|
209
|
+
rng = rng if rng is not None else np.random.default_rng(0)
|
|
210
|
+
n, d = z.shape
|
|
211
|
+
if d == 0 or n < 2:
|
|
212
|
+
return cls(columns, np.ones(1), np.zeros((1, d)), np.eye(d)[None],
|
|
213
|
+
reg_covar=reg_covar)
|
|
214
|
+
x = z if n <= MAX_FIT_ROWS else z[np.sort(rng.choice(n, MAX_FIT_ROWS, replace=False))]
|
|
215
|
+
min_support = int(policy.min_category_support)
|
|
216
|
+
if n_components is not None:
|
|
217
|
+
k = int(n_components)
|
|
218
|
+
diags: list[dict[str, float]] = []
|
|
219
|
+
else:
|
|
220
|
+
k, diags = select_k(x, max(1, int(max_k)), rng, reg_covar=reg_covar,
|
|
221
|
+
min_support=min_support)
|
|
222
|
+
w, m, c, _ = fit_gmm(x, k, rng, reg_covar=reg_covar)
|
|
223
|
+
# disclosure: drop small-support components and re-run EM on the survivors
|
|
224
|
+
for _ in range(k):
|
|
225
|
+
keep = w * n >= min_support
|
|
226
|
+
if keep.all() or not keep.any():
|
|
227
|
+
if not keep.any():
|
|
228
|
+
w, m, c, _ = fit_gmm(x, 1, rng, reg_covar=reg_covar)
|
|
229
|
+
break
|
|
230
|
+
w, m, c, _ = fit_gmm(x, int(keep.sum()), rng, reg_covar=reg_covar,
|
|
231
|
+
init=(w[keep] / w[keep].sum(), m[keep], c[keep]))
|
|
232
|
+
w = coarsen_array(w, policy)
|
|
233
|
+
m = coarsen_array(m, policy)
|
|
234
|
+
c = coarsen_array(c, policy)
|
|
235
|
+
c = np.stack([_nearest_pd(ci) for ci in c])
|
|
236
|
+
model = cls(columns, w, m, c, reg_covar=reg_covar)
|
|
237
|
+
model.selection = diags
|
|
238
|
+
return model
|
|
239
|
+
|
|
240
|
+
# -- marginal CDF of the mixture ----------------------------------------------------------
|
|
241
|
+
def _marginal_log_cdf_sf(self, x: np.ndarray, j: int) -> tuple[np.ndarray, np.ndarray]:
|
|
242
|
+
t = (x[:, None] - self.means[None, :, j]) / self._sd[None, :, j]
|
|
243
|
+
lw = np.log(self.weights)[None, :]
|
|
244
|
+
return (special.logsumexp(lw + special.log_ndtr(t), axis=1),
|
|
245
|
+
special.logsumexp(lw + special.log_ndtr(-t), axis=1))
|
|
246
|
+
|
|
247
|
+
def _to_normal(self, x: np.ndarray) -> np.ndarray:
|
|
248
|
+
"""Map raw mixture draws to N(0,1) margins via Phi^-1(F_mix_j(x_j))."""
|
|
249
|
+
out = np.column_stack([self._to_normal_1d(x[:, j], j) for j in range(x.shape[1])])
|
|
250
|
+
return np.clip(out, -38.0, 38.0)
|
|
251
|
+
|
|
252
|
+
def _from_normal(self, z: np.ndarray, iters: int = 80) -> np.ndarray:
|
|
253
|
+
"""Inverse of ``_to_normal`` per dimension (vectorised bisection)."""
|
|
254
|
+
out = np.empty_like(z)
|
|
255
|
+
for j in range(z.shape[1]):
|
|
256
|
+
lo = np.full(len(z), float(np.min(self.means[:, j] - 40 * self._sd[:, j])))
|
|
257
|
+
hi = np.full(len(z), float(np.max(self.means[:, j] + 40 * self._sd[:, j])))
|
|
258
|
+
target = z[:, j]
|
|
259
|
+
for _ in range(iters):
|
|
260
|
+
mid = 0.5 * (lo + hi)
|
|
261
|
+
go_up = self._to_normal_1d(mid, j) < target
|
|
262
|
+
lo = np.where(go_up, mid, lo)
|
|
263
|
+
hi = np.where(go_up, hi, mid)
|
|
264
|
+
out[:, j] = 0.5 * (lo + hi)
|
|
265
|
+
return out
|
|
266
|
+
|
|
267
|
+
def _to_normal_1d(self, x: np.ndarray, j: int) -> np.ndarray:
|
|
268
|
+
lc, ls = self._marginal_log_cdf_sf(x, j)
|
|
269
|
+
return np.where(lc < math.log(0.5), special.ndtri(np.exp(np.minimum(lc, 0.0))),
|
|
270
|
+
-special.ndtri(np.exp(np.minimum(ls, 0.0))))
|
|
271
|
+
|
|
272
|
+
# -- sampling / density -------------------------------------------------------------------
|
|
273
|
+
def sample_raw(self, n: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]:
|
|
274
|
+
"""Raw mixture draws and their component labels (before re-standardisation)."""
|
|
275
|
+
d = len(self.columns)
|
|
276
|
+
u = rng.random(n)
|
|
277
|
+
lab = np.minimum(np.searchsorted(np.cumsum(self.weights), u, side="right"),
|
|
278
|
+
len(self.weights) - 1)
|
|
279
|
+
e = rng.standard_normal((n, d))
|
|
280
|
+
x = np.empty((n, d))
|
|
281
|
+
for k in range(len(self.weights)):
|
|
282
|
+
idx = lab == k
|
|
283
|
+
x[idx] = self.means[k] + e[idx] @ self._chols[k].T
|
|
284
|
+
return x, lab
|
|
285
|
+
|
|
286
|
+
def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
|
|
287
|
+
if not self.columns:
|
|
288
|
+
return np.zeros((n, 0))
|
|
289
|
+
x, _ = self.sample_raw(n, rng)
|
|
290
|
+
return self._to_normal(x)
|
|
291
|
+
|
|
292
|
+
def logpdf(self, z: np.ndarray) -> np.ndarray:
|
|
293
|
+
"""Log density of the latent scores ``z`` under the sampled distribution
|
|
294
|
+
(mixture copula with N(0,1) margins)."""
|
|
295
|
+
z = np.asarray(z, dtype=np.float64)
|
|
296
|
+
d = z.shape[1]
|
|
297
|
+
x = self._from_normal(z)
|
|
298
|
+
out = mixture_loglik(x, self.weights, self.means, self.covs)
|
|
299
|
+
lw = np.log(self.weights)[None, :]
|
|
300
|
+
for j in range(d):
|
|
301
|
+
t = (x[:, j:j + 1] - self.means[None, :, j]) / self._sd[None, :, j]
|
|
302
|
+
logf = special.logsumexp(lw - 0.5 * t * t - 0.5 * LOG_2PI
|
|
303
|
+
- np.log(self._sd[None, :, j]), axis=1)
|
|
304
|
+
out = out - logf - 0.5 * z[:, j] ** 2 - 0.5 * LOG_2PI
|
|
305
|
+
return out
|
|
306
|
+
|
|
307
|
+
def predict_component(self, z: np.ndarray) -> np.ndarray:
|
|
308
|
+
"""Most likely component for each row of latent scores."""
|
|
309
|
+
x = self._from_normal(np.asarray(z, dtype=np.float64))
|
|
310
|
+
return np.argmax(_weighted_logpdf(x, self.weights, self.means, self.covs), axis=1)
|
|
311
|
+
|
|
312
|
+
@property
|
|
313
|
+
def n_components(self) -> int:
|
|
314
|
+
return len(self.weights)
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def n_parameters(self) -> int:
|
|
318
|
+
return _n_params(self.n_components, len(self.columns))
|
|
319
|
+
|
|
320
|
+
# -- serialisation ------------------------------------------------------------------------
|
|
321
|
+
def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
|
|
322
|
+
arrays = {"weights": store.put(f"{prefix}weights", self.weights),
|
|
323
|
+
"means": store.put(f"{prefix}means", self.means),
|
|
324
|
+
"covariances": store.put(f"{prefix}covariances", self.covs)}
|
|
325
|
+
params: dict[str, Any] = {"columns": list(self.columns),
|
|
326
|
+
"n_components": self.n_components,
|
|
327
|
+
"reg_covar": self.reg_covar}
|
|
328
|
+
return ModelSpec(kind=self.kind, params=params, arrays=arrays)
|
|
329
|
+
|
|
330
|
+
@classmethod
|
|
331
|
+
def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> GaussianMixtureCopula:
|
|
332
|
+
cols = [str(c) for c in spec.params.get("columns", [])] # type: ignore[union-attr]
|
|
333
|
+
return cls(cols, np.asarray(store.get(spec.arrays["weights"]), dtype=np.float64),
|
|
334
|
+
np.asarray(store.get(spec.arrays["means"]), dtype=np.float64),
|
|
335
|
+
np.asarray(store.get(spec.arrays["covariances"]), dtype=np.float64),
|
|
336
|
+
reg_covar=float(spec.params.get("reg_covar", 1e-3))) # type: ignore[arg-type]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Optional learned joint models (M31).
|
|
2
|
+
|
|
3
|
+
* :class:`LatentVAE` (kind ``"latent_vae"``): a small pure-NumPy VAE on latent scores.
|
|
4
|
+
* :class:`TorchModuleAdapter` / :class:`TorchMLPFlow` (kind ``"torch_mlp_flow"``): declared,
|
|
5
|
+
whitelisted MLP architectures with hashed float32 weights, executed in NumPy; PyTorch is
|
|
6
|
+
needed only for training (``pip install ectype-data[neural]``).
|
|
7
|
+
* :func:`should_escalate`: the escalation rule (sealed fidelity must improve, privacy risk
|
|
8
|
+
must not get worse).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from ectype.models.neural.adapter import (
|
|
12
|
+
TorchMLPFlow,
|
|
13
|
+
TorchModuleAdapter,
|
|
14
|
+
should_escalate,
|
|
15
|
+
train_with_torch,
|
|
16
|
+
validate_config,
|
|
17
|
+
)
|
|
18
|
+
from ectype.models.neural.vae import LatentVAE
|
|
19
|
+
|
|
20
|
+
__all__ = ["LatentVAE", "TorchMLPFlow", "TorchModuleAdapter", "should_escalate",
|
|
21
|
+
"train_with_torch", "validate_config"]
|