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 ADDED
@@ -0,0 +1,37 @@
1
+ """vecgen: Declarative, reproducible synthetic datasets with dependent columns."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import vecgen.accessor as _accessor # noqa: F401
6
+ from vecgen.builder import DatasetBuilder
7
+ from vecgen.distributions import sample_choice, sample_distribution
8
+ from vecgen.engine import case_when, set_values
9
+ from vecgen.exceptions import (
10
+ CircularDependencyError,
11
+ RuleEvaluationError,
12
+ SchemaError,
13
+ VecgenError,
14
+ )
15
+ from vecgen.noise import inject_duplicates, inject_nulls, inject_outliers
16
+ from vecgen.report import CorruptionRecord, CorruptionReport, EvaluationResult
17
+
18
+ __version__ = "0.3.0"
19
+
20
+ __all__ = [
21
+ "CircularDependencyError",
22
+ "CorruptionRecord",
23
+ "CorruptionReport",
24
+ "DatasetBuilder",
25
+ "EvaluationResult",
26
+ "RuleEvaluationError",
27
+ "SchemaError",
28
+ "VecgenError",
29
+ "__version__",
30
+ "case_when",
31
+ "inject_duplicates",
32
+ "inject_nulls",
33
+ "inject_outliers",
34
+ "sample_choice",
35
+ "sample_distribution",
36
+ "set_values",
37
+ ]
vecgen/_compat.py ADDED
@@ -0,0 +1,167 @@
1
+ """Internal adapters normalizing DataFrame, Series, and 1D/2D ndarray I/O."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+ from typing import Any, Literal
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from vecgen.exceptions import SchemaError
13
+ from vecgen.types import ColRef, DataType
14
+
15
+ ContainerKind = Literal["dataframe", "series", "ndarray_1d", "ndarray_2d"]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class NormalizedData:
20
+ """Internal representation wrapping any supported DataType."""
21
+
22
+ kind: ContainerKind
23
+ frame: pd.DataFrame
24
+ original: DataType
25
+ series_name: Any = None
26
+ col_names: tuple[str, ...] = ()
27
+
28
+
29
+ def normalize_input(
30
+ data: DataType,
31
+ *,
32
+ columns: Sequence[str] | None = None,
33
+ copy: bool = True,
34
+ ) -> NormalizedData:
35
+ """Convert a DataFrame, Series, or 1D/2D ndarray into a working DataFrame.
36
+
37
+ Args:
38
+ data: Input container (DataFrame, Series, or 1D/2D ndarray).
39
+ columns: Optional column names when ``data`` is a 2D ndarray (or name for 1D/Series).
40
+ copy: If True, ensures the working DataFrame owns a copy of the data (FR-8).
41
+ """
42
+ if isinstance(data, pd.DataFrame):
43
+ frame = data.copy(deep=True) if copy else data
44
+ return NormalizedData(
45
+ kind="dataframe",
46
+ frame=frame,
47
+ original=data,
48
+ )
49
+
50
+ if isinstance(data, pd.Series):
51
+ s = data.copy(deep=True) if copy else data
52
+ col_label = columns[0] if columns else (s.name if s.name is not None else "__value__")
53
+ frame = s.to_frame(name=col_label)
54
+ return NormalizedData(
55
+ kind="series",
56
+ frame=frame,
57
+ original=data,
58
+ series_name=s.name,
59
+ col_names=(str(col_label),),
60
+ )
61
+
62
+ if isinstance(data, np.ndarray):
63
+ arr = data.copy() if copy else data
64
+ if arr.ndim == 1:
65
+ col_label = columns[0] if columns else "__value__"
66
+ frame = pd.DataFrame({col_label: arr})
67
+ return NormalizedData(
68
+ kind="ndarray_1d",
69
+ frame=frame,
70
+ original=data,
71
+ col_names=(col_label,),
72
+ )
73
+ if arr.ndim == 2:
74
+ n_cols = arr.shape[1]
75
+ if columns is not None:
76
+ if len(columns) != n_cols:
77
+ raise SchemaError(
78
+ f"Expected {n_cols} column names for 2D array, got {len(columns)}."
79
+ )
80
+ col_names = tuple(columns)
81
+ else:
82
+ col_names = tuple(f"col_{i}" for i in range(n_cols))
83
+ frame = pd.DataFrame(arr, columns=list(col_names))
84
+ return NormalizedData(
85
+ kind="ndarray_2d",
86
+ frame=frame,
87
+ original=data,
88
+ col_names=col_names,
89
+ )
90
+ raise SchemaError(f"Only 1D and 2D numpy arrays are supported, got {arr.ndim}D.")
91
+
92
+ raise TypeError(
93
+ f"Unsupported data type {type(data).__name__!r}. "
94
+ "Expected pd.DataFrame, pd.Series, or 1D/2D np.ndarray."
95
+ )
96
+
97
+
98
+ def resolve_column_name(norm: NormalizedData, col: ColRef | None) -> str:
99
+ """Resolve a user-supplied column reference to the working DataFrame's column label."""
100
+ if norm.kind in ("series", "ndarray_1d"):
101
+ if col is not None and col != 0 and col != norm.col_names[0]:
102
+ raise SchemaError(
103
+ f"Cannot reference column {col!r} on a 1D {norm.kind}. "
104
+ "Omit `col` or pass `col=0`."
105
+ )
106
+ return norm.col_names[0]
107
+
108
+ if norm.kind == "ndarray_2d":
109
+ if col is None:
110
+ raise SchemaError("`col` must be specified when modifying a 2D numpy array.")
111
+ if isinstance(col, int):
112
+ if col < 0:
113
+ col = len(norm.col_names) + col
114
+ if not (0 <= col < len(norm.col_names)):
115
+ raise SchemaError(
116
+ f"Column index {col} out of bounds for array with "
117
+ f"{len(norm.col_names)} columns."
118
+ )
119
+ return norm.col_names[col]
120
+ if col in norm.frame.columns:
121
+ return col
122
+ raise SchemaError(f"Column {col!r} not found in 2D array columns {norm.col_names}.")
123
+
124
+ # DataFrame
125
+ if col is None:
126
+ raise SchemaError("`col` must be specified when modifying a DataFrame.")
127
+ if isinstance(col, int) and col not in norm.frame.columns:
128
+ raise SchemaError(
129
+ f"Column {col!r} not found in DataFrame. Pass a string column name."
130
+ )
131
+ return str(col)
132
+
133
+
134
+ def restore_output(norm: NormalizedData, frame: pd.DataFrame) -> DataType:
135
+ """Convert the working DataFrame back into the exact original container type and metadata."""
136
+ if norm.kind == "dataframe":
137
+ return frame
138
+
139
+ if norm.kind == "series":
140
+ col_label = norm.col_names[0]
141
+ out = frame[col_label]
142
+ out.name = norm.series_name
143
+ return out
144
+
145
+ if norm.kind == "ndarray_1d":
146
+ col_label = norm.col_names[0]
147
+ return frame[col_label].to_numpy()
148
+
149
+ # ndarray_2d
150
+ assert isinstance(norm.original, np.ndarray)
151
+ arr_out = frame.to_numpy()
152
+ if arr_out.shape != norm.original.shape:
153
+ raise SchemaError(
154
+ f"Operation changed 2D array shape from {norm.original.shape} to {arr_out.shape}."
155
+ )
156
+ return arr_out
157
+
158
+
159
+ def make_nullable_if_needed(series: pd.Series) -> pd.Series:
160
+ """Promote non-nullable integer/bool Series to pandas nullable dtypes before NaN injection."""
161
+ if isinstance(series.dtype, pd.api.extensions.ExtensionDtype):
162
+ return series
163
+ if pd.api.types.is_integer_dtype(series.dtype):
164
+ return series.astype("Int64")
165
+ if pd.api.types.is_bool_dtype(series.dtype):
166
+ return series.astype("boolean")
167
+ return series
vecgen/_graph.py ADDED
@@ -0,0 +1,114 @@
1
+ """Column dependency graph: topological sorting and cycle detection (FR-9)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import deque
6
+ from collections.abc import Mapping, Sequence
7
+
8
+ from vecgen.exceptions import CircularDependencyError, SchemaError
9
+
10
+
11
+ def resolve_execution_order(
12
+ columns: Sequence[str],
13
+ dependencies: Mapping[str, set[str]],
14
+ ) -> list[str]:
15
+ """Compute a deterministic topological execution order for dataset columns.
16
+
17
+ Preserves declaration order as a tie-breaker whenever multiple columns have
18
+ all dependencies satisfied.
19
+
20
+ Args:
21
+ columns: Ordered sequence of column names in declaration order.
22
+ dependencies: Mapping from ``col_name`` -> set of upstream column names it depends on.
23
+
24
+ Returns:
25
+ List of column names ordered so every dependency appears before its dependents.
26
+
27
+ Raises:
28
+ SchemaError: If a column references an unknown dependency not in ``columns``.
29
+ CircularDependencyError: If a dependency cycle (including self-dependency) exists.
30
+ """
31
+ col_set = set(columns)
32
+ declaration_rank = {col: idx for idx, col in enumerate(columns)}
33
+
34
+ in_degree: dict[str, int] = {col: 0 for col in columns}
35
+ dependents: dict[str, list[str]] = {col: [] for col in columns}
36
+
37
+ for col in columns:
38
+ deps = dependencies.get(col, set())
39
+ if col in deps:
40
+ raise CircularDependencyError(
41
+ f"Circular dependency detected: column {col!r} depends on itself."
42
+ )
43
+ unknown = deps - col_set
44
+ if unknown:
45
+ unknown_str = ", ".join(repr(u) for u in sorted(unknown))
46
+ raise SchemaError(
47
+ f"Column {col!r} depends on undefined column(s): {unknown_str}."
48
+ )
49
+ in_degree[col] = len(deps)
50
+ for upstream in deps:
51
+ dependents[upstream].append(col)
52
+
53
+ # Ready queue ordered by original declaration position for deterministic tie-breaking
54
+ initial = [col for col, deg in in_degree.items() if deg == 0]
55
+ ready = deque(sorted(initial, key=declaration_rank.__getitem__))
56
+ order: list[str] = []
57
+
58
+ while ready:
59
+ current = ready.popleft()
60
+ order.append(current)
61
+ newly_ready: list[str] = []
62
+ for downstream in dependents[current]:
63
+ in_degree[downstream] -= 1
64
+ if in_degree[downstream] == 0:
65
+ newly_ready.append(downstream)
66
+ if newly_ready:
67
+ # Merge newly unlocked nodes while maintaining declaration-order stability
68
+ merged = sorted([*ready, *newly_ready], key=declaration_rank.__getitem__)
69
+ ready = deque(merged)
70
+
71
+ if len(order) != len(columns):
72
+ cycle_nodes = [col for col in columns if col not in set(order)]
73
+ cycle_path = _find_cycle_path(cycle_nodes, dependencies)
74
+ raise CircularDependencyError(
75
+ f"Circular dependency detected among columns: {' -> '.join(cycle_path)}."
76
+ )
77
+
78
+ return order
79
+
80
+
81
+ def _find_cycle_path(
82
+ candidates: Sequence[str],
83
+ dependencies: Mapping[str, set[str]],
84
+ ) -> list[str]:
85
+ """Trace an explicit cycle path for clear error reporting."""
86
+ candidate_set = set(candidates)
87
+ visited: set[str] = set()
88
+ stack: list[str] = []
89
+ on_stack: set[str] = set()
90
+
91
+ def dfs(node: str) -> list[str] | None:
92
+ visited.add(node)
93
+ stack.append(node)
94
+ on_stack.add(node)
95
+ for dep in sorted(dependencies.get(node, set())):
96
+ if dep not in candidate_set:
97
+ continue
98
+ if dep in on_stack:
99
+ start_idx = stack.index(dep)
100
+ return [*stack[start_idx:], dep]
101
+ if dep not in visited:
102
+ found = dfs(dep)
103
+ if found is not None:
104
+ return found
105
+ stack.pop()
106
+ on_stack.remove(node)
107
+ return None
108
+
109
+ for start in candidates:
110
+ if start not in visited:
111
+ cycle = dfs(start)
112
+ if cycle is not None:
113
+ return cycle
114
+ return list(candidates)
vecgen/accessor.py ADDED
@@ -0,0 +1,222 @@
1
+ """Custom pandas DataFrame and Series `.gen` accessor registration (FR-1, FR-7)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from typing import Any, Literal, overload
7
+
8
+ import pandas as pd
9
+
10
+ from vecgen.engine import _UNSET, case_when, set_values
11
+ from vecgen.noise import inject_duplicates, inject_nulls, inject_outliers
12
+ from vecgen.report import CorruptionReport
13
+ from vecgen.types import ColRef, RuleType, SeedType, ValueType
14
+
15
+
16
+ @pd.api.extensions.register_dataframe_accessor("gen")
17
+ class VecgenDataFrameAccessor:
18
+ """Ergonomic ``df.gen.*`` accessor wrapping vecgen transformations (FR-7)."""
19
+
20
+ def __init__(self, pandas_obj: pd.DataFrame) -> None:
21
+ self._obj = pandas_obj
22
+
23
+ def apply_rule(
24
+ self,
25
+ *,
26
+ col: ColRef,
27
+ rule: RuleType,
28
+ value: ValueType,
29
+ default: Any = _UNSET,
30
+ inplace: bool = False,
31
+ ) -> pd.DataFrame:
32
+ """Apply a single conditional rule to produce or update ``col``."""
33
+ return set_values(
34
+ self._obj,
35
+ col=col,
36
+ rule=rule,
37
+ value=value,
38
+ default=default,
39
+ inplace=inplace,
40
+ )
41
+
42
+ def case_when(
43
+ self,
44
+ *,
45
+ col: ColRef,
46
+ cases: Sequence[tuple[RuleType, ValueType]],
47
+ default: Any = _UNSET,
48
+ inplace: bool = False,
49
+ ) -> pd.DataFrame:
50
+ """Apply ordered multi-condition CASE WHEN rules to ``col``."""
51
+ return case_when(
52
+ self._obj,
53
+ col=col,
54
+ cases=cases,
55
+ default=default,
56
+ inplace=inplace,
57
+ )
58
+
59
+ @overload
60
+ def inject_nulls(
61
+ self,
62
+ *,
63
+ cols: Sequence[ColRef] | None = ...,
64
+ rate: float = ...,
65
+ seed: SeedType = ...,
66
+ inplace: bool = ...,
67
+ return_report: Literal[False] = ...,
68
+ ) -> pd.DataFrame: ...
69
+
70
+ @overload
71
+ def inject_nulls(
72
+ self,
73
+ *,
74
+ cols: Sequence[ColRef] | None = ...,
75
+ rate: float = ...,
76
+ seed: SeedType = ...,
77
+ inplace: bool = ...,
78
+ return_report: Literal[True],
79
+ ) -> tuple[pd.DataFrame, CorruptionReport]: ...
80
+
81
+ def inject_nulls(
82
+ self,
83
+ *,
84
+ cols: Sequence[ColRef] | None = None,
85
+ rate: float = 0.05,
86
+ seed: SeedType = None,
87
+ inplace: bool = False,
88
+ return_report: bool = False,
89
+ ) -> pd.DataFrame | tuple[pd.DataFrame, CorruptionReport]:
90
+ """Inject missing values into specified columns."""
91
+ if return_report:
92
+ return inject_nulls(
93
+ self._obj, cols=cols, rate=rate, seed=seed, inplace=inplace, return_report=True
94
+ )
95
+ return inject_nulls(
96
+ self._obj, cols=cols, rate=rate, seed=seed, inplace=inplace, return_report=False
97
+ )
98
+
99
+ @overload
100
+ def inject_outliers(
101
+ self,
102
+ *,
103
+ cols: Sequence[ColRef] | None = ...,
104
+ rate: float = ...,
105
+ magnitude: float = ...,
106
+ seed: SeedType = ...,
107
+ inplace: bool = ...,
108
+ return_report: Literal[False] = ...,
109
+ ) -> pd.DataFrame: ...
110
+
111
+ @overload
112
+ def inject_outliers(
113
+ self,
114
+ *,
115
+ cols: Sequence[ColRef] | None = ...,
116
+ rate: float = ...,
117
+ magnitude: float = ...,
118
+ seed: SeedType = ...,
119
+ inplace: bool = ...,
120
+ return_report: Literal[True],
121
+ ) -> tuple[pd.DataFrame, CorruptionReport]: ...
122
+
123
+ def inject_outliers(
124
+ self,
125
+ *,
126
+ cols: Sequence[ColRef] | None = None,
127
+ rate: float = 0.05,
128
+ magnitude: float = 5.0,
129
+ seed: SeedType = None,
130
+ inplace: bool = False,
131
+ return_report: bool = False,
132
+ ) -> pd.DataFrame | tuple[pd.DataFrame, CorruptionReport]:
133
+ """Inject numeric outliers into specified columns."""
134
+ if return_report:
135
+ return inject_outliers(
136
+ self._obj,
137
+ cols=cols,
138
+ rate=rate,
139
+ magnitude=magnitude,
140
+ seed=seed,
141
+ inplace=inplace,
142
+ return_report=True,
143
+ )
144
+ return inject_outliers(
145
+ self._obj,
146
+ cols=cols,
147
+ rate=rate,
148
+ magnitude=magnitude,
149
+ seed=seed,
150
+ inplace=inplace,
151
+ return_report=False,
152
+ )
153
+
154
+ @overload
155
+ def inject_duplicates(
156
+ self,
157
+ *,
158
+ rate: float = ...,
159
+ seed: SeedType = ...,
160
+ return_report: Literal[False] = ...,
161
+ ) -> pd.DataFrame: ...
162
+
163
+ @overload
164
+ def inject_duplicates(
165
+ self,
166
+ *,
167
+ rate: float = ...,
168
+ seed: SeedType = ...,
169
+ return_report: Literal[True],
170
+ ) -> tuple[pd.DataFrame, CorruptionReport]: ...
171
+
172
+ def inject_duplicates(
173
+ self,
174
+ *,
175
+ rate: float = 0.05,
176
+ seed: SeedType = None,
177
+ return_report: bool = False,
178
+ ) -> pd.DataFrame | tuple[pd.DataFrame, CorruptionReport]:
179
+ """Append duplicated rows at the end of the DataFrame."""
180
+ if return_report:
181
+ return inject_duplicates(self._obj, rate=rate, seed=seed, return_report=True)
182
+ return inject_duplicates(self._obj, rate=rate, seed=seed, return_report=False)
183
+
184
+
185
+ @pd.api.extensions.register_series_accessor("gen")
186
+ class VecgenSeriesAccessor:
187
+ """Ergonomic ``s.gen.*`` accessor wrapping vecgen Series transformations (FR-7)."""
188
+
189
+ def __init__(self, pandas_obj: pd.Series) -> None:
190
+ self._obj = pandas_obj
191
+
192
+ def apply_rule(
193
+ self,
194
+ *,
195
+ rule: RuleType,
196
+ value: ValueType,
197
+ default: Any = _UNSET,
198
+ inplace: bool = False,
199
+ ) -> pd.Series:
200
+ """Apply a single conditional rule to the Series."""
201
+ return set_values(
202
+ self._obj,
203
+ rule=rule,
204
+ value=value,
205
+ default=default,
206
+ inplace=inplace,
207
+ )
208
+
209
+ def case_when(
210
+ self,
211
+ *,
212
+ cases: Sequence[tuple[RuleType, ValueType]],
213
+ default: Any = _UNSET,
214
+ inplace: bool = False,
215
+ ) -> pd.Series:
216
+ """Apply ordered multi-condition CASE WHEN rules to the Series."""
217
+ return case_when(
218
+ self._obj,
219
+ cases=cases,
220
+ default=default,
221
+ inplace=inplace,
222
+ )