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,235 @@
1
+ """Synthetic identifier generators (identifiers are always regenerated, never copied).
2
+
3
+ Kinds (``manifest.model.identifiers[col].kind``):
4
+
5
+ * ``int_sequence`` ``{start}`` -- ``start + global_row_index``. Globally unique across chunks
6
+ because the generator passes the number of rows already emitted as ``offset``.
7
+ * ``uuid4`` ``{}`` -- RFC 4122 version-4 UUID strings built from the chunk's identifier stream
8
+ bytes (deterministic for a given seed and chunk layout).
9
+ * ``string_token`` ``{length, pattern}`` -- tokens shaped like ``pattern`` (``A`` becomes an
10
+ upper-case letter, ``9`` a digit, other characters are kept). Without a pattern the token is
11
+ ``length`` upper-case alphanumerics. Tokens are a keyed pseudo-random *permutation* of the
12
+ global row index (a Feistel network with cycle walking over the token space), so they look
13
+ random but are unique across chunks without keeping state, and they depend only on the seed
14
+ and the global row index (hence they are invariant to chunk size). Requesting more rows than
15
+ the token space holds raises :class:`GenerationError`.
16
+
17
+ Every generator has the signature ``(spec, column, n, offset, key_rng, chunk_rng) -> pl.Series``:
18
+ ``key_rng`` is a per-run stream (same for all chunks), ``chunk_rng`` a per-chunk stream.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from collections.abc import Callable
24
+ from typing import Any
25
+
26
+ import numpy as np
27
+ import polars as pl
28
+
29
+ from ectype.errors import GenerationError
30
+ from ectype.fingerprint.schema import ColumnSchema, ModelSpec
31
+
32
+ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33
+ DIGITS = "0123456789"
34
+ ALNUM = DIGITS + LETTERS
35
+
36
+ #: Largest index space handled by the permutation (positions beyond it are filled randomly).
37
+ _MAX_PERM_BITS = 60
38
+ _FEISTEL_ROUNDS = 6
39
+
40
+ IdentifierFn = Callable[[ModelSpec, "ColumnSchema | None", int, int, np.random.Generator,
41
+ np.random.Generator], pl.Series]
42
+ IDENTIFIERS: dict[str, IdentifierFn] = {}
43
+
44
+
45
+ def register(kind: str) -> Callable[[IdentifierFn], IdentifierFn]:
46
+ def deco(fn: IdentifierFn) -> IdentifierFn:
47
+ IDENTIFIERS[kind] = fn
48
+ return fn
49
+
50
+ return deco
51
+
52
+
53
+ def _name(column: ColumnSchema | None, spec: ModelSpec) -> str:
54
+ return column.name if column is not None else str(spec.params.get("column", "id"))
55
+
56
+
57
+ # ---------------------------------------------------------------------------------------------
58
+ # int_sequence
59
+ # ---------------------------------------------------------------------------------------------
60
+
61
+
62
+ @register("int_sequence")
63
+ def int_sequence(spec: ModelSpec, column: ColumnSchema | None, n: int, offset: int,
64
+ key_rng: np.random.Generator, chunk_rng: np.random.Generator) -> pl.Series:
65
+ start = int(spec.params.get("start", 1) or 0)
66
+ return pl.Series(_name(column, spec), np.arange(n, dtype=np.int64) + start + offset)
67
+
68
+
69
+ # ---------------------------------------------------------------------------------------------
70
+ # uuid4
71
+ # ---------------------------------------------------------------------------------------------
72
+
73
+ _HEX = np.frombuffer(b"0123456789abcdef", dtype=np.uint8)
74
+ _DASHES = (8, 13, 18, 23)
75
+
76
+
77
+ @register("uuid4")
78
+ def uuid4(spec: ModelSpec, column: ColumnSchema | None, n: int, offset: int,
79
+ key_rng: np.random.Generator, chunk_rng: np.random.Generator) -> pl.Series:
80
+ name = _name(column, spec)
81
+ if n == 0:
82
+ return pl.Series(name, [], dtype=pl.String)
83
+ b = np.frombuffer(chunk_rng.bytes(16 * n), dtype=np.uint8).reshape(n, 16).copy()
84
+ b[:, 6] = (b[:, 6] & 0x0F) | 0x40 # version 4
85
+ b[:, 8] = (b[:, 8] & 0x3F) | 0x80 # RFC 4122 variant
86
+ hexed = np.empty((n, 32), dtype=np.uint8)
87
+ hexed[:, 0::2] = _HEX[b >> 4]
88
+ hexed[:, 1::2] = _HEX[b & 0x0F]
89
+ out = np.full((n, 36), ord("-"), dtype=np.uint8)
90
+ keep = [i for i in range(36) if i not in _DASHES]
91
+ out[:, keep] = hexed
92
+ strs = out.view("S36").ravel().astype("U36")
93
+ return pl.Series(name, strs.tolist(), dtype=pl.String)
94
+
95
+
96
+ # ---------------------------------------------------------------------------------------------
97
+ # string_token
98
+ # ---------------------------------------------------------------------------------------------
99
+
100
+
101
+ def token_alphabets(length: int, pattern: str | None) -> list[str]:
102
+ """Per-position alphabets for a token (a one-character alphabet is a literal)."""
103
+ alphabets: list[str] = []
104
+ if pattern:
105
+ for ch in pattern:
106
+ alphabets.append(LETTERS if ch == "A" else DIGITS if ch == "9" else ch)
107
+ while len(alphabets) < max(int(length), 1):
108
+ alphabets.append(ALNUM)
109
+ return alphabets
110
+
111
+
112
+ def _mix(x: np.ndarray, key: np.uint64) -> np.ndarray:
113
+ """splitmix64-style mixing of uint64 values (wrapping arithmetic)."""
114
+ z = x ^ key
115
+ z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
116
+ z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
117
+ return z ^ (z >> np.uint64(31))
118
+
119
+
120
+ def keyed_permutation(idx: np.ndarray, space: int, keys: np.ndarray) -> np.ndarray:
121
+ """Bijection of ``[0, space)`` (balanced Feistel network plus cycle walking)."""
122
+ if space <= 1:
123
+ return np.zeros_like(idx)
124
+ bits = max(2, int(space - 1).bit_length())
125
+ bits += bits % 2
126
+ half = np.uint64(bits // 2)
127
+ mask = np.uint64((1 << (bits // 2)) - 1)
128
+ lim = np.uint64(space)
129
+ x = idx.astype(np.uint64)
130
+ todo = np.ones(x.shape[0], dtype=bool)
131
+ out = x.copy()
132
+ with np.errstate(over="ignore"):
133
+ while todo.any():
134
+ v = out[todo]
135
+ left, right = v >> half, v & mask
136
+ for k in keys:
137
+ left, right = right, left ^ (_mix(right, k) & mask)
138
+ v = (left << half) | right
139
+ out[todo] = v
140
+ todo[todo] = v >= lim
141
+ return out
142
+
143
+
144
+ @register("string_token")
145
+ def string_token(spec: ModelSpec, column: ColumnSchema | None, n: int, offset: int,
146
+ key_rng: np.random.Generator, chunk_rng: np.random.Generator) -> pl.Series:
147
+ name = _name(column, spec)
148
+ pattern = spec.params.get("pattern")
149
+ alphabets = token_alphabets(int(spec.params.get("length", 12) or 12),
150
+ pattern if isinstance(pattern, str) else None)
151
+ if n == 0:
152
+ return pl.Series(name, [], dtype=pl.String)
153
+ radices = [len(a) for a in alphabets]
154
+ # Trailing variable positions carry the permuted index; leading ones beyond the
155
+ # permutation capacity are filled from the chunk stream.
156
+ perm_pos: list[int] = []
157
+ space = 1
158
+ for p in range(len(alphabets) - 1, -1, -1):
159
+ r = radices[p]
160
+ if r == 1:
161
+ continue
162
+ if (space * r).bit_length() > _MAX_PERM_BITS:
163
+ break
164
+ perm_pos.append(p)
165
+ space *= r
166
+ if offset + n > space and len(perm_pos) == sum(r > 1 for r in radices):
167
+ raise GenerationError(
168
+ f"identifier column {name!r}: token space ({space} values for pattern "
169
+ f"{pattern!r}) is too small for {offset + n} unique rows")
170
+ keys = key_rng.integers(0, 2**63, size=_FEISTEL_ROUNDS, dtype=np.uint64)
171
+ idx = np.arange(offset, offset + n, dtype=np.uint64) % np.uint64(max(space, 1))
172
+ v = keyed_permutation(idx, space, keys)
173
+ digits = np.zeros((n, len(alphabets)), dtype=np.int64)
174
+ for p in perm_pos: # least significant first
175
+ rad = np.uint64(radices[p])
176
+ digits[:, p] = (v % rad).astype(np.int64)
177
+ v = v // rad
178
+ perm_set = set(perm_pos)
179
+ for p, r in enumerate(radices):
180
+ if r > 1 and p not in perm_set:
181
+ digits[:, p] = chunk_rng.integers(0, r, size=n)
182
+ cols = []
183
+ for p, alpha in enumerate(alphabets):
184
+ table = np.frombuffer(alpha.encode("utf-32-le"), dtype=np.uint32)
185
+ cols.append(table[digits[:, p]])
186
+ chars = np.stack(cols, axis=1).astype(np.uint32)
187
+ strs = np.ascontiguousarray(chars).view(f"U{len(alphabets)}").ravel()
188
+ return pl.Series(name, strs.tolist(), dtype=pl.String)
189
+
190
+
191
+ def generate_identifier(spec: ModelSpec, column: ColumnSchema | None, n: int, offset: int,
192
+ key_rng: np.random.Generator, chunk_rng: np.random.Generator
193
+ ) -> pl.Series:
194
+ try:
195
+ fn = IDENTIFIERS[spec.kind]
196
+ except KeyError:
197
+ known = ", ".join(sorted(IDENTIFIERS))
198
+ raise GenerationError(f"unknown identifier kind {spec.kind!r}; known: {known}") from None
199
+ return fn(spec, column, n, offset, key_rng, chunk_rng)
200
+
201
+
202
+ #: Value ranges of the integer dtypes an ``int_sequence`` identifier may be stored as.
203
+ _INT_RANGES: dict[str, tuple[int, int]] = {
204
+ "Int8": (-(2**7), 2**7 - 1), "Int16": (-(2**15), 2**15 - 1),
205
+ "Int32": (-(2**31), 2**31 - 1), "Int64": (-(2**63), 2**63 - 1),
206
+ "UInt8": (0, 2**8 - 1), "UInt16": (0, 2**16 - 1), "UInt32": (0, 2**32 - 1),
207
+ "UInt64": (0, 2**64 - 1),
208
+ }
209
+
210
+
211
+ def identifier_capacity(spec: ModelSpec, column: ColumnSchema | None = None) -> int | None:
212
+ """Number of distinct values a generator can produce (``None`` = effectively unbounded).
213
+
214
+ For ``int_sequence`` the capacity is bounded by the output column's integer dtype: values
215
+ ``start .. dtype max`` (``int64`` arithmetic when the dtype is unknown)."""
216
+ if spec.kind == "int_sequence":
217
+ start = int(spec.params.get("start", 1) or 0)
218
+ dtype = column.physical_dtype if column is not None else "Int64"
219
+ lo, hi = _INT_RANGES.get(str(dtype).strip(), _INT_RANGES["Int64"])
220
+ if start < lo or start > hi:
221
+ return 0
222
+ return hi - start + 1
223
+ if spec.kind != "string_token":
224
+ return None
225
+ pattern: Any = spec.params.get("pattern")
226
+ alphabets = token_alphabets(int(spec.params.get("length", 12) or 12),
227
+ pattern if isinstance(pattern, str) else None)
228
+ cap = 1
229
+ for a in alphabets:
230
+ cap *= len(a)
231
+ return cap
232
+
233
+
234
+ __all__ = ["IDENTIFIERS", "generate_identifier", "identifier_capacity", "keyed_permutation",
235
+ "register", "token_alphabets"]
@@ -0,0 +1,71 @@
1
+ """The generation manifest written for every generation run (§5.3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import importlib.metadata as md
7
+ import json
8
+ from dataclasses import asdict, dataclass, field
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from ectype._version import __version__
13
+ from ectype.fingerprint.container import canonical_json
14
+
15
+ DEPENDENCIES = ("polars", "numpy", "scipy", "pyarrow", "pydantic")
16
+
17
+
18
+ def dependency_versions() -> dict[str, str]:
19
+ out: dict[str, str] = {}
20
+ for pkg in DEPENDENCIES:
21
+ try:
22
+ out[pkg] = md.version(pkg)
23
+ except md.PackageNotFoundError:
24
+ pass
25
+ return out
26
+
27
+
28
+ def config_hash(config: dict[str, Any]) -> str:
29
+ return hashlib.sha256(canonical_json(config)).hexdigest()
30
+
31
+
32
+ @dataclass
33
+ class ConstraintStats:
34
+ enforcement: str
35
+ violations: int = 0 # rows rejected because they violated this constraint
36
+ repaired: int = 0 # rows clamped by repair (repair constraints only)
37
+
38
+
39
+ @dataclass
40
+ class GenerationManifest:
41
+ fingerprint_hash: str
42
+ seed: int
43
+ n_rows: int
44
+ chunk_size: int
45
+ n_chunks: int
46
+ engine_version: str = __version__
47
+ dependencies: dict[str, str] = field(default_factory=dependency_versions)
48
+ config: dict[str, Any] = field(default_factory=dict)
49
+ config_hash: str = ""
50
+ rows_sampled: int = 0 # candidate rows drawn, including rejected ones
51
+ acceptance_rate: float = 1.0 # n_rows / rows_sampled
52
+ constraints: dict[str, ConstraintStats] = field(default_factory=dict)
53
+ chunk_size_invariant: bool = False
54
+ #: per column: generated "__other__" values of numerically coded categoricals emitted as null
55
+ pooled_to_null: dict[str, int] = field(default_factory=dict)
56
+ wall_time_s: float = 0.0
57
+ output_path: str | None = None
58
+ format: str | None = None
59
+ notes: list[str] = field(default_factory=list)
60
+
61
+ def to_dict(self) -> dict[str, Any]:
62
+ return asdict(self)
63
+
64
+ def to_json(self, path: str | Path | None = None, *, indent: int = 2) -> str:
65
+ text = json.dumps(self.to_dict(), indent=indent, sort_keys=True, default=str)
66
+ if path is not None:
67
+ Path(path).write_text(text, encoding="utf-8")
68
+ return text
69
+
70
+
71
+ __all__ = ["ConstraintStats", "GenerationManifest", "config_hash", "dependency_versions"]
@@ -0,0 +1,229 @@
1
+ """Multiprocess generation with a chunk- and worker-invariance contract (M32).
2
+
3
+ Contract
4
+ --------
5
+ For a fixed fingerprint (content hash), seed, ``chunk_size``, engine version and pinned
6
+ dependencies, :func:`generate_parallel` writes **exactly the same file** as the sequential
7
+ ``Generator.generate_to`` with the same ``chunk_size``, for any number of workers. This holds
8
+ because
9
+
10
+ * chunk ``i`` covers global rows ``[i * chunk_size, min(n, (i + 1) * chunk_size))``; every
11
+ chunk except the last is full, so a chunk's global row offset is ``i * chunk_size``;
12
+ * all randomness of chunk ``i`` comes from ``rng.stream(seed, "chunk", i, ...)`` (and the
13
+ run-level identifier key stream), which depends only on ``(seed, i)``, never on which worker
14
+ runs the chunk or what ran before it;
15
+ * identifiers are assigned from the global row offset, which the worker sets explicitly;
16
+ * the parent writes chunks strictly in chunk order with the same writer settings.
17
+
18
+ Output is still **not** invariant to ``chunk_size`` (see ``generation/generator.py``).
19
+
20
+ Mechanics: workers are started with the ``spawn`` method (safe with polars' thread pool, and the
21
+ only option on Windows). Each worker loads the ``.dfp`` from disk once (an in-memory
22
+ fingerprint is saved to a temporary file first), generates its assigned chunks, and writes each
23
+ one to a temporary Arrow IPC file. The parent streams those files into the output in chunk
24
+ order (``ParquetWriter`` / CSV append), deleting each as it goes, so memory stays bounded by a
25
+ few chunks and temporary disk by roughly ``workers`` chunks in flight plus out-of-order ones.
26
+
27
+ Generator API note: ``Generator`` has no public "generate chunk ``i``" method yet, so this
28
+ module calls the private ``Generator._chunk(i, m, seed, stats)`` with a ``_RunStats`` whose
29
+ ``emitted`` is preset to the chunk's global row offset. The minimal public method the
30
+ generator should grow is::
31
+
32
+ def generate_chunk(self, i: int, n: int, seed: int | None = None, *,
33
+ chunk_size: int | None = None) -> tuple[pl.DataFrame, ChunkStats]
34
+ # rows [i*chunk, min(n, (i+1)*chunk)) of generate(n, seed, chunk_size=chunk)
35
+
36
+ plus a way to build a ``GenerationManifest`` from merged per-chunk stats.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import io
42
+ import math
43
+ import multiprocessing as mp
44
+ import os
45
+ import tempfile
46
+ import time
47
+ from pathlib import Path
48
+ from typing import Any
49
+
50
+ import polars as pl
51
+
52
+ from ectype.fingerprint.core import Fingerprint
53
+ from ectype.generation.generator import FORMATS, Generator, _RunStats
54
+ from ectype.generation.manifest import GenerationManifest
55
+
56
+ __all__ = ["generate_parallel"]
57
+
58
+ _WORKER: dict[str, Any] = {}
59
+
60
+
61
+ # ---------------------------------------------------------------------------------------------
62
+ # worker side
63
+ # ---------------------------------------------------------------------------------------------
64
+
65
+
66
+ def _init_worker(fp_path: str, tmp_dir: str) -> None:
67
+ _WORKER["gen"] = Generator(Fingerprint.load(fp_path))
68
+ _WORKER["tmp"] = tmp_dir
69
+
70
+
71
+ def _run_chunk(gen: Generator, i: int, n: int, seed: int, chunk: int
72
+ ) -> tuple[pl.DataFrame, _RunStats]:
73
+ """Chunk ``i`` exactly as the sequential generator produces it."""
74
+ # Public per-chunk API: same streams and identifier offsets as sequential generation.
75
+ return gen.generate_chunk(i, n, seed, chunk_size=chunk)
76
+
77
+
78
+ def _stats_dict(stats: _RunStats) -> dict[str, Any]:
79
+ return {"sampled": stats.sampled, "violations": dict(stats.violations),
80
+ "repaired": dict(stats.repaired), "pooled_to_null": dict(stats.pooled_to_null)}
81
+
82
+
83
+ def _chunk_file(tmp_dir: str, i: int) -> str:
84
+ return os.path.join(tmp_dir, f"chunk-{i:09d}.arrow")
85
+
86
+
87
+ def _worker_task(args: tuple[int, int, int, int]) -> tuple[int, dict[str, Any]]:
88
+ i, n, seed, chunk = args
89
+ df, stats = _run_chunk(_WORKER["gen"], i, n, seed, chunk)
90
+ df.write_ipc(_chunk_file(_WORKER["tmp"], i), compression="uncompressed")
91
+ return i, _stats_dict(stats)
92
+
93
+
94
+ # ---------------------------------------------------------------------------------------------
95
+ # parent side
96
+ # ---------------------------------------------------------------------------------------------
97
+
98
+
99
+ def _merge_stats(total: _RunStats, part: dict[str, Any]) -> None:
100
+ total.sampled += int(part["sampled"])
101
+ for attr in ("violations", "repaired", "pooled_to_null"):
102
+ acc = getattr(total, attr)
103
+ for k, v in part[attr].items():
104
+ acc[k] = acc.get(k, 0) + int(v)
105
+
106
+
107
+ class _OrderedWriter:
108
+ def __init__(self, path: Path, fmt: str) -> None:
109
+ self.path, self.fmt = path, fmt
110
+ self._pq: Any = None
111
+ self._fh: Any = None
112
+ self._first = True
113
+
114
+ def write(self, df: pl.DataFrame) -> None:
115
+ if self.fmt == "parquet":
116
+ import pyarrow.parquet as pq
117
+
118
+ table = df.to_arrow()
119
+ if self._pq is None: # same settings as Generator.generate_to
120
+ self._pq = pq.ParquetWriter(str(self.path), table.schema, compression="snappy")
121
+ self._pq.write_table(table)
122
+ else:
123
+ if self._fh is None:
124
+ self._fh = self.path.open("wb")
125
+ df.write_csv(self._fh, include_header=self._first)
126
+ self._first = False
127
+
128
+ def close(self) -> None:
129
+ if self._pq is not None:
130
+ self._pq.close()
131
+ if self._fh is not None:
132
+ self._fh.close()
133
+
134
+
135
+ def _resolve_format(path: Path, format: str | None) -> str:
136
+ fmt = (format or path.suffix.lstrip(".")).lower()
137
+ if fmt == "pq":
138
+ fmt = "parquet"
139
+ if fmt not in FORMATS:
140
+ raise ValueError(f"unsupported output format {fmt!r}; use one of {FORMATS}")
141
+ return fmt
142
+
143
+
144
+ def generate_parallel(fp_or_path: Fingerprint | str | Path, n: int, seed: int | None = None,
145
+ *, chunk_size: int | None = None, workers: int = 2,
146
+ path: str | Path, format: str | None = None,
147
+ tmp_dir: str | Path | None = None,
148
+ threads_per_worker: int | None = 1) -> GenerationManifest:
149
+ """Generate ``n`` rows to ``path`` with ``workers`` processes; identical to
150
+ ``Generator.generate_to(path, n, seed, chunk_size=chunk_size)`` for any ``workers``.
151
+
152
+ ``workers=1`` runs in-process. ``tmp_dir`` holds per-chunk temporary files (default: a
153
+ temporary directory next to ``path``). ``threads_per_worker`` caps each worker's polars
154
+ thread pool (``POLARS_MAX_THREADS``) to avoid oversubscription; ``None`` leaves it alone.
155
+ Returns the run's ``GenerationManifest`` (worker count and wall time are reflected in
156
+ ``notes`` / ``wall_time_s``; the config hash matches the sequential run).
157
+ """
158
+ t0 = time.perf_counter()
159
+ if isinstance(workers, bool) or int(workers) < 1:
160
+ raise ValueError(f"workers must be a positive integer, got {workers!r}")
161
+ workers = int(workers)
162
+ path = Path(path)
163
+ fmt = _resolve_format(path, format)
164
+
165
+ fp = fp_or_path if isinstance(fp_or_path, Fingerprint) else Fingerprint.load(fp_or_path)
166
+ gen = Generator(fp)
167
+ n, seed, chunk = gen._resolve(n, seed, chunk_size)
168
+ n_chunks = math.ceil(n / chunk)
169
+ if n_chunks <= 1:
170
+ return gen.generate_to(path, n, seed, chunk_size=chunk, format=fmt)
171
+
172
+ path.parent.mkdir(parents=True, exist_ok=True)
173
+ stats = _RunStats()
174
+ writer = _OrderedWriter(path, fmt)
175
+ try:
176
+ if workers == 1:
177
+ for i in range(n_chunks):
178
+ df, st = _run_chunk(gen, i, n, seed, chunk)
179
+ _merge_stats(stats, _stats_dict(st))
180
+ writer.write(df)
181
+ else:
182
+ base = Path(tmp_dir) if tmp_dir is not None else path.parent
183
+ base.mkdir(parents=True, exist_ok=True)
184
+ with tempfile.TemporaryDirectory(prefix=".ts-parallel-", dir=base) as tmp:
185
+ if isinstance(fp_or_path, Fingerprint):
186
+ fp_file = os.path.join(tmp, "fingerprint.dfp")
187
+ fp.save(fp_file)
188
+ else:
189
+ fp_file = str(fp_or_path)
190
+ _run_pool(fp_file, tmp, n, seed, chunk, n_chunks, min(workers, n_chunks),
191
+ threads_per_worker, writer, stats)
192
+ finally:
193
+ writer.close()
194
+ stats.emitted = n
195
+ manifest = gen._manifest(n, seed, chunk, stats, time.perf_counter() - t0, str(path), fmt)
196
+ manifest.notes.append(f"generated in parallel: {workers} worker process(es), "
197
+ f"{n_chunks} chunks; worker-count invariant")
198
+ gen.last_manifest = manifest
199
+ return manifest
200
+
201
+
202
+ def _run_pool(fp_file: str, tmp: str, n: int, seed: int, chunk: int, n_chunks: int,
203
+ workers: int, threads: int | None, writer: _OrderedWriter,
204
+ stats: _RunStats) -> None:
205
+ ctx = mp.get_context("spawn")
206
+ key = "POLARS_MAX_THREADS"
207
+ old = os.environ.get(key)
208
+ if threads is not None:
209
+ os.environ[key] = str(int(threads)) # read by polars at import time in the child
210
+ try:
211
+ pool = ctx.Pool(workers, initializer=_init_worker, initargs=(fp_file, tmp))
212
+ finally:
213
+ if threads is not None:
214
+ if old is None:
215
+ os.environ.pop(key, None)
216
+ else:
217
+ os.environ[key] = old
218
+ with pool:
219
+ tasks = ((i, n, seed, chunk) for i in range(n_chunks))
220
+ # imap preserves task order, so chunks are written strictly in chunk order.
221
+ for i, part in pool.imap(_worker_task, tasks, chunksize=1):
222
+ f = _chunk_file(tmp, i)
223
+ df = pl.read_ipc(io.BytesIO(Path(f).read_bytes())) # no mmap: file is removed next
224
+ writer.write(df)
225
+ del df
226
+ os.remove(f)
227
+ _merge_stats(stats, part)
228
+ pool.close()
229
+ pool.join()
ectype/io/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """IO edges: read/write tables and convert between source dtypes and engine values."""
2
+
3
+ from ectype.io.adapters import FORMATS, infer_format, read_table, to_pandas, write_table
4
+ from ectype.io.values import OTHER, category_codes, column_to_values, values_to_column
5
+
6
+ __all__ = [
7
+ "FORMATS",
8
+ "OTHER",
9
+ "category_codes",
10
+ "column_to_values",
11
+ "infer_format",
12
+ "read_table",
13
+ "to_pandas",
14
+ "values_to_column",
15
+ "write_table",
16
+ ]