menddata 0.1.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.
MendData/fixers.py ADDED
@@ -0,0 +1,511 @@
1
+ """Data-cleaning fixer classes for MendData."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+ from .issue import Issue
10
+ from .utils import validate_choice, validate_dataframe
11
+
12
+ __all__ = [
13
+ "BaseFixer",
14
+ "ImputeFixer",
15
+ "DropFixer",
16
+ "ClipFixer",
17
+ ]
18
+
19
+
20
+ def _is_true_numeric_dtype(series: pd.Series) -> bool:
21
+ """Return True if a Series is numeric and not boolean.
22
+
23
+ Args:
24
+ series: Series to inspect.
25
+
26
+ Returns:
27
+ True when the Series has a numeric dtype excluding booleans,
28
+ otherwise False.
29
+ """
30
+ return pd.api.types.is_numeric_dtype(series) and not pd.api.types.is_bool_dtype(
31
+ series
32
+ )
33
+
34
+
35
+ def _validate_issue(issue: Any) -> Issue:
36
+ """Validate that an object is an Issue instance.
37
+
38
+ Args:
39
+ issue: Candidate issue object.
40
+
41
+ Returns:
42
+ The validated Issue instance.
43
+
44
+ Raises:
45
+ TypeError: If issue is not an Issue instance.
46
+ """
47
+ if not isinstance(issue, Issue):
48
+ raise TypeError(
49
+ f"Expected an Issue instance, got {type(issue).__name__}."
50
+ )
51
+ return issue
52
+
53
+
54
+ def _validate_column_present(data: pd.DataFrame, issue: Issue) -> Any:
55
+ """Validate and return the column name for a column-level Issue.
56
+
57
+ Args:
58
+ data: Target DataFrame.
59
+ issue: Issue referencing a column.
60
+
61
+ Returns:
62
+ The validated column label from issue.
63
+
64
+ Raises:
65
+ ValueError: If issue.column is None or missing from data.columns.
66
+ """
67
+ if issue.column is None:
68
+ raise ValueError(
69
+ f"Issue of kind '{issue.kind}' requires a non-None column name."
70
+ )
71
+ if issue.column not in data.columns:
72
+ raise ValueError(
73
+ f"Column '{issue.column}' is not present in the DataFrame."
74
+ )
75
+ return issue.column
76
+
77
+
78
+ class BaseFixer(ABC):
79
+ """Abstract base class for fixers that resolve data quality issues.
80
+
81
+ Attributes:
82
+ HANDLES: Tuple of Issue.kind values that this fixer can resolve.
83
+ """
84
+
85
+ HANDLES: tuple[str, ...] = ()
86
+
87
+ def __init__(self, strategy: str) -> None:
88
+ """Initialize the fixer with a strategy name.
89
+
90
+ Args:
91
+ strategy: Name of the fixing strategy shown in audit logs.
92
+
93
+ Raises:
94
+ TypeError: If strategy is not a string.
95
+ ValueError: If strategy is empty or whitespace-only.
96
+ """
97
+ if not isinstance(strategy, str):
98
+ raise TypeError(
99
+ f"Expected strategy to be a str, got {type(strategy).__name__}."
100
+ )
101
+ if not strategy.strip():
102
+ raise ValueError("Strategy name must not be empty.")
103
+ self._strategy = strategy
104
+
105
+ @property
106
+ def strategy(self) -> str:
107
+ """Return the fixer strategy name.
108
+
109
+ Returns:
110
+ Strategy identifier string.
111
+ """
112
+ return self._strategy
113
+
114
+ def can_fix(self, issue: Issue) -> bool:
115
+ """Check whether this fixer supports the given issue kind.
116
+
117
+ Args:
118
+ issue: Issue instance to inspect.
119
+
120
+ Returns:
121
+ True if issue.kind is in HANDLES, otherwise False.
122
+
123
+ Raises:
124
+ TypeError: If issue is not an Issue instance.
125
+ """
126
+ validated_issue = _validate_issue(issue)
127
+ return validated_issue.kind in self.HANDLES
128
+
129
+ @abstractmethod
130
+ def fix(self, data: pd.DataFrame, issue: Issue) -> pd.DataFrame:
131
+ """Apply the fix for an issue to a copy of the DataFrame.
132
+
133
+ Args:
134
+ data: Input DataFrame to clean without mutating the original.
135
+ issue: Issue describing the problem to resolve.
136
+
137
+ Returns:
138
+ A new DataFrame with the fix applied.
139
+
140
+ Raises:
141
+ TypeError: If data is not a DataFrame or issue is not an Issue.
142
+ ValueError: If the fixer cannot handle the issue or inputs are invalid.
143
+ """
144
+
145
+ @abstractmethod
146
+ def explain(self, issue: Issue) -> str:
147
+ """Return a plain-English present-tense explanation of the fix.
148
+
149
+ Args:
150
+ issue: Issue being addressed.
151
+
152
+ Returns:
153
+ One present-tense sentence describing the action taken.
154
+
155
+ Raises:
156
+ TypeError: If issue is not an Issue instance.
157
+ ValueError: If the fixer cannot handle the issue.
158
+ """
159
+
160
+
161
+ class ImputeFixer(BaseFixer):
162
+ """Fixer that fills missing values in a column using a chosen strategy.
163
+
164
+ Attributes:
165
+ HANDLES: Tuple containing only Issue.MISSING.
166
+ VALID_STRATEGIES: Supported imputation strategies ('mean', 'median', 'mode').
167
+ """
168
+
169
+ HANDLES: tuple[str, ...] = (Issue.MISSING,)
170
+ VALID_STRATEGIES: tuple[str, ...] = ("mean", "median", "mode")
171
+
172
+ def __init__(self, strategy: str = "median") -> None:
173
+ """Initialize ImputeFixer with an imputation strategy.
174
+
175
+ Args:
176
+ strategy: Imputation strategy ('mean', 'median', or 'mode').
177
+ Defaults to 'median'.
178
+
179
+ Raises:
180
+ TypeError: If strategy is not a string.
181
+ ValueError: If strategy is not one of 'mean', 'median', or 'mode'.
182
+ """
183
+ if not isinstance(strategy, str):
184
+ raise TypeError(
185
+ f"Expected strategy to be a str, got {type(strategy).__name__}."
186
+ )
187
+ validate_choice(strategy, self.VALID_STRATEGIES, "strategy")
188
+ super().__init__(strategy)
189
+
190
+ def _compute_fill_value(self, series: pd.Series) -> tuple[bool, Any]:
191
+ """Compute the replacement value for missing entries in a Series.
192
+
193
+ Args:
194
+ series: Target column Series.
195
+
196
+ Returns:
197
+ A tuple (has_value, fill_value) where has_value indicates whether
198
+ a valid non-missing replacement value was found.
199
+ """
200
+ if series.dropna().empty:
201
+ return False, None
202
+
203
+ effective_strategy = self._strategy
204
+ if effective_strategy in ("mean", "median") and not _is_true_numeric_dtype(
205
+ series
206
+ ):
207
+ effective_strategy = "mode"
208
+
209
+ if effective_strategy == "mean":
210
+ val = series.mean()
211
+ if pd.isna(val):
212
+ return False, None
213
+ return True, val
214
+
215
+ if effective_strategy == "median":
216
+ val = series.median()
217
+ if pd.isna(val):
218
+ return False, None
219
+ return True, val
220
+
221
+ modes = series.mode(dropna=True)
222
+ if modes.empty:
223
+ return False, None
224
+ return True, modes.iloc[0]
225
+
226
+ def fix(self, data: pd.DataFrame, issue: Issue) -> pd.DataFrame:
227
+ """Fill missing values in issue.column and return a new DataFrame.
228
+
229
+ Args:
230
+ data: Input DataFrame.
231
+ issue: Missing-value Issue to fix.
232
+
233
+ Returns:
234
+ A new DataFrame with missing values in issue.column imputed when
235
+ a usable replacement value exists.
236
+
237
+ Raises:
238
+ TypeError: If data is not a DataFrame or issue is not an Issue.
239
+ ValueError: If issue cannot be fixed by ImputeFixer or column is missing.
240
+ """
241
+ validate_dataframe(data)
242
+ validated_issue = _validate_issue(issue)
243
+ if not self.can_fix(validated_issue):
244
+ raise ValueError(
245
+ f"ImputeFixer cannot fix issue of kind '{validated_issue.kind}'."
246
+ )
247
+
248
+ col = _validate_column_present(data, validated_issue)
249
+ result = data.copy()
250
+
251
+ has_value, fill_value = self._compute_fill_value(result[col])
252
+ if not has_value:
253
+ return result
254
+
255
+ result[col] = result[col].fillna(fill_value)
256
+ return result
257
+
258
+ def explain(self, issue: Issue) -> str:
259
+ """Explain how ImputeFixer addresses the given issue in plain English.
260
+
261
+ Args:
262
+ issue: Missing-value Issue to describe.
263
+
264
+ Returns:
265
+ A single present-tense sentence describing the imputation.
266
+
267
+ Raises:
268
+ TypeError: If issue is not an Issue instance.
269
+ ValueError: If issue cannot be fixed by ImputeFixer or column is None.
270
+ """
271
+ validated_issue = _validate_issue(issue)
272
+ if not self.can_fix(validated_issue):
273
+ raise ValueError(
274
+ f"ImputeFixer cannot explain issue of kind '{validated_issue.kind}'."
275
+ )
276
+ if validated_issue.column is None:
277
+ raise ValueError("Missing issue requires a column name.")
278
+
279
+ return (
280
+ f"Replace {validated_issue.count} missing values in "
281
+ f"'{validated_issue.column}' using the column {self._strategy}."
282
+ )
283
+
284
+
285
+ class DropFixer(BaseFixer):
286
+ """Fixer that removes rows affected by missing values or duplicate records.
287
+
288
+ Attributes:
289
+ HANDLES: Tuple of supported issue kinds (Issue.MISSING, Issue.DUPLICATE).
290
+ """
291
+
292
+ HANDLES: tuple[str, ...] = (Issue.MISSING, Issue.DUPLICATE)
293
+
294
+ def __init__(self) -> None:
295
+ """Initialize DropFixer with strategy name 'drop'."""
296
+ super().__init__("drop")
297
+
298
+ def _resolve_duplicate_subset(
299
+ self, data: pd.DataFrame, issue: Issue
300
+ ) -> list[str] | None:
301
+ """Validate and normalize the subset column list for duplicate issues.
302
+
303
+ Args:
304
+ data: Target DataFrame.
305
+ issue: Duplicate Issue containing optional details['subset'].
306
+
307
+ Returns:
308
+ A list of column names or None to evaluate all columns.
309
+
310
+ Raises:
311
+ ValueError: If details['subset'] is invalid or references unknown columns.
312
+ """
313
+ details = issue.details or {}
314
+ if "subset" not in details or details["subset"] is None:
315
+ return None
316
+
317
+ raw_subset = details["subset"]
318
+ if isinstance(raw_subset, (str, bytes)) or not isinstance(
319
+ raw_subset, (list, tuple)
320
+ ):
321
+ raise ValueError(
322
+ "Duplicate issue 'subset' detail must be a list/tuple of column names or None."
323
+ )
324
+
325
+ subset_list = list(raw_subset)
326
+ missing_cols = [c for c in subset_list if c not in data.columns]
327
+ if missing_cols:
328
+ raise ValueError(
329
+ f"Subset columns not found in DataFrame: {missing_cols}."
330
+ )
331
+ return subset_list
332
+
333
+ def fix(self, data: pd.DataFrame, issue: Issue) -> pd.DataFrame:
334
+ """Drop rows with missing values or duplicate rows and return a new DataFrame.
335
+
336
+ Args:
337
+ data: Input DataFrame.
338
+ issue: Issue of kind Issue.MISSING or Issue.DUPLICATE.
339
+
340
+ Returns:
341
+ A new DataFrame with matching rows dropped.
342
+
343
+ Raises:
344
+ TypeError: If data is not a DataFrame or issue is not an Issue.
345
+ ValueError: If issue cannot be fixed by DropFixer or column/subset is invalid.
346
+ """
347
+ validate_dataframe(data)
348
+ validated_issue = _validate_issue(issue)
349
+ if not self.can_fix(validated_issue):
350
+ raise ValueError(
351
+ f"DropFixer cannot fix issue of kind '{validated_issue.kind}'."
352
+ )
353
+
354
+ result = data.copy()
355
+ if validated_issue.kind == Issue.MISSING:
356
+ col = _validate_column_present(result, validated_issue)
357
+ return result.dropna(subset=[col])
358
+
359
+ subset = self._resolve_duplicate_subset(result, validated_issue)
360
+ return result.drop_duplicates(subset=subset)
361
+
362
+ def explain(self, issue: Issue) -> str:
363
+ """Explain how DropFixer resolves the given issue in plain English.
364
+
365
+ Args:
366
+ issue: Issue of kind Issue.MISSING or Issue.DUPLICATE.
367
+
368
+ Returns:
369
+ A single present-tense sentence describing the row removal.
370
+
371
+ Raises:
372
+ TypeError: If issue is not an Issue instance.
373
+ ValueError: If issue cannot be fixed by DropFixer or column is invalid.
374
+ """
375
+ validated_issue = _validate_issue(issue)
376
+ if not self.can_fix(validated_issue):
377
+ raise ValueError(
378
+ f"DropFixer cannot explain issue of kind '{validated_issue.kind}'."
379
+ )
380
+
381
+ if validated_issue.kind == Issue.MISSING:
382
+ if validated_issue.column is None:
383
+ raise ValueError("Missing issue requires a column name.")
384
+ return (
385
+ f"Drop rows with missing values in '{validated_issue.column}'."
386
+ )
387
+
388
+ return f"Remove {validated_issue.count} duplicate rows from the dataset."
389
+
390
+
391
+ class ClipFixer(BaseFixer):
392
+ """Fixer that clips numeric column values to detector-provided bounds.
393
+
394
+ Attributes:
395
+ HANDLES: Tuple containing only Issue.OUTLIER.
396
+ """
397
+
398
+ HANDLES: tuple[str, ...] = (Issue.OUTLIER,)
399
+
400
+ def __init__(self) -> None:
401
+ """Initialize ClipFixer with strategy name 'clip'."""
402
+ super().__init__("clip")
403
+
404
+ def _validate_bound(self, bound: Any, name: str) -> float:
405
+ """Validate that an outlier bound is a finite real number.
406
+
407
+ Args:
408
+ bound: Bound value from issue.details.
409
+ name: Bound label ('lower' or 'upper') for error messages.
410
+
411
+ Returns:
412
+ The bound converted to float.
413
+
414
+ Raises:
415
+ ValueError: If bound is missing, boolean, non-numeric, or non-finite.
416
+ """
417
+ if bound is None or isinstance(bound, bool) or not isinstance(bound, (int, float, np.number)):
418
+ raise ValueError(
419
+ f"Outlier issue requires a numeric '{name}' bound in details."
420
+ )
421
+ value = float(bound)
422
+ if not np.isfinite(value):
423
+ raise ValueError(
424
+ f"Outlier issue '{name}' bound must be finite, got {bound}."
425
+ )
426
+ return value
427
+
428
+ def _extract_bounds(self, issue: Issue) -> tuple[float, float]:
429
+ """Extract and validate lower and upper clipping bounds from issue.details.
430
+
431
+ Args:
432
+ issue: Outlier Issue containing 'lower' and 'upper' in details.
433
+
434
+ Returns:
435
+ Tuple of (lower, upper) bounds as floats.
436
+
437
+ Raises:
438
+ ValueError: If bounds are missing, invalid, or lower exceeds upper.
439
+ """
440
+ details = issue.details
441
+ if not isinstance(details, dict) or "lower" not in details or "upper" not in details:
442
+ raise ValueError(
443
+ "Outlier issue details must include both 'lower' and 'upper' bounds."
444
+ )
445
+
446
+ lower = self._validate_bound(details["lower"], "lower")
447
+ upper = self._validate_bound(details["upper"], "upper")
448
+ if lower > upper:
449
+ raise ValueError(
450
+ f"Lower bound ({lower}) cannot be greater than upper bound ({upper})."
451
+ )
452
+ return lower, upper
453
+
454
+ def fix(self, data: pd.DataFrame, issue: Issue) -> pd.DataFrame:
455
+ """Clip values in issue.column to lower and upper bounds on a new DataFrame.
456
+
457
+ Args:
458
+ data: Input DataFrame.
459
+ issue: Outlier Issue with lower and upper bounds in details.
460
+
461
+ Returns:
462
+ A new DataFrame with issue.column clipped to [lower, upper].
463
+
464
+ Raises:
465
+ TypeError: If data is not a DataFrame or issue is not an Issue.
466
+ ValueError: If issue is unsupported, column is missing, or bounds are invalid.
467
+ """
468
+ validate_dataframe(data)
469
+ validated_issue = _validate_issue(issue)
470
+ if not self.can_fix(validated_issue):
471
+ raise ValueError(
472
+ f"ClipFixer cannot fix issue of kind '{validated_issue.kind}'."
473
+ )
474
+
475
+ col = _validate_column_present(data, validated_issue)
476
+ lower, upper = self._extract_bounds(validated_issue)
477
+
478
+ result = data.copy()
479
+ if not _is_true_numeric_dtype(result[col]):
480
+ raise ValueError(
481
+ f"Column '{col}' must be numeric to apply clipping."
482
+ )
483
+
484
+ result[col] = result[col].clip(lower=lower, upper=upper)
485
+ return result
486
+
487
+ def explain(self, issue: Issue) -> str:
488
+ """Explain how ClipFixer clips values for the given outlier issue.
489
+
490
+ Args:
491
+ issue: Outlier Issue with lower and upper bounds in details.
492
+
493
+ Returns:
494
+ A single present-tense sentence describing the clipping bounds.
495
+
496
+ Raises:
497
+ TypeError: If issue is not an Issue instance.
498
+ ValueError: If issue is unsupported, column is None, or bounds are invalid.
499
+ """
500
+ validated_issue = _validate_issue(issue)
501
+ if not self.can_fix(validated_issue):
502
+ raise ValueError(
503
+ f"ClipFixer cannot explain issue of kind '{validated_issue.kind}'."
504
+ )
505
+ if validated_issue.column is None:
506
+ raise ValueError("Outlier issue requires a column name.")
507
+
508
+ lower, upper = self._extract_bounds(validated_issue)
509
+ return (
510
+ f"Clip values in '{validated_issue.column}' between {lower} and {upper}."
511
+ )