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/engine.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Core vectorized conditional value assignment (set_values, case_when)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import Any, overload
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from vecgen._compat import NormalizedData, normalize_input, resolve_column_name, restore_output
|
|
12
|
+
from vecgen.exceptions import RuleEvaluationError, SchemaError
|
|
13
|
+
from vecgen.rules import evaluate_rule
|
|
14
|
+
from vecgen.types import BoolArray, ColRef, DataType, NDArrayAny, RuleType, ValueType
|
|
15
|
+
|
|
16
|
+
_UNSET = object()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@overload
|
|
20
|
+
def set_values(
|
|
21
|
+
data: pd.DataFrame,
|
|
22
|
+
*,
|
|
23
|
+
col: ColRef,
|
|
24
|
+
rule: RuleType,
|
|
25
|
+
value: ValueType,
|
|
26
|
+
default: Any = ...,
|
|
27
|
+
inplace: bool = ...,
|
|
28
|
+
) -> pd.DataFrame: ...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@overload
|
|
32
|
+
def set_values(
|
|
33
|
+
data: pd.Series,
|
|
34
|
+
*,
|
|
35
|
+
col: ColRef | None = ...,
|
|
36
|
+
rule: RuleType,
|
|
37
|
+
value: ValueType,
|
|
38
|
+
default: Any = ...,
|
|
39
|
+
inplace: bool = ...,
|
|
40
|
+
) -> pd.Series: ...
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@overload
|
|
44
|
+
def set_values(
|
|
45
|
+
data: NDArrayAny,
|
|
46
|
+
*,
|
|
47
|
+
col: ColRef | None = ...,
|
|
48
|
+
rule: RuleType,
|
|
49
|
+
value: ValueType,
|
|
50
|
+
default: Any = ...,
|
|
51
|
+
inplace: bool = ...,
|
|
52
|
+
columns: Sequence[str] | None = ...,
|
|
53
|
+
) -> NDArrayAny: ...
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def set_values(
|
|
57
|
+
data: DataType,
|
|
58
|
+
*,
|
|
59
|
+
col: ColRef | None = None,
|
|
60
|
+
rule: RuleType,
|
|
61
|
+
value: ValueType,
|
|
62
|
+
default: Any = _UNSET,
|
|
63
|
+
inplace: bool = False,
|
|
64
|
+
columns: Sequence[str] | None = None,
|
|
65
|
+
) -> DataType:
|
|
66
|
+
"""Assign values conditionally using vectorized operations (FR-1, FR-4, FR-8).
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
data: Input DataFrame, Series, or 1D/2D NumPy array.
|
|
70
|
+
col: Target column name (DataFrame) or integer index (2D ndarray). Optional for 1D data.
|
|
71
|
+
rule: Boolean mask, callable, or pandas query string.
|
|
72
|
+
value: Scalar, array/Series, or callable used where ``rule`` is True.
|
|
73
|
+
default: Value used where ``rule`` is False. If omitted, existing column values are kept
|
|
74
|
+
(or NaN if creating a new column on a DataFrame).
|
|
75
|
+
inplace: If True, mutates ``data`` in place when possible. Defaults to False.
|
|
76
|
+
columns: Optional column names when ``data`` is a 2D ndarray using query string rules.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
An object of the exact same type, shape, and metadata as ``data``.
|
|
80
|
+
"""
|
|
81
|
+
norm = normalize_input(data, columns=columns, copy=not inplace)
|
|
82
|
+
target_col = resolve_column_name(norm, col)
|
|
83
|
+
n_rows = len(norm.frame)
|
|
84
|
+
|
|
85
|
+
mask = evaluate_rule(rule, norm, raw_input=data)
|
|
86
|
+
true_vals = _resolve_value_array(value, norm, raw_input=data, n_rows=n_rows)
|
|
87
|
+
|
|
88
|
+
if default is _UNSET:
|
|
89
|
+
if target_col in norm.frame.columns:
|
|
90
|
+
false_vals = norm.frame[target_col].to_numpy()
|
|
91
|
+
else:
|
|
92
|
+
false_vals = np.full(n_rows, np.nan, dtype=object)
|
|
93
|
+
else:
|
|
94
|
+
false_vals = _resolve_value_array(default, norm, raw_input=data, n_rows=n_rows)
|
|
95
|
+
|
|
96
|
+
combined = _vectorized_where(mask, true_vals, false_vals)
|
|
97
|
+
norm.frame[target_col] = combined
|
|
98
|
+
|
|
99
|
+
if inplace:
|
|
100
|
+
_apply_inplace_mutation(data, norm, target_col, combined)
|
|
101
|
+
return data
|
|
102
|
+
|
|
103
|
+
return restore_output(norm, norm.frame)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@overload
|
|
107
|
+
def case_when(
|
|
108
|
+
data: pd.DataFrame,
|
|
109
|
+
*,
|
|
110
|
+
col: ColRef,
|
|
111
|
+
cases: Sequence[tuple[RuleType, ValueType]],
|
|
112
|
+
default: Any = ...,
|
|
113
|
+
inplace: bool = ...,
|
|
114
|
+
) -> pd.DataFrame: ...
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@overload
|
|
118
|
+
def case_when(
|
|
119
|
+
data: pd.Series,
|
|
120
|
+
*,
|
|
121
|
+
col: ColRef | None = ...,
|
|
122
|
+
cases: Sequence[tuple[RuleType, ValueType]],
|
|
123
|
+
default: Any = ...,
|
|
124
|
+
inplace: bool = ...,
|
|
125
|
+
) -> pd.Series: ...
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@overload
|
|
129
|
+
def case_when(
|
|
130
|
+
data: NDArrayAny,
|
|
131
|
+
*,
|
|
132
|
+
col: ColRef | None = ...,
|
|
133
|
+
cases: Sequence[tuple[RuleType, ValueType]],
|
|
134
|
+
default: Any = ...,
|
|
135
|
+
inplace: bool = ...,
|
|
136
|
+
columns: Sequence[str] | None = ...,
|
|
137
|
+
) -> NDArrayAny: ...
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def case_when(
|
|
141
|
+
data: DataType,
|
|
142
|
+
*,
|
|
143
|
+
col: ColRef | None = None,
|
|
144
|
+
cases: Sequence[tuple[RuleType, ValueType]],
|
|
145
|
+
default: Any = _UNSET,
|
|
146
|
+
inplace: bool = False,
|
|
147
|
+
columns: Sequence[str] | None = None,
|
|
148
|
+
) -> DataType:
|
|
149
|
+
"""Multi-condition ordered priority assignment (SQL CASE WHEN semantics) (FR-4).
|
|
150
|
+
|
|
151
|
+
First matching condition wins.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
data: Input DataFrame, Series, or 1D/2D NumPy array.
|
|
155
|
+
col: Target column name or integer index.
|
|
156
|
+
cases: Ordered sequence of ``(rule, value)`` pairs.
|
|
157
|
+
default: Fallback value when no condition matches.
|
|
158
|
+
inplace: If True, mutates ``data`` in place when possible.
|
|
159
|
+
columns: Optional column names when ``data`` is a 2D ndarray.
|
|
160
|
+
"""
|
|
161
|
+
if not cases:
|
|
162
|
+
raise SchemaError("`cases` must contain at least one (rule, value) pair.")
|
|
163
|
+
|
|
164
|
+
norm = normalize_input(data, columns=columns, copy=not inplace)
|
|
165
|
+
target_col = resolve_column_name(norm, col)
|
|
166
|
+
n_rows = len(norm.frame)
|
|
167
|
+
|
|
168
|
+
condlist: list[BoolArray] = []
|
|
169
|
+
choicelist: list[NDArrayAny] = []
|
|
170
|
+
for rule, val in cases:
|
|
171
|
+
condlist.append(evaluate_rule(rule, norm, raw_input=data))
|
|
172
|
+
choicelist.append(_resolve_value_array(val, norm, raw_input=data, n_rows=n_rows))
|
|
173
|
+
|
|
174
|
+
if default is _UNSET:
|
|
175
|
+
if target_col in norm.frame.columns:
|
|
176
|
+
default_arr = norm.frame[target_col].to_numpy()
|
|
177
|
+
else:
|
|
178
|
+
default_arr = np.full(n_rows, np.nan, dtype=object)
|
|
179
|
+
else:
|
|
180
|
+
default_arr = _resolve_value_array(default, norm, raw_input=data, n_rows=n_rows)
|
|
181
|
+
|
|
182
|
+
combined = _vectorized_select(condlist, choicelist, default_arr)
|
|
183
|
+
norm.frame[target_col] = combined
|
|
184
|
+
|
|
185
|
+
if inplace:
|
|
186
|
+
_apply_inplace_mutation(data, norm, target_col, combined)
|
|
187
|
+
return data
|
|
188
|
+
|
|
189
|
+
return restore_output(norm, norm.frame)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _resolve_value_array(
|
|
193
|
+
val: ValueType,
|
|
194
|
+
norm: NormalizedData,
|
|
195
|
+
*,
|
|
196
|
+
raw_input: DataType,
|
|
197
|
+
n_rows: int,
|
|
198
|
+
) -> NDArrayAny:
|
|
199
|
+
"""Materialize a scalar, Series, ndarray, sequence, or callable into a 1D ndarray."""
|
|
200
|
+
if callable(val):
|
|
201
|
+
try:
|
|
202
|
+
resolved = val(raw_input)
|
|
203
|
+
except Exception as exc:
|
|
204
|
+
raise RuleEvaluationError(f"Failed to evaluate value callable: {exc}") from exc
|
|
205
|
+
else:
|
|
206
|
+
resolved = val
|
|
207
|
+
|
|
208
|
+
if isinstance(resolved, pd.Series):
|
|
209
|
+
return resolved.to_numpy()
|
|
210
|
+
if isinstance(resolved, np.ndarray):
|
|
211
|
+
if resolved.ndim == 0:
|
|
212
|
+
return np.full(n_rows, resolved.item())
|
|
213
|
+
if resolved.ndim != 1 or resolved.shape[0] != n_rows:
|
|
214
|
+
raise RuleEvaluationError(
|
|
215
|
+
f"Value array shape {resolved.shape} incompatible with {n_rows} rows."
|
|
216
|
+
)
|
|
217
|
+
return resolved
|
|
218
|
+
if isinstance(resolved, Sequence) and not isinstance(resolved, (str, bytes)):
|
|
219
|
+
arr = np.asarray(resolved)
|
|
220
|
+
if arr.shape != (n_rows,):
|
|
221
|
+
raise RuleEvaluationError(
|
|
222
|
+
f"Value sequence length {len(resolved)} does not match {n_rows} rows."
|
|
223
|
+
)
|
|
224
|
+
return arr
|
|
225
|
+
|
|
226
|
+
# Scalar (including None, str, int, float, bool)
|
|
227
|
+
if resolved is None:
|
|
228
|
+
return np.full(n_rows, None, dtype=object)
|
|
229
|
+
return np.full(n_rows, resolved)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _vectorized_where(
|
|
233
|
+
mask: BoolArray,
|
|
234
|
+
true_vals: NDArrayAny,
|
|
235
|
+
false_vals: NDArrayAny,
|
|
236
|
+
) -> NDArrayAny:
|
|
237
|
+
"""Apply np.where while cleanly handling mixed scalar/string/object dtypes."""
|
|
238
|
+
common_dtype = np.result_type(true_vals.dtype, false_vals.dtype)
|
|
239
|
+
if common_dtype.kind in ("U", "S", "O"):
|
|
240
|
+
return np.where(mask, true_vals.astype(object), false_vals.astype(object))
|
|
241
|
+
return np.where(mask, true_vals, false_vals)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _vectorized_select(
|
|
245
|
+
condlist: list[BoolArray],
|
|
246
|
+
choicelist: list[NDArrayAny],
|
|
247
|
+
default_arr: NDArrayAny,
|
|
248
|
+
) -> NDArrayAny:
|
|
249
|
+
"""Apply np.select while cleanly handling mixed string/object dtypes."""
|
|
250
|
+
all_arrays = [*choicelist, default_arr]
|
|
251
|
+
common_dtype = np.result_type(*(arr.dtype for arr in all_arrays))
|
|
252
|
+
if common_dtype.kind in ("U", "S", "O"):
|
|
253
|
+
obj_choices = [arr.astype(object) for arr in choicelist]
|
|
254
|
+
return np.select(condlist, obj_choices, default=default_arr.astype(object))
|
|
255
|
+
return np.select(condlist, choicelist, default=default_arr)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _apply_inplace_mutation(
|
|
259
|
+
data: DataType,
|
|
260
|
+
norm: NormalizedData,
|
|
261
|
+
target_col: str,
|
|
262
|
+
values: NDArrayAny,
|
|
263
|
+
) -> None:
|
|
264
|
+
"""Write computed column values back into the original container when inplace=True."""
|
|
265
|
+
if isinstance(data, pd.DataFrame):
|
|
266
|
+
data[target_col] = values
|
|
267
|
+
elif isinstance(data, pd.Series):
|
|
268
|
+
data.iloc[:] = values
|
|
269
|
+
elif isinstance(data, np.ndarray):
|
|
270
|
+
if data.ndim == 1:
|
|
271
|
+
data[:] = values
|
|
272
|
+
else:
|
|
273
|
+
col_idx = norm.col_names.index(target_col)
|
|
274
|
+
data[:, col_idx] = values
|
vecgen/exceptions.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Custom exceptions for vecgen."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class VecgenError(Exception):
|
|
7
|
+
"""Base exception for all vecgen errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RuleEvaluationError(VecgenError):
|
|
11
|
+
"""Raised when a rule mask, callable, or query string cannot be evaluated."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SchemaError(VecgenError):
|
|
15
|
+
"""Raised when a DatasetBuilder definition, branch, or serialization config is invalid."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class CircularDependencyError(SchemaError):
|
|
19
|
+
"""Raised when column definitions contain a dependency cycle."""
|