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/__init__.py +37 -0
- vecgen/_compat.py +167 -0
- vecgen/_graph.py +114 -0
- vecgen/accessor.py +222 -0
- vecgen/builder.py +338 -0
- vecgen/distributions.py +176 -0
- vecgen/engine.py +274 -0
- vecgen/exceptions.py +19 -0
- vecgen/noise.py +534 -0
- vecgen/py.typed +0 -0
- vecgen/report.py +239 -0
- vecgen/rules.py +142 -0
- vecgen/serialization.py +279 -0
- vecgen/types.py +34 -0
- vecgen-0.3.0.dist-info/METADATA +177 -0
- vecgen-0.3.0.dist-info/RECORD +18 -0
- vecgen-0.3.0.dist-info/WHEEL +4 -0
- vecgen-0.3.0.dist-info/licenses/LICENSE +21 -0
vecgen/report.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Ground-truth manifest and evaluation metrics for data corruption (FR-10)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Literal, cast
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
from vecgen.exceptions import SchemaError
|
|
14
|
+
from vecgen.types import BoolArray
|
|
15
|
+
|
|
16
|
+
CorruptionKind = Literal["null", "duplicate", "outlier"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class CorruptionRecord:
|
|
21
|
+
"""Single row/cell change recorded by an anomaly injector."""
|
|
22
|
+
|
|
23
|
+
row_position: int
|
|
24
|
+
index_label: Any
|
|
25
|
+
column: str | None
|
|
26
|
+
kind: CorruptionKind
|
|
27
|
+
original_value: Any
|
|
28
|
+
new_value: Any
|
|
29
|
+
source_row: int | None = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class EvaluationResult:
|
|
34
|
+
"""Precision/recall comparison between pipeline flags and a CorruptionReport."""
|
|
35
|
+
|
|
36
|
+
precision: float
|
|
37
|
+
recall: float
|
|
38
|
+
true_positives: int
|
|
39
|
+
false_positives: int
|
|
40
|
+
false_negatives: int
|
|
41
|
+
missed: list[int]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class CorruptionReport:
|
|
46
|
+
"""Ground-truth manifest of injected corruptions (FR-10)."""
|
|
47
|
+
|
|
48
|
+
records: list[CorruptionRecord] = field(default_factory=list)
|
|
49
|
+
n_rows: int = 0
|
|
50
|
+
columns: tuple[str, ...] = ()
|
|
51
|
+
|
|
52
|
+
def __len__(self) -> int:
|
|
53
|
+
return len(self.records)
|
|
54
|
+
|
|
55
|
+
def __add__(self, other: CorruptionReport) -> CorruptionReport:
|
|
56
|
+
if not isinstance(other, CorruptionReport):
|
|
57
|
+
return NotImplemented
|
|
58
|
+
merged_cols = tuple(dict.fromkeys([*self.columns, *other.columns]))
|
|
59
|
+
return CorruptionReport(
|
|
60
|
+
records=[*self.records, *other.records],
|
|
61
|
+
n_rows=max(self.n_rows, other.n_rows),
|
|
62
|
+
columns=merged_cols,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def summary(self) -> pd.DataFrame:
|
|
66
|
+
"""Return counts grouped by corruption ``kind`` and ``column``."""
|
|
67
|
+
if not self.records:
|
|
68
|
+
return cast(pd.DataFrame, pd.DataFrame(columns=["kind", "column", "count"]))
|
|
69
|
+
df = self.to_frame()
|
|
70
|
+
df["column"] = df["column"].fillna("<row>")
|
|
71
|
+
grouped: pd.DataFrame = (
|
|
72
|
+
df.groupby(["kind", "column"], dropna=False, sort=True)
|
|
73
|
+
.size()
|
|
74
|
+
.reset_index(name="count")
|
|
75
|
+
)
|
|
76
|
+
return grouped
|
|
77
|
+
|
|
78
|
+
def to_frame(self) -> pd.DataFrame:
|
|
79
|
+
"""Convert the manifest into a ``pd.DataFrame`` of individual changes."""
|
|
80
|
+
cols = [
|
|
81
|
+
"row_position",
|
|
82
|
+
"index_label",
|
|
83
|
+
"column",
|
|
84
|
+
"kind",
|
|
85
|
+
"original_value",
|
|
86
|
+
"new_value",
|
|
87
|
+
"source_row",
|
|
88
|
+
]
|
|
89
|
+
if not self.records:
|
|
90
|
+
return cast(pd.DataFrame, pd.DataFrame(columns=cols))
|
|
91
|
+
rows = [
|
|
92
|
+
{
|
|
93
|
+
"row_position": r.row_position,
|
|
94
|
+
"index_label": r.index_label,
|
|
95
|
+
"column": r.column,
|
|
96
|
+
"kind": r.kind,
|
|
97
|
+
"original_value": r.original_value,
|
|
98
|
+
"new_value": r.new_value,
|
|
99
|
+
"source_row": r.source_row,
|
|
100
|
+
}
|
|
101
|
+
for r in self.records
|
|
102
|
+
]
|
|
103
|
+
return cast(pd.DataFrame, pd.DataFrame(rows, columns=cols))
|
|
104
|
+
|
|
105
|
+
def to_json(self, path: str | None = None, *, indent: int = 2) -> str:
|
|
106
|
+
"""Serialize the manifest to a JSON string (and optionally write to ``path``)."""
|
|
107
|
+
payload = {
|
|
108
|
+
"n_rows": self.n_rows,
|
|
109
|
+
"columns": list(self.columns),
|
|
110
|
+
"records": [
|
|
111
|
+
{
|
|
112
|
+
"row_position": r.row_position,
|
|
113
|
+
"index_label": _json_safe(r.index_label),
|
|
114
|
+
"column": r.column,
|
|
115
|
+
"kind": r.kind,
|
|
116
|
+
"original_value": _json_safe(r.original_value),
|
|
117
|
+
"new_value": _json_safe(r.new_value),
|
|
118
|
+
"source_row": r.source_row,
|
|
119
|
+
}
|
|
120
|
+
for r in self.records
|
|
121
|
+
],
|
|
122
|
+
}
|
|
123
|
+
serialized = json.dumps(payload, indent=indent)
|
|
124
|
+
if path is not None:
|
|
125
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
126
|
+
fh.write(serialized)
|
|
127
|
+
return serialized
|
|
128
|
+
|
|
129
|
+
def evaluate(
|
|
130
|
+
self,
|
|
131
|
+
detected: BoolArray | pd.Series | pd.DataFrame | Sequence[int],
|
|
132
|
+
*,
|
|
133
|
+
kind: CorruptionKind | None = None,
|
|
134
|
+
) -> EvaluationResult:
|
|
135
|
+
"""Compare detector flags against ground-truth corruptions (FR-10).
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
detected: Boolean 1D row mask, boolean 2D cell mask (matching ``n_rows x n_cols``),
|
|
139
|
+
or sequence of integer row positions flagged by a detector.
|
|
140
|
+
kind: Optional filter to evaluate only ``"null"``, ``"duplicate"``, or ``"outlier"``.
|
|
141
|
+
"""
|
|
142
|
+
filtered = [r for r in self.records if kind is None or r.kind == kind]
|
|
143
|
+
|
|
144
|
+
if isinstance(detected, pd.DataFrame):
|
|
145
|
+
cell_mask = detected.to_numpy(dtype=np.bool_)
|
|
146
|
+
return self._evaluate_cell_mask(cell_mask, filtered)
|
|
147
|
+
|
|
148
|
+
if isinstance(detected, np.ndarray) and detected.ndim == 2:
|
|
149
|
+
return self._evaluate_cell_mask(detected.astype(np.bool_, copy=False), filtered)
|
|
150
|
+
|
|
151
|
+
# Row-level evaluation (1D boolean mask or sequence of integer row positions)
|
|
152
|
+
truth_rows = {r.row_position for r in filtered}
|
|
153
|
+
flagged_rows = self._coerce_detected_rows(detected)
|
|
154
|
+
|
|
155
|
+
tp = len(truth_rows & flagged_rows)
|
|
156
|
+
fp = len(flagged_rows - truth_rows)
|
|
157
|
+
fn = len(truth_rows - flagged_rows)
|
|
158
|
+
missed = sorted(truth_rows - flagged_rows)
|
|
159
|
+
|
|
160
|
+
precision = tp / (tp + fp) if (tp + fp) > 0 else (1.0 if fn == 0 else 0.0)
|
|
161
|
+
recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0
|
|
162
|
+
return EvaluationResult(
|
|
163
|
+
precision=precision,
|
|
164
|
+
recall=recall,
|
|
165
|
+
true_positives=tp,
|
|
166
|
+
false_positives=fp,
|
|
167
|
+
false_negatives=fn,
|
|
168
|
+
missed=missed,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
def _evaluate_cell_mask(
|
|
172
|
+
self,
|
|
173
|
+
cell_mask: BoolArray,
|
|
174
|
+
records: list[CorruptionRecord],
|
|
175
|
+
) -> EvaluationResult:
|
|
176
|
+
col_to_idx = {col: i for i, col in enumerate(self.columns)}
|
|
177
|
+
truth_cells: set[tuple[int, int]] = set()
|
|
178
|
+
for r in records:
|
|
179
|
+
if r.column is None:
|
|
180
|
+
for c_idx in range(len(self.columns)):
|
|
181
|
+
truth_cells.add((r.row_position, c_idx))
|
|
182
|
+
elif r.column in col_to_idx:
|
|
183
|
+
truth_cells.add((r.row_position, col_to_idx[r.column]))
|
|
184
|
+
|
|
185
|
+
row_indices, col_indices = np.nonzero(cell_mask)
|
|
186
|
+
flagged_cells = {(int(r), int(c)) for r, c in zip(row_indices, col_indices)}
|
|
187
|
+
|
|
188
|
+
tp = len(truth_cells & flagged_cells)
|
|
189
|
+
fp = len(flagged_cells - truth_cells)
|
|
190
|
+
fn = len(truth_cells - flagged_cells)
|
|
191
|
+
missed = sorted({r for r, _ in (truth_cells - flagged_cells)})
|
|
192
|
+
|
|
193
|
+
precision = tp / (tp + fp) if (tp + fp) > 0 else (1.0 if fn == 0 else 0.0)
|
|
194
|
+
recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0
|
|
195
|
+
return EvaluationResult(
|
|
196
|
+
precision=precision,
|
|
197
|
+
recall=recall,
|
|
198
|
+
true_positives=tp,
|
|
199
|
+
false_positives=fp,
|
|
200
|
+
false_negatives=fn,
|
|
201
|
+
missed=missed,
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
def _coerce_detected_rows(
|
|
205
|
+
self,
|
|
206
|
+
detected: BoolArray | pd.Series | Sequence[int],
|
|
207
|
+
) -> set[int]:
|
|
208
|
+
if isinstance(detected, pd.Series):
|
|
209
|
+
arr = detected.to_numpy()
|
|
210
|
+
if arr.dtype == np.bool_:
|
|
211
|
+
return {int(i) for i in np.nonzero(arr)[0]}
|
|
212
|
+
return {int(v) for v in arr}
|
|
213
|
+
|
|
214
|
+
if isinstance(detected, np.ndarray):
|
|
215
|
+
if detected.ndim != 1:
|
|
216
|
+
raise SchemaError(
|
|
217
|
+
f"Expected 1D array for row detection, got {detected.ndim}D."
|
|
218
|
+
)
|
|
219
|
+
if detected.dtype == np.bool_:
|
|
220
|
+
return {int(i) for i in np.nonzero(detected)[0]}
|
|
221
|
+
return {int(v) for v in detected}
|
|
222
|
+
|
|
223
|
+
seq = list(detected)
|
|
224
|
+
if not seq:
|
|
225
|
+
return set()
|
|
226
|
+
if all(isinstance(x, (bool, np.bool_)) for x in seq):
|
|
227
|
+
return {i for i, flag in enumerate(seq) if flag}
|
|
228
|
+
return {int(x) for x in seq}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _json_safe(val: Any) -> Any:
|
|
232
|
+
"""Convert NumPy/pandas scalars and NA values into JSON-serializable Python values."""
|
|
233
|
+
if val is None or val is pd.NA:
|
|
234
|
+
return None
|
|
235
|
+
if isinstance(val, (float, np.floating)) and np.isnan(val):
|
|
236
|
+
return None
|
|
237
|
+
if isinstance(val, np.generic):
|
|
238
|
+
return val.item()
|
|
239
|
+
return val
|
vecgen/rules.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Vectorized rule parser and expression dependency extractor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import keyword
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
from vecgen._compat import NormalizedData
|
|
14
|
+
from vecgen.exceptions import RuleEvaluationError
|
|
15
|
+
from vecgen.types import BoolArray, DataType, RuleType
|
|
16
|
+
|
|
17
|
+
_BUILTIN_NAMES = frozenset(
|
|
18
|
+
{
|
|
19
|
+
"True",
|
|
20
|
+
"False",
|
|
21
|
+
"None",
|
|
22
|
+
"and",
|
|
23
|
+
"or",
|
|
24
|
+
"not",
|
|
25
|
+
"in",
|
|
26
|
+
"is",
|
|
27
|
+
"abs",
|
|
28
|
+
"round",
|
|
29
|
+
"min",
|
|
30
|
+
"max",
|
|
31
|
+
"sin",
|
|
32
|
+
"cos",
|
|
33
|
+
"tan",
|
|
34
|
+
"exp",
|
|
35
|
+
"log",
|
|
36
|
+
"log10",
|
|
37
|
+
"sqrt",
|
|
38
|
+
"floor",
|
|
39
|
+
"ceil",
|
|
40
|
+
}
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def extract_dependencies(expr: str, known_columns: set[str] | None = None) -> set[str]:
|
|
45
|
+
"""Extract referenced column identifiers from a pandas query or arithmetic expression.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
expr: A pandas-compatible boolean query or arithmetic expression string.
|
|
49
|
+
known_columns: Optional set of valid column names to filter identifiers against.
|
|
50
|
+
If provided, only names present in ``known_columns`` are returned.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
Set of column names referenced by the expression.
|
|
54
|
+
"""
|
|
55
|
+
if not isinstance(expr, str) or not expr.strip():
|
|
56
|
+
return set()
|
|
57
|
+
|
|
58
|
+
# Handle pandas @var syntax by stripping leading '@' so Python's AST can parse it
|
|
59
|
+
sanitized = expr.replace("@", "")
|
|
60
|
+
try:
|
|
61
|
+
tree = ast.parse(sanitized, mode="eval")
|
|
62
|
+
except SyntaxError as exc:
|
|
63
|
+
raise RuleEvaluationError(f"Invalid syntax in expression {expr!r}: {exc.msg}") from exc
|
|
64
|
+
|
|
65
|
+
names: set[str] = set()
|
|
66
|
+
for node in ast.walk(tree):
|
|
67
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
|
|
68
|
+
ident = node.id
|
|
69
|
+
if ident in _BUILTIN_NAMES or keyword.iskeyword(ident):
|
|
70
|
+
continue
|
|
71
|
+
if known_columns is None or ident in known_columns:
|
|
72
|
+
names.add(ident)
|
|
73
|
+
return names
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def evaluate_rule(
|
|
77
|
+
rule: RuleType,
|
|
78
|
+
norm: NormalizedData,
|
|
79
|
+
*,
|
|
80
|
+
raw_input: DataType | None = None,
|
|
81
|
+
) -> BoolArray:
|
|
82
|
+
"""Evaluate a mask, callable, or query string into a 1D boolean NumPy array.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
rule: Boolean mask, callable accepting the input container, or query string.
|
|
86
|
+
norm: NormalizedData wrapper containing the working DataFrame.
|
|
87
|
+
raw_input: Original container passed to callables (falls back to ``norm.frame``).
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
1D boolean numpy array of length ``len(norm.frame)``.
|
|
91
|
+
"""
|
|
92
|
+
n_rows = len(norm.frame)
|
|
93
|
+
target_for_callable = raw_input if raw_input is not None else norm.frame
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
if isinstance(rule, str):
|
|
97
|
+
if not rule.strip():
|
|
98
|
+
raise RuleEvaluationError("Rule string cannot be empty.")
|
|
99
|
+
result = norm.frame.eval(rule)
|
|
100
|
+
elif callable(rule):
|
|
101
|
+
result = rule(target_for_callable)
|
|
102
|
+
else:
|
|
103
|
+
result = rule
|
|
104
|
+
except RuleEvaluationError:
|
|
105
|
+
raise
|
|
106
|
+
except Exception as exc:
|
|
107
|
+
raise RuleEvaluationError(f"Failed to evaluate rule {rule!r}: {exc}") from exc
|
|
108
|
+
|
|
109
|
+
mask = _coerce_to_bool_array(result, expected_len=n_rows, rule=rule)
|
|
110
|
+
return mask
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _coerce_to_bool_array(result: Any, *, expected_len: int, rule: Any) -> BoolArray:
|
|
114
|
+
"""Validate and convert a rule evaluation result into a 1D bool ndarray."""
|
|
115
|
+
if isinstance(result, pd.Series):
|
|
116
|
+
if result.isna().any():
|
|
117
|
+
arr = result.fillna(False).to_numpy(dtype=np.bool_)
|
|
118
|
+
else:
|
|
119
|
+
arr = result.to_numpy(dtype=np.bool_)
|
|
120
|
+
elif isinstance(result, np.ndarray):
|
|
121
|
+
if result.ndim != 1:
|
|
122
|
+
raise RuleEvaluationError(
|
|
123
|
+
f"Rule {rule!r} produced a {result.ndim}D array; expected 1D boolean mask."
|
|
124
|
+
)
|
|
125
|
+
if np.issubdtype(result.dtype, np.floating):
|
|
126
|
+
arr = np.nan_to_num(result, nan=0.0).astype(np.bool_)
|
|
127
|
+
else:
|
|
128
|
+
arr = result.astype(np.bool_, copy=False)
|
|
129
|
+
elif isinstance(result, Sequence) and not isinstance(result, (str, bytes)):
|
|
130
|
+
arr = np.asarray(result, dtype=np.bool_)
|
|
131
|
+
elif isinstance(result, (bool, np.bool_)):
|
|
132
|
+
arr = np.full(expected_len, bool(result), dtype=np.bool_)
|
|
133
|
+
else:
|
|
134
|
+
raise RuleEvaluationError(
|
|
135
|
+
f"Rule {rule!r} returned unsupported mask type {type(result).__name__!r}."
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
if arr.shape != (expected_len,):
|
|
139
|
+
raise RuleEvaluationError(
|
|
140
|
+
f"Rule mask length {arr.shape[0]} does not match data length {expected_len}."
|
|
141
|
+
)
|
|
142
|
+
return arr
|
vecgen/serialization.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Builder <-> dict/JSON conversion using stdlib json only (FR-11, NFR-3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
10
|
+
|
|
11
|
+
from vecgen.exceptions import SchemaError
|
|
12
|
+
from vecgen.types import DistName
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from vecgen.builder import DatasetBuilder, _ColumnBranch
|
|
16
|
+
|
|
17
|
+
_SCHEMA_VERSION = 1
|
|
18
|
+
_VALID_DISTS = frozenset({"uniform", "normal", "lognormal", "exponential", "randint"})
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def builder_to_dict(builder: DatasetBuilder) -> dict[str, Any]:
|
|
22
|
+
"""Serialize a ``DatasetBuilder`` definition into a JSON-compatible dictionary."""
|
|
23
|
+
columns_payload: dict[str, list[dict[str, Any]]] = {}
|
|
24
|
+
for col, branches in builder._columns.items():
|
|
25
|
+
columns_payload[col] = [_serialize_branch(col, branch) for branch in branches]
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
"vecgen_schema_version": _SCHEMA_VERSION,
|
|
29
|
+
"rows": builder.rows,
|
|
30
|
+
"seed": builder.seed,
|
|
31
|
+
"columns": columns_payload,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def builder_to_json(
|
|
36
|
+
builder: DatasetBuilder,
|
|
37
|
+
path: str | os.PathLike[str] | None = None,
|
|
38
|
+
*,
|
|
39
|
+
indent: int = 2,
|
|
40
|
+
) -> str:
|
|
41
|
+
"""Serialize a ``DatasetBuilder`` to a JSON string and optionally write to ``path``."""
|
|
42
|
+
payload = builder_to_dict(builder)
|
|
43
|
+
serialized = json.dumps(payload, indent=indent)
|
|
44
|
+
if path is not None:
|
|
45
|
+
Path(path).write_text(serialized, encoding="utf-8")
|
|
46
|
+
return serialized
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def builder_from_dict(data: Mapping[str, Any]) -> DatasetBuilder:
|
|
50
|
+
"""Reconstruct a ``DatasetBuilder`` from a serialized dictionary."""
|
|
51
|
+
from vecgen.builder import DatasetBuilder
|
|
52
|
+
|
|
53
|
+
if not isinstance(data, Mapping):
|
|
54
|
+
raise SchemaError(f"Expected a mapping for builder schema, got {type(data).__name__!r}.")
|
|
55
|
+
|
|
56
|
+
if "rows" not in data or not isinstance(data["rows"], int) or isinstance(data["rows"], bool):
|
|
57
|
+
raise SchemaError("Serialized builder schema must include an integer `rows` field.")
|
|
58
|
+
|
|
59
|
+
seed = data.get("seed")
|
|
60
|
+
if seed is not None and (not isinstance(seed, int) or isinstance(seed, bool)):
|
|
61
|
+
raise SchemaError("Serialized builder `seed` must be an integer or null.")
|
|
62
|
+
|
|
63
|
+
raw_columns = data.get("columns")
|
|
64
|
+
if not isinstance(raw_columns, Mapping):
|
|
65
|
+
raise SchemaError("Serialized builder schema must include a `columns` mapping.")
|
|
66
|
+
|
|
67
|
+
builder = DatasetBuilder(rows=data["rows"], seed=seed)
|
|
68
|
+
for col, raw_branches in raw_columns.items():
|
|
69
|
+
if not isinstance(col, str) or not col:
|
|
70
|
+
raise SchemaError(f"Invalid column name {col!r} in serialized schema.")
|
|
71
|
+
if not isinstance(raw_branches, list) or not raw_branches:
|
|
72
|
+
raise SchemaError(f"Column {col!r} must have a non-empty list of branches.")
|
|
73
|
+
|
|
74
|
+
for raw_branch in raw_branches:
|
|
75
|
+
branch: _ColumnBranch = _deserialize_branch(col, raw_branch)
|
|
76
|
+
builder._register_branch(col, branch)
|
|
77
|
+
|
|
78
|
+
return builder
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def builder_from_json(source: str | os.PathLike[str]) -> DatasetBuilder:
|
|
82
|
+
"""Load a ``DatasetBuilder`` from a JSON string or a path to a ``.json`` file."""
|
|
83
|
+
raw_text: str
|
|
84
|
+
|
|
85
|
+
if isinstance(source, os.PathLike):
|
|
86
|
+
raw_text = Path(source).read_text(encoding="utf-8")
|
|
87
|
+
elif isinstance(source, str):
|
|
88
|
+
stripped = source.lstrip()
|
|
89
|
+
if stripped.startswith(("{", "[")):
|
|
90
|
+
raw_text = source
|
|
91
|
+
else:
|
|
92
|
+
raw_text = Path(source).read_text(encoding="utf-8")
|
|
93
|
+
else:
|
|
94
|
+
raise SchemaError(f"Expected JSON string or path, got {type(source).__name__!r}.")
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
parsed = json.loads(raw_text)
|
|
98
|
+
except json.JSONDecodeError as exc:
|
|
99
|
+
raise SchemaError(f"Invalid builder JSON: {exc.msg}") from exc
|
|
100
|
+
|
|
101
|
+
if not isinstance(parsed, Mapping):
|
|
102
|
+
raise SchemaError("Top-level builder JSON must be a JSON object.")
|
|
103
|
+
|
|
104
|
+
return builder_from_dict(parsed)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _serialize_branch(col: str, branch: _ColumnBranch) -> dict[str, Any]:
|
|
108
|
+
when_val = _validate_rule_serializable(col, branch.when, field_name="when")
|
|
109
|
+
base: dict[str, Any] = {
|
|
110
|
+
"kind": branch.kind,
|
|
111
|
+
"when": when_val,
|
|
112
|
+
"depends_on": sorted(branch.depends_on),
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if branch.kind == "distribution":
|
|
116
|
+
if branch.dist is None:
|
|
117
|
+
raise SchemaError(f"Column {col!r} distribution branch is missing `dist`.")
|
|
118
|
+
params_out: dict[str, int | float | str] = {}
|
|
119
|
+
for k, v in branch.params.items():
|
|
120
|
+
if not isinstance(v, (int, float, str)) or isinstance(v, bool):
|
|
121
|
+
raise SchemaError(
|
|
122
|
+
f"Column {col!r} parameter {k!r} has non-JSON-serializable type "
|
|
123
|
+
f"{type(v).__name__!r}."
|
|
124
|
+
)
|
|
125
|
+
params_out[k] = v
|
|
126
|
+
base["dist"] = branch.dist
|
|
127
|
+
base["params"] = params_out
|
|
128
|
+
base["clip"] = list(branch.clip) if branch.clip is not None else None
|
|
129
|
+
base["dtype"] = branch.dtype
|
|
130
|
+
return base
|
|
131
|
+
|
|
132
|
+
if branch.kind == "choice":
|
|
133
|
+
_ensure_json_primitive_list(col, branch.choices, field_name="choices")
|
|
134
|
+
base["choices"] = list(branch.choices)
|
|
135
|
+
base["weights"] = list(branch.weights) if branch.weights is not None else None
|
|
136
|
+
base["dtype"] = branch.dtype
|
|
137
|
+
return base
|
|
138
|
+
|
|
139
|
+
# branch.kind == "rule"
|
|
140
|
+
rule_val = _validate_rule_serializable(col, branch.rule, field_name="rule")
|
|
141
|
+
if rule_val is None:
|
|
142
|
+
raise SchemaError(f"Column {col!r} rule branch cannot have `rule=None`.")
|
|
143
|
+
val_out = _validate_scalar_serializable(col, branch.value, field_name="value")
|
|
144
|
+
def_out = _validate_scalar_serializable(col, branch.default, field_name="default")
|
|
145
|
+
base["rule"] = rule_val
|
|
146
|
+
base["value"] = val_out
|
|
147
|
+
base["default"] = def_out
|
|
148
|
+
return base
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _deserialize_branch(col: str, raw: Any) -> _ColumnBranch:
|
|
152
|
+
from vecgen.builder import DatasetBuilder, _ColumnBranch
|
|
153
|
+
|
|
154
|
+
if not isinstance(raw, Mapping):
|
|
155
|
+
raise SchemaError(f"Column {col!r} branch must be a JSON object.")
|
|
156
|
+
|
|
157
|
+
kind = raw.get("kind")
|
|
158
|
+
when = raw.get("when")
|
|
159
|
+
if when is not None and not isinstance(when, str):
|
|
160
|
+
raise SchemaError(f"Column {col!r} `when` condition must be a query string or null.")
|
|
161
|
+
|
|
162
|
+
raw_deps = raw.get("depends_on", [])
|
|
163
|
+
if not isinstance(raw_deps, list) or not all(isinstance(d, str) for d in raw_deps):
|
|
164
|
+
raise SchemaError(f"Column {col!r} `depends_on` must be a list of strings.")
|
|
165
|
+
|
|
166
|
+
if kind == "distribution":
|
|
167
|
+
dist = raw.get("dist")
|
|
168
|
+
if dist not in _VALID_DISTS:
|
|
169
|
+
raise SchemaError(f"Column {col!r} has unsupported distribution {dist!r}.")
|
|
170
|
+
params = raw.get("params", {})
|
|
171
|
+
if not isinstance(params, Mapping) or not all(
|
|
172
|
+
isinstance(k, str) and isinstance(v, (int, float, str)) and not isinstance(v, bool)
|
|
173
|
+
for k, v in params.items()
|
|
174
|
+
):
|
|
175
|
+
raise SchemaError(f"Column {col!r} `params` must map names to scalars or expressions.")
|
|
176
|
+
|
|
177
|
+
raw_clip = raw.get("clip")
|
|
178
|
+
clip: tuple[float | None, float | None] | None = None
|
|
179
|
+
if raw_clip is not None:
|
|
180
|
+
if not isinstance(raw_clip, list) or len(raw_clip) != 2:
|
|
181
|
+
raise SchemaError(f"Column {col!r} `clip` must be a 2-element list or null.")
|
|
182
|
+
clip = (raw_clip[0], raw_clip[1])
|
|
183
|
+
|
|
184
|
+
dtype = raw.get("dtype")
|
|
185
|
+
if dtype is not None and not isinstance(dtype, str):
|
|
186
|
+
raise SchemaError(f"Column {col!r} `dtype` must be a string or null.")
|
|
187
|
+
|
|
188
|
+
deps = DatasetBuilder._collect_branch_deps(
|
|
189
|
+
when=when,
|
|
190
|
+
depends_on=raw_deps,
|
|
191
|
+
expressions=[v for v in params.values() if isinstance(v, str)],
|
|
192
|
+
)
|
|
193
|
+
return _ColumnBranch(
|
|
194
|
+
kind="distribution",
|
|
195
|
+
when=when,
|
|
196
|
+
depends_on=deps,
|
|
197
|
+
dist=cast(DistName, dist),
|
|
198
|
+
params=dict(params),
|
|
199
|
+
clip=clip,
|
|
200
|
+
dtype=dtype,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
if kind == "choice":
|
|
204
|
+
choices = raw.get("choices")
|
|
205
|
+
if not isinstance(choices, list) or not choices:
|
|
206
|
+
raise SchemaError(f"Column {col!r} `choices` must be a non-empty list.")
|
|
207
|
+
weights = raw.get("weights")
|
|
208
|
+
if weights is not None and (
|
|
209
|
+
not isinstance(weights, list)
|
|
210
|
+
or not all(isinstance(w, (int, float)) and not isinstance(w, bool) for w in weights)
|
|
211
|
+
):
|
|
212
|
+
raise SchemaError(f"Column {col!r} `weights` must be a list of numbers or null.")
|
|
213
|
+
dtype = raw.get("dtype")
|
|
214
|
+
if dtype is not None and not isinstance(dtype, str):
|
|
215
|
+
raise SchemaError(f"Column {col!r} `dtype` must be a string or null.")
|
|
216
|
+
|
|
217
|
+
deps = DatasetBuilder._collect_branch_deps(
|
|
218
|
+
when=when, depends_on=raw_deps, expressions=[]
|
|
219
|
+
)
|
|
220
|
+
return _ColumnBranch(
|
|
221
|
+
kind="choice",
|
|
222
|
+
when=when,
|
|
223
|
+
depends_on=deps,
|
|
224
|
+
choices=list(choices),
|
|
225
|
+
weights=[float(w) for w in weights] if weights is not None else None,
|
|
226
|
+
dtype=dtype,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
if kind == "rule":
|
|
230
|
+
rule = raw.get("rule")
|
|
231
|
+
if not isinstance(rule, str) or not rule.strip():
|
|
232
|
+
raise SchemaError(f"Column {col!r} rule branch requires a non-empty string `rule`.")
|
|
233
|
+
value = raw.get("value")
|
|
234
|
+
default = raw.get("default")
|
|
235
|
+
_validate_scalar_serializable(col, value, field_name="value")
|
|
236
|
+
_validate_scalar_serializable(col, default, field_name="default")
|
|
237
|
+
|
|
238
|
+
deps = DatasetBuilder._collect_branch_deps(
|
|
239
|
+
when=when, depends_on=raw_deps, expressions=[rule]
|
|
240
|
+
)
|
|
241
|
+
return _ColumnBranch(
|
|
242
|
+
kind="rule",
|
|
243
|
+
when=when,
|
|
244
|
+
depends_on=deps,
|
|
245
|
+
rule=rule,
|
|
246
|
+
value=value,
|
|
247
|
+
default=default,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
raise SchemaError(f"Column {col!r} has unsupported branch kind {kind!r}.")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _validate_rule_serializable(col: str, rule: Any, *, field_name: str) -> str | None:
|
|
254
|
+
if rule is None:
|
|
255
|
+
return None
|
|
256
|
+
if isinstance(rule, str):
|
|
257
|
+
return rule
|
|
258
|
+
raise SchemaError(
|
|
259
|
+
f"Cannot serialize column {col!r}: `{field_name}` must be a query string, "
|
|
260
|
+
f"got {type(rule).__name__!r} (callables and boolean masks are not JSON-serializable)."
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _validate_scalar_serializable(col: str, val: Any, *, field_name: str) -> Any:
|
|
265
|
+
if val is None or isinstance(val, (bool, int, float, str)):
|
|
266
|
+
return val
|
|
267
|
+
raise SchemaError(
|
|
268
|
+
f"Cannot serialize column {col!r}: `{field_name}` must be a JSON scalar "
|
|
269
|
+
f"(int, float, str, bool, or None), got {type(val).__name__!r}."
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _ensure_json_primitive_list(col: str, items: list[Any], *, field_name: str) -> None:
|
|
274
|
+
for item in items:
|
|
275
|
+
if item is not None and not isinstance(item, (bool, int, float, str)):
|
|
276
|
+
raise SchemaError(
|
|
277
|
+
f"Cannot serialize column {col!r}: `{field_name}` contains non-JSON-serializable "
|
|
278
|
+
f"value of type {type(item).__name__!r}."
|
|
279
|
+
)
|
vecgen/types.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Shared type aliases for vecgen."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Sequence
|
|
6
|
+
from typing import Any, Literal, Union
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import numpy.typing as npt
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
# Primary supported tabular/array data containers (FR-1)
|
|
13
|
+
NDArrayAny = npt.NDArray[Any]
|
|
14
|
+
BoolArray = npt.NDArray[np.bool_]
|
|
15
|
+
DataType = Union[pd.DataFrame, pd.Series, NDArrayAny]
|
|
16
|
+
|
|
17
|
+
# Column identifiers (string name for DataFrame, integer index for 2D ndarray)
|
|
18
|
+
ColRef = Union[str, int]
|
|
19
|
+
|
|
20
|
+
# Conditional rule formats (FR-3)
|
|
21
|
+
MaskType = Union[pd.Series, BoolArray, Sequence[bool]]
|
|
22
|
+
RuleCallable = Callable[[Any], MaskType]
|
|
23
|
+
RuleType = Union[MaskType, RuleCallable, str]
|
|
24
|
+
|
|
25
|
+
# Target value formats for assignments (FR-4)
|
|
26
|
+
ScalarType = Union[int, float, str, bool, None, np.generic]
|
|
27
|
+
ValueCallable = Callable[[Any], Any]
|
|
28
|
+
ValueType = Union[ScalarType, pd.Series, NDArrayAny, Sequence[Any], ValueCallable]
|
|
29
|
+
|
|
30
|
+
# Reproducibility seed inputs (NFR-2)
|
|
31
|
+
SeedType = Union[int, np.random.Generator, np.random.SeedSequence, None]
|
|
32
|
+
|
|
33
|
+
# Supported distribution names (FR-5)
|
|
34
|
+
DistName = Literal["uniform", "normal", "lognormal", "exponential", "randint"]
|