vecgen 0.3.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.
vecgen/builder.py ADDED
@@ -0,0 +1,338 @@
1
+ """Declarative DatasetBuilder with conditional branches and column dependency resolution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Mapping, Sequence
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Literal, overload
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ from vecgen._compat import NormalizedData
14
+ from vecgen._graph import resolve_execution_order
15
+ from vecgen.distributions import derive_column_rng, sample_choice, sample_distribution
16
+ from vecgen.engine import _resolve_value_array
17
+ from vecgen.exceptions import SchemaError
18
+ from vecgen.rules import evaluate_rule, extract_dependencies
19
+ from vecgen.types import BoolArray, DistName, NDArrayAny, RuleType, ValueType
20
+
21
+ BranchKind = Literal["distribution", "choice", "rule"]
22
+
23
+
24
+ @dataclass
25
+ class _ColumnBranch:
26
+ """Single conditional or fallback definition for a column."""
27
+
28
+ kind: BranchKind
29
+ when: RuleType | None = None
30
+ depends_on: set[str] = field(default_factory=set)
31
+ # Distribution fields
32
+ dist: DistName | None = None
33
+ params: dict[str, int | float | str] = field(default_factory=dict)
34
+ clip: tuple[float | None, float | None] | None = None
35
+ dtype: str | None = None
36
+ # Choice fields
37
+ choices: list[Any] = field(default_factory=list)
38
+ weights: list[float] | None = None
39
+ # Rule fields
40
+ rule: RuleType | None = None
41
+ value: ValueType = None
42
+ default: ValueType = None
43
+
44
+
45
+ class DatasetBuilder:
46
+ """Declarative generator for synthetic DataFrames and NumPy arrays (FR-2, FR-9)."""
47
+
48
+ def __init__(self, rows: int, *, seed: int | None = None) -> None:
49
+ if rows < 0:
50
+ raise SchemaError(f"`rows` must be non-negative, got {rows}.")
51
+ self.rows = rows
52
+ self.seed = seed
53
+ self._columns: dict[str, list[_ColumnBranch]] = {}
54
+
55
+ def add_distribution(
56
+ self,
57
+ col: str,
58
+ *,
59
+ dist: DistName,
60
+ when: RuleType | None = None,
61
+ depends_on: Sequence[str] | None = None,
62
+ clip: tuple[float | None, float | None] | None = None,
63
+ dtype: str | None = None,
64
+ **params: int | float | str,
65
+ ) -> DatasetBuilder:
66
+ """Add a statistical distribution branch for ``col``."""
67
+ deps = self._collect_branch_deps(
68
+ when=when,
69
+ depends_on=depends_on,
70
+ expressions=[v for v in params.values() if isinstance(v, str)],
71
+ )
72
+ branch = _ColumnBranch(
73
+ kind="distribution",
74
+ when=when,
75
+ depends_on=deps,
76
+ dist=dist,
77
+ params=dict(params),
78
+ clip=clip,
79
+ dtype=dtype,
80
+ )
81
+ self._register_branch(col, branch)
82
+ return self
83
+
84
+ def add_choice(
85
+ self,
86
+ col: str,
87
+ *,
88
+ choices: Sequence[Any],
89
+ weights: Sequence[float] | None = None,
90
+ when: RuleType | None = None,
91
+ depends_on: Sequence[str] | None = None,
92
+ dtype: str | None = None,
93
+ ) -> DatasetBuilder:
94
+ """Add a discrete categorical choice branch for ``col``."""
95
+ deps = self._collect_branch_deps(when=when, depends_on=depends_on, expressions=[])
96
+ branch = _ColumnBranch(
97
+ kind="choice",
98
+ when=when,
99
+ depends_on=deps,
100
+ choices=list(choices),
101
+ weights=list(weights) if weights is not None else None,
102
+ dtype=dtype,
103
+ )
104
+ self._register_branch(col, branch)
105
+ return self
106
+
107
+ def add_rule(
108
+ self,
109
+ col: str,
110
+ *,
111
+ rule: RuleType,
112
+ value: ValueType,
113
+ default: ValueType = None,
114
+ when: RuleType | None = None,
115
+ depends_on: Sequence[str] | None = None,
116
+ ) -> DatasetBuilder:
117
+ """Add a conditional rule-based assignment branch for ``col``."""
118
+ exprs = [rule] if isinstance(rule, str) else []
119
+ deps = self._collect_branch_deps(when=when, depends_on=depends_on, expressions=exprs)
120
+ branch = _ColumnBranch(
121
+ kind="rule",
122
+ when=when,
123
+ depends_on=deps,
124
+ rule=rule,
125
+ value=value,
126
+ default=default,
127
+ )
128
+ self._register_branch(col, branch)
129
+ return self
130
+
131
+ def build(self, *, rows: int | None = None) -> pd.DataFrame:
132
+ """Generate the synthetic dataset as a ``pd.DataFrame`` (FR-2, FR-9)."""
133
+ n_rows = self.rows if rows is None else rows
134
+ if n_rows < 0:
135
+ raise SchemaError(f"`rows` must be non-negative, got {n_rows}.")
136
+
137
+ if not self._columns:
138
+ empty: pd.DataFrame = pd.DataFrame(index=pd.RangeIndex(n_rows))
139
+ return empty
140
+
141
+ col_order = list(self._columns.keys())
142
+ dep_map: dict[str, set[str]] = {
143
+ col: set().union(*(b.depends_on for b in branches))
144
+ for col, branches in self._columns.items()
145
+ }
146
+ exec_order = resolve_execution_order(col_order, dep_map)
147
+
148
+ frame = pd.DataFrame(index=pd.RangeIndex(n_rows))
149
+ for col in exec_order:
150
+ col_rng = derive_column_rng(self.seed, col)
151
+ frame[col] = self._evaluate_column(col, frame=frame, n_rows=n_rows, rng=col_rng)
152
+
153
+ # Return columns in user declaration order
154
+ result: pd.DataFrame = frame[col_order]
155
+ return result
156
+
157
+ @overload
158
+ def build_numpy(
159
+ self,
160
+ *,
161
+ target: None = None,
162
+ rows: int | None = None,
163
+ dtype: str | np.dtype[Any] | None = None,
164
+ ) -> NDArrayAny: ...
165
+
166
+ @overload
167
+ def build_numpy(
168
+ self,
169
+ *,
170
+ target: str,
171
+ rows: int | None = None,
172
+ dtype: str | np.dtype[Any] | None = None,
173
+ ) -> tuple[NDArrayAny, NDArrayAny]: ...
174
+
175
+ def build_numpy(
176
+ self,
177
+ *,
178
+ target: str | None = None,
179
+ rows: int | None = None,
180
+ dtype: str | np.dtype[Any] | None = None,
181
+ ) -> NDArrayAny | tuple[NDArrayAny, NDArrayAny]:
182
+ """Generate the dataset as a 2D NumPy array or ``(X, y)`` tuple (FR-2)."""
183
+ df = self.build(rows=rows)
184
+ if target is None:
185
+ arr = df.to_numpy(dtype=dtype) if dtype is not None else df.to_numpy()
186
+ return arr
187
+
188
+ if target not in df.columns:
189
+ raise SchemaError(f"Target column {target!r} not found in generated columns.")
190
+
191
+ y = df[target].to_numpy()
192
+ feature_df: pd.DataFrame = df.drop(columns=[target])
193
+ x = feature_df.to_numpy(dtype=dtype) if dtype is not None else feature_df.to_numpy()
194
+ return x, y
195
+
196
+ def _register_branch(self, col: str, branch: _ColumnBranch) -> None:
197
+ branches = self._columns.setdefault(col, [])
198
+ if branches and branches[-1].when is None:
199
+ raise SchemaError(
200
+ f"Column {col!r} already has a fallback branch (without `when`); "
201
+ "cannot add another branch after a fallback."
202
+ )
203
+ branches.append(branch)
204
+
205
+ def to_dict(self) -> dict[str, Any]:
206
+ """Serialize this builder definition to a JSON-compatible dictionary (FR-11)."""
207
+ from vecgen.serialization import builder_to_dict
208
+
209
+ return builder_to_dict(self)
210
+
211
+ def to_json(self, path: str | os.PathLike[str] | None = None, *, indent: int = 2) -> str:
212
+ """Serialize this builder definition to JSON and optionally write to ``path`` (FR-11)."""
213
+ from vecgen.serialization import builder_to_json
214
+
215
+ return builder_to_json(self, path=path, indent=indent)
216
+
217
+ @classmethod
218
+ def from_dict(cls, data: Mapping[str, Any]) -> DatasetBuilder:
219
+ """Reconstruct a ``DatasetBuilder`` from a serialized dictionary (FR-11)."""
220
+ from vecgen.serialization import builder_from_dict
221
+
222
+ return builder_from_dict(data)
223
+
224
+ @classmethod
225
+ def from_json(cls, source: str | os.PathLike[str]) -> DatasetBuilder:
226
+ """Load a ``DatasetBuilder`` from a JSON string or ``.json`` file path (FR-11)."""
227
+ from vecgen.serialization import builder_from_json
228
+
229
+ return builder_from_json(source)
230
+
231
+ @staticmethod
232
+ def _collect_branch_deps(
233
+ *,
234
+ when: RuleType | None,
235
+ depends_on: Sequence[str] | None,
236
+ expressions: Sequence[str],
237
+ ) -> set[str]:
238
+ deps: set[str] = set(depends_on) if depends_on is not None else set()
239
+ if isinstance(when, str):
240
+ deps |= extract_dependencies(when)
241
+ for expr in expressions:
242
+ deps |= extract_dependencies(expr)
243
+ return deps
244
+
245
+ def _evaluate_column(
246
+ self,
247
+ col: str,
248
+ *,
249
+ frame: pd.DataFrame,
250
+ n_rows: int,
251
+ rng: np.random.Generator,
252
+ ) -> NDArrayAny:
253
+ branches = self._columns[col]
254
+ norm = NormalizedData(kind="dataframe", frame=frame, original=frame)
255
+
256
+ assigned: BoolArray = np.zeros(n_rows, dtype=np.bool_)
257
+ branch_outputs: list[tuple[BoolArray, NDArrayAny]] = []
258
+
259
+ for branch in branches:
260
+ if branch.when is None:
261
+ active_mask = ~assigned
262
+ else:
263
+ raw_mask = evaluate_rule(branch.when, norm, raw_input=frame)
264
+ active_mask = raw_mask & (~assigned)
265
+
266
+ matched_count = int(active_mask.sum())
267
+ if matched_count > 0 or n_rows == 0:
268
+ sub_frame = frame.iloc[active_mask].reset_index(drop=True)
269
+ sub_values = self._sample_branch(
270
+ branch, sub_frame=sub_frame, count=matched_count, rng=rng
271
+ )
272
+ branch_outputs.append((active_mask, sub_values))
273
+ assigned |= active_mask
274
+
275
+ if not np.all(assigned):
276
+ unmatched = int((~assigned).sum())
277
+ raise SchemaError(
278
+ f"Column {col!r} has {unmatched} row(s) not matched by any `when` branch "
279
+ "and no fallback branch was defined."
280
+ )
281
+
282
+ if len(branch_outputs) == 1:
283
+ return branch_outputs[0][1]
284
+
285
+ out_dtype = np.result_type(*(vals.dtype for _, vals in branch_outputs))
286
+ if out_dtype.kind in ("U", "S", "O"):
287
+ result: NDArrayAny = np.empty(n_rows, dtype=object)
288
+ else:
289
+ result = np.empty(n_rows, dtype=out_dtype)
290
+
291
+ for mask, vals in branch_outputs:
292
+ result[mask] = vals
293
+
294
+ return result
295
+
296
+ @staticmethod
297
+ def _sample_branch(
298
+ branch: _ColumnBranch,
299
+ *,
300
+ sub_frame: pd.DataFrame,
301
+ count: int,
302
+ rng: np.random.Generator,
303
+ ) -> NDArrayAny:
304
+ if branch.kind == "distribution":
305
+ assert branch.dist is not None
306
+ return sample_distribution(
307
+ dist=branch.dist,
308
+ size=count,
309
+ params=branch.params,
310
+ context=sub_frame,
311
+ clip=branch.clip,
312
+ dtype=branch.dtype,
313
+ seed=rng,
314
+ )
315
+
316
+ if branch.kind == "choice":
317
+ return sample_choice(
318
+ choices=branch.choices,
319
+ size=count,
320
+ weights=branch.weights,
321
+ dtype=branch.dtype,
322
+ seed=rng,
323
+ )
324
+
325
+ # branch.kind == "rule"
326
+ assert branch.rule is not None
327
+ sub_norm = NormalizedData(kind="dataframe", frame=sub_frame, original=sub_frame)
328
+ rule_mask = evaluate_rule(branch.rule, sub_norm, raw_input=sub_frame)
329
+ true_vals = _resolve_value_array(
330
+ branch.value, sub_norm, raw_input=sub_frame, n_rows=count
331
+ )
332
+ false_vals = _resolve_value_array(
333
+ branch.default, sub_norm, raw_input=sub_frame, n_rows=count
334
+ )
335
+ common_dtype = np.result_type(true_vals.dtype, false_vals.dtype)
336
+ if common_dtype.kind in ("U", "S", "O"):
337
+ return np.where(rule_mask, true_vals.astype(object), false_vals.astype(object))
338
+ return np.where(rule_mask, true_vals, false_vals)
@@ -0,0 +1,176 @@
1
+ """Seeded NumPy statistical & categorical sampling with scalar or expression parameters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from vecgen.exceptions import RuleEvaluationError, SchemaError
13
+ from vecgen.types import DistName, NDArrayAny, SeedType
14
+
15
+
16
+ def resolve_rng(seed: SeedType = None) -> np.random.Generator:
17
+ """Normalize an int, SeedSequence, Generator, or None into a np.random.Generator."""
18
+ if isinstance(seed, np.random.Generator):
19
+ return seed
20
+ return np.random.default_rng(seed)
21
+
22
+
23
+ def derive_column_rng(master_seed: int | None, column_name: str) -> np.random.Generator:
24
+ """Derive a deterministic per-column RNG stream from master_seed and column_name (NFR-2)."""
25
+ if master_seed is None:
26
+ return np.random.default_rng()
27
+ digest = hashlib.sha256(f"{master_seed}:{column_name}".encode()).digest()
28
+ col_entropy = int.from_bytes(digest[:16], "little")
29
+ seq = np.random.SeedSequence([master_seed, col_entropy])
30
+ return np.random.default_rng(seq)
31
+
32
+
33
+ def resolve_param(
34
+ param: int | float | str,
35
+ context: pd.DataFrame | None,
36
+ *,
37
+ n_rows: int,
38
+ param_name: str,
39
+ ) -> float | int | NDArrayAny:
40
+ """Evaluate a distribution parameter that may be a scalar or a column expression."""
41
+ if isinstance(param, (int, float, np.number)):
42
+ return float(param) if isinstance(param, (float, np.floating)) else int(param)
43
+
44
+ if isinstance(param, str):
45
+ if context is None:
46
+ raise SchemaError(
47
+ f"Expression parameter {param_name}={param!r} requires a DataFrame context."
48
+ )
49
+ try:
50
+ evaluated: Any = context.eval(param)
51
+ except Exception as exc:
52
+ raise RuleEvaluationError(
53
+ f"Failed to evaluate parameter expression {param_name}={param!r}: {exc}"
54
+ ) from exc
55
+
56
+ if isinstance(evaluated, pd.Series):
57
+ arr = evaluated.to_numpy()
58
+ elif isinstance(evaluated, np.ndarray):
59
+ arr = evaluated
60
+ elif isinstance(evaluated, (int, float, np.number)):
61
+ return (
62
+ float(evaluated)
63
+ if isinstance(evaluated, (float, np.floating))
64
+ else int(evaluated)
65
+ )
66
+ elif isinstance(evaluated, Sequence) and not isinstance(evaluated, (str, bytes)):
67
+ arr = np.asarray(evaluated)
68
+ else:
69
+ raise RuleEvaluationError(
70
+ f"Parameter {param_name}={param!r} evaluated to unsupported type "
71
+ f"{type(evaluated).__name__!r}."
72
+ )
73
+
74
+ if arr.shape != (n_rows,):
75
+ raise RuleEvaluationError(
76
+ f"Parameter {param_name}={param!r} evaluated to shape {arr.shape}, "
77
+ f"expected ({n_rows},)."
78
+ )
79
+ return arr
80
+
81
+ raise SchemaError(
82
+ f"Unsupported parameter type {type(param).__name__!r} for {param_name!r}."
83
+ )
84
+
85
+
86
+ def sample_distribution(
87
+ *,
88
+ dist: DistName,
89
+ size: int,
90
+ params: Mapping[str, int | float | str],
91
+ context: pd.DataFrame | None = None,
92
+ clip: tuple[float | None, float | None] | None = None,
93
+ dtype: str | np.dtype[Any] | None = None,
94
+ seed: SeedType = None,
95
+ ) -> NDArrayAny:
96
+ """Sample ``size`` values from a statistical distribution (FR-5, FR-9)."""
97
+ if size == 0:
98
+ out_dtype = np.dtype(dtype) if dtype is not None else np.dtype(np.float64)
99
+ return np.empty(0, dtype=out_dtype)
100
+
101
+ rng = resolve_rng(seed)
102
+ samples: NDArrayAny
103
+
104
+ if dist == "uniform":
105
+ low = resolve_param(params.get("low", 0.0), context, n_rows=size, param_name="low")
106
+ high = resolve_param(params.get("high", 1.0), context, n_rows=size, param_name="high")
107
+ samples = rng.uniform(low=low, high=high, size=size)
108
+ elif dist == "normal":
109
+ mean = resolve_param(params.get("mean", 0.0), context, n_rows=size, param_name="mean")
110
+ std = resolve_param(params.get("std", 1.0), context, n_rows=size, param_name="std")
111
+ samples = rng.normal(loc=mean, scale=std, size=size)
112
+ elif dist == "lognormal":
113
+ mean = resolve_param(params.get("mean", 0.0), context, n_rows=size, param_name="mean")
114
+ sigma = resolve_param(params.get("sigma", 1.0), context, n_rows=size, param_name="sigma")
115
+ samples = rng.lognormal(mean=mean, sigma=sigma, size=size)
116
+ elif dist == "exponential":
117
+ scale = resolve_param(params.get("scale", 1.0), context, n_rows=size, param_name="scale")
118
+ samples = rng.exponential(scale=scale, size=size)
119
+ elif dist == "randint":
120
+ if "low" not in params or "high" not in params:
121
+ raise SchemaError("`randint` distribution requires `low` and `high` parameters.")
122
+ low_i = resolve_param(params["low"], context, n_rows=size, param_name="low")
123
+ high_i = resolve_param(params["high"], context, n_rows=size, param_name="high")
124
+ samples = rng.integers(low=low_i, high=high_i, size=size) # type: ignore[arg-type]
125
+ else:
126
+ raise SchemaError(f"Unsupported distribution {dist!r}.")
127
+
128
+ arr: NDArrayAny = np.asarray(samples)
129
+ if clip is not None:
130
+ lo, hi = clip
131
+ if lo is not None or hi is not None:
132
+ arr = np.clip(arr, a_min=lo, a_max=hi)
133
+
134
+ if dtype is not None:
135
+ arr = arr.astype(dtype)
136
+
137
+ return arr
138
+
139
+
140
+ def sample_choice(
141
+ *,
142
+ choices: Sequence[Any],
143
+ size: int,
144
+ weights: Sequence[float] | None = None,
145
+ dtype: str | np.dtype[Any] | None = None,
146
+ seed: SeedType = None,
147
+ ) -> NDArrayAny:
148
+ """Sample ``size`` values from discrete choices with optional probability weights (FR-5)."""
149
+ if not choices:
150
+ raise SchemaError("`choices` must be a non-empty sequence.")
151
+
152
+ choices_arr = np.asarray(choices)
153
+ if size == 0:
154
+ out_dtype = np.dtype(dtype) if dtype is not None else choices_arr.dtype
155
+ return np.empty(0, dtype=out_dtype)
156
+
157
+ probs: NDArrayAny | None = None
158
+ if weights is not None:
159
+ if len(weights) != len(choices):
160
+ raise SchemaError(
161
+ f"`weights` length ({len(weights)}) must match `choices` length ({len(choices)})."
162
+ )
163
+ probs = np.asarray(weights, dtype=np.float64)
164
+ total = float(probs.sum())
165
+ if total <= 0:
166
+ raise SchemaError("`weights` must sum to a positive number.")
167
+ probs = probs / total
168
+
169
+ rng = resolve_rng(seed)
170
+ idx = rng.choice(len(choices_arr), size=size, replace=True, p=probs)
171
+ arr: NDArrayAny = choices_arr[idx]
172
+
173
+ if dtype is not None:
174
+ arr = arr.astype(dtype)
175
+
176
+ return arr