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,418 @@
|
|
|
1
|
+
"""Generate a set of related tables from a :class:`RelationalFingerprint`.
|
|
2
|
+
|
|
3
|
+
Order is topological (parents first):
|
|
4
|
+
|
|
5
|
+
1. **Root tables** are generated with the normal :class:`~ectype.Generator`; their
|
|
6
|
+
``__n_<child>`` helper columns give the number of children of every generated row.
|
|
7
|
+
2. **Child tables**: every generated parent row with count ``m`` gets ``m`` child rows drawn
|
|
8
|
+
from the child fingerprint *conditionally on that parent* (below). Child rows are emitted
|
|
9
|
+
grouped by parent, in parent order.
|
|
10
|
+
3. **Keys**: primary keys come from each table's identifier generator (fresh values, never
|
|
11
|
+
copied); each foreign key is the primary key of the synthetic parent the row was generated
|
|
12
|
+
for, so referential integrity is 100% by construction.
|
|
13
|
+
4. Helper columns (``__n_*``, ``__parent_*``) are dropped from the output; columns come out in
|
|
14
|
+
source order and source dtypes.
|
|
15
|
+
|
|
16
|
+
Conditional copula sampling
|
|
17
|
+
---------------------------
|
|
18
|
+
The child's latent vector is split into the parent-helper block ``p`` (``__parent_*`` scores and
|
|
19
|
+
their missingness indicators) and the rest ``c``. The generated parent values are encoded with
|
|
20
|
+
the *child's* encoder (so they live in the child's latent space), and the remaining latents are
|
|
21
|
+
drawn rejection-free from the Gaussian conditional::
|
|
22
|
+
|
|
23
|
+
z_c | z_p ~ N( R_cp R_pp^-1 z_p , R_cc - R_cp R_pp^-1 R_pc )
|
|
24
|
+
|
|
25
|
+
then decoded with the child's encoder; the helper columns are overwritten with the exact parent
|
|
26
|
+
values. Children of one parent are conditionally independent given the parent's features.
|
|
27
|
+
|
|
28
|
+
Approximations (documented):
|
|
29
|
+
|
|
30
|
+
* When the child's joint model is not a Gaussian copula (mixture / vine copula), the latent
|
|
31
|
+
correlation ``R`` is the empirical correlation of a fixed-seed sample of 20 000 draws from the
|
|
32
|
+
joint, i.e. a moment-matched Gaussian approximation of its dependence on the parent block.
|
|
33
|
+
The independence joint is exact (``R = I``: the parent has no influence).
|
|
34
|
+
* A ``__parent_*`` categorical column that the encoder made a conditional child of a non-helper
|
|
35
|
+
categorical (Chow-Liu forest) is encoded with its marginal intervals, because the column it
|
|
36
|
+
is conditioned on is not known before the child row is drawn.
|
|
37
|
+
* Encoding discrete/categorical parent values uses a randomized PIT inside the value's interval
|
|
38
|
+
(one draw per parent, shared by its children).
|
|
39
|
+
|
|
40
|
+
Child counts: when the fingerprint stores count strata (per-category count quantiles of the
|
|
41
|
+
categorical parent column most associated with the count), the copula's counts are
|
|
42
|
+
quantile-matched within each category after the parent table is generated (see
|
|
43
|
+
:func:`stratify_counts`): a Gaussian copula alone attenuates category -> count relations.
|
|
44
|
+
|
|
45
|
+
Constraints: the child's own hard constraints and the cross-table constraints (evaluated on the
|
|
46
|
+
child row joined with its parent row) are enforced by rejection *per child row*: violating rows
|
|
47
|
+
are redrawn for the same parent from the continued streams, for at most
|
|
48
|
+
``manifest.generation.max_rejection_rounds`` rounds, else :class:`GenerationError`.
|
|
49
|
+
|
|
50
|
+
Reproducibility: output is a deterministic function of the relational fingerprint, ``n_root``
|
|
51
|
+
and ``seed`` (all randomness from ``rng.stream(seed, "relational", ...)``).
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
from __future__ import annotations
|
|
55
|
+
|
|
56
|
+
from typing import Any
|
|
57
|
+
|
|
58
|
+
import numpy as np
|
|
59
|
+
import polars as pl
|
|
60
|
+
|
|
61
|
+
from ectype.errors import GenerationError
|
|
62
|
+
from ectype.generation.enforce import (
|
|
63
|
+
apply_repairs,
|
|
64
|
+
cast_to,
|
|
65
|
+
dtype_from_string,
|
|
66
|
+
violation_masks,
|
|
67
|
+
)
|
|
68
|
+
from ectype.generation.generator import Generator
|
|
69
|
+
from ectype.generation.identifiers import generate_identifier
|
|
70
|
+
from ectype.relational.fit import (
|
|
71
|
+
OTHER,
|
|
72
|
+
RelationalFingerprint,
|
|
73
|
+
RelationshipFit,
|
|
74
|
+
cross_violations,
|
|
75
|
+
strata_labels,
|
|
76
|
+
)
|
|
77
|
+
from ectype.rng import stream
|
|
78
|
+
|
|
79
|
+
_ROW = "__rel_row__"
|
|
80
|
+
_FALLBACK_DRAWS = 20_000
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _table_seed(seed: int, name: str) -> int:
|
|
84
|
+
return int(stream(seed, "relational", "table", name).integers(0, 2**31 - 1))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _nearest_pd(s: np.ndarray, floor: float = 1e-9) -> np.ndarray:
|
|
88
|
+
s = 0.5 * (s + s.T)
|
|
89
|
+
w, v = np.linalg.eigh(s)
|
|
90
|
+
return (v * np.maximum(w, floor)) @ v.T
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class _ChildSampler:
|
|
94
|
+
"""Conditional sampler for one child table (see module doc)."""
|
|
95
|
+
|
|
96
|
+
def __init__(self, gen: Generator, fit: RelationshipFit) -> None:
|
|
97
|
+
from ectype.models.copulas import GaussianCopula
|
|
98
|
+
from ectype.models.encoding import missing_name
|
|
99
|
+
|
|
100
|
+
self.gen = gen
|
|
101
|
+
self.fit = fit
|
|
102
|
+
self.plan = gen.plan
|
|
103
|
+
self.helpers = [c.helper_column for c in fit.conditioning]
|
|
104
|
+
self.notes: list[str] = []
|
|
105
|
+
enc, joint = gen.encoder, gen.joint
|
|
106
|
+
self.encoder = enc
|
|
107
|
+
if enc is None or joint is None:
|
|
108
|
+
self.latent: list[str] = []
|
|
109
|
+
self.p_idx = np.zeros(0, dtype=np.int64)
|
|
110
|
+
self.c_idx = np.zeros(0, dtype=np.int64)
|
|
111
|
+
return
|
|
112
|
+
latent = list(enc.latent_columns)
|
|
113
|
+
self.latent = latent
|
|
114
|
+
jcols = list(joint.columns)
|
|
115
|
+
pos = {c: j for j, c in enumerate(jcols)}
|
|
116
|
+
perm = np.array([pos[c] for c in latent], dtype=np.int64)
|
|
117
|
+
if isinstance(joint, GaussianCopula):
|
|
118
|
+
r = np.asarray(joint.corr, dtype=float)[np.ix_(perm, perm)]
|
|
119
|
+
else:
|
|
120
|
+
draws = joint.sample(_FALLBACK_DRAWS, stream(0, "relational", "fallback", fit.
|
|
121
|
+
relationship.child))[:, perm]
|
|
122
|
+
r = np.corrcoef(draws, rowvar=False) if len(latent) > 1 else np.ones((1, 1))
|
|
123
|
+
r = np.nan_to_num(np.atleast_2d(r))
|
|
124
|
+
np.fill_diagonal(r, 1.0)
|
|
125
|
+
self.notes.append(f"{fit.relationship.child}: joint {joint.kind!r} is not a "
|
|
126
|
+
f"Gaussian copula; conditional sampling uses its moment-matched "
|
|
127
|
+
f"Gaussian approximation")
|
|
128
|
+
helper_latent = set(self.helpers) | {missing_name(h) for h in self.helpers}
|
|
129
|
+
self.p_idx = np.array([j for j, c in enumerate(latent) if c in helper_latent],
|
|
130
|
+
dtype=np.int64)
|
|
131
|
+
self.c_idx = np.array([j for j, c in enumerate(latent) if c not in helper_latent],
|
|
132
|
+
dtype=np.int64)
|
|
133
|
+
d = len(latent)
|
|
134
|
+
if self.p_idx.size:
|
|
135
|
+
rpp = r[np.ix_(self.p_idx, self.p_idx)]
|
|
136
|
+
rpc = r[np.ix_(self.p_idx, self.c_idx)]
|
|
137
|
+
rcc = r[np.ix_(self.c_idx, self.c_idx)]
|
|
138
|
+
rpp = _nearest_pd(rpp, 1e-6)
|
|
139
|
+
sol = np.linalg.solve(rpp, rpc) # R_pp^-1 R_pc
|
|
140
|
+
self.coef = sol.T # (c, p)
|
|
141
|
+
cov = _nearest_pd(rcc - rpc.T @ sol)
|
|
142
|
+
else:
|
|
143
|
+
self.coef = np.zeros((self.c_idx.size, 0))
|
|
144
|
+
cov = r[np.ix_(self.c_idx, self.c_idx)] if d else np.zeros((0, 0))
|
|
145
|
+
self.chol = np.linalg.cholesky(_nearest_pd(cov)) if self.c_idx.size else \
|
|
146
|
+
np.zeros((0, 0))
|
|
147
|
+
parents = enc.conditional_parents
|
|
148
|
+
for h in self.helpers:
|
|
149
|
+
par = parents.get(h)
|
|
150
|
+
if par is not None and par not in self.helpers:
|
|
151
|
+
self.notes.append(f"{fit.relationship.child}: helper {h!r} is encoded "
|
|
152
|
+
f"conditionally on child column {par!r}; parent values use "
|
|
153
|
+
f"marginal intervals (approximation)")
|
|
154
|
+
self._dtypes = {c: dtype_from_string(self.plan.schemas[c].physical_dtype)
|
|
155
|
+
if c in self.plan.schemas else None for c in self.plan.output_columns}
|
|
156
|
+
|
|
157
|
+
# -- latent ----------------------------------------------------------------------------
|
|
158
|
+
def encode_parents(self, helper_values: pl.DataFrame, rng: np.random.Generator
|
|
159
|
+
) -> np.ndarray:
|
|
160
|
+
"""Helper latents ``(n_parents, |p|)`` of the generated parent values."""
|
|
161
|
+
enc = self.encoder
|
|
162
|
+
n = helper_values.height
|
|
163
|
+
if enc is None or not self.p_idx.size:
|
|
164
|
+
return np.zeros((n, 0))
|
|
165
|
+
cols = []
|
|
166
|
+
for name in enc.columns:
|
|
167
|
+
dt = dtype_from_string(self.plan.schemas[name].physical_dtype)
|
|
168
|
+
if name in helper_values.columns:
|
|
169
|
+
cols.append(cast_to(helper_values.get_column(name), dt).alias(name))
|
|
170
|
+
else:
|
|
171
|
+
cols.append(pl.Series(name, [None] * n, dtype=dt or pl.Float64))
|
|
172
|
+
z = enc.encode(pl.DataFrame(cols, height=n), rng)
|
|
173
|
+
return z[:, self.p_idx]
|
|
174
|
+
|
|
175
|
+
def sample_latent(self, zp: np.ndarray, rng: np.random.Generator) -> np.ndarray:
|
|
176
|
+
m = zp.shape[0]
|
|
177
|
+
z = np.empty((m, len(self.latent)))
|
|
178
|
+
if self.p_idx.size:
|
|
179
|
+
z[:, self.p_idx] = zp
|
|
180
|
+
if self.c_idx.size:
|
|
181
|
+
e = rng.standard_normal((m, self.c_idx.size))
|
|
182
|
+
z[:, self.c_idx] = zp @ self.coef.T + e @ self.chol.T
|
|
183
|
+
return z
|
|
184
|
+
|
|
185
|
+
# -- rows ------------------------------------------------------------------------------
|
|
186
|
+
def candidates(self, z: np.ndarray, helper_rows: pl.DataFrame,
|
|
187
|
+
decode_rng: np.random.Generator) -> pl.DataFrame:
|
|
188
|
+
plan = self.plan
|
|
189
|
+
m = z.shape[0]
|
|
190
|
+
df = pl.DataFrame({_ROW: np.zeros(m, dtype=np.int8)})
|
|
191
|
+
if self.encoder is not None and len(self.latent):
|
|
192
|
+
feats = self.encoder.decode(z, decode_rng)
|
|
193
|
+
fixed = [cast_to(feats.get_column(c), self._dtypes.get(c)) for c in feats.columns]
|
|
194
|
+
df = df.hstack(fixed)
|
|
195
|
+
if helper_rows.width:
|
|
196
|
+
df = df.with_columns(cast_to(helper_rows.get_column(h), self._dtypes.get(h))
|
|
197
|
+
.alias(h) for h in helper_rows.columns if h in df.columns)
|
|
198
|
+
if plan.repairs:
|
|
199
|
+
df, _ = apply_repairs(df, plan.repairs)
|
|
200
|
+
extra = []
|
|
201
|
+
for c, v in plan.constants.items():
|
|
202
|
+
s = cast_to(pl.Series(c, [v]), self._dtypes.get(c))
|
|
203
|
+
extra.append(s.new_from_index(0, m) if m else s.clear())
|
|
204
|
+
for c in plan.unmodeled:
|
|
205
|
+
extra.append(pl.repeat(None, m, dtype=self._dtypes.get(c) or pl.Null,
|
|
206
|
+
eager=True).alias(c))
|
|
207
|
+
if extra:
|
|
208
|
+
df = df.with_columns(extra)
|
|
209
|
+
for d in plan.derived:
|
|
210
|
+
df = df.with_columns(d.expr.alias(d.column))
|
|
211
|
+
dt = self._dtypes.get(d.column)
|
|
212
|
+
if dt is not None and df.schema[d.column] != dt:
|
|
213
|
+
df = df.with_columns(cast_to(df.get_column(d.column), dt))
|
|
214
|
+
return df
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class RelationalGenerator:
|
|
218
|
+
"""Generate related tables from a :class:`RelationalFingerprint`."""
|
|
219
|
+
|
|
220
|
+
def __init__(self, rfp: RelationalFingerprint) -> None:
|
|
221
|
+
self.rfp = rfp
|
|
222
|
+
self.schema = rfp.schema
|
|
223
|
+
self.generators = {n: Generator(fp) for n, fp in rfp.fingerprints.items()}
|
|
224
|
+
self.samplers: dict[str, _ChildSampler] = {}
|
|
225
|
+
self.notes: list[str] = []
|
|
226
|
+
for f in rfp.section.relationships:
|
|
227
|
+
s = _ChildSampler(self.generators[f.relationship.child], f)
|
|
228
|
+
self.samplers[f.relationship.child] = s
|
|
229
|
+
self.notes.extend(s.notes)
|
|
230
|
+
|
|
231
|
+
@classmethod
|
|
232
|
+
def from_fingerprint(cls, rfp_or_path: Any) -> RelationalGenerator:
|
|
233
|
+
if isinstance(rfp_or_path, RelationalFingerprint):
|
|
234
|
+
return cls(rfp_or_path)
|
|
235
|
+
return cls(RelationalFingerprint.load(rfp_or_path))
|
|
236
|
+
|
|
237
|
+
def _roots(self, n_root: dict[str, int] | int | None) -> dict[str, int]:
|
|
238
|
+
roots = self.schema.roots
|
|
239
|
+
info = self.rfp.section.tables
|
|
240
|
+
if n_root is None:
|
|
241
|
+
out = {r: info[r].source_records for r in roots}
|
|
242
|
+
elif isinstance(n_root, dict):
|
|
243
|
+
unknown = sorted(set(n_root) - set(roots))
|
|
244
|
+
if unknown:
|
|
245
|
+
raise ValueError(f"n_root names non-root tables {unknown}; roots are {roots}")
|
|
246
|
+
out = {r: int(n_root.get(r, info[r].source_records)) for r in roots}
|
|
247
|
+
else:
|
|
248
|
+
out = {r: int(n_root) for r in roots}
|
|
249
|
+
for r, n in out.items():
|
|
250
|
+
if n < 0:
|
|
251
|
+
raise ValueError(f"n_root[{r!r}] must be >= 0")
|
|
252
|
+
return out
|
|
253
|
+
|
|
254
|
+
# -----------------------------------------------------------------------------------------
|
|
255
|
+
def generate(self, n_root: dict[str, int] | int | None = None, seed: int = 42, *,
|
|
256
|
+
keep_helpers: bool = False) -> dict[str, pl.DataFrame]:
|
|
257
|
+
"""Generate every table. ``n_root`` sets the row count of the root tables (an int
|
|
258
|
+
applies to every root; default: the source sizes). Child sizes follow from the
|
|
259
|
+
generated child counts."""
|
|
260
|
+
seed = int(seed)
|
|
261
|
+
sizes = self._roots(n_root)
|
|
262
|
+
full: dict[str, pl.DataFrame] = {}
|
|
263
|
+
for name in self.schema.topological_order():
|
|
264
|
+
if name in sizes:
|
|
265
|
+
full[name] = self.generators[name].generate(sizes[name],
|
|
266
|
+
seed=_table_seed(seed, name))
|
|
267
|
+
else:
|
|
268
|
+
rel = self.schema.parents_of(name)[0]
|
|
269
|
+
full[name] = self._child(name, rel, full[rel.parent], seed)
|
|
270
|
+
for crel in self.schema.children_of(name):
|
|
271
|
+
fit = self.samplers[crel.child].fit
|
|
272
|
+
if fit.count_strata is not None:
|
|
273
|
+
full[name] = stratify_counts(full[name], fit,
|
|
274
|
+
stream(seed, "relational", crel.child,
|
|
275
|
+
"strata"))
|
|
276
|
+
out = {}
|
|
277
|
+
for name in self.schema.tables:
|
|
278
|
+
info = self.rfp.section.tables[name]
|
|
279
|
+
df = full[name]
|
|
280
|
+
cols = list(info.columns)
|
|
281
|
+
if keep_helpers:
|
|
282
|
+
cols += [c for c in info.count_columns if c in df.columns]
|
|
283
|
+
out[name] = df.select(cols)
|
|
284
|
+
return out
|
|
285
|
+
|
|
286
|
+
def _child(self, name: str, rel: Any, parent: pl.DataFrame, seed: int) -> pl.DataFrame:
|
|
287
|
+
sampler = self.samplers[name]
|
|
288
|
+
fit = sampler.fit
|
|
289
|
+
fp = self.rfp.fingerprints[name]
|
|
290
|
+
cross = [c for c in self.rfp.section.cross_constraints if c.child == name]
|
|
291
|
+
counts_s = parent.get_column(fit.count_column).cast(pl.Float64).fill_null(0.0)
|
|
292
|
+
counts = np.clip(np.rint(counts_s.fill_nan(0.0).to_numpy()), 0, None).astype(np.int64)
|
|
293
|
+
m = int(counts.sum())
|
|
294
|
+
idx = np.repeat(np.arange(parent.height), counts)
|
|
295
|
+
helper_parent = parent.select([pl.col(c.parent_column).alias(c.helper_column)
|
|
296
|
+
for c in fit.conditioning])
|
|
297
|
+
zp_par = sampler.encode_parents(helper_parent, stream(seed, "relational", name,
|
|
298
|
+
"parent_encode"))
|
|
299
|
+
if zp_par.ndim != 2 or zp_par.shape[0] != parent.height:
|
|
300
|
+
# No conditioning columns (child independent of parent attributes): an empty
|
|
301
|
+
# (rows, 0) latent block keeps indexing and Gaussian conditioning well-defined.
|
|
302
|
+
zp_par = np.zeros((parent.height, 0))
|
|
303
|
+
zp = zp_par[idx]
|
|
304
|
+
helper_rows = helper_parent[idx] if helper_parent.width else pl.DataFrame()
|
|
305
|
+
parent_rows = parent[idx]
|
|
306
|
+
lat_rng = stream(seed, "relational", name, "latent")
|
|
307
|
+
dec_rng = stream(seed, "relational", name, "decode")
|
|
308
|
+
|
|
309
|
+
frame = sampler.candidates(sampler.sample_latent(zp, lat_rng), helper_rows, dec_rng)
|
|
310
|
+
max_rounds = max(1, int(fp.manifest.generation.max_rejection_rounds))
|
|
311
|
+
rounds = 1
|
|
312
|
+
while True:
|
|
313
|
+
bad = self._violations(frame, sampler, cross, parent_rows, rel)
|
|
314
|
+
if not bad.any():
|
|
315
|
+
break
|
|
316
|
+
if rounds >= max_rounds:
|
|
317
|
+
raise GenerationError(
|
|
318
|
+
f"table {name!r}: {int(bad.sum())} of {m} child rows still violate "
|
|
319
|
+
f"constraints after {rounds} rejection rounds; the constraints may be "
|
|
320
|
+
f"infeasible given the parent rows")
|
|
321
|
+
rows = np.flatnonzero(bad)
|
|
322
|
+
redo = sampler.candidates(sampler.sample_latent(zp[rows], lat_rng),
|
|
323
|
+
helper_rows[rows] if helper_rows.width
|
|
324
|
+
else pl.DataFrame(), dec_rng)
|
|
325
|
+
frame = _replace_rows(frame, rows, redo)
|
|
326
|
+
rounds += 1
|
|
327
|
+
|
|
328
|
+
# keys: fresh primary key; foreign key -> synthetic parent's primary key
|
|
329
|
+
plan = sampler.plan
|
|
330
|
+
ids = []
|
|
331
|
+
for col, spec in plan.identifiers.items():
|
|
332
|
+
s = generate_identifier(spec, plan.schemas.get(col), m, 0,
|
|
333
|
+
stream(seed, "relational", name, "identifier", col, "key"),
|
|
334
|
+
stream(seed, "relational", name, "identifier", col))
|
|
335
|
+
ids.append(cast_to(s.alias(col), sampler._dtypes.get(col)))
|
|
336
|
+
if ids:
|
|
337
|
+
frame = frame.with_columns(ids)
|
|
338
|
+
if plan.references:
|
|
339
|
+
# reference keys of the child's own columns (ADR-0013): group sizes -> fresh keys
|
|
340
|
+
from ectype.profiling.reference import finish_references
|
|
341
|
+
frame = finish_references(
|
|
342
|
+
frame, plan.references, 0,
|
|
343
|
+
lambda col: stream(seed, "relational", name, "reference", col))
|
|
344
|
+
fk_schema = next((c for c in fp.manifest.columns if c.name == rel.child_fk), None)
|
|
345
|
+
fk = parent_rows.get_column(rel.parent_key)
|
|
346
|
+
fk = cast_to(fk, dtype_from_string(fk_schema.physical_dtype) if fk_schema else None)
|
|
347
|
+
frame = frame.with_columns(fk.alias(rel.child_fk))
|
|
348
|
+
cols = [c for c in plan.output_columns if c in frame.columns]
|
|
349
|
+
if rel.child_fk not in cols:
|
|
350
|
+
cols.append(rel.child_fk)
|
|
351
|
+
return frame.select([cast_to(frame.get_column(c), sampler._dtypes.get(c))
|
|
352
|
+
if c in sampler._dtypes else frame.get_column(c) for c in cols])
|
|
353
|
+
|
|
354
|
+
@staticmethod
|
|
355
|
+
def _violations(frame: pl.DataFrame, sampler: _ChildSampler, cross: list[Any],
|
|
356
|
+
parent_rows: pl.DataFrame, rel: Any) -> np.ndarray:
|
|
357
|
+
bad = np.zeros(frame.height, dtype=bool)
|
|
358
|
+
if sampler.plan.constraints:
|
|
359
|
+
for mk in violation_masks(frame, sampler.plan.constraints).values():
|
|
360
|
+
bad |= mk
|
|
361
|
+
if cross and frame.height:
|
|
362
|
+
p = parent_rows.rename({c: f"parent.{c}" for c in parent_rows.columns})
|
|
363
|
+
joined = pl.concat([frame, p], how="horizontal")
|
|
364
|
+
for mk in cross_violations(joined, cross).values():
|
|
365
|
+
bad |= mk
|
|
366
|
+
return bad
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def stratify_counts(parent: pl.DataFrame, fit: RelationshipFit, rng: np.random.Generator
|
|
370
|
+
) -> pl.DataFrame:
|
|
371
|
+
"""Within-category quantile matching of the generated child counts.
|
|
372
|
+
|
|
373
|
+
For every category ``g`` of ``fit.count_strata.column`` the generated counts of the parents
|
|
374
|
+
in ``g`` are ranked (ties broken at random), mapped to ``u = (rank + 0.5) / n_g`` and
|
|
375
|
+
replaced by the stored conditional quantile ``Q_{count | g}(u)`` (linear interpolation over
|
|
376
|
+
the stored levels, rounded). The copula's ordering *within* each category -- and so its
|
|
377
|
+
dependence on the other parent attributes -- is kept; the conditional count distribution
|
|
378
|
+
per category matches the fingerprint. Unseen / pooled labels use ``"__other__"``.
|
|
379
|
+
"""
|
|
380
|
+
st = fit.count_strata
|
|
381
|
+
col = fit.count_column
|
|
382
|
+
if st is None or st.column not in parent.columns or col not in parent.columns or parent.height == 0:
|
|
383
|
+
return parent
|
|
384
|
+
lab = strata_labels(parent.get_column(st.column))
|
|
385
|
+
known = set(st.labels)
|
|
386
|
+
lab = np.where(np.isin(lab, list(known)), lab, OTHER)
|
|
387
|
+
counts = parent.get_column(col).cast(pl.Float64).fill_null(0.0).fill_nan(0.0).to_numpy()
|
|
388
|
+
jitter = rng.random(counts.size)
|
|
389
|
+
out = counts.copy()
|
|
390
|
+
for g, lv, q in zip(st.labels, st.levels, st.quantiles, strict=True):
|
|
391
|
+
idx = np.flatnonzero(lab == g)
|
|
392
|
+
if idx.size == 0:
|
|
393
|
+
continue
|
|
394
|
+
order = np.lexsort((jitter[idx], counts[idx]))
|
|
395
|
+
u = np.empty(idx.size)
|
|
396
|
+
u[order] = (np.arange(idx.size) + 0.5) / idx.size
|
|
397
|
+
out[idx] = np.rint(np.interp(u, np.asarray(lv), np.asarray(q)))
|
|
398
|
+
s = pl.Series(col, np.clip(out, 0, None)).cast(parent.schema[col], strict=False)
|
|
399
|
+
return parent.with_columns(s)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _replace_rows(frame: pl.DataFrame, rows: np.ndarray, redo: pl.DataFrame) -> pl.DataFrame:
|
|
403
|
+
redo = redo.select(frame.columns)
|
|
404
|
+
pos = np.arange(frame.height)
|
|
405
|
+
keep = np.ones(frame.height, dtype=bool)
|
|
406
|
+
keep[rows] = False
|
|
407
|
+
a = frame.filter(pl.Series(keep)).with_columns(pl.Series("__pos", pos[keep]))
|
|
408
|
+
b = redo.with_columns(pl.Series("__pos", rows))
|
|
409
|
+
return pl.concat([a, b], how="vertical_relaxed").sort("__pos").drop("__pos")
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def generate_relational(rfp: RelationalFingerprint | Any, n_root: dict[str, int] | int | None
|
|
413
|
+
= None, seed: int = 42) -> dict[str, pl.DataFrame]:
|
|
414
|
+
"""Shortcut for ``RelationalGenerator.from_fingerprint(rfp).generate(n_root, seed)``."""
|
|
415
|
+
return RelationalGenerator.from_fingerprint(rfp).generate(n_root, seed)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
__all__ = ["RelationalGenerator", "generate_relational", "stratify_counts"]
|