vecgen 0.3.0__tar.gz
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-0.3.0/.github/workflows/ci.yml +56 -0
- vecgen-0.3.0/.github/workflows/publish.yml +35 -0
- vecgen-0.3.0/.gitignore +27 -0
- vecgen-0.3.0/LICENSE +21 -0
- vecgen-0.3.0/PKG-INFO +177 -0
- vecgen-0.3.0/README.md +139 -0
- vecgen-0.3.0/docs/api_guide.md +161 -0
- vecgen-0.3.0/docs/project_structure.txt +42 -0
- vecgen-0.3.0/docs/project_vision.md +65 -0
- vecgen-0.3.0/pyproject.toml +82 -0
- vecgen-0.3.0/src/vecgen/__init__.py +37 -0
- vecgen-0.3.0/src/vecgen/_compat.py +167 -0
- vecgen-0.3.0/src/vecgen/_graph.py +114 -0
- vecgen-0.3.0/src/vecgen/accessor.py +222 -0
- vecgen-0.3.0/src/vecgen/builder.py +338 -0
- vecgen-0.3.0/src/vecgen/distributions.py +176 -0
- vecgen-0.3.0/src/vecgen/engine.py +274 -0
- vecgen-0.3.0/src/vecgen/exceptions.py +19 -0
- vecgen-0.3.0/src/vecgen/noise.py +534 -0
- vecgen-0.3.0/src/vecgen/py.typed +0 -0
- vecgen-0.3.0/src/vecgen/report.py +239 -0
- vecgen-0.3.0/src/vecgen/rules.py +142 -0
- vecgen-0.3.0/src/vecgen/serialization.py +279 -0
- vecgen-0.3.0/src/vecgen/types.py +34 -0
- vecgen-0.3.0/tests/conftest.py +46 -0
- vecgen-0.3.0/tests/test_accessor.py +48 -0
- vecgen-0.3.0/tests/test_builder.py +137 -0
- vecgen-0.3.0/tests/test_compat.py +121 -0
- vecgen-0.3.0/tests/test_distributions.py +135 -0
- vecgen-0.3.0/tests/test_engine.py +144 -0
- vecgen-0.3.0/tests/test_graph.py +51 -0
- vecgen-0.3.0/tests/test_noise.py +162 -0
- vecgen-0.3.0/tests/test_performance.py +91 -0
- vecgen-0.3.0/tests/test_report.py +127 -0
- vecgen-0.3.0/tests/test_rules.py +66 -0
- vecgen-0.3.0/tests/test_serialization.py +116 -0
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [main]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
quality:
|
|
11
|
+
name: Lint & Type Check
|
|
12
|
+
runs-on: ubuntu-latest
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: "3.12"
|
|
19
|
+
|
|
20
|
+
- name: Install dependencies
|
|
21
|
+
run: |
|
|
22
|
+
python -m pip install --upgrade pip
|
|
23
|
+
pip install -e ".[dev]"
|
|
24
|
+
|
|
25
|
+
- name: Run Ruff
|
|
26
|
+
run: ruff check src tests
|
|
27
|
+
|
|
28
|
+
- name: Run Mypy
|
|
29
|
+
run: mypy src/vecgen
|
|
30
|
+
|
|
31
|
+
test:
|
|
32
|
+
name: Tests (Python ${{ matrix.python-version }})
|
|
33
|
+
runs-on: ${{ matrix.os }}
|
|
34
|
+
strategy:
|
|
35
|
+
fail-fast: false
|
|
36
|
+
matrix:
|
|
37
|
+
os: [ubuntu-latest]
|
|
38
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
39
|
+
include:
|
|
40
|
+
- os: ubuntu-24.04
|
|
41
|
+
python-version: "3.9"
|
|
42
|
+
|
|
43
|
+
steps:
|
|
44
|
+
- uses: actions/checkout@v4
|
|
45
|
+
|
|
46
|
+
- uses: actions/setup-python@v5
|
|
47
|
+
with:
|
|
48
|
+
python-version: ${{ matrix.python-version }}
|
|
49
|
+
|
|
50
|
+
- name: Install test dependencies
|
|
51
|
+
run: |
|
|
52
|
+
python -m pip install --upgrade pip
|
|
53
|
+
pip install -e . "pytest>=8.0.0" "pytest-cov>=5.0.0"
|
|
54
|
+
|
|
55
|
+
- name: Run pytest with branch coverage
|
|
56
|
+
run: pytest --cov=vecgen --cov-report=term-missing
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- "v*"
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
build-and-publish:
|
|
10
|
+
name: Build & Publish Distribution
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
permissions:
|
|
13
|
+
id-token: write
|
|
14
|
+
contents: read
|
|
15
|
+
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v4
|
|
18
|
+
|
|
19
|
+
- uses: actions/setup-python@v5
|
|
20
|
+
with:
|
|
21
|
+
python-version: "3.12"
|
|
22
|
+
|
|
23
|
+
- name: Install build tools
|
|
24
|
+
run: |
|
|
25
|
+
python -m pip install --upgrade pip
|
|
26
|
+
pip install build twine
|
|
27
|
+
|
|
28
|
+
- name: Build sdist and wheel
|
|
29
|
+
run: python -m build
|
|
30
|
+
|
|
31
|
+
- name: Check distribution metadata
|
|
32
|
+
run: twine check dist/*
|
|
33
|
+
|
|
34
|
+
- name: Publish package to PyPI
|
|
35
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
vecgen-0.3.0/.gitignore
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Virtual environments
|
|
2
|
+
.venv/
|
|
3
|
+
venv/
|
|
4
|
+
env/
|
|
5
|
+
|
|
6
|
+
# Python bytecode & caches
|
|
7
|
+
__pycache__/
|
|
8
|
+
*.py[cod]
|
|
9
|
+
*$py.class
|
|
10
|
+
.mypy_cache/
|
|
11
|
+
.ruff_cache/
|
|
12
|
+
.pytest_cache/
|
|
13
|
+
|
|
14
|
+
# Coverage reports
|
|
15
|
+
.coverage
|
|
16
|
+
.coverage.*
|
|
17
|
+
htmlcov/
|
|
18
|
+
coverage.xml
|
|
19
|
+
|
|
20
|
+
# Packaging & build artifacts
|
|
21
|
+
build/
|
|
22
|
+
dist/
|
|
23
|
+
*.egg-info/
|
|
24
|
+
|
|
25
|
+
# Generated live LLM context https://github.com/pchaher03/context-generate
|
|
26
|
+
.context/
|
|
27
|
+
.contextignore
|
vecgen-0.3.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Pablo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
vecgen-0.3.0/PKG-INFO
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: vecgen
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Declarative, reproducible synthetic datasets with dependent columns, plus data corruption with a ground-truth report.
|
|
5
|
+
Project-URL: Homepage, https://github.com/pchaher03/vecgen
|
|
6
|
+
Project-URL: Repository, https://github.com/pchaher03/vecgen
|
|
7
|
+
Project-URL: Issues, https://github.com/pchaher03/vecgen/issues
|
|
8
|
+
Author: Pablo
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: data-quality,dataset,machine-learning,numpy,pandas,synthetic-data,testing
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering
|
|
24
|
+
Classifier: Topic :: Software Development :: Testing
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Requires-Dist: numpy>=1.24.0
|
|
28
|
+
Requires-Dist: pandas>=2.0.0
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: build>=1.2.0; extra == 'dev'
|
|
31
|
+
Requires-Dist: mypy>=1.11.0; extra == 'dev'
|
|
32
|
+
Requires-Dist: pandas-stubs>=2.0.0; extra == 'dev'
|
|
33
|
+
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
|
|
34
|
+
Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
35
|
+
Requires-Dist: ruff>=0.6.0; extra == 'dev'
|
|
36
|
+
Requires-Dist: twine>=5.0.0; extra == 'dev'
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# vecgen
|
|
40
|
+
|
|
41
|
+
**Declarative, reproducible synthetic datasets with dependent columns, plus data corruption that comes with a ground-truth report.**
|
|
42
|
+
|
|
43
|
+
`vecgen` (short for **Vectorized Generator**) lets you describe a dataset as rules, distributions, and dependencies between columns, generate it deterministically with a seed, and then break it on purpose while recording exactly what was broken. You can also inject rule-driven values and edge cases into existing `pandas` DataFrames, Series, and `numpy` arrays.
|
|
44
|
+
|
|
45
|
+
All outputs are native `pandas` and `numpy` structures, making `vecgen` immediately compatible with **scikit-learn**, **PyTorch**, and **TensorFlow** without extra dependencies.
|
|
46
|
+
|
|
47
|
+
## Key Features
|
|
48
|
+
|
|
49
|
+
* **Conditional & Dependent Columns:** Define a column differently per condition (`when="country == 'MX'"`), or make distribution parameters depend on other columns (`mean="age * 800"`). Columns are resolved in dependency order, so you can declare them in any order.
|
|
50
|
+
* **Corruption with a Ground-Truth Report:** `inject_nulls`, `inject_duplicates`, and `inject_outliers` can return a `CorruptionReport` listing every row, column, and value they changed. Use it to check that your pipeline or validation rules caught what they should have.
|
|
51
|
+
* **Serializable Builders:** Save a `DatasetBuilder` definition to JSON and reload it later. The same JSON plus the same seed gives the same dataset.
|
|
52
|
+
* **Pandas & NumPy Polymorphism:** Accepts `pd.DataFrame`, `pd.Series`, and 1D/2D `np.ndarray` inputs and returns the exact same type, shape, and preserved index/column metadata.
|
|
53
|
+
* **Flexible Rule Engine:** Define conditional logic using boolean masks, Python callables (`lambda df: ...`), or pandas query strings (`"age >= 18 and country == 'MX'"`).
|
|
54
|
+
* **ML-Ready Dataset Builder:** Generate synthetic DataFrames via `.build()` or export pure NumPy `(X, y)` feature/target arrays directly via `.build_numpy(target=...)`.
|
|
55
|
+
* **Vectorized & Deterministic:** Built purely on NumPy and pandas vectorized operations, non-destructive by default (`inplace=False`), and fully reproducible via `seed`.
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install vecgen
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
For local development:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
git clone https://github.com/pchaher03/vecgen.git
|
|
67
|
+
cd vecgen
|
|
68
|
+
pip install -e ".[dev]"
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Quickstart
|
|
72
|
+
|
|
73
|
+
### 1. Generate a Dataset with Conditional and Dependent Columns
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from vecgen import DatasetBuilder
|
|
77
|
+
|
|
78
|
+
builder = DatasetBuilder(rows=10_000, seed=42)
|
|
79
|
+
|
|
80
|
+
builder.add_distribution("age", dist="normal", mean=35, std=10, clip=(18, 90), dtype="int64")
|
|
81
|
+
builder.add_choice("country", choices=["MX", "US", "CA"], weights=[0.5, 0.3, 0.2])
|
|
82
|
+
|
|
83
|
+
# Parameters can be expressions of other columns
|
|
84
|
+
builder.add_distribution("income", dist="normal", mean="age * 800", std=6_000, clip=(0, None))
|
|
85
|
+
|
|
86
|
+
# Same column, different behavior per condition (first match wins; no `when` = fallback)
|
|
87
|
+
builder.add_distribution("spend", dist="lognormal", mean=4.0, sigma=0.5, when="country == 'MX'")
|
|
88
|
+
builder.add_distribution("spend", dist="normal", mean=150, std=40, when="country == 'US'")
|
|
89
|
+
builder.add_distribution("spend", dist="normal", mean=120, std=30)
|
|
90
|
+
|
|
91
|
+
# Rules can depend on any column; declaration order does not matter
|
|
92
|
+
builder.add_rule("is_eligible", rule="age >= 21 and country in ['MX', 'US']", value=1, default=0)
|
|
93
|
+
|
|
94
|
+
# Export as a pandas DataFrame
|
|
95
|
+
df = builder.build()
|
|
96
|
+
|
|
97
|
+
# Or export directly as NumPy (X, y) arrays for scikit-learn / PyTorch / TensorFlow
|
|
98
|
+
X, y = builder.build_numpy(target="is_eligible")
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Dependencies in string rules and expressions are detected automatically. If you use a callable, declare its inputs with `depends_on=["age"]`. Circular dependencies raise `CircularDependencyError`.
|
|
102
|
+
|
|
103
|
+
### 2. Corrupt the Data and Get a Ground-Truth Report
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
import vecgen as vg
|
|
107
|
+
|
|
108
|
+
dirty, report = vg.inject_outliers(
|
|
109
|
+
df, cols=["spend"], rate=0.05, magnitude=5, seed=42, return_report=True
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
report.summary() # counts per corruption kind and column
|
|
113
|
+
report.to_frame() # row_position, index_label, column, kind, original_value, new_value
|
|
114
|
+
|
|
115
|
+
# Compare against whatever your pipeline flagged
|
|
116
|
+
flagged = my_outlier_detector(dirty) # boolean row mask or row positions
|
|
117
|
+
result = report.evaluate(flagged, kind="outlier")
|
|
118
|
+
print(result.recall, result.precision, result.missed)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Reports can be combined with `+`, so you can inject nulls, duplicates, and outliers in sequence and keep a single manifest. Without `return_report=True` the injectors return just the corrupted data, so they still work inside `df.pipe(...)`.
|
|
122
|
+
|
|
123
|
+
### 3. Save and Reload a Builder
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
builder.to_json("orders_v1.json")
|
|
127
|
+
same_builder = DatasetBuilder.from_json("orders_v1.json")
|
|
128
|
+
assert same_builder.build().equals(df)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Only JSON-representable definitions can be exported: string rules, string expressions, and scalar parameters. Callables and boolean masks raise a `SchemaError` that names the offending column. Loaded rules are evaluated as pandas expressions, so treat JSON files from untrusted sources the way you would treat any config that contains code.
|
|
132
|
+
|
|
133
|
+
### 4. Augment an Existing DataFrame or NumPy Array
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
import numpy as np
|
|
137
|
+
import pandas as pd
|
|
138
|
+
import vecgen as vg
|
|
139
|
+
|
|
140
|
+
df = pd.DataFrame({
|
|
141
|
+
"age": [17, 25, 68, 42],
|
|
142
|
+
"spend": [20.0, 150.0, 300.0, 85.0],
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
df = (
|
|
146
|
+
df.pipe(vg.set_values, col="tier", rule="spend >= 100", value="premium", default="standard")
|
|
147
|
+
.pipe(vg.set_values, col="discount", rule=lambda d: d["age"] >= 65, value=0.20, default=0.0)
|
|
148
|
+
.pipe(vg.inject_nulls, cols=["spend"], rate=0.25, seed=42)
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
# Pure 2D NumPy array (returns a copy of the same shape)
|
|
152
|
+
arr = np.array([[17, 20.0], [68, 300.0]])
|
|
153
|
+
arr_updated = vg.set_values(arr, col=1, rule=lambda x: x[:, 0] >= 65, value=0.0)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### 5. Use the Pandas `.gen` Accessor
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
import pandas as pd
|
|
160
|
+
import vecgen # Registers the .gen accessor on DataFrames and Series
|
|
161
|
+
|
|
162
|
+
df = pd.DataFrame({"score": [45, 82, 91, 60]})
|
|
163
|
+
df = df.gen.apply_rule(col="passed", rule=df["score"] >= 70, value=True, default=False)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
## What vecgen is (and is not)
|
|
167
|
+
|
|
168
|
+
`vecgen` preserves the distributions, conditions, and dependencies that you declare. It does not learn them from real data and it does not make privacy guarantees. If you need statistical cloning of real datasets, look at tools such as SDV.
|
|
169
|
+
|
|
170
|
+
## Project Documentation
|
|
171
|
+
|
|
172
|
+
* [Project Vision & Requirements (FR-1 – FR-11, NFR-1 – NFR-7)](docs/project_vision.md)
|
|
173
|
+
* [Repository & Architecture Structure](docs/project_structure.txt)
|
|
174
|
+
|
|
175
|
+
## License
|
|
176
|
+
|
|
177
|
+
Distributed under the MIT License. See `LICENSE` for more information.
|
vecgen-0.3.0/README.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# vecgen
|
|
2
|
+
|
|
3
|
+
**Declarative, reproducible synthetic datasets with dependent columns, plus data corruption that comes with a ground-truth report.**
|
|
4
|
+
|
|
5
|
+
`vecgen` (short for **Vectorized Generator**) lets you describe a dataset as rules, distributions, and dependencies between columns, generate it deterministically with a seed, and then break it on purpose while recording exactly what was broken. You can also inject rule-driven values and edge cases into existing `pandas` DataFrames, Series, and `numpy` arrays.
|
|
6
|
+
|
|
7
|
+
All outputs are native `pandas` and `numpy` structures, making `vecgen` immediately compatible with **scikit-learn**, **PyTorch**, and **TensorFlow** without extra dependencies.
|
|
8
|
+
|
|
9
|
+
## Key Features
|
|
10
|
+
|
|
11
|
+
* **Conditional & Dependent Columns:** Define a column differently per condition (`when="country == 'MX'"`), or make distribution parameters depend on other columns (`mean="age * 800"`). Columns are resolved in dependency order, so you can declare them in any order.
|
|
12
|
+
* **Corruption with a Ground-Truth Report:** `inject_nulls`, `inject_duplicates`, and `inject_outliers` can return a `CorruptionReport` listing every row, column, and value they changed. Use it to check that your pipeline or validation rules caught what they should have.
|
|
13
|
+
* **Serializable Builders:** Save a `DatasetBuilder` definition to JSON and reload it later. The same JSON plus the same seed gives the same dataset.
|
|
14
|
+
* **Pandas & NumPy Polymorphism:** Accepts `pd.DataFrame`, `pd.Series`, and 1D/2D `np.ndarray` inputs and returns the exact same type, shape, and preserved index/column metadata.
|
|
15
|
+
* **Flexible Rule Engine:** Define conditional logic using boolean masks, Python callables (`lambda df: ...`), or pandas query strings (`"age >= 18 and country == 'MX'"`).
|
|
16
|
+
* **ML-Ready Dataset Builder:** Generate synthetic DataFrames via `.build()` or export pure NumPy `(X, y)` feature/target arrays directly via `.build_numpy(target=...)`.
|
|
17
|
+
* **Vectorized & Deterministic:** Built purely on NumPy and pandas vectorized operations, non-destructive by default (`inplace=False`), and fully reproducible via `seed`.
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install vecgen
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
For local development:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
git clone https://github.com/pchaher03/vecgen.git
|
|
29
|
+
cd vecgen
|
|
30
|
+
pip install -e ".[dev]"
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Quickstart
|
|
34
|
+
|
|
35
|
+
### 1. Generate a Dataset with Conditional and Dependent Columns
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from vecgen import DatasetBuilder
|
|
39
|
+
|
|
40
|
+
builder = DatasetBuilder(rows=10_000, seed=42)
|
|
41
|
+
|
|
42
|
+
builder.add_distribution("age", dist="normal", mean=35, std=10, clip=(18, 90), dtype="int64")
|
|
43
|
+
builder.add_choice("country", choices=["MX", "US", "CA"], weights=[0.5, 0.3, 0.2])
|
|
44
|
+
|
|
45
|
+
# Parameters can be expressions of other columns
|
|
46
|
+
builder.add_distribution("income", dist="normal", mean="age * 800", std=6_000, clip=(0, None))
|
|
47
|
+
|
|
48
|
+
# Same column, different behavior per condition (first match wins; no `when` = fallback)
|
|
49
|
+
builder.add_distribution("spend", dist="lognormal", mean=4.0, sigma=0.5, when="country == 'MX'")
|
|
50
|
+
builder.add_distribution("spend", dist="normal", mean=150, std=40, when="country == 'US'")
|
|
51
|
+
builder.add_distribution("spend", dist="normal", mean=120, std=30)
|
|
52
|
+
|
|
53
|
+
# Rules can depend on any column; declaration order does not matter
|
|
54
|
+
builder.add_rule("is_eligible", rule="age >= 21 and country in ['MX', 'US']", value=1, default=0)
|
|
55
|
+
|
|
56
|
+
# Export as a pandas DataFrame
|
|
57
|
+
df = builder.build()
|
|
58
|
+
|
|
59
|
+
# Or export directly as NumPy (X, y) arrays for scikit-learn / PyTorch / TensorFlow
|
|
60
|
+
X, y = builder.build_numpy(target="is_eligible")
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Dependencies in string rules and expressions are detected automatically. If you use a callable, declare its inputs with `depends_on=["age"]`. Circular dependencies raise `CircularDependencyError`.
|
|
64
|
+
|
|
65
|
+
### 2. Corrupt the Data and Get a Ground-Truth Report
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
import vecgen as vg
|
|
69
|
+
|
|
70
|
+
dirty, report = vg.inject_outliers(
|
|
71
|
+
df, cols=["spend"], rate=0.05, magnitude=5, seed=42, return_report=True
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
report.summary() # counts per corruption kind and column
|
|
75
|
+
report.to_frame() # row_position, index_label, column, kind, original_value, new_value
|
|
76
|
+
|
|
77
|
+
# Compare against whatever your pipeline flagged
|
|
78
|
+
flagged = my_outlier_detector(dirty) # boolean row mask or row positions
|
|
79
|
+
result = report.evaluate(flagged, kind="outlier")
|
|
80
|
+
print(result.recall, result.precision, result.missed)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Reports can be combined with `+`, so you can inject nulls, duplicates, and outliers in sequence and keep a single manifest. Without `return_report=True` the injectors return just the corrupted data, so they still work inside `df.pipe(...)`.
|
|
84
|
+
|
|
85
|
+
### 3. Save and Reload a Builder
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
builder.to_json("orders_v1.json")
|
|
89
|
+
same_builder = DatasetBuilder.from_json("orders_v1.json")
|
|
90
|
+
assert same_builder.build().equals(df)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Only JSON-representable definitions can be exported: string rules, string expressions, and scalar parameters. Callables and boolean masks raise a `SchemaError` that names the offending column. Loaded rules are evaluated as pandas expressions, so treat JSON files from untrusted sources the way you would treat any config that contains code.
|
|
94
|
+
|
|
95
|
+
### 4. Augment an Existing DataFrame or NumPy Array
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import numpy as np
|
|
99
|
+
import pandas as pd
|
|
100
|
+
import vecgen as vg
|
|
101
|
+
|
|
102
|
+
df = pd.DataFrame({
|
|
103
|
+
"age": [17, 25, 68, 42],
|
|
104
|
+
"spend": [20.0, 150.0, 300.0, 85.0],
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
df = (
|
|
108
|
+
df.pipe(vg.set_values, col="tier", rule="spend >= 100", value="premium", default="standard")
|
|
109
|
+
.pipe(vg.set_values, col="discount", rule=lambda d: d["age"] >= 65, value=0.20, default=0.0)
|
|
110
|
+
.pipe(vg.inject_nulls, cols=["spend"], rate=0.25, seed=42)
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
# Pure 2D NumPy array (returns a copy of the same shape)
|
|
114
|
+
arr = np.array([[17, 20.0], [68, 300.0]])
|
|
115
|
+
arr_updated = vg.set_values(arr, col=1, rule=lambda x: x[:, 0] >= 65, value=0.0)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### 5. Use the Pandas `.gen` Accessor
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
import pandas as pd
|
|
122
|
+
import vecgen # Registers the .gen accessor on DataFrames and Series
|
|
123
|
+
|
|
124
|
+
df = pd.DataFrame({"score": [45, 82, 91, 60]})
|
|
125
|
+
df = df.gen.apply_rule(col="passed", rule=df["score"] >= 70, value=True, default=False)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## What vecgen is (and is not)
|
|
129
|
+
|
|
130
|
+
`vecgen` preserves the distributions, conditions, and dependencies that you declare. It does not learn them from real data and it does not make privacy guarantees. If you need statistical cloning of real datasets, look at tools such as SDV.
|
|
131
|
+
|
|
132
|
+
## Project Documentation
|
|
133
|
+
|
|
134
|
+
* [Project Vision & Requirements (FR-1 – FR-11, NFR-1 – NFR-7)](docs/project_vision.md)
|
|
135
|
+
* [Repository & Architecture Structure](docs/project_structure.txt)
|
|
136
|
+
|
|
137
|
+
## License
|
|
138
|
+
|
|
139
|
+
Distributed under the MIT License. See `LICENSE` for more information.
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# `vecgen` API Guide
|
|
2
|
+
|
|
3
|
+
`vecgen` provides vectorized primitives for rule-based data transformation, declarative synthetic dataset generation with column dependencies, controlled data corruption with ground-truth manifests, and JSON builder serialization.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Polymorphic Transformations (`set_values` & `case_when`)
|
|
8
|
+
|
|
9
|
+
All core transformation functions accept `pd.DataFrame`, `pd.Series`, and 1D/2D `np.ndarray` objects, returning the exact same container type, shape, and index/column metadata. Inputs are never mutated unless `inplace=True` is passed.
|
|
10
|
+
|
|
11
|
+
### Rule Formats
|
|
12
|
+
Rules can be expressed in three interchangeable formats:
|
|
13
|
+
1. **Boolean Masks:** A 1D `np.ndarray` or `pd.Series` of booleans matching the input row count.
|
|
14
|
+
2. **Callables:** `lambda data: ...` receiving the input container and returning a 1D boolean mask.
|
|
15
|
+
3. **Query Strings:** Pandas expressions such as `"age >= 21 and country in ['MX', 'US']"` (supported on `pd.DataFrame` or 2D `np.ndarray` when `columns=[...]` is provided).
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
import numpy as np
|
|
19
|
+
import pandas as pd
|
|
20
|
+
import vecgen as vg
|
|
21
|
+
|
|
22
|
+
df = pd.DataFrame({
|
|
23
|
+
"age": [17, 25, 68, 42],
|
|
24
|
+
"spend": [20.0, 150.0, 300.0, 85.0],
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
# Single condition (if / else)
|
|
28
|
+
df = vg.set_values(df, col="tier", rule="spend >= 100", value="premium", default="standard")
|
|
29
|
+
|
|
30
|
+
# Multi-condition ordered priority (first matching condition wins)
|
|
31
|
+
df = vg.case_when(
|
|
32
|
+
df,
|
|
33
|
+
col="segment",
|
|
34
|
+
cases=[
|
|
35
|
+
("age >= 65", "senior"),
|
|
36
|
+
("spend >= 150", "vip"),
|
|
37
|
+
],
|
|
38
|
+
default="regular",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# 2D NumPy array with integer column index
|
|
42
|
+
arr = np.array([[17.0, 20.0], [68.0, 300.0]])
|
|
43
|
+
updated_arr = vg.set_values(arr, col=1, rule=lambda x: x[:, 0] >= 65, value=0.0)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 2. Declarative Dataset Generation (`DatasetBuilder`)
|
|
49
|
+
|
|
50
|
+
`DatasetBuilder` generates synthetic `pd.DataFrame` tables or NumPy `(X, y)` arrays from statistical distributions, weighted categorical choices, and conditional rules.
|
|
51
|
+
|
|
52
|
+
### Conditional Branches & Dependent Columns
|
|
53
|
+
|
|
54
|
+
- **Ordered Branches (`when`):** Registering multiple definitions for the same column creates ordered, first-match-wins branches. A definition without `when` acts as the fallback. If any rows remain unmatched and no fallback is defined, `.build()` raises `SchemaError`.
|
|
55
|
+
- **Expression Parameters:** Distribution parameters (`mean`, `std`, `low`, `high`, `scale`, `sigma`) accept either numeric scalars or string expressions referencing other columns (e.g., `mean="age * 800"`).
|
|
56
|
+
- **Automatic Topological Sorting:** Dependencies in string rules and parameter expressions are extracted automatically and resolved in dependency order regardless of declaration order. If you pass a Python callable, declare its upstream columns via `depends_on=[...]`. Cycles raise `CircularDependencyError`.
|
|
57
|
+
- **Per-Column Seed Isolation:** Each column's random stream is derived deterministically from `(seed, column_name)`, so adding or reordering unrelated columns never alters existing columns.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from vecgen import DatasetBuilder
|
|
61
|
+
|
|
62
|
+
builder = DatasetBuilder(rows=10_000, seed=42)
|
|
63
|
+
|
|
64
|
+
# Dependents can be declared before their upstream columns
|
|
65
|
+
builder.add_rule(
|
|
66
|
+
"is_eligible",
|
|
67
|
+
rule="age >= 21 and country in ['MX', 'US']",
|
|
68
|
+
value=1,
|
|
69
|
+
default=0,
|
|
70
|
+
)
|
|
71
|
+
builder.add_distribution(
|
|
72
|
+
"income",
|
|
73
|
+
dist="normal",
|
|
74
|
+
mean="age * 800",
|
|
75
|
+
std=250.0,
|
|
76
|
+
clip=(0.0, None),
|
|
77
|
+
)
|
|
78
|
+
builder.add_distribution("spend", dist="uniform", low=10.0, high=50.0, when="country == 'MX'")
|
|
79
|
+
builder.add_distribution("spend", dist="uniform", low=50.0, high=200.0) # fallback branch
|
|
80
|
+
builder.add_choice("country", choices=["MX", "US", "CA"], weights=[0.5, 0.3, 0.2])
|
|
81
|
+
builder.add_distribution("age", dist="randint", low=18, high=75)
|
|
82
|
+
|
|
83
|
+
# Export as pandas DataFrame (columns returned in declaration order)
|
|
84
|
+
df = builder.build()
|
|
85
|
+
|
|
86
|
+
# Or export as NumPy (X, y) arrays for scikit-learn / PyTorch / TensorFlow
|
|
87
|
+
X, y = builder.build_numpy(target="is_eligible")
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 3. Data Corruption & Ground-Truth Manifests (`CorruptionReport`)
|
|
93
|
+
|
|
94
|
+
`inject_nulls`, `inject_outliers`, and `inject_duplicates` accept `pd.DataFrame`, `pd.Series`, and 1D/2D `np.ndarray` inputs.
|
|
95
|
+
|
|
96
|
+
- By default (`return_report=False`), they return only the corrupted container so they compose directly inside `df.pipe(...)`.
|
|
97
|
+
- When `return_report=True`, they return `(corrupted_data, report)` where `report` is a `CorruptionReport` recording every modified cell or duplicated row (`row_position`, `index_label`, `column`, `kind`, `original_value`, `new_value`, and `source_row` for duplicates).
|
|
98
|
+
- Duplicated rows are appended at the end of the dataset so earlier row positions remain valid.
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
import vecgen as vg
|
|
102
|
+
|
|
103
|
+
dirty, r_nulls = vg.inject_nulls(df, cols=["spend"], rate=0.05, seed=42, return_report=True)
|
|
104
|
+
dirty, r_outliers = vg.inject_outliers(
|
|
105
|
+
dirty, cols=["spend"], rate=0.02, magnitude=5.0, seed=43, return_report=True
|
|
106
|
+
)
|
|
107
|
+
dirty, r_dups = vg.inject_duplicates(dirty, rate=0.01, seed=44, return_report=True)
|
|
108
|
+
|
|
109
|
+
# Merge manifests sequentially using +
|
|
110
|
+
manifest = r_nulls + r_outliers + r_dups
|
|
111
|
+
|
|
112
|
+
print(manifest.summary())
|
|
113
|
+
manifest_df = manifest.to_frame()
|
|
114
|
+
manifest_json = manifest.to_json()
|
|
115
|
+
|
|
116
|
+
# Benchmark a detector or validation rule against ground truth
|
|
117
|
+
flagged_rows = dirty["spend"] > 1_000.0
|
|
118
|
+
eval_result = manifest.evaluate(flagged_rows, kind="outlier")
|
|
119
|
+
print(f"Precision: {eval_result.precision:.2f}, Recall: {eval_result.recall:.2f}")
|
|
120
|
+
print("Missed row positions:", eval_result.missed)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## 4. Pandas `.gen` Accessor
|
|
126
|
+
|
|
127
|
+
Importing `vecgen` automatically registers the `.gen` accessor on `pd.DataFrame` and `pd.Series`:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
import pandas as pd
|
|
131
|
+
import vecgen # registers .gen accessor
|
|
132
|
+
|
|
133
|
+
df = pd.DataFrame({"score": [45, 82, 91, 60], "spend": [10.0, 200.0, 350.0, 40.0]})
|
|
134
|
+
|
|
135
|
+
df = (
|
|
136
|
+
df.gen.apply_rule(col="passed", rule="score >= 70", value=True, default=False)
|
|
137
|
+
.gen.case_when(col="tier", cases=[("spend >= 300", "gold")], default="base")
|
|
138
|
+
.gen.inject_nulls(cols=["spend"], rate=0.25, seed=7)
|
|
139
|
+
)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## 5. Builder JSON Serialization & Security Notice
|
|
145
|
+
|
|
146
|
+
`DatasetBuilder` definitions can be serialized to dictionaries or JSON strings/files and reloaded later to reproduce identical datasets from the same seed:
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
from vecgen import DatasetBuilder
|
|
150
|
+
|
|
151
|
+
payload = builder.to_dict()
|
|
152
|
+
builder.to_json("schema_v1.json")
|
|
153
|
+
|
|
154
|
+
reloaded = DatasetBuilder.from_json("schema_v1.json")
|
|
155
|
+
assert reloaded.build().equals(builder.build())
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Serialization Constraints & Untrusted Input Warning
|
|
159
|
+
|
|
160
|
+
- **JSON-Representable Rules Only:** Only string rules (`"age >= 18"`), string parameter expressions (`"age * 800"`), and scalar values can be serialized. Attempting to export a builder containing Python callables or raw boolean masks raises `SchemaError` naming the offending column.
|
|
161
|
+
- **Security Warning:** Reloaded string rules and parameter expressions are evaluated via `pandas.DataFrame.eval()` / `query()`. Treat serialized builder JSON files from untrusted sources the same way you would treat configuration files containing executable code—do not load untrusted JSON schemas without reviewing their rule and expression strings first.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
vecgen/
|
|
2
|
+
├── .github/
|
|
3
|
+
│ └── workflows/
|
|
4
|
+
│ ├── ci.yml # Runs pytest (>=90% cov), ruff, and mypy on push/PR (NFR-5, NFR-6)
|
|
5
|
+
│ └── publish.yml # Builds sdist/wheel and publishes to PyPI on release tags
|
|
6
|
+
├── docs/
|
|
7
|
+
│ ├── project_vision.md # Vision, differentiators, scope, FR-1..FR-11, and NFR-1..NFR-7
|
|
8
|
+
│ ├── project_structure.txt # Repository layout and module responsibility map
|
|
9
|
+
│ └── api_guide.md # Usage patterns for rules, DatasetBuilder (conditional/dependent columns), corruption reports, JSON export, and .gen accessor
|
|
10
|
+
├── src/
|
|
11
|
+
│ └── vecgen/
|
|
12
|
+
│ ├── __init__.py # Public API exports (__all__), __version__, and .gen accessor registration
|
|
13
|
+
│ ├── py.typed # PEP 561 marker enabling downstream IDE/mypy type checking (NFR-5)
|
|
14
|
+
│ ├── exceptions.py # Custom exceptions: RuleEvaluationError, SchemaError, CircularDependencyError(SchemaError) (NFR-4)
|
|
15
|
+
│ ├── types.py # Shared type aliases (DataType, RuleType, ValueType, SeedType) & @overloads incl. return_report (NFR-5)
|
|
16
|
+
│ ├── _compat.py # Internal adapters normalizing DataFrame, Series, and 1D/2D ndarray I/O (FR-1, FR-8, NFR-4)
|
|
17
|
+
│ ├── rules.py # Vectorized rule parser: boolean masks, callables, and query strings; dependency extraction from strings (FR-3, FR-9, NFR-1)
|
|
18
|
+
│ ├── engine.py # Core vectorized assignment: set_values, case_when with copy-by-default (FR-1, FR-4, FR-8)
|
|
19
|
+
│ ├── distributions.py # Seeded NumPy sampling: uniform, normal, lognormal, exponential, randint, choice; parameters may be scalars or evaluated expressions (FR-5, FR-9, NFR-2)
|
|
20
|
+
│ ├── _graph.py # Column dependency graph: topological ordering, cycle detection, depends_on handling (FR-9, NFR-4)
|
|
21
|
+
│ ├── noise.py # Anomaly injectors: inject_nulls, inject_duplicates, inject_outliers, with optional return_report (FR-6, FR-10, NFR-2)
|
|
22
|
+
│ ├── report.py # CorruptionReport: manifest of changes, summary(), to_frame(), to_json(), merge via +, evaluate() precision/recall (FR-10)
|
|
23
|
+
│ ├── builder.py # DatasetBuilder: ordered branches with `when`, fallback handling, per-column seeded streams, .build() -> DataFrame, .build_numpy(target=...) -> ndarray/(X, y) (FR-2, FR-9, NFR-2)
|
|
24
|
+
│ ├── serialization.py # Builder <-> dict/JSON conversion using stdlib json only; rejects callables and masks (FR-11, NFR-3)
|
|
25
|
+
│ └── accessor.py # @register_dataframe_accessor("gen") & @register_series_accessor("gen") (FR-1, FR-7)
|
|
26
|
+
├── tests/
|
|
27
|
+
│ ├── conftest.py # Shared pytest fixtures (DataFrames, Series, 1D/2D ndarrays, seeded RNGs)
|
|
28
|
+
│ ├── test_compat.py # Tests for same-type-out polymorphism, dtype preservation, and immutability (FR-1, FR-8, NFR-4)
|
|
29
|
+
│ ├── test_rules.py # Unit tests for mask, callable, and query string rule evaluation and dependency extraction (FR-3, FR-9)
|
|
30
|
+
│ ├── test_engine.py # Tests for set_values and multi-condition case_when across pandas & numpy (FR-4)
|
|
31
|
+
│ ├── test_distributions.py # Tests for statistical distributions, categorical weights, expression parameters, and seed determinism (FR-5, FR-9, NFR-2)
|
|
32
|
+
│ ├── test_graph.py # Tests for dependency ordering, declaration-order independence, and circular dependency errors (FR-9)
|
|
33
|
+
│ ├── test_noise.py # Tests for null, duplicate, and outlier injection rates and dtype handling (FR-6, NFR-4)
|
|
34
|
+
│ ├── test_report.py # Tests for manifest accuracy, report merging, and evaluate() metrics (FR-10)
|
|
35
|
+
│ ├── test_builder.py # End-to-end tests for DatasetBuilder .build() / .build_numpy(), branches, fallbacks, and unmatched-row errors (FR-2, FR-9)
|
|
36
|
+
│ ├── test_serialization.py # Tests for JSON round-trip identical output, rejected callables/masks, and seed preservation (FR-11)
|
|
37
|
+
│ ├── test_accessor.py # Tests for df.gen.* and s.gen.* pandas accessor methods (FR-7)
|
|
38
|
+
│ └── test_performance.py # Benchmarks: 5 rules on 1M rows <500ms (NFR-1); conditional/dependent builder and corruption-with-report at 1M rows
|
|
39
|
+
├── .gitignore # Ignores __pycache__/, dist/, build/, .pytest_cache/, .mypy_cache/, .venv/
|
|
40
|
+
├── LICENSE # MIT License
|
|
41
|
+
├── pyproject.toml # Hatchling build config, core deps (pandas>=2.0, numpy>=1.24), ruff/mypy/pytest settings
|
|
42
|
+
└── README.md # End-user landing page, installation, and quickstart
|