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/noise.py ADDED
@@ -0,0 +1,534 @@
1
+ """Anomaly and noise injectors with optional ground-truth CorruptionReport (FR-6, FR-10)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from typing import Any, Literal, overload
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ from vecgen._compat import (
12
+ NormalizedData,
13
+ make_nullable_if_needed,
14
+ normalize_input,
15
+ resolve_column_name,
16
+ restore_output,
17
+ )
18
+ from vecgen.distributions import resolve_rng
19
+ from vecgen.exceptions import SchemaError
20
+ from vecgen.report import CorruptionRecord, CorruptionReport
21
+ from vecgen.types import ColRef, DataType, NDArrayAny, SeedType
22
+
23
+
24
+ def _validate_rate(rate: float) -> None:
25
+ if not (0.0 <= rate <= 1.0):
26
+ raise SchemaError(f"`rate` must be between 0.0 and 1.0, got {rate}.")
27
+
28
+
29
+ def _resolve_target_columns(norm: NormalizedData, cols: Sequence[ColRef] | None) -> list[str]:
30
+ if norm.kind in ("series", "ndarray_1d"):
31
+ if cols is not None:
32
+ return [resolve_column_name(norm, c) for c in cols]
33
+ return [norm.col_names[0]]
34
+
35
+ if cols is None:
36
+ return list(norm.frame.columns)
37
+ return [resolve_column_name(norm, c) for c in cols]
38
+
39
+
40
+ def _numpy_dtype_of(dtype: Any) -> np.dtype[Any]:
41
+ """Return the NumPy dtype backing a NumPy or pandas nullable numeric dtype."""
42
+ np_dtype = getattr(dtype, "numpy_dtype", dtype)
43
+ resolved: np.dtype[Any] = np.dtype(np_dtype)
44
+ return resolved
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # inject_nulls
49
+ # ---------------------------------------------------------------------------
50
+
51
+
52
+ @overload
53
+ def inject_nulls(
54
+ data: pd.DataFrame,
55
+ *,
56
+ cols: Sequence[ColRef] | None = ...,
57
+ rate: float = ...,
58
+ seed: SeedType = ...,
59
+ inplace: bool = ...,
60
+ return_report: Literal[False] = ...,
61
+ ) -> pd.DataFrame: ...
62
+
63
+
64
+ @overload
65
+ def inject_nulls(
66
+ data: pd.DataFrame,
67
+ *,
68
+ cols: Sequence[ColRef] | None = ...,
69
+ rate: float = ...,
70
+ seed: SeedType = ...,
71
+ inplace: bool = ...,
72
+ return_report: Literal[True],
73
+ ) -> tuple[pd.DataFrame, CorruptionReport]: ...
74
+
75
+
76
+ @overload
77
+ def inject_nulls(
78
+ data: pd.Series,
79
+ *,
80
+ cols: Sequence[ColRef] | None = ...,
81
+ rate: float = ...,
82
+ seed: SeedType = ...,
83
+ inplace: bool = ...,
84
+ return_report: Literal[False] = ...,
85
+ ) -> pd.Series: ...
86
+
87
+
88
+ @overload
89
+ def inject_nulls(
90
+ data: pd.Series,
91
+ *,
92
+ cols: Sequence[ColRef] | None = ...,
93
+ rate: float = ...,
94
+ seed: SeedType = ...,
95
+ inplace: bool = ...,
96
+ return_report: Literal[True],
97
+ ) -> tuple[pd.Series, CorruptionReport]: ...
98
+
99
+
100
+ @overload
101
+ def inject_nulls(
102
+ data: NDArrayAny,
103
+ *,
104
+ cols: Sequence[ColRef] | None = ...,
105
+ rate: float = ...,
106
+ seed: SeedType = ...,
107
+ inplace: bool = ...,
108
+ return_report: Literal[False] = ...,
109
+ ) -> NDArrayAny: ...
110
+
111
+
112
+ @overload
113
+ def inject_nulls(
114
+ data: NDArrayAny,
115
+ *,
116
+ cols: Sequence[ColRef] | None = ...,
117
+ rate: float = ...,
118
+ seed: SeedType = ...,
119
+ inplace: bool = ...,
120
+ return_report: Literal[True],
121
+ ) -> tuple[NDArrayAny, CorruptionReport]: ...
122
+
123
+
124
+ def inject_nulls(
125
+ data: DataType,
126
+ *,
127
+ cols: Sequence[ColRef] | None = None,
128
+ rate: float = 0.05,
129
+ seed: SeedType = None,
130
+ inplace: bool = False,
131
+ return_report: bool = False,
132
+ ) -> DataType | tuple[DataType, CorruptionReport]:
133
+ """Inject missing values (NaN / pd.NA) at ``rate`` into specified columns (FR-6, FR-10)."""
134
+ _validate_rate(rate)
135
+ norm = normalize_input(data, copy=not inplace)
136
+ target_cols = _resolve_target_columns(norm, cols)
137
+ n_rows = len(norm.frame)
138
+ rng = resolve_rng(seed)
139
+
140
+ records: list[CorruptionRecord] = []
141
+ index_vals = norm.frame.index.to_numpy()
142
+ updated_cols: dict[Any, pd.Series] = {}
143
+
144
+ for col in target_cols:
145
+ if col not in norm.frame.columns:
146
+ raise SchemaError(f"Column {col!r} not found.")
147
+ if n_rows == 0 or rate == 0.0:
148
+ continue
149
+
150
+ n_corrupt = round(n_rows * rate)
151
+ if n_corrupt == 0:
152
+ continue
153
+
154
+ chosen_rows = np.sort(rng.choice(n_rows, size=n_corrupt, replace=False))
155
+ series = norm.frame[col]
156
+
157
+ # Promote integer/bool Series to nullable pandas dtypes so NaN/NA is preserved (NFR-4)
158
+ if norm.kind in ("dataframe", "series"):
159
+ series = make_nullable_if_needed(series)
160
+ elif not pd.api.types.is_float_dtype(series.dtype) and not pd.api.types.is_object_dtype(
161
+ series.dtype
162
+ ):
163
+ series = series.astype(np.float64)
164
+
165
+ is_ext = isinstance(series.dtype, pd.api.extensions.ExtensionDtype)
166
+ null_sentinel: Any = pd.NA if is_ext else np.nan
167
+
168
+ if return_report:
169
+ orig_vals = series.iloc[chosen_rows].astype(object).to_numpy()
170
+ for row_pos, orig in zip(chosen_rows, orig_vals):
171
+ records.append(
172
+ CorruptionRecord(
173
+ row_position=int(row_pos),
174
+ index_label=index_vals[row_pos],
175
+ column=col,
176
+ kind="null",
177
+ original_value=orig,
178
+ new_value=null_sentinel,
179
+ )
180
+ )
181
+
182
+ if is_ext:
183
+ ext_arr = series.array.copy()
184
+ ext_arr[chosen_rows] = pd.NA
185
+ series = pd.Series(ext_arr, index=series.index, name=series.name, dtype=series.dtype)
186
+ else:
187
+ np_arr = series.to_numpy(copy=True)
188
+ np_arr[chosen_rows] = np.nan
189
+ series = pd.Series(np_arr, index=series.index, name=series.name, dtype=series.dtype)
190
+
191
+ updated_cols[col] = series
192
+
193
+ if updated_cols:
194
+ new_frame = pd.DataFrame(
195
+ {
196
+ c: updated_cols[c] if c in updated_cols else norm.frame[c]
197
+ for c in norm.frame.columns
198
+ },
199
+ index=norm.frame.index,
200
+ )
201
+ norm = NormalizedData(
202
+ kind=norm.kind,
203
+ frame=new_frame,
204
+ original=norm.original,
205
+ series_name=norm.series_name,
206
+ col_names=norm.col_names,
207
+ )
208
+
209
+ out = _finalize_output(data, norm, inplace=inplace)
210
+ if return_report:
211
+ report = CorruptionReport(
212
+ records=records,
213
+ n_rows=n_rows,
214
+ columns=tuple(norm.frame.columns.astype(str)),
215
+ )
216
+ return out, report
217
+ return out
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # inject_outliers
222
+ # ---------------------------------------------------------------------------
223
+
224
+
225
+ @overload
226
+ def inject_outliers(
227
+ data: pd.DataFrame,
228
+ *,
229
+ cols: Sequence[ColRef] | None = ...,
230
+ rate: float = ...,
231
+ magnitude: float = ...,
232
+ seed: SeedType = ...,
233
+ inplace: bool = ...,
234
+ return_report: Literal[False] = ...,
235
+ ) -> pd.DataFrame: ...
236
+
237
+
238
+ @overload
239
+ def inject_outliers(
240
+ data: pd.DataFrame,
241
+ *,
242
+ cols: Sequence[ColRef] | None = ...,
243
+ rate: float = ...,
244
+ magnitude: float = ...,
245
+ seed: SeedType = ...,
246
+ inplace: bool = ...,
247
+ return_report: Literal[True],
248
+ ) -> tuple[pd.DataFrame, CorruptionReport]: ...
249
+
250
+
251
+ @overload
252
+ def inject_outliers(
253
+ data: pd.Series,
254
+ *,
255
+ cols: Sequence[ColRef] | None = ...,
256
+ rate: float = ...,
257
+ magnitude: float = ...,
258
+ seed: SeedType = ...,
259
+ inplace: bool = ...,
260
+ return_report: Literal[False] = ...,
261
+ ) -> pd.Series: ...
262
+
263
+
264
+ @overload
265
+ def inject_outliers(
266
+ data: pd.Series,
267
+ *,
268
+ cols: Sequence[ColRef] | None = ...,
269
+ rate: float = ...,
270
+ magnitude: float = ...,
271
+ seed: SeedType = ...,
272
+ inplace: bool = ...,
273
+ return_report: Literal[True],
274
+ ) -> tuple[pd.Series, CorruptionReport]: ...
275
+
276
+
277
+ @overload
278
+ def inject_outliers(
279
+ data: NDArrayAny,
280
+ *,
281
+ cols: Sequence[ColRef] | None = ...,
282
+ rate: float = ...,
283
+ magnitude: float = ...,
284
+ seed: SeedType = ...,
285
+ inplace: bool = ...,
286
+ return_report: Literal[False] = ...,
287
+ ) -> NDArrayAny: ...
288
+
289
+
290
+ @overload
291
+ def inject_outliers(
292
+ data: NDArrayAny,
293
+ *,
294
+ cols: Sequence[ColRef] | None = ...,
295
+ rate: float = ...,
296
+ magnitude: float = ...,
297
+ seed: SeedType = ...,
298
+ inplace: bool = ...,
299
+ return_report: Literal[True],
300
+ ) -> tuple[NDArrayAny, CorruptionReport]: ...
301
+
302
+
303
+ def inject_outliers(
304
+ data: DataType,
305
+ *,
306
+ cols: Sequence[ColRef] | None = None,
307
+ rate: float = 0.05,
308
+ magnitude: float = 5.0,
309
+ seed: SeedType = None,
310
+ inplace: bool = False,
311
+ return_report: bool = False,
312
+ ) -> DataType | tuple[DataType, CorruptionReport]:
313
+ """Inject numeric outliers shifted by ``±magnitude * std`` into numeric columns."""
314
+ _validate_rate(rate)
315
+ if magnitude <= 0:
316
+ raise SchemaError(f"`magnitude` must be positive, got {magnitude}.")
317
+
318
+ norm = normalize_input(data, copy=not inplace)
319
+ if cols is None:
320
+ target_cols = [
321
+ str(c)
322
+ for c in norm.frame.columns
323
+ if pd.api.types.is_numeric_dtype(norm.frame[c].dtype)
324
+ and not pd.api.types.is_bool_dtype(norm.frame[c].dtype)
325
+ ]
326
+ else:
327
+ target_cols = _resolve_target_columns(norm, cols)
328
+
329
+ n_rows = len(norm.frame)
330
+ rng = resolve_rng(seed)
331
+ records: list[CorruptionRecord] = []
332
+ index_vals = norm.frame.index.to_numpy()
333
+
334
+ for col in target_cols:
335
+ if col not in norm.frame.columns:
336
+ raise SchemaError(f"Column {col!r} not found.")
337
+ series = norm.frame[col]
338
+ if not pd.api.types.is_numeric_dtype(series.dtype) or pd.api.types.is_bool_dtype(
339
+ series.dtype
340
+ ):
341
+ raise SchemaError(f"Cannot inject numeric outliers into non-numeric column {col!r}.")
342
+
343
+ if n_rows == 0 or rate == 0.0:
344
+ continue
345
+ n_corrupt = round(n_rows * rate)
346
+ if n_corrupt == 0:
347
+ continue
348
+
349
+ chosen_rows = np.sort(rng.choice(n_rows, size=n_corrupt, replace=False))
350
+ signs = rng.choice(np.array([-1.0, 1.0]), size=n_corrupt)
351
+
352
+ col_vals = series.to_numpy(dtype=np.float64, na_value=np.nan)
353
+ std = float(np.nanstd(col_vals))
354
+ scale = std if std > 0.0 else (float(np.nanmean(np.abs(col_vals))) or 1.0)
355
+ deltas = signs * magnitude * scale
356
+
357
+ orig_slice = series.iloc[chosen_rows].to_numpy()
358
+ new_slice = col_vals[chosen_rows] + deltas
359
+
360
+ target_np_dtype = _numpy_dtype_of(series.dtype)
361
+ if pd.api.types.is_integer_dtype(series.dtype):
362
+ casted_new: NDArrayAny = np.round(new_slice).astype(target_np_dtype)
363
+ else:
364
+ casted_new = new_slice.astype(target_np_dtype)
365
+
366
+ if return_report:
367
+ for row_pos, orig, updated in zip(chosen_rows, orig_slice, casted_new):
368
+ records.append(
369
+ CorruptionRecord(
370
+ row_position=int(row_pos),
371
+ index_label=index_vals[row_pos],
372
+ column=col,
373
+ kind="outlier",
374
+ original_value=orig,
375
+ new_value=updated,
376
+ )
377
+ )
378
+
379
+ series.iloc[chosen_rows] = casted_new
380
+ norm.frame[col] = series
381
+
382
+ out = _finalize_output(data, norm, inplace=inplace)
383
+ if return_report:
384
+ report = CorruptionReport(
385
+ records=records,
386
+ n_rows=n_rows,
387
+ columns=tuple(norm.frame.columns.astype(str)),
388
+ )
389
+ return out, report
390
+ return out
391
+
392
+
393
+ # ---------------------------------------------------------------------------
394
+ # inject_duplicates
395
+ # ---------------------------------------------------------------------------
396
+
397
+
398
+ @overload
399
+ def inject_duplicates(
400
+ data: pd.DataFrame,
401
+ *,
402
+ rate: float = ...,
403
+ seed: SeedType = ...,
404
+ return_report: Literal[False] = ...,
405
+ ) -> pd.DataFrame: ...
406
+
407
+
408
+ @overload
409
+ def inject_duplicates(
410
+ data: pd.DataFrame,
411
+ *,
412
+ rate: float = ...,
413
+ seed: SeedType = ...,
414
+ return_report: Literal[True],
415
+ ) -> tuple[pd.DataFrame, CorruptionReport]: ...
416
+
417
+
418
+ @overload
419
+ def inject_duplicates(
420
+ data: pd.Series,
421
+ *,
422
+ rate: float = ...,
423
+ seed: SeedType = ...,
424
+ return_report: Literal[False] = ...,
425
+ ) -> pd.Series: ...
426
+
427
+
428
+ @overload
429
+ def inject_duplicates(
430
+ data: pd.Series,
431
+ *,
432
+ rate: float = ...,
433
+ seed: SeedType = ...,
434
+ return_report: Literal[True],
435
+ ) -> tuple[pd.Series, CorruptionReport]: ...
436
+
437
+
438
+ @overload
439
+ def inject_duplicates(
440
+ data: NDArrayAny,
441
+ *,
442
+ rate: float = ...,
443
+ seed: SeedType = ...,
444
+ return_report: Literal[False] = ...,
445
+ ) -> NDArrayAny: ...
446
+
447
+
448
+ @overload
449
+ def inject_duplicates(
450
+ data: NDArrayAny,
451
+ *,
452
+ rate: float = ...,
453
+ seed: SeedType = ...,
454
+ return_report: Literal[True],
455
+ ) -> tuple[NDArrayAny, CorruptionReport]: ...
456
+
457
+
458
+ def inject_duplicates(
459
+ data: DataType,
460
+ *,
461
+ rate: float = 0.05,
462
+ seed: SeedType = None,
463
+ return_report: bool = False,
464
+ ) -> DataType | tuple[DataType, CorruptionReport]:
465
+ """Append duplicated rows at the end so earlier row positions remain valid (FR-6, FR-10)."""
466
+ _validate_rate(rate)
467
+ norm = normalize_input(data, copy=True)
468
+ n_rows = len(norm.frame)
469
+ rng = resolve_rng(seed)
470
+
471
+ records: list[CorruptionRecord] = []
472
+ if n_rows > 0 and rate > 0.0:
473
+ n_dups = round(n_rows * rate)
474
+ if n_dups > 0:
475
+ source_positions = rng.choice(n_rows, size=n_dups, replace=True)
476
+ dup_rows = norm.frame.iloc[source_positions].copy()
477
+ combined = pd.concat([norm.frame, dup_rows], axis=0)
478
+
479
+ if return_report:
480
+ orig_index = norm.frame.index.to_numpy()
481
+ for offset, src_pos in enumerate(source_positions):
482
+ out_pos = n_rows + offset
483
+ records.append(
484
+ CorruptionRecord(
485
+ row_position=int(out_pos),
486
+ index_label=orig_index[src_pos],
487
+ column=None,
488
+ kind="duplicate",
489
+ original_value=None,
490
+ new_value=int(src_pos),
491
+ source_row=int(src_pos),
492
+ )
493
+ )
494
+ norm = NormalizedData(
495
+ kind=norm.kind,
496
+ frame=combined,
497
+ original=norm.original,
498
+ series_name=norm.series_name,
499
+ col_names=norm.col_names,
500
+ )
501
+
502
+ out = _restore_with_new_length(norm)
503
+ if return_report:
504
+ report = CorruptionReport(
505
+ records=records,
506
+ n_rows=len(norm.frame),
507
+ columns=tuple(norm.frame.columns.astype(str)),
508
+ )
509
+ return out, report
510
+ return out
511
+
512
+
513
+ def _finalize_output(data: DataType, norm: NormalizedData, *, inplace: bool) -> DataType:
514
+ if inplace:
515
+ if isinstance(data, pd.DataFrame):
516
+ for col in norm.frame.columns:
517
+ data[col] = norm.frame[col]
518
+ return data
519
+ if isinstance(data, pd.Series):
520
+ data.iloc[:] = norm.frame[norm.col_names[0]].to_numpy()
521
+ return data
522
+ if isinstance(data, np.ndarray):
523
+ if data.ndim == 1:
524
+ data[:] = norm.frame[norm.col_names[0]].to_numpy()
525
+ else:
526
+ data[:, :] = norm.frame.to_numpy()
527
+ return data
528
+ return restore_output(norm, norm.frame)
529
+
530
+
531
+ def _restore_with_new_length(norm: NormalizedData) -> DataType:
532
+ if norm.kind == "ndarray_2d":
533
+ return norm.frame.to_numpy()
534
+ return restore_output(norm, norm.frame)
vecgen/py.typed ADDED
File without changes