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,525 @@
1
+ """Fixed-count generation from a fingerprint (no source data needed).
2
+
3
+ Pipeline for every chunk ``i`` (random streams are ``rng.stream(seed, "chunk", i, component)``):
4
+
5
+ 1. ``joint.sample`` latent normal scores (component ``"joint"``). A candidate row with a
6
+ score that is not a finite number would decode to nulls; it is dropped and replaced like a
7
+ rejected row and counted in the manifest's notes;
8
+ 2. ``encoder.decode`` to feature columns in source dtypes, nulls applied from the missingness
9
+ indicators (component ``"decode"``); with structural transforms (format 0.3,
10
+ ``profiling.structure``) the encoder is a :class:`~ectype.profiling.structure.
11
+ StructuredEncoder`: the inverse transforms run right after decoding, in topological order
12
+ (``target = base + sign * delta`` converted back with the target's schema, then
13
+ ``target = a op b`` rounded to its decimals), and the hidden ``__delta__*`` latents are
14
+ dropped, so everything below sees the source columns only. Orderings enforced without a
15
+ transform (format 0.4, ``model.orderings``) run in the same pass, each after what produces
16
+ its bounds: a row that breaks one gets a new value of the ordering's target from that
17
+ column's marginal truncated at the bound (``profiling.structure.redraw``; deterministic).
18
+ Calendars (format 0.4, ``model.calendars``, ADR-0012) run next: a date column with a
19
+ weekly profile has its rows moved by whole days onto that profile, with one uniform number
20
+ per row and calendar from the chunk's ``"decode"`` stream (``profiling.calendar``).
21
+ Entity groups (format 0.4, ``model.entities``, ADR-0013) run last: the key of a group is
22
+ made to agree with the group's anchor column (a row whose key belongs to another anchor
23
+ value gets a key of its own value, with one uniform number per row and anchored group
24
+ from the same ``"decode"`` stream), then every attribute of a row whose key has an entry
25
+ in the group's table is replaced by that entry (``profiling.entity``);
26
+ 3. clamp repair of simple bound constraints (``enforcement: repair``);
27
+ 4. constants, then null columns for columns that have no generator;
28
+ 5. derived columns, in dependency order, via native Polars expressions;
29
+ 6. hard constraints: rows whose expression is ``false`` are rejected (``null`` counts as
30
+ satisfied, SQL ``CHECK`` semantics). The chunk is topped up by drawing more candidates from
31
+ the *same, continued* chunk streams, for at most
32
+ ``manifest.generation.max_rejection_rounds`` rounds; if the chunk is still short (or no row
33
+ at all was accepted in the first ``ZERO_ACCEPTANCE_ROUNDS`` rounds) a
34
+ :class:`GenerationError` reports the acceptance rate and the violated constraint ids;
35
+ 7. identifiers are assigned to the accepted rows from the *global* output row index
36
+ (``int_sequence`` is ``start + index``, so it is unique across chunks);
37
+ 8. reference keys (format 0.4, ``model.references``, ADR-0013): up to here a ``reference``
38
+ column holds the group size the model drew for the row. The accepted rows of the chunk
39
+ that drew the same size are now grouped at random, and every group gets a fresh key
40
+ numbered from the global row index (``profiling.reference.assign_keys``; stream
41
+ ``(seed, "chunk", i, "reference", column)``). A group never spans two chunks.
42
+
43
+ Output has exactly ``n`` rows (``n == 0`` gives an empty frame with the output schema), the
44
+ columns in ``plan.output_columns`` order with source dtypes; excluded columns are omitted.
45
+
46
+ Reproducibility contract
47
+ ------------------------
48
+ Output is bit-for-bit identical for the same fingerprint (content hash), seed, chunk size,
49
+ engine version and pinned dependency versions (``generate_to`` writes byte-identical files).
50
+ Output is **not invariant to chunk size**: streams are keyed per chunk, so changing
51
+ ``chunk_size`` changes the rows (only ``int_sequence`` and ``string_token`` identifiers depend
52
+ on the global row index alone). Different chunk sizes are statistically equivalent.
53
+ """
54
+
55
+ from __future__ import annotations
56
+
57
+ import math
58
+ import time
59
+ from collections.abc import Iterator
60
+ from dataclasses import dataclass, field
61
+ from pathlib import Path
62
+ from typing import TYPE_CHECKING, Any
63
+
64
+ import numpy as np
65
+ import polars as pl
66
+
67
+ from ectype.compiler.plan import Plan, compile_plan, enum_downgrades
68
+ from ectype.errors import FingerprintError, GenerationError
69
+ from ectype.fingerprint.core import Fingerprint
70
+ from ectype.generation.enforce import (
71
+ apply_repairs,
72
+ cast_to,
73
+ dtype_from_string,
74
+ violation_masks,
75
+ )
76
+ from ectype.generation.identifiers import generate_identifier, identifier_capacity
77
+ from ectype.generation.manifest import (
78
+ ConstraintStats,
79
+ GenerationManifest,
80
+ config_hash,
81
+ )
82
+ from ectype.io.values import OTHER
83
+ from ectype.profiling.reference import finish_references, reference_capacity
84
+ from ectype.rng import stream
85
+
86
+ #: Give up on a chunk early if no candidate at all was accepted in this many rounds.
87
+ ZERO_ACCEPTANCE_ROUNDS = 5
88
+ #: Floor on the estimated acceptance rate when sizing top-up batches.
89
+ _MIN_RATE = 0.01
90
+ _ROW = "__ts_row__"
91
+ #: key of ``_RunStats.violations`` under which candidates dropped for a non-finite latent score
92
+ #: are counted (never a constraint id: those cannot start with two underscores and end so)
93
+ NONFINITE = "__nonfinite_scores__"
94
+ FORMATS = ("parquet", "csv")
95
+
96
+ if TYPE_CHECKING:
97
+ from ectype.models.base import JointModel
98
+ from ectype.models.encoding import MixedEncoder
99
+ from ectype.profiling.entity import EntityEncoder
100
+ from ectype.profiling.structure import StructuredEncoder
101
+
102
+
103
+ @dataclass
104
+ class _RunStats:
105
+ sampled: int = 0
106
+ emitted: int = 0
107
+ violations: dict[str, int] = field(default_factory=dict)
108
+ repaired: dict[str, int] = field(default_factory=dict)
109
+ pooled_to_null: dict[str, int] = field(default_factory=dict)
110
+
111
+
112
+ def _cast_identifier(s: pl.Series, dtype: pl.DataType | None) -> pl.Series:
113
+ """Cast an identifier column strictly: an out-of-range value must never become null."""
114
+ if dtype is None or s.dtype == dtype:
115
+ return s
116
+ try:
117
+ return s.cast(dtype, strict=True)
118
+ except (pl.exceptions.PolarsError, OverflowError) as exc:
119
+ raise GenerationError(f"identifier column {s.name!r} cannot be represented as "
120
+ f"{dtype}: {exc}") from exc
121
+
122
+
123
+ class Generator:
124
+ """Generate synthetic rows from a compiled fingerprint."""
125
+
126
+ last_manifest: GenerationManifest | None
127
+ joint: JointModel | None
128
+ #: decodes latent scores to source columns (a ``StructuredEncoder`` when the fingerprint
129
+ #: has structural transforms: its ``decode`` already applies them)
130
+ encoder: MixedEncoder | StructuredEncoder | EntityEncoder | None
131
+
132
+ def __init__(self, fp: Fingerprint, plan: Plan | None = None) -> None:
133
+ from ectype.models.base import joint_from_spec, marginal_from_spec
134
+ from ectype.models.copulas import IndependentJoint
135
+ from ectype.models.encoding import MISSING_PREFIX, MixedEncoder
136
+ from ectype.profiling.structure import StructuredEncoder
137
+
138
+ self.fingerprint = fp
139
+ self.plan = plan if plan is not None else compile_plan(fp)
140
+ self.last_manifest = None
141
+ model = fp.manifest.model
142
+ plan_ = self.plan
143
+ self.notes = list(plan_.notes)
144
+
145
+ self.encoder = None
146
+ self.joint = None
147
+ self._perm: np.ndarray | None = None
148
+ if plan_.feature_columns:
149
+ marginals = {c: marginal_from_spec(model.marginals[c], fp.arrays)
150
+ for c in plan_.feature_columns}
151
+ specs = dict(model.encodings)
152
+ for col, spec in model.missingness.items():
153
+ key = col if col.startswith(MISSING_PREFIX) else f"{MISSING_PREFIX}{col}"
154
+ specs[key] = spec
155
+ columns = [plan_.schema_of(c) for c in plan_.feature_columns]
156
+ inner = MixedEncoder.from_specs(specs, marginals, columns, fp.arrays)
157
+ self.encoder = inner
158
+ if plan_.transforms or plan_.orderings or plan_.calendars or plan_.sums:
159
+ self.encoder = StructuredEncoder(inner, plan_.transforms,
160
+ {**plan_.schemas, **plan_.latent_schemas},
161
+ plan_.orderings, plan_.calendars, plan_.sums)
162
+ if plan_.entities:
163
+ from ectype.profiling.entity import EntityEncoder
164
+ self.encoder = EntityEncoder(self.encoder, plan_.entities)
165
+ latent = list(self.encoder.latent_columns)
166
+ if model.joint is None:
167
+ self.joint = IndependentJoint(latent)
168
+ self.notes.append("no joint model in fingerprint; sampling independently")
169
+ else:
170
+ self.joint = joint_from_spec(model.joint, fp.arrays)
171
+ jcols = list(self.joint.columns)
172
+ if jcols != latent:
173
+ if sorted(jcols) != sorted(latent):
174
+ raise FingerprintError(
175
+ f"joint model columns {jcols} do not match the encoder's latent "
176
+ f"columns {latent}")
177
+ pos = {c: j for j, c in enumerate(jcols)}
178
+ self._perm = np.array([pos[c] for c in latent], dtype=np.int64)
179
+
180
+ self._dtypes = {c: dtype_from_string(plan_.schemas[c].physical_dtype)
181
+ if c in plan_.schemas else None for c in plan_.output_columns}
182
+ # Enum columns whose model can emit labels outside the categories (the pooled
183
+ # "__other__" bucket) are generated as String; compile_plan records the downgrade.
184
+ for c in enum_downgrades(fp):
185
+ if c in self._dtypes:
186
+ self._dtypes[c] = pl.String()
187
+ self._constants: dict[str, pl.Series] = {}
188
+ for c, v in plan_.constants.items():
189
+ self._constants[c] = cast_to(pl.Series(c, [v]), self._dtypes.get(c))
190
+
191
+ # -- construction --------------------------------------------------------------------
192
+ @classmethod
193
+ def from_fingerprint(cls, fp_or_path: Fingerprint | str | Path) -> Generator:
194
+ fp = fp_or_path if isinstance(fp_or_path, Fingerprint) else Fingerprint.load(fp_or_path)
195
+ return cls(fp)
196
+
197
+ # -- configuration ---------------------------------------------------------------------
198
+ def _resolve(self, n: int, seed: int | None, chunk_size: int | None) -> tuple[int, int, int]:
199
+ if isinstance(n, bool) or int(n) != n or n < 0:
200
+ raise ValueError(f"n must be a non-negative integer, got {n!r}")
201
+ gen = self.fingerprint.manifest.generation
202
+ seed = gen.default_seed if seed is None else int(seed)
203
+ chunk = gen.chunk_size if chunk_size is None else int(chunk_size)
204
+ if chunk < 1:
205
+ raise ValueError(f"chunk_size must be >= 1, got {chunk_size!r}")
206
+ for col, spec in self.plan.identifiers.items():
207
+ cap = identifier_capacity(spec, self.plan.schemas.get(col))
208
+ if cap is not None and cap < n:
209
+ raise GenerationError(f"identifier column {col!r} can produce at most {cap} "
210
+ f"unique values; {n} rows requested")
211
+ for col, spec in self.plan.references.items():
212
+ cap = reference_capacity(spec, self._dtypes.get(col))
213
+ if cap is not None and cap < n:
214
+ raise GenerationError(f"reference column {col!r} has room for {cap} fresh "
215
+ f"keys in its dtype; {n} rows requested")
216
+ return int(n), seed, chunk
217
+
218
+ # -- candidate rows --------------------------------------------------------------------
219
+ def _candidates(self, b: int, joint_rng: np.random.Generator,
220
+ decode_rng: np.random.Generator, stats: _RunStats) -> pl.DataFrame:
221
+ if self.encoder is not None and self.joint is not None:
222
+ z = self.joint.sample(b, joint_rng)
223
+ if self._perm is not None:
224
+ z = z[:, self._perm]
225
+ # A score that is not a number decodes to a null, also in a column (or in the
226
+ # hidden gap of a difference target) that is never missing. No joint model should
227
+ # return one; a candidate row that has one is dropped like a rejected row (the
228
+ # chunk is topped up from the same streams) and counted in the manifest.
229
+ finite = np.isfinite(z).all(axis=1)
230
+ if not finite.all():
231
+ stats.violations[NONFINITE] = stats.violations.get(NONFINITE, 0) + int(
232
+ (~finite).sum())
233
+ z = z[finite]
234
+ feats = self.encoder.decode(z, decode_rng)
235
+ df = pl.DataFrame({_ROW: np.zeros(feats.height, dtype=np.int8)})
236
+ df = df.hstack(self._normalize(feats, stats))
237
+ else:
238
+ df = pl.DataFrame({_ROW: np.zeros(b, dtype=np.int8)})
239
+ return self._complete(df, stats)
240
+
241
+ def _complete(self, df: pl.DataFrame, stats: _RunStats) -> pl.DataFrame:
242
+ """Repairs, constants, null columns and derived columns on decoded features."""
243
+ plan = self.plan
244
+ b = df.height
245
+ repairs = plan.repairs
246
+ if repairs:
247
+ df, counts = apply_repairs(df, repairs)
248
+ for k, v in counts.items():
249
+ stats.repaired[k] = stats.repaired.get(k, 0) + v
250
+ extra = []
251
+ for s1 in self._constants.values():
252
+ extra.append(s1.new_from_index(0, b) if b else s1.clear())
253
+ for c in plan.unmodeled:
254
+ extra.append(pl.repeat(None, b, dtype=self._dtypes.get(c) or pl.Null,
255
+ eager=True).alias(c))
256
+ if extra:
257
+ df = df.with_columns(extra)
258
+ for d in plan.derived:
259
+ df = df.with_columns(d.expr.alias(d.column))
260
+ dt = self._dtypes.get(d.column)
261
+ if dt is not None and df.schema[d.column] != dt:
262
+ df = df.with_columns(cast_to(df.get_column(d.column), dt))
263
+ return df
264
+
265
+ def _normalize(self, feats: pl.DataFrame, stats: _RunStats) -> pl.DataFrame:
266
+ """Cast decoded features to their source dtypes so the schema never depends on the
267
+ chunk. The pooled ``"__other__"`` category of a numerically coded categorical column
268
+ has no representation in that dtype and becomes null (counted in the manifest)."""
269
+ fixed = []
270
+ for name, dt in feats.schema.items():
271
+ target = self._dtypes.get(name)
272
+ if target is None or dt == target or name in self.plan.references:
273
+ continue # (a reference column holds group sizes until _finish)
274
+ s = feats.get_column(name)
275
+ if dt == pl.String:
276
+ n_other = int((s == OTHER).sum())
277
+ if n_other:
278
+ stats.pooled_to_null[name] = stats.pooled_to_null.get(name, 0) + n_other
279
+ fixed.append(cast_to(s, target))
280
+ return feats.with_columns(fixed) if fixed else feats
281
+
282
+ def rejection_mask(self, features: pl.DataFrame) -> np.ndarray:
283
+ """``True`` for rows of decoded feature columns that the hard constraints would reject
284
+ (after the same normalisation, repair and derivation the generator applies). Used to
285
+ diagnose how rejection reweights sub-populations, e.g. merged components."""
286
+ stats = _RunStats()
287
+ plan = self.plan
288
+ df = pl.DataFrame({_ROW: np.zeros(features.height, dtype=np.int8)})
289
+ if features.width:
290
+ feats = features.select([c for c in features.columns
291
+ if c in plan.decoded_columns or c in plan.latent_schemas])
292
+ if plan.steps or plan.sums:
293
+ # undecoded latents (rather than source columns): compute their targets; the
294
+ # orderings are enforced as in decoding (a no-op on rows that went through it)
295
+ from ectype.profiling.structure import apply_structure
296
+ from ectype.profiling.sums import apply_sums
297
+ inner = getattr(self.encoder, "inner", None)
298
+ marginals = inner.marginals if inner is not None else {}
299
+ known = {**plan.schemas, **plan.latent_schemas}
300
+ feats = apply_sums(apply_structure(feats, plan.steps, known, marginals),
301
+ plan.sums, known)
302
+ feats = feats.drop([c for c in feats.columns if c in plan.latent_schemas])
303
+ df = df.hstack(self._normalize(feats, stats))
304
+ df = self._complete(df, stats)
305
+ bad = np.zeros(df.height, dtype=bool)
306
+ for mk in violation_masks(df, self.plan.constraints).values():
307
+ bad |= mk
308
+ return bad
309
+
310
+ def generate_chunk(self, i: int, n: int, seed: int | None = None, *,
311
+ chunk_size: int | None = None) -> tuple[pl.DataFrame, _RunStats]:
312
+ """Generate chunk ``i`` of an ``n``-row run exactly as the sequential generator would.
313
+
314
+ Used by parallel/distributed generation: concatenating chunks ``0..k`` in order equals
315
+ ``generate(n, seed, chunk_size=chunk_size)`` byte for byte. Returns the frame and the
316
+ chunk's enforcement statistics (mergeable).
317
+ """
318
+ gen_defaults = self.fingerprint.manifest.generation
319
+ s = gen_defaults.default_seed if seed is None else int(seed)
320
+ chunk = int(chunk_size or gen_defaults.chunk_size)
321
+ start = i * chunk
322
+ if i < 0 or (n > 0 and start >= n):
323
+ raise GenerationError(f"chunk {i} is outside a {n}-row run of {chunk}-row chunks")
324
+ m = max(0, min(chunk, n - start))
325
+ stats = _RunStats()
326
+ stats.emitted = start
327
+ return self._chunk(i, m, s, stats), stats
328
+
329
+ def _chunk(self, i: int, m: int, seed: int, stats: _RunStats) -> pl.DataFrame:
330
+ plan = self.plan
331
+ joint_rng = stream(seed, "chunk", i, "joint")
332
+ decode_rng = stream(seed, "chunk", i, "decode")
333
+ max_rounds = max(1, int(self.fingerprint.manifest.generation.max_rejection_rounds))
334
+ parts: list[pl.DataFrame] = []
335
+ accepted = sampled = 0
336
+ cap = max(4 * m, 64)
337
+ rounds = 0
338
+ while True:
339
+ need = m - accepted
340
+ if rounds == 0:
341
+ b = m
342
+ else:
343
+ rate = max(accepted / max(sampled, 1), _MIN_RATE)
344
+ b = min(cap, math.ceil(need / rate * 1.2) + 8)
345
+ frame = self._candidates(b, joint_rng, decode_rng, stats)
346
+ sampled += b
347
+ rounds += 1
348
+ if plan.constraints:
349
+ masks = violation_masks(frame, plan.constraints)
350
+ bad = np.zeros(frame.height, dtype=bool)
351
+ for cid, mk in masks.items():
352
+ stats.violations[cid] = stats.violations.get(cid, 0) + int(mk.sum())
353
+ bad |= mk
354
+ if bad.any():
355
+ frame = frame.filter(pl.Series(~bad))
356
+ parts.append(frame)
357
+ accepted += frame.height
358
+ if accepted >= m:
359
+ break
360
+ if rounds >= max_rounds or (accepted == 0 and rounds >= ZERO_ACCEPTANCE_ROUNDS):
361
+ stats.sampled += sampled
362
+ worst = sorted(((v, k) for k, v in stats.violations.items() if v), reverse=True)
363
+ ids = [k for _, k in worst]
364
+ rate = accepted / max(sampled, 1)
365
+ raise GenerationError(
366
+ f"could not generate {m} rows for chunk {i} after {rounds} rejection "
367
+ f"rounds: accepted {accepted} of {sampled} candidates (acceptance rate "
368
+ f"{rate:.4%}). Violated constraints (most violations first): {ids} "
369
+ f"(violation counts {dict((k, v) for v, k in worst)}). The constraints "
370
+ f"may be infeasible under the model, or contradictory.")
371
+ stats.sampled += sampled
372
+ out = pl.concat(parts, how="vertical") if len(parts) > 1 else parts[0]
373
+ out = out.head(m)
374
+ return self._finish(out, ("chunk", i), seed, stats)
375
+
376
+ def _finish(self, df: pl.DataFrame, key: tuple[str | int, ...], seed: int,
377
+ stats: _RunStats) -> pl.DataFrame:
378
+ m = df.height
379
+ ids = []
380
+ for col, spec in self.plan.identifiers.items():
381
+ s = generate_identifier(spec, self.plan.schemas.get(col), m, stats.emitted,
382
+ stream(seed, "identifier", col, "key"),
383
+ stream(seed, *key, "identifier", col))
384
+ s = _cast_identifier(s.alias(col), self._dtypes.get(col))
385
+ # An identifier that is empty in part of the source (an optional reference such as
386
+ # a parent key) keeps that share of empty cells. The cells are chosen independently
387
+ # of the other columns: the identifier itself is regenerated, never modelled.
388
+ schema = self.plan.schemas.get(col)
389
+ null_share = float(getattr(schema, "null_fraction", 0.0) or 0.0)
390
+ if null_share > 0.0:
391
+ empty = stream(seed, *key, "identifier", col, "null").random(m) < null_share
392
+ s = pl.select(pl.when(pl.Series(empty)).then(None).otherwise(s).alias(col)
393
+ ).to_series()
394
+ ids.append(s)
395
+ if ids:
396
+ df = df.with_columns(ids)
397
+ if self.plan.references:
398
+ df = finish_references(df, self.plan.references, stats.emitted,
399
+ lambda col: stream(seed, *key, "reference", col))
400
+ stats.emitted += m
401
+ cols = []
402
+ for c in self.plan.output_columns:
403
+ s = df.get_column(c)
404
+ cols.append(cast_to(s, self._dtypes.get(c)))
405
+ return pl.DataFrame(cols)
406
+
407
+ def _empty(self, seed: int) -> pl.DataFrame:
408
+ stats = _RunStats()
409
+ df = self._candidates(0, stream(seed, "empty", "joint"), stream(seed, "empty", "decode"),
410
+ stats)
411
+ return self._finish(df, ("empty",), seed, stats)
412
+
413
+ def iter_chunks(self, n: int, seed: int | None = None, *, chunk_size: int | None = None
414
+ ) -> Iterator[pl.DataFrame]:
415
+ """Yield the output in chunks (memory bounded by ``chunk_size``)."""
416
+ n, seed, chunk = self._resolve(n, seed, chunk_size)
417
+ yield from self._iter(n, seed, chunk, _RunStats())
418
+
419
+ def _iter(self, n: int, seed: int, chunk: int, stats: _RunStats) -> Iterator[pl.DataFrame]:
420
+ n_chunks = math.ceil(n / chunk)
421
+ for i in range(n_chunks):
422
+ m = min(chunk, n - i * chunk)
423
+ yield self._chunk(i, m, seed, stats)
424
+
425
+ # -- manifest ----------------------------------------------------------------------------
426
+ def _manifest(self, n: int, seed: int, chunk: int, stats: _RunStats, wall: float,
427
+ path: str | None = None, fmt: str | None = None) -> GenerationManifest:
428
+ gen = self.fingerprint.manifest.generation
429
+ config: dict[str, Any] = {
430
+ "n": n, "seed": seed, "chunk_size": chunk,
431
+ "max_rejection_rounds": gen.max_rejection_rounds,
432
+ "zero_acceptance_rounds": ZERO_ACCEPTANCE_ROUNDS,
433
+ "format": fmt,
434
+ }
435
+ constraints = {
436
+ c.id: ConstraintStats(enforcement=c.enforcement.value,
437
+ violations=stats.violations.get(c.id, 0),
438
+ repaired=stats.repaired.get(c.id, 0))
439
+ for c in self.plan.constraints}
440
+ for c in self.plan.measured:
441
+ constraints[c.id] = ConstraintStats(enforcement="none")
442
+ notes = list(self.notes)
443
+ if stats.violations.get(NONFINITE):
444
+ notes.append(f"{stats.violations[NONFINITE]} candidate row(s) were dropped and "
445
+ f"replaced because the joint model returned a latent score that is "
446
+ f"not a finite number (a fault of the joint model: please report it)")
447
+ return GenerationManifest(
448
+ fingerprint_hash=self.plan.fingerprint_hash, seed=seed, n_rows=n,
449
+ chunk_size=chunk, n_chunks=math.ceil(n / chunk), config=config,
450
+ config_hash=config_hash(config), rows_sampled=stats.sampled,
451
+ acceptance_rate=(n / stats.sampled) if stats.sampled else 1.0,
452
+ constraints=constraints, chunk_size_invariant=False, wall_time_s=wall,
453
+ output_path=path, format=fmt, notes=notes,
454
+ pooled_to_null=dict(stats.pooled_to_null))
455
+
456
+ # -- public API --------------------------------------------------------------------------
457
+ def generate(self, n: int, seed: int | None = None, *, chunk_size: int | None = None
458
+ ) -> pl.DataFrame:
459
+ """Generate exactly ``n`` rows. Sets :attr:`last_manifest`."""
460
+ t0 = time.perf_counter()
461
+ n, seed, chunk = self._resolve(n, seed, chunk_size)
462
+ stats = _RunStats()
463
+ parts = list(self._iter(n, seed, chunk, stats))
464
+ if not parts:
465
+ out = self._empty(seed)
466
+ elif len(parts) == 1:
467
+ out = parts[0]
468
+ else:
469
+ out = pl.concat(parts, how="vertical")
470
+ self.last_manifest = self._manifest(n, seed, chunk, stats, time.perf_counter() - t0)
471
+ return out
472
+
473
+ def generate_to(self, path: str | Path, n: int, seed: int | None = None, *,
474
+ chunk_size: int | None = None, format: str | None = None
475
+ ) -> GenerationManifest:
476
+ """Stream ``n`` rows to a Parquet or CSV file chunk by chunk (bounded memory)."""
477
+ t0 = time.perf_counter()
478
+ n, seed, chunk = self._resolve(n, seed, chunk_size)
479
+ path = Path(path)
480
+ fmt = (format or path.suffix.lstrip(".")).lower()
481
+ if fmt == "pq":
482
+ fmt = "parquet"
483
+ if fmt not in FORMATS:
484
+ raise ValueError(f"unsupported output format {fmt!r}; use one of {FORMATS}")
485
+ path.parent.mkdir(parents=True, exist_ok=True)
486
+ stats = _RunStats()
487
+ chunks = self._iter(n, seed, chunk, stats)
488
+ if fmt == "parquet":
489
+ import pyarrow.parquet as pq
490
+
491
+ writer = None
492
+ try:
493
+ for df in chunks:
494
+ table = df.to_arrow()
495
+ if writer is None:
496
+ writer = pq.ParquetWriter(str(path), table.schema, compression="snappy")
497
+ writer.write_table(table)
498
+ if writer is None:
499
+ table = self._empty(seed).to_arrow()
500
+ writer = pq.ParquetWriter(str(path), table.schema, compression="snappy")
501
+ writer.write_table(table)
502
+ finally:
503
+ if writer is not None:
504
+ writer.close()
505
+ else:
506
+ with path.open("wb") as fh:
507
+ first = True
508
+ for df in chunks:
509
+ df.write_csv(fh, include_header=first)
510
+ first = False
511
+ if first:
512
+ self._empty(seed).write_csv(fh, include_header=True)
513
+ manifest = self._manifest(n, seed, chunk, stats, time.perf_counter() - t0,
514
+ str(path), fmt)
515
+ self.last_manifest = manifest
516
+ return manifest
517
+
518
+
519
+ def generate(fp_or_path: Fingerprint | str | Path, n: int, seed: int | None = None, *,
520
+ chunk_size: int | None = None) -> pl.DataFrame:
521
+ """Shortcut for ``Generator.from_fingerprint(fp).generate(n, seed, chunk_size=...)``."""
522
+ return Generator.from_fingerprint(fp_or_path).generate(n, seed, chunk_size=chunk_size)
523
+
524
+
525
+ __all__ = ["FORMATS", "Generator", "ZERO_ACCEPTANCE_ROUNDS", "generate"]