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,334 @@
|
|
|
1
|
+
"""Reference keys (ADR-0013): repeating keys that are regenerated, with their repeat structure.
|
|
2
|
+
|
|
3
|
+
A *reference* is a key to another record that occurs on several rows: a parent or master
|
|
4
|
+
record, an order on its order lines, a household on its members. It is not unique, so it is not
|
|
5
|
+
an identifier; its values are not levels worth keeping either, because nearly all of them occur
|
|
6
|
+
on a handful of rows. What such a column holds is a **repeat structure**: how many rows share a
|
|
7
|
+
key, which rows have none, and how both relate to the other columns.
|
|
8
|
+
|
|
9
|
+
A column with the role ``reference`` is therefore modeled by one number per row, the *group
|
|
10
|
+
size*: the number of rows that carry the same key (null where the cell is empty).
|
|
11
|
+
|
|
12
|
+
* **At the door.** :func:`rewrite_references` runs right after the structural profile and
|
|
13
|
+
pseudonymisation, before anything is fitted. It replaces every key by its group size, so the
|
|
14
|
+
marginal, the encoding, the slot in the joint model, the targets and the diagnostics are those
|
|
15
|
+
of an ordinary discrete column whose values are counts. No stage that stores something ever
|
|
16
|
+
sees a key value, and nothing derived from a single key is kept.
|
|
17
|
+
* **At generation.** The model draws a group size per row (or an empty cell, through the
|
|
18
|
+
column's missingness indicator, which the joint model ties to the other columns like any
|
|
19
|
+
other). :func:`assign_keys` then forms the groups: among the rows of a chunk that drew size
|
|
20
|
+
``s``, every ``s`` rows get one fresh key (the last group of a size is smaller when the rows
|
|
21
|
+
do not divide). Rows are matched at random, so nothing but the size ties the members of a
|
|
22
|
+
group together.
|
|
23
|
+
* **Surrogate values** never equal a source value:
|
|
24
|
+
|
|
25
|
+
``sequence`` integer columns: ``start + n`` with ``start`` above every key of the source
|
|
26
|
+
(the largest key rounded up to two significant digits, so the stored number
|
|
27
|
+
says how long the keys are and nothing more precise).
|
|
28
|
+
``token`` text columns: ``<column>_<tag>_<n>``, with a tag drawn at fit time such that no
|
|
29
|
+
source value starts with it.
|
|
30
|
+
|
|
31
|
+
``n`` is the position of the group in the whole output (the offset of the chunk plus a
|
|
32
|
+
number shuffled inside the chunk), so keys are unique across chunks and parallel generation
|
|
33
|
+
equals sequential generation.
|
|
34
|
+
|
|
35
|
+
Validation compares a table through the same lens: :func:`size_view` replaces the reference
|
|
36
|
+
columns of any frame (synthetic or real) by group sizes before a target is measured, so no
|
|
37
|
+
comparison ever needs a key to match.
|
|
38
|
+
|
|
39
|
+
Limits. A group lives inside one chunk (``chunk_size`` rows, 100,000 by default), and group
|
|
40
|
+
sizes are counts, not shares: a table generated at another size has groups as large as the
|
|
41
|
+
source's, and more or fewer of them.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
from __future__ import annotations
|
|
45
|
+
|
|
46
|
+
import math
|
|
47
|
+
import re
|
|
48
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
49
|
+
from typing import Any
|
|
50
|
+
|
|
51
|
+
import numpy as np
|
|
52
|
+
import polars as pl
|
|
53
|
+
|
|
54
|
+
from ectype.errors import GenerationError, ProfilingError
|
|
55
|
+
from ectype.fingerprint.disclosure import clip_bounds
|
|
56
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, ModelSpec
|
|
57
|
+
from ectype.rng import stream
|
|
58
|
+
from ectype.types import LogicalType, Role
|
|
59
|
+
|
|
60
|
+
__all__ = ["KINDS", "KIND_SEQUENCE", "KIND_TOKEN", "START_DIGITS", "TAG_LENGTH",
|
|
61
|
+
"assign_keys", "check_references", "finish_references", "group_sizes", "has_room",
|
|
62
|
+
"model_view", "reference_capacity",
|
|
63
|
+
"rewrite_references", "size_view", "supports_reference"]
|
|
64
|
+
|
|
65
|
+
KIND_SEQUENCE = "surrogate_sequence"
|
|
66
|
+
KIND_TOKEN = "surrogate_token"
|
|
67
|
+
KINDS = (KIND_SEQUENCE, KIND_TOKEN)
|
|
68
|
+
#: significant digits of the first surrogate integer (the largest source key, rounded up)
|
|
69
|
+
START_DIGITS = 2
|
|
70
|
+
#: length and alphabet of the tag of text surrogates (as for pseudonym tokens: no vowels, no
|
|
71
|
+
#: characters that are easily confused)
|
|
72
|
+
TAG_LENGTH = 4
|
|
73
|
+
_TAG_ALPHABET = "bcdfghjkmnpqrstvwxz23456789"
|
|
74
|
+
#: an integer column needs room for this many times its rows above ``start``
|
|
75
|
+
_ROOM_FACTOR = 100
|
|
76
|
+
_FLOAT_MAX = 2.0 ** 53
|
|
77
|
+
_TAG_DRAWS = 50
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def supports_reference(dtype: pl.DataType, integral: bool = True) -> bool:
|
|
81
|
+
"""Whether a column of ``dtype`` can be a reference: text, or integer keys (an integer
|
|
82
|
+
dtype, or a float column whose values are all whole numbers)."""
|
|
83
|
+
if dtype in (pl.String, pl.Categorical) or isinstance(dtype, pl.Enum):
|
|
84
|
+
return True
|
|
85
|
+
if dtype.is_integer():
|
|
86
|
+
return True
|
|
87
|
+
return bool(dtype.is_float() and integral)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _clean(s: pl.Series) -> pl.Series:
|
|
91
|
+
return s.fill_nan(None) if s.dtype.is_float() else s
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def group_sizes(s: pl.Series) -> pl.Series:
|
|
95
|
+
"""For every row, the number of rows of ``s`` that hold the same value (null for an empty
|
|
96
|
+
cell), as ``Int64``."""
|
|
97
|
+
s = _clean(s)
|
|
98
|
+
if isinstance(s.dtype, pl.Categorical | pl.Enum):
|
|
99
|
+
s = s.cast(pl.String)
|
|
100
|
+
frame = pl.DataFrame({"k": s})
|
|
101
|
+
return frame.select(
|
|
102
|
+
pl.when(pl.col("k").is_null()).then(None).otherwise(pl.len().over("k"))
|
|
103
|
+
.cast(pl.Int64).alias(s.name)).to_series()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _dtype_max(dtype: pl.DataType) -> float:
|
|
107
|
+
if dtype.is_float():
|
|
108
|
+
return _FLOAT_MAX
|
|
109
|
+
try:
|
|
110
|
+
return float(np.iinfo(str(dtype).lower()).max)
|
|
111
|
+
except (TypeError, ValueError):
|
|
112
|
+
return _FLOAT_MAX
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _round_up(value: int, digits: int = START_DIGITS) -> int:
|
|
116
|
+
"""The smallest integer with at most ``digits`` significant digits that is above
|
|
117
|
+
``value``."""
|
|
118
|
+
v = max(int(value), 0) + 1
|
|
119
|
+
scale = 10 ** max(len(str(v)) - digits, 0)
|
|
120
|
+
return int(math.ceil(v / scale) * scale)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _slug(name: str) -> str:
|
|
124
|
+
return re.sub(r"[^0-9a-z]+", "_", str(name).lower()).strip("_") or "key"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def has_room(dtype: pl.DataType, nonnull: pl.Series) -> bool:
|
|
128
|
+
"""Whether a numeric dtype has room for fresh keys above the largest of ``nonnull``."""
|
|
129
|
+
top = int(nonnull.max()) if nonnull.len() else 0 # type: ignore[arg-type]
|
|
130
|
+
return _dtype_max(dtype) - _round_up(top) >= _ROOM_FACTOR * max(nonnull.len(), 1)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _spec(s: pl.Series, col: ColumnSchema, seed: int) -> ModelSpec:
|
|
134
|
+
"""How the surrogate keys of ``s`` are written (see the module docstring)."""
|
|
135
|
+
nn = _clean(s).drop_nulls()
|
|
136
|
+
if s.dtype.is_numeric():
|
|
137
|
+
if not has_room(s.dtype, nn):
|
|
138
|
+
raise ProfilingError(
|
|
139
|
+
f"column {col.name!r} cannot have the role 'reference': its dtype {s.dtype} "
|
|
140
|
+
f"has no room for fresh keys above the source's (cast the column to Int64 or "
|
|
141
|
+
f"to strings first)")
|
|
142
|
+
top = int(nn.max()) if nn.len() else 0 # type: ignore[arg-type]
|
|
143
|
+
return ModelSpec(kind=KIND_SEQUENCE, params={"start": _round_up(top)})
|
|
144
|
+
text = nn.cast(pl.String)
|
|
145
|
+
if text.len() and bool(text.str.contains(r"^[0-9]{1,17}$").all()):
|
|
146
|
+
# digit strings: the keys stay digit strings, above every key of the source
|
|
147
|
+
top = int(text.cast(pl.Int64).max()) # type: ignore[arg-type]
|
|
148
|
+
return ModelSpec(kind=KIND_SEQUENCE, params={"start": _round_up(top)})
|
|
149
|
+
rng = stream(seed, "reference", col.name, "tag")
|
|
150
|
+
slug = _slug(col.name)
|
|
151
|
+
for _ in range(_TAG_DRAWS):
|
|
152
|
+
tag = "".join(_TAG_ALPHABET[int(i)]
|
|
153
|
+
for i in rng.integers(0, len(_TAG_ALPHABET), TAG_LENGTH))
|
|
154
|
+
prefix = f"{slug}_{tag}_"
|
|
155
|
+
if not bool(text.str.starts_with(prefix).any()):
|
|
156
|
+
return ModelSpec(kind=KIND_TOKEN, params={"prefix": prefix})
|
|
157
|
+
raise ProfilingError(f"cannot give column {col.name!r} the role 'reference': no free "
|
|
158
|
+
f"prefix for its surrogate keys") # pragma: no cover
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _rewrite(s: pl.Series, col: ColumnSchema, policy: DisclosurePolicySpec, seed: int
|
|
162
|
+
) -> tuple[pl.Series, ColumnSchema, ModelSpec]:
|
|
163
|
+
clean = _clean(s)
|
|
164
|
+
nn = clean.drop_nulls()
|
|
165
|
+
integral = bool((nn == nn.round(0)).all()) if s.dtype.is_float() and nn.len() else True
|
|
166
|
+
if not supports_reference(s.dtype, integral):
|
|
167
|
+
raise ProfilingError(
|
|
168
|
+
f"column {col.name!r} ({s.dtype}) cannot have the role 'reference': it needs text "
|
|
169
|
+
f"or integer keys")
|
|
170
|
+
spec = _spec(s, col, seed)
|
|
171
|
+
sizes = group_sizes(s)
|
|
172
|
+
values = sizes.drop_nulls().cast(pl.Float64).to_numpy()
|
|
173
|
+
lo, hi = (None, None)
|
|
174
|
+
if values.size:
|
|
175
|
+
a, b = clip_bounds(values, policy)
|
|
176
|
+
if math.isfinite(a) and math.isfinite(b):
|
|
177
|
+
lo, hi = max(float(a), 1.0), float(b)
|
|
178
|
+
physical = col.physical_dtype
|
|
179
|
+
if physical.startswith(("Enum", "Categorical")):
|
|
180
|
+
physical = "String" # an Enum dtype lists the source keys
|
|
181
|
+
nulls = int(clean.null_count())
|
|
182
|
+
how = ("fresh integers above every key of the source" if spec.kind == KIND_SEQUENCE
|
|
183
|
+
else f"fresh tokens such as '{spec.params['prefix']}000123'")
|
|
184
|
+
note = (f"reference key: modeled by the number of rows that share a key (and by its empty "
|
|
185
|
+
f"cells); generated keys are {how}, never a source value")
|
|
186
|
+
schema = col.model_copy(update={
|
|
187
|
+
"logical_type": LogicalType.DISCRETE, "physical_dtype": physical,
|
|
188
|
+
"nullable": nulls > 0, "null_fraction": float(nulls / s.len()) if s.len() else 0.0,
|
|
189
|
+
"n_unique": None, "decimals": 0, "min_value": lo, "max_value": hi,
|
|
190
|
+
"integer_valued": True, "pattern": None, "bool_labels": None,
|
|
191
|
+
"datetime_unit": None, "timezone": None, "is_date": False,
|
|
192
|
+
"notes": [*col.notes, note]})
|
|
193
|
+
return sizes.alias(col.name), schema, spec
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def rewrite_references(df: pl.DataFrame, columns: Sequence[ColumnSchema],
|
|
197
|
+
policy: DisclosurePolicySpec, seed: int
|
|
198
|
+
) -> tuple[pl.DataFrame, list[ColumnSchema], dict[str, ModelSpec]]:
|
|
199
|
+
"""Replace the keys of every ``reference`` column of ``df`` by group sizes.
|
|
200
|
+
|
|
201
|
+
Returns the rewritten frame, the column schemas (each reference column as a discrete
|
|
202
|
+
column of counts, with a note) and the surrogate-key spec of each such column
|
|
203
|
+
(``manifest.model.references``). ``df`` is returned unchanged when no column has the role.
|
|
204
|
+
"""
|
|
205
|
+
out: list[ColumnSchema] = []
|
|
206
|
+
replaced: list[pl.Series] = []
|
|
207
|
+
specs: dict[str, ModelSpec] = {}
|
|
208
|
+
for col in columns:
|
|
209
|
+
if col.role != Role.REFERENCE or col.name not in df.columns:
|
|
210
|
+
out.append(col)
|
|
211
|
+
continue
|
|
212
|
+
series, schema, spec = _rewrite(df.get_column(col.name), col, policy, seed)
|
|
213
|
+
replaced.append(series)
|
|
214
|
+
out.append(schema)
|
|
215
|
+
specs[col.name] = spec
|
|
216
|
+
if replaced:
|
|
217
|
+
df = df.with_columns(replaced)
|
|
218
|
+
return df, out, specs
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def size_view(df: pl.DataFrame, columns: Sequence[str]) -> pl.DataFrame:
|
|
222
|
+
"""``df`` with each of ``columns`` (reference columns holding keys) replaced by the group
|
|
223
|
+
size of its rows: the form in which a reference column is modeled and measured."""
|
|
224
|
+
present = [c for c in columns if c in df.columns]
|
|
225
|
+
if not present:
|
|
226
|
+
return df
|
|
227
|
+
return df.with_columns([group_sizes(df.get_column(c)) for c in present])
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def model_view(df: pl.DataFrame, manifest: Any) -> pl.DataFrame:
|
|
231
|
+
"""Generated (or real) rows as the model and its targets see them: the ``reference``
|
|
232
|
+
columns of ``manifest`` as group sizes (:func:`size_view`). Everything that measures a
|
|
233
|
+
table against a fingerprint's targets (validation, calibration, the scenario operations)
|
|
234
|
+
reads it through this."""
|
|
235
|
+
return size_view(df, [c.name for c in manifest.columns if c.role == Role.REFERENCE])
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
# ---------------------------------------------------------------------------------------------
|
|
239
|
+
# Generation
|
|
240
|
+
# ---------------------------------------------------------------------------------------------
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def check_references(references: Mapping[str, ModelSpec],
|
|
244
|
+
schemas: Mapping[str, ColumnSchema]) -> list[str]:
|
|
245
|
+
"""Problems that make ``references`` unusable (empty when they are fine)."""
|
|
246
|
+
problems: list[str] = []
|
|
247
|
+
for col, spec in references.items():
|
|
248
|
+
schema = schemas.get(col)
|
|
249
|
+
if schema is None or schema.role != Role.REFERENCE:
|
|
250
|
+
problems.append(f"reference {col!r}: not a column with the role 'reference'")
|
|
251
|
+
continue
|
|
252
|
+
if spec.kind == KIND_SEQUENCE:
|
|
253
|
+
start = spec.params.get("start")
|
|
254
|
+
if isinstance(start, bool) or not isinstance(start, int) or start < 0:
|
|
255
|
+
problems.append(f"reference {col!r}: 'start' must be a non-negative integer")
|
|
256
|
+
unknown = sorted(set(spec.params) - {"start"})
|
|
257
|
+
elif spec.kind == KIND_TOKEN:
|
|
258
|
+
prefix = spec.params.get("prefix")
|
|
259
|
+
if not isinstance(prefix, str) or not prefix:
|
|
260
|
+
problems.append(f"reference {col!r}: 'prefix' must be a non-empty string")
|
|
261
|
+
unknown = sorted(set(spec.params) - {"prefix"})
|
|
262
|
+
else:
|
|
263
|
+
problems.append(f"reference {col!r}: unknown kind {spec.kind!r}")
|
|
264
|
+
continue
|
|
265
|
+
if unknown:
|
|
266
|
+
problems.append(f"reference {col!r}: unknown parameter(s) {unknown}")
|
|
267
|
+
return problems
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def reference_capacity(spec: ModelSpec, dtype: pl.DataType | None) -> int | None:
|
|
271
|
+
"""How many rows a reference column can be generated for (``None``: no limit)."""
|
|
272
|
+
if spec.kind != KIND_SEQUENCE or dtype is None or not dtype.is_numeric():
|
|
273
|
+
return None
|
|
274
|
+
return max(int(_dtype_max(dtype) - int(spec.params["start"])), 0) # type: ignore[call-overload]
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def assign_keys(sizes: pl.Series, spec: ModelSpec, offset: int,
|
|
278
|
+
rng: np.random.Generator) -> pl.Series:
|
|
279
|
+
"""Fresh keys for one chunk of generated rows.
|
|
280
|
+
|
|
281
|
+
``sizes`` holds the group size the model drew for each row (null: an empty cell; any
|
|
282
|
+
dtype, read as numbers). Among the rows with size ``s``, taken in a random order, every
|
|
283
|
+
``s`` consecutive rows form a group. Group ``g`` of the chunk gets the surrogate number
|
|
284
|
+
``offset + p(g) + 1`` with ``p`` a random permutation of the chunk's rows, so numbers are
|
|
285
|
+
unique within the chunk, unrelated to the sizes, and (``offset`` being the number of rows
|
|
286
|
+
emitted before the chunk) unique across chunks. Returns ``Int64`` keys for a
|
|
287
|
+
``sequence`` spec and text for a ``token`` spec.
|
|
288
|
+
"""
|
|
289
|
+
m = sizes.len()
|
|
290
|
+
raw = sizes.cast(pl.Float64, strict=False).fill_nan(None)
|
|
291
|
+
empty = raw.is_null().to_numpy()
|
|
292
|
+
s = np.where(empty, 1.0, np.maximum(np.rint(raw.fill_null(1.0).to_numpy()), 1.0))
|
|
293
|
+
s = s.astype(np.int64)
|
|
294
|
+
shuffle = rng.random(m)
|
|
295
|
+
slots = rng.permutation(m)
|
|
296
|
+
order = np.lexsort((shuffle, s, empty)) # filled rows first, by size, shuffled
|
|
297
|
+
n_filled = int((~empty).sum())
|
|
298
|
+
filled = order[:n_filled]
|
|
299
|
+
number = np.zeros(m, dtype=np.int64)
|
|
300
|
+
if n_filled:
|
|
301
|
+
ss = s[filled]
|
|
302
|
+
first = np.flatnonzero(np.r_[True, ss[1:] != ss[:-1]])
|
|
303
|
+
run = np.repeat(first, np.diff(np.r_[first, n_filled]))
|
|
304
|
+
within = (np.arange(n_filled) - run) // ss # group number inside a size
|
|
305
|
+
new_group = np.r_[True, (ss[1:] != ss[:-1]) | (within[1:] != within[:-1])]
|
|
306
|
+
group = np.cumsum(new_group) - 1 # group number inside the chunk
|
|
307
|
+
number[filled] = int(offset) + slots[group] + 1
|
|
308
|
+
keys: pl.Series
|
|
309
|
+
if spec.kind == KIND_SEQUENCE:
|
|
310
|
+
keys = pl.Series(sizes.name, number + int(spec.params["start"]), # type: ignore[call-overload]
|
|
311
|
+
dtype=pl.Int64)
|
|
312
|
+
elif spec.kind == KIND_TOKEN:
|
|
313
|
+
prefix = str(spec.params["prefix"])
|
|
314
|
+
keys = (prefix + pl.Series(sizes.name, number).cast(pl.String).str.zfill(6)
|
|
315
|
+
).alias(sizes.name)
|
|
316
|
+
else:
|
|
317
|
+
raise GenerationError(f"reference {sizes.name!r}: unknown kind {spec.kind!r}")
|
|
318
|
+
return pl.select(pl.when(pl.Series(empty)).then(None).otherwise(keys)
|
|
319
|
+
.alias(sizes.name)).to_series()
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def finish_references(df: pl.DataFrame, references: Mapping[str, ModelSpec], offset: int,
|
|
323
|
+
rng_for: Callable[[str], np.random.Generator]) -> pl.DataFrame:
|
|
324
|
+
"""Replace the group sizes in the reference columns of a finished chunk by fresh keys
|
|
325
|
+
(:func:`assign_keys`); ``rng_for(column)`` gives the stream of each column."""
|
|
326
|
+
done: list[pl.Series] = []
|
|
327
|
+
for col, spec in references.items():
|
|
328
|
+
if col in df.columns:
|
|
329
|
+
done.append(assign_keys(df.get_column(col), spec, offset, rng_for(col)))
|
|
330
|
+
return df.with_columns(done) if done else df
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def describe(references: Mapping[str, ModelSpec]) -> dict[str, Any]:
|
|
334
|
+
return {c: s.kind for c, s in references.items()}
|