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/session.py ADDED
@@ -0,0 +1,502 @@
1
+ """The ``CleaningSession`` class: the main entry point of MendData.
2
+
3
+ A session wraps a DataFrame and runs the library's order of work: scan for
4
+ problems, fix each one, score the quality before and after, and explain every
5
+ change in plain English. It is written against the team contract (Section 5 of
6
+ Narrative Report 1), so it only relies on these methods of its collaborators:
7
+
8
+ detector ``detect(data) -> list[Issue]``
9
+ fixer ``can_fix(issue)``, ``fix(data, issue) -> DataFrame``,
10
+ ``explain(issue) -> str``
11
+ scorer ``compare(before, after) -> {'before', 'after', 'change'}``
12
+ log ``record(step, reason, affected)``, ``export() -> str``,
13
+ ``len(log)``
14
+
15
+ Any object with those methods works, which is what makes the session easy to
16
+ test with simple stand-ins before the real classes exist.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import numbers
22
+ from collections.abc import Mapping
23
+ from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional
24
+
25
+ import pandas as pd
26
+
27
+ from . import utils
28
+ from .issue import Issue
29
+
30
+ if TYPE_CHECKING:
31
+ from .audit import AuditLog
32
+ from .detectors import BaseDetector
33
+ from .fixers import BaseFixer
34
+ from .scoring import QualityScorer
35
+
36
+ __all__ = ["CleaningSession"]
37
+
38
+
39
+ def _default_detectors() -> list:
40
+ """Build the default detectors: missing values, duplicates, outliers."""
41
+ from .detectors import DuplicateDetector, MissingValueDetector, OutlierDetector
42
+
43
+ return [MissingValueDetector(), DuplicateDetector(), OutlierDetector()]
44
+
45
+
46
+ def _default_fixers() -> Dict[str, Any]:
47
+ """Build the default fixer for each kind of issue."""
48
+ from .fixers import ClipFixer, DropFixer, ImputeFixer
49
+
50
+ return {
51
+ Issue.MISSING: ImputeFixer("median"),
52
+ Issue.DUPLICATE: DropFixer(),
53
+ Issue.OUTLIER: ClipFixer(),
54
+ }
55
+
56
+
57
+ def _default_scorer() -> Any:
58
+ """Build the default quality scorer."""
59
+ from .scoring import QualityScorer
60
+
61
+ return QualityScorer()
62
+
63
+
64
+ def _default_log() -> Any:
65
+ """Build an empty audit log."""
66
+ from .audit import AuditLog
67
+
68
+ return AuditLog()
69
+
70
+ def _plural(count: int, word: str) -> str:
71
+ """Return ``word`` with an ``s`` added unless ``count`` is exactly 1.
72
+
73
+ Args:
74
+ count: The number the word describes.
75
+ word: A singular noun, such as ``'issue'``.
76
+
77
+ Returns:
78
+ ``word`` when ``count`` is 1, otherwise ``word`` followed by ``s``.
79
+ """
80
+ return word if count == 1 else word + "s"
81
+
82
+
83
+ def _require_methods(obj: Any, names: Iterable[str], role: str) -> None:
84
+ """Check that ``obj`` has every method in ``names``.
85
+
86
+ Args:
87
+ obj: The collaborator to check.
88
+ names: The method names it must provide.
89
+ role: How to refer to the object in the error message.
90
+
91
+ Raises:
92
+ TypeError: If a method is missing or not callable.
93
+ """
94
+ for name in names:
95
+ if not callable(getattr(obj, name, None)):
96
+ raise TypeError(
97
+ f"{role} must have a {name}() method; got {type(obj).__name__}."
98
+ )
99
+
100
+
101
+ def _validate_fixer_map(fixers: Any) -> Dict[str, Any]:
102
+ """Check a dict that maps an issue kind to a fixer.
103
+
104
+ Args:
105
+ fixers: The mapping to check, for example
106
+ ``{'missing': ImputeFixer('mean')}``.
107
+
108
+ Returns:
109
+ A new dict with the same entries.
110
+
111
+ Raises:
112
+ TypeError: If ``fixers`` is not a mapping, or a fixer lacks the
113
+ fixer methods.
114
+ ValueError: If a key is not one of ``Issue.KINDS``.
115
+ """
116
+ if not isinstance(fixers, Mapping):
117
+ raise TypeError(
118
+ "fixers must be a dict that maps an issue kind to a fixer, "
119
+ f"got {type(fixers).__name__}."
120
+ )
121
+ checked: Dict[str, Any] = {}
122
+ for kind, fixer in fixers.items():
123
+ utils.validate_choice(kind, Issue.KINDS, "fixer kind")
124
+ _require_methods(fixer, ("can_fix", "fix", "explain"), f"The {kind!r} fixer")
125
+ checked[kind] = fixer
126
+ return checked
127
+
128
+
129
+ def _count_changes(before: pd.DataFrame, after: pd.DataFrame) -> int:
130
+ """Count how much a cleaning step changed: rows dropped or cells changed.
131
+
132
+ Args:
133
+ before: The data before the step.
134
+ after: The data after the step.
135
+
136
+ Returns:
137
+ The number of rows removed or added when the row count differs.
138
+ Otherwise the number of cells whose value changed (a missing value
139
+ that became a number counts as a change). If the columns differ, the
140
+ whole of ``after`` counts as changed.
141
+ """
142
+ if len(before) != len(after):
143
+ return abs(len(before) - len(after))
144
+ old = before.reset_index(drop=True)
145
+ new = after.reset_index(drop=True)
146
+ if list(old.columns) != list(new.columns):
147
+ return int(new.size)
148
+ old = old.astype(object)
149
+ new = new.astype(object)
150
+ changed = old.ne(new) & ~(old.isna() & new.isna())
151
+ return int(changed.to_numpy().sum())
152
+
153
+
154
+ class CleaningSession:
155
+ """Scan, fix, score and explain the cleaning of one DataFrame.
156
+
157
+ The session owns a working copy of the data, the detectors that find
158
+ problems, a fixer for each kind of problem, a quality scorer and an audit
159
+ log. It never changes the DataFrame you give it. Methods return values
160
+ and never print.
161
+
162
+ Usage::
163
+
164
+ session = CleaningSession(df)
165
+ session.scan()
166
+ session.fix_all()
167
+ print(session.score())
168
+ print(session.report())
169
+
170
+ Args:
171
+ data: The DataFrame to clean. It is copied.
172
+ detectors: Objects with a ``detect(data)`` method. Defaults to a
173
+ missing-value, a duplicate and an outlier detector.
174
+ fixers: A dict that maps an issue kind (``'missing'``,
175
+ ``'duplicate'`` or ``'outlier'``) to a fixer. Kinds you leave out
176
+ use the defaults: median fill, drop duplicates, clip outliers.
177
+ scorer: Object with a ``compare(before, after)`` method. Defaults to
178
+ ``QualityScorer()``.
179
+ log: Object with ``record``, ``export`` and ``len()``. Defaults to an
180
+ empty ``AuditLog()``.
181
+ max_history: How many cleaning steps ``undo()`` can go back through.
182
+ The oldest step is forgotten first. ``reset()`` always works.
183
+
184
+ Raises:
185
+ TypeError: If ``data`` is not a DataFrame, or a collaborator lacks
186
+ the methods it needs.
187
+ ValueError: If ``detectors`` is empty, a key of ``fixers`` is not an
188
+ issue kind, or ``max_history`` is less than 1.
189
+ """
190
+
191
+ def __init__(
192
+ self,
193
+ data: pd.DataFrame,
194
+ detectors: Optional[Iterable["BaseDetector"]] = None,
195
+ fixers: Optional[Mapping] = None,
196
+ scorer: Optional["QualityScorer"] = None,
197
+ log: Optional["AuditLog"] = None,
198
+ max_history: int = 20,
199
+ ) -> None:
200
+ """Validate the arguments and set up the session.
201
+
202
+ See the class docstring for the meaning of each argument and for the
203
+ errors that can be raised.
204
+ """
205
+ utils.validate_dataframe(data)
206
+ if isinstance(max_history, bool) or not isinstance(max_history, numbers.Integral):
207
+ raise TypeError(
208
+ f"max_history must be an integer, got {type(max_history).__name__}."
209
+ )
210
+ if max_history < 1:
211
+ raise ValueError(f"max_history must be at least 1, got {max_history}.")
212
+
213
+ if detectors is None:
214
+ detector_list = _default_detectors()
215
+ else:
216
+ detector_list = list(detectors)
217
+ if not detector_list:
218
+ raise ValueError(
219
+ "detectors cannot be empty; pass None to use the defaults."
220
+ )
221
+ for detector in detector_list:
222
+ _require_methods(detector, ("detect",), "A detector")
223
+
224
+ fixer_map = {} if fixers is None else _validate_fixer_map(fixers)
225
+ if any(kind not in fixer_map for kind in Issue.KINDS):
226
+ fixer_map = {**_default_fixers(), **fixer_map}
227
+
228
+ if scorer is None:
229
+ scorer = _default_scorer()
230
+ _require_methods(scorer, ("compare",), "The scorer")
231
+
232
+ if log is None:
233
+ log = _default_log()
234
+ _require_methods(log, ("record", "export"), "The log")
235
+
236
+ self._original = data.copy()
237
+ self._data = data.copy()
238
+ # Each entry is (data before the step, step description, issue to restore).
239
+ self._history: List[tuple] = []
240
+ # None until scan() runs; afterwards the issues that are still open.
241
+ self._issues: Optional[List[Issue]] = None
242
+ self._max_history = int(max_history)
243
+ self._detectors = detector_list
244
+ self._fixers = fixer_map
245
+ self._scorer = scorer
246
+ self._log = log
247
+
248
+
249
+ @property
250
+ def data(self) -> pd.DataFrame:
251
+ """A copy of the current data, so callers cannot change the session."""
252
+ return self._data.copy()
253
+
254
+ @property
255
+ def issues(self) -> List[Issue]:
256
+ """The issues found by the last scan that are still open (a copy)."""
257
+ return [] if self._issues is None else list(self._issues)
258
+
259
+
260
+
261
+ def scan(self) -> List[Issue]:
262
+ """Run every detector and rank the issues, worst first.
263
+
264
+ Replaces the issues from any earlier scan and logs one entry.
265
+
266
+ Returns:
267
+ The issues found, highest severity first (a copy).
268
+
269
+ Raises:
270
+ TypeError: If a detector returns something that is not an
271
+ ``Issue``.
272
+ """
273
+ found: List[Issue] = []
274
+ for detector in self._detectors:
275
+ for item in detector.detect(self._data):
276
+ if not isinstance(item, Issue):
277
+ raise TypeError(
278
+ f"{type(detector).__name__}.detect() must return Issue "
279
+ f"objects, got {type(item).__name__}."
280
+ )
281
+ found.append(item)
282
+ found.sort(reverse=True) # highest severity first; ties keep their order
283
+ self._issues = found
284
+ count = len(found)
285
+ self._log.record(
286
+ step=f"Scanned the data and found {count} {_plural(count, 'issue')}.",
287
+ reason="To find problems before cleaning.",
288
+ affected=0,
289
+ )
290
+ return self.issues
291
+
292
+ def fix(self, issue: Issue, fixer: Optional["BaseFixer"] = None) -> pd.DataFrame:
293
+ """Apply one cleaning step: one fixer to one issue.
294
+
295
+ Args:
296
+ issue: The issue to resolve.
297
+ fixer: The fixer to use. Defaults to the fixer set for
298
+ ``issue.kind``.
299
+
300
+ Returns:
301
+ A copy of the cleaned data.
302
+
303
+ Raises:
304
+ TypeError: If ``issue`` is not an ``Issue``, ``fixer`` lacks the
305
+ fixer methods, or the fixer does not return a DataFrame.
306
+ ValueError: If the fixer cannot handle this kind of issue.
307
+ """
308
+ if not isinstance(issue, Issue):
309
+ raise TypeError(f"issue must be an Issue, got {type(issue).__name__}.")
310
+ if fixer is None:
311
+ fixer = self._fixers[issue.kind]
312
+ else:
313
+ _require_methods(fixer, ("can_fix", "fix", "explain"), "The fixer")
314
+ if not fixer.can_fix(issue):
315
+ raise ValueError(
316
+ f"{type(fixer).__name__} cannot fix {issue.kind!r} issues."
317
+ )
318
+ self._apply(issue, fixer)
319
+ return self.data
320
+
321
+ def fix_all(self, fixers: Optional[Mapping] = None) -> pd.DataFrame:
322
+ """Fix every open issue, worst first.
323
+
324
+ Scans first if no scan has been run. Every issue is checked against
325
+ its fixer before anything changes, so a mismatch stops the whole
326
+ call instead of leaving the data half-cleaned.
327
+
328
+ Args:
329
+ fixers: Optional dict that maps an issue kind to a fixer for this
330
+ call only, for example ``{'missing': ImputeFixer('mean')}``.
331
+ Kinds you leave out use the session's fixers.
332
+
333
+ Returns:
334
+ A copy of the cleaned data.
335
+
336
+ Raises:
337
+ TypeError: If ``fixers`` is not a dict of fixers.
338
+ ValueError: If a key of ``fixers`` is not an issue kind, or a
339
+ fixer cannot handle one of the issues.
340
+ """
341
+ overrides = {} if fixers is None else _validate_fixer_map(fixers)
342
+ if self._issues is None:
343
+ self.scan()
344
+
345
+ plan = []
346
+ for issue in list(self._issues):
347
+ fixer = overrides.get(issue.kind, self._fixers[issue.kind])
348
+ if not fixer.can_fix(issue):
349
+ raise ValueError(
350
+ f"{type(fixer).__name__} cannot fix {issue.kind!r} issues."
351
+ )
352
+ plan.append((issue, fixer))
353
+ for issue, fixer in plan:
354
+ self._apply(issue, fixer)
355
+ return self.data
356
+
357
+ def score(self) -> Dict[str, Any]:
358
+ """Compare the quality of the original data with the current data.
359
+
360
+ Returns:
361
+ The scorer's result: a dict with ``'before'``, ``'after'`` and
362
+ ``'change'``.
363
+ """
364
+ return self._scorer.compare(self._original, self._data)
365
+
366
+ def report(self) -> str:
367
+ """Summarise the cleaning in plain English.
368
+
369
+ Returns:
370
+ A text report with the size of the data, the quality score
371
+ before and after, the issues still open, and every step in the
372
+ audit log.
373
+ """
374
+ rows_then, cols_then = self._original.shape
375
+ rows_now, cols_now = self._data.shape
376
+ scores = self.score()
377
+
378
+ lines = [
379
+ "MendData cleaning report",
380
+ "========================",
381
+ f"Data: {rows_now} rows x {cols_now} columns now "
382
+ f"(started with {rows_then} rows x {cols_then} columns).",
383
+ f"Quality score: {scores['before']} -> {scores['after']} "
384
+ f"({scores['change']:+})",
385
+ "",
386
+ ]
387
+ if self._issues is None:
388
+ lines.append("Issues: no scan has been run yet.")
389
+ elif not self._issues:
390
+ lines.append("Issues: none left from the last scan.")
391
+ else:
392
+ lines.append("Issues still open from the last scan:")
393
+ for number, issue in enumerate(self._issues, start=1):
394
+ lines.append(f" {number}. {issue.describe()}")
395
+ lines.append("")
396
+ lines.append("What was done:")
397
+ if len(self._log) == 0:
398
+ lines.append(" Nothing yet.")
399
+ else:
400
+ lines.append(self._log.export())
401
+ return "\n".join(lines)
402
+
403
+
404
+ def undo(self) -> pd.DataFrame:
405
+ """Revert the last cleaning step (one fixer applied to one issue).
406
+
407
+ The data goes back to how it was, the issue becomes open again, and
408
+ an 'Undid ...' entry is added to the log. Old log entries are never
409
+ deleted, so the log always tells the truth.
410
+
411
+ Returns:
412
+ A copy of the restored data.
413
+
414
+ Raises:
415
+ RuntimeError: If there is nothing to undo.
416
+ """
417
+ if not self._history:
418
+ raise RuntimeError("Nothing to undo.")
419
+ snapshot, step, restore = self._history.pop()
420
+ affected = _count_changes(self._data, snapshot)
421
+ self._data = snapshot
422
+ if restore is not None and self._issues is not None:
423
+ if restore not in self._issues:
424
+ self._issues.append(restore)
425
+ self._issues.sort(reverse=True)
426
+ self._log.record(
427
+ step=f"Undid: {step}",
428
+ reason="The last cleaning step was reverted.",
429
+ affected=affected,
430
+ )
431
+ return self.data
432
+
433
+ def reset(self) -> pd.DataFrame:
434
+ """Go back to the original data and clear the step history.
435
+
436
+ The issues from the last scan are cleared too, because they no longer
437
+ match the data. The reset is logged.
438
+
439
+ Returns:
440
+ A copy of the original data.
441
+ """
442
+ affected = _count_changes(self._data, self._original)
443
+ self._data = self._original.copy()
444
+ self._history.clear()
445
+ self._issues = None
446
+ self._log.record(
447
+ step="Reset the data to its original state.",
448
+ reason="All cleaning steps were reverted.",
449
+ affected=affected,
450
+ )
451
+ return self.data
452
+
453
+
454
+ def _apply(self, issue: Issue, fixer: Any) -> None:
455
+ """Run one fixer on one issue and record the step.
456
+
457
+ The data is only replaced after the fixer succeeds, so a failing
458
+ fixer leaves the session untouched. A copy of the data is saved
459
+ first, which protects undo even from a fixer that changes its input.
460
+
461
+ Args:
462
+ issue: The issue to resolve.
463
+ fixer: A fixer that can handle ``issue``.
464
+
465
+ Raises:
466
+ TypeError: If the fixer does not return a DataFrame.
467
+ """
468
+ snapshot = self._data.copy()
469
+ result = fixer.fix(self._data, issue)
470
+ if not isinstance(result, pd.DataFrame):
471
+ raise TypeError(
472
+ f"{type(fixer).__name__}.fix() must return a DataFrame, "
473
+ f"got {type(result).__name__}."
474
+ )
475
+ step = fixer.explain(issue)
476
+ affected = _count_changes(snapshot, result)
477
+
478
+ restore = None
479
+ if self._issues is not None and issue in self._issues:
480
+ self._issues.remove(issue)
481
+ restore = issue
482
+ self._history.append((snapshot, step, restore))
483
+ if len(self._history) > self._max_history:
484
+ del self._history[0]
485
+ self._data = result
486
+ self._log.record(step=step, reason=issue.describe(), affected=affected)
487
+
488
+
489
+ def __repr__(self) -> str:
490
+ """Return a short summary of the session.
491
+
492
+ Returns:
493
+ A string such as ``CleaningSession(rows=200, columns=5, issues=3,
494
+ steps=2)``, where ``issues`` counts open issues and ``steps``
495
+ counts the cleaning steps ``undo()`` can still revert.
496
+ """
497
+ rows, columns = self._data.shape
498
+ open_issues = 0 if self._issues is None else len(self._issues)
499
+ return (
500
+ f"CleaningSession(rows={rows}, columns={columns}, "
501
+ f"issues={open_issues}, steps={len(self._history)})"
502
+ )
MendData/utils.py ADDED
@@ -0,0 +1,82 @@
1
+ """Shared input-validation helpers for MendData.
2
+
3
+ These are internal helpers: every public method checks its inputs with them so
4
+ mistakes produce a clear, plain-English error. They are deliberately not
5
+ exported from ``MendData/__init__.py``.
6
+
7
+ Each helper returns the value it checked, so it can be used inline::
8
+
9
+ self._weights = validate_fraction(weight, 'weight')
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import numbers
15
+ from typing import Any, Iterable
16
+
17
+ import pandas as pd
18
+
19
+ __all__ = ["validate_dataframe", "validate_choice", "validate_fraction"]
20
+
21
+
22
+ def validate_dataframe(data: Any, name: str = "data") -> pd.DataFrame:
23
+ """Check that ``data`` is a pandas DataFrame.
24
+
25
+ Args:
26
+ data: The object to check.
27
+ name: How to refer to the argument in the error message.
28
+
29
+ Returns:
30
+ ``data`` itself, unchanged.
31
+
32
+ Raises:
33
+ TypeError: If ``data`` is not a ``pandas.DataFrame``.
34
+ """
35
+ if not isinstance(data, pd.DataFrame):
36
+ raise TypeError(
37
+ f"{name} must be a pandas DataFrame, got {type(data).__name__}."
38
+ )
39
+ return data
40
+
41
+
42
+ def validate_choice(value: Any, allowed: Iterable[Any], name: str) -> Any:
43
+ """Check that ``value`` is one of the allowed choices.
44
+
45
+ Args:
46
+ value: The value to check.
47
+ allowed: The values that are accepted.
48
+ name: How to refer to the argument in the error message.
49
+
50
+ Returns:
51
+ ``value`` itself, unchanged.
52
+
53
+ Raises:
54
+ ValueError: If ``value`` is not one of ``allowed``.
55
+ """
56
+ options = tuple(allowed)
57
+ if value not in options:
58
+ listed = ", ".join(repr(option) for option in options)
59
+ raise ValueError(f"{name} must be one of {listed}; got {value!r}.")
60
+ return value
61
+
62
+
63
+ def validate_fraction(value: Any, name: str) -> float:
64
+ """Check that ``value`` is a number from 0 to 1 (inclusive).
65
+
66
+ Args:
67
+ value: The value to check. NumPy numbers are accepted.
68
+ name: How to refer to the argument in the error message.
69
+
70
+ Returns:
71
+ ``value`` as a plain ``float``.
72
+
73
+ Raises:
74
+ TypeError: If ``value`` is not a number (booleans do not count).
75
+ ValueError: If ``value`` is outside the range 0 to 1.
76
+ """
77
+ if isinstance(value, bool) or not isinstance(value, numbers.Real):
78
+ raise TypeError(f"{name} must be a number, got {type(value).__name__}.")
79
+ number = float(value)
80
+ if not 0.0 <= number <= 1.0:
81
+ raise ValueError(f"{name} must be between 0 and 1, got {number}.")
82
+ return number