File size: 21,965 Bytes
9deebf2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 | """
Base classes for the GotPsi data cleaning pipeline.
Defines abstract base classes that establish the interface
for cleaners, processors, and exporters.
"""
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Dict, List, Optional
import warnings
import pandas as pd
from collections import defaultdict
warnings.filterwarnings('ignore', message='.*empty or all-NA entries.*')
from .config import Config
from .errata_logger import ErrataLogger
from .file_discovery_logger import FileDiscoveryLogger
class BaseCleaner(ABC):
"""
Abstract base class for data cleaning modules.
Cleaners handle specific aspects of data cleaning such as
encoding normalization, delimiter standardization, etc.
"""
def __init__(self, config: Config, errata_logger: Optional[ErrataLogger] = None):
"""
Initialize cleaner with configuration.
Args:
config: Configuration object
errata_logger: Optional errata logger for error tracking
"""
self.config = config
self.errata_logger = errata_logger
@abstractmethod
def clean(self, data: Any, **kwargs) -> Any:
"""
Clean the input data.
Args:
data: Input data to clean (format varies by cleaner)
**kwargs: Additional parameters
Returns:
Cleaned data
"""
pass
def log_error(
self,
error_type: str,
message: str,
**kwargs
) -> None:
"""
Log an error to the errata logger if available.
Args:
error_type: Type of error
message: Error message
**kwargs: Additional context (file_path, row_number, etc.)
"""
if self.errata_logger:
self.errata_logger.log_error(error_type, message, **kwargs)
class BaseProcessor(ABC):
"""
Abstract base class for dataset-specific processors.
Processors handle the complete data cleaning workflow for
a specific dataset type (e.g., card tests, RV tests).
"""
def __init__(self, config: Config, dataset_name: str):
"""
Initialize processor for a dataset.
Args:
config: Configuration object
dataset_name: Name of the dataset to process
"""
self.config = config
self.dataset_name = dataset_name
self.dataset_config = config.dataset_config(dataset_name)
# Initialize errata logger
errata_dir = config.logs_dir / 'errata'
self.errata_logger = ErrataLogger(errata_dir, dataset_name)
# Initialize file discovery logger
file_discovery_dir = config.logs_dir / 'file_discovery'
self.file_discovery_logger = FileDiscoveryLogger(file_discovery_dir, dataset_name)
def process(self, max_files: Optional[int] = None, chunk_size: int = 100) -> pd.DataFrame:
"""
Process all files with parallel cleaning and chunked concatenation.
Override this in subclasses that need custom post-processing (e.g., users).
Args:
max_files: Optional limit on number of files to process
chunk_size: Number of files to process before concatenating (default: 100)
Returns:
Combined DataFrame
"""
import gc
from .exceptions import ProcessorError
files = self.get_file_list()
if max_files:
files = files[:max_files]
print(f"Processing {len(files)} {self.dataset_name} files...")
# Phase 1: Parallel batch cleaning
use_delim = getattr(self, 'BATCH_DELIMITER_CLEAN', True)
cleaned_texts = self._batch_clean_files(files, use_delimiter_cleaner=use_delim)
print(f"Successfully cleaned {len(cleaned_texts)}/{len(files)} files")
# Phase 2: Sequential process_file with pre-cleaned text
intermediate_chunks = []
current_chunk = []
try:
from tqdm import tqdm
iterator = tqdm(files, desc=f"Processing {self.dataset_name} files")
except ImportError:
iterator = files
for file_path in iterator:
pre_cleaned = cleaned_texts.get(file_path)
if pre_cleaned is None:
continue # file failed cleaning, already logged
df = self.process_file(file_path, pre_cleaned_text=pre_cleaned)
if df is not None and not df.empty:
current_chunk.append(df)
if len(current_chunk) >= chunk_size:
chunk_df = pd.concat(current_chunk, ignore_index=True)
del current_chunk
current_chunk = []
intermediate_chunks.append(chunk_df)
gc.collect()
if current_chunk:
chunk_df = pd.concat(current_chunk, ignore_index=True)
del current_chunk
intermediate_chunks.append(chunk_df)
gc.collect()
if not intermediate_chunks:
raise ProcessorError("No valid data processed")
print(f"Combining {len(intermediate_chunks)} intermediate chunks...")
# Progressive pair-wise concatenation to minimize peak memory
while len(intermediate_chunks) > 1:
pair_results = []
for i in range(0, len(intermediate_chunks), 2):
if i + 1 < len(intermediate_chunks):
pair_df = pd.concat(
[intermediate_chunks[i], intermediate_chunks[i + 1]],
ignore_index=True
)
pair_results.append(pair_df)
else:
pair_results.append(intermediate_chunks[i])
intermediate_chunks = pair_results
gc.collect()
combined = intermediate_chunks[0]
del intermediate_chunks
gc.collect()
# Post-processing hooks
combined = self._post_process(combined)
# Close errata logger
self.errata_logger.close()
return combined
def _post_process(self, combined: pd.DataFrame) -> pd.DataFrame:
"""
Post-processing hook called after all files are combined.
Default: removes audit columns if audit_mode is disabled.
Override in subclasses for custom post-processing.
"""
# Remove audit columns if audit mode is disabled
audit_mode = self.config.get('processing.audit_mode', False)
if not audit_mode:
audit_cols = ['source_file', 'source_row_number']
cols_to_drop = [col for col in audit_cols if col in combined.columns]
if cols_to_drop:
combined = combined.drop(columns=cols_to_drop)
print(f"Audit mode disabled: Removed columns {cols_to_drop}")
print()
return combined
def pre_validate_csv_lines(
self,
text: str,
file_path: Optional[str] = None,
) -> str:
"""Remove lines with inconsistent column counts, logging each drop.
Determines the modal (most common) comma count, then filters out
any non-blank line that doesn't match. This replaces the silent
on_bad_lines='skip' with an audited pre-filter.
"""
from collections import Counter
lines = text.split('\n')
if not lines:
return text
comma_counts = []
for line in lines:
stripped = line.strip()
if stripped:
comma_counts.append(stripped.count(','))
if not comma_counts:
return text
modal_count = Counter(comma_counts).most_common(1)[0][0]
kept = []
dropped = 0
for lineno, line in enumerate(lines, 1):
stripped = line.strip()
if not stripped:
kept.append(line)
continue
if stripped.count(',') == modal_count:
kept.append(line)
else:
dropped += 1
if dropped <= 20:
preview = stripped[:120]
self.errata_logger.log_error(
'bad_csv_line',
f"Line {lineno}: expected {modal_count} commas, got {stripped.count(',')}: {preview!r}",
file_path=file_path,
line_number=lineno,
scope='row',
)
if dropped > 0:
self.errata_logger.log_error(
'bad_csv_lines_total',
f"{dropped} line(s) dropped due to inconsistent column count (expected {modal_count + 1} columns)",
file_path=file_path,
scope='file',
)
return '\n'.join(kept)
def to_numeric_logged(
self,
series: pd.Series,
col_name: str,
file_path: Optional[str] = None,
) -> pd.Series:
"""Convert series to numeric, logging any values that get coerced to NaN."""
coerced = pd.to_numeric(series, errors='coerce')
bad_mask = coerced.isna() & series.notna() & (series.astype(str).str.strip() != '')
if bad_mask.any():
bad_values = series[bad_mask].astype(str).unique()[:10]
self.errata_logger.log_error(
'numeric_coercion',
f"{bad_mask.sum()} non-numeric value(s) coerced to NaN in '{col_name}': {list(bad_values)}",
file_path=file_path,
scope='row',
)
return coerced
@abstractmethod
def process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]:
"""
Process a single file.
Args:
file_path: Path to the raw data file
pre_cleaned_text: Pre-cleaned text (from parallel batch cleaning).
If None, the processor should clean the file itself.
Returns:
DataFrame or None if processing fails
"""
pass
# Class attribute: subclasses set this to their glob patterns
FILE_PATTERNS: List[str] = []
def get_file_list(self) -> List[Path]:
"""
Get list of files to process for this dataset.
Checks config 'file_discovery.use_manifest':
- False (default): recursive glob using FILE_PATTERNS
- True: reads from manifest.json in the experiment directory
Returns:
List of file paths
"""
use_manifest = self.config.get('file_discovery.use_manifest', False)
if use_manifest:
experiment_dir = self.config.raw_data_dir / self.dataset_name
return self.discover_files_from_manifest(experiment_dir)
else:
files = self.discover_files(self.FILE_PATTERNS)
if not files:
from .exceptions import ProcessorError
raise ProcessorError(
f"No {self.dataset_name} files found matching patterns "
f"{self.FILE_PATTERNS} in {self.config.raw_data_dir}"
)
return files
def get_dataset_path(self) -> Path:
"""
Get the full path to the dataset directory.
Returns:
Path to dataset directory
"""
rel_path = self.dataset_config['path']
return self.config.raw_data_dir / rel_path
def discover_files(self, patterns: List[str], search_root: Optional[Path] = None) -> List[Path]:
"""
Recursively discover files matching patterns, with deduplication.
Searches the data directory recursively for files matching the given patterns.
When duplicate filenames are found, keeps the larger file.
Logs all discoveries and deduplication decisions.
Args:
patterns: List of filename patterns (e.g., ['users*.dat', 'questions*.dat'])
search_root: Root directory to search (defaults to config.raw_data_dir)
Returns:
List of unique file paths (deduplicated)
"""
if search_root is None:
search_root = Path(self.config.raw_data_dir)
# Log search parameters
self.file_discovery_logger.set_search_params(search_root, patterns)
# Discover all matching files
all_files = []
for pattern in patterns:
matching_files = list(search_root.rglob(pattern))
all_files.extend(matching_files)
# Log all discovered files
print(f"File Discovery: Found {len(all_files)} file(s) matching patterns {patterns}")
for file_path in all_files:
self.file_discovery_logger.add_discovered_file(file_path)
print(f" - {file_path.name}: {file_path.stat().st_size / (1024*1024):.2f} MB")
# Deduplicate by filename (keep larger file)
deduplicated_files = self._deduplicate_files(all_files)
# Log selected files
print(f"\nAfter deduplication: {len(deduplicated_files)} unique file(s) selected")
for file_path in deduplicated_files:
self.file_discovery_logger.add_selected_file(file_path)
# Finalize and write log
self.file_discovery_logger.finalize_and_write()
print(f"File discovery log: {self.file_discovery_logger.get_log_file()}")
print()
return deduplicated_files
def _deduplicate_files(self, files: List[Path]) -> List[Path]:
"""
Deduplicate files by name, keeping the larger file.
Args:
files: List of file paths
Returns:
Deduplicated list of file paths
"""
# Group files by name
files_by_name = defaultdict(list)
for file_path in files:
files_by_name[file_path.name].append(file_path)
# Select one file per name (largest)
selected_files = []
for filename, file_list in files_by_name.items():
if len(file_list) == 1:
# No duplicates, just add it
selected_files.append(file_list[0])
else:
# Multiple files with same name, keep largest
largest_file = max(file_list, key=lambda f: f.stat().st_size)
selected_files.append(largest_file)
# Log the duplicate set
self.file_discovery_logger.add_duplicate_set(
files=file_list,
selected_file=largest_file,
reason=f"Largest file ({largest_file.stat().st_size} bytes)"
)
# Print warning about duplicates
print(f"\n⚠ Found {len(file_list)} copies of '{filename}':")
for f in file_list:
marker = "✓ SELECTED" if f == largest_file else " skipped"
print(f" {marker}: {f} ({f.stat().st_size / (1024*1024):.2f} MB)")
return sorted(selected_files)
def discover_files_from_manifest(self, experiment_dir: Path) -> List[Path]:
"""
Discover files by reading the experiment directory's manifest.json.
Args:
experiment_dir: Path to the experiment directory containing manifest.json
Returns:
List of file paths that exist on disk
Raises:
ProcessorError: If no manifest-listed files exist on disk
"""
import json
import logging
from .exceptions import ProcessorError
logger = logging.getLogger(__name__)
manifest_path = experiment_dir / 'manifest.json'
if not manifest_path.exists():
raise ProcessorError(
f"No manifest.json found in {experiment_dir}. "
f"Run scripts/migrate_raw_data.py first."
)
manifest = json.loads(manifest_path.read_text())
found = []
missing = []
for entry in manifest.get('files', []):
file_path = experiment_dir / entry['filename']
if file_path.exists():
found.append(file_path)
else:
missing.append(entry['filename'])
logger.warning(f"Manifest-listed file not found: {file_path}")
if missing:
logger.warning(
f"{len(missing)}/{len(manifest['files'])} manifest files missing "
f"in {experiment_dir}"
)
if not found:
raise ProcessorError(
f"No manifest-listed files found in {experiment_dir}. "
f"Run scripts/download_data.py to fetch the data."
)
return sorted(found)
def _read_and_clean_text(
self,
file_path: Path,
use_delimiter_cleaner: bool = True
) -> str:
"""
Read a file and clean its encoding and delimiters.
This is the unit of work for parallel batch cleaning.
Args:
file_path: Path to the raw data file
use_delimiter_cleaner: Whether to apply delimiter standardization
Returns:
Cleaned UTF-8 text string
"""
# Step 1: encoding clean (detect + decode + mojibake fix)
text = self.encoding_cleaner.clean(file_path)
# Step 2: optional delimiter standardization
if use_delimiter_cleaner and hasattr(self, 'delimiter_cleaner'):
text = self.delimiter_cleaner.clean(text, file_path=str(file_path))
return text
def _batch_clean_files(
self,
files: List[Path],
use_delimiter_cleaner: bool = True,
max_workers: Optional[int] = None
) -> Dict[Path, str]:
"""
Clean all files in parallel using ThreadPoolExecutor.
Encoding detection (chardet) and file I/O release the GIL,
making threads effective here.
Args:
files: List of file paths to clean
use_delimiter_cleaner: Whether to apply delimiter standardization
max_workers: Max threads (defaults to min(8, len(files)))
Returns:
Dict mapping file path to cleaned text. Failed files are excluded.
"""
from concurrent.futures import ThreadPoolExecutor, as_completed
if not files:
return {}
if max_workers is None:
max_workers = min(8, len(files))
results: Dict[Path, str] = {}
def clean_one(file_path: Path) -> tuple:
try:
text = self._read_and_clean_text(file_path, use_delimiter_cleaner)
return (file_path, text, None)
except Exception as e:
return (file_path, None, e)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(clean_one, f): f for f in files}
try:
from tqdm import tqdm
iterator = tqdm(
as_completed(futures),
total=len(futures),
desc="Cleaning files"
)
except ImportError:
iterator = as_completed(futures)
for future in iterator:
file_path, text, error = future.result()
if error is not None:
self.errata_logger.log_error(
'batch_clean_failed',
f'Failed to clean file: {error}',
file_path=str(file_path),
scope='file'
)
else:
results[file_path] = text
return results
class BaseProfiler(ABC):
"""
Abstract base class for file profilers.
Profilers analyze files to detect format characteristics
such as encoding, delimiters, and schema.
"""
def __init__(self, config: Config):
"""
Initialize profiler with configuration.
Args:
config: Configuration object
"""
self.config = config
@abstractmethod
def profile(self, file_path: str | Path) -> Dict[str, Any]:
"""
Profile a file to detect its characteristics.
Args:
file_path: Path to file to profile
Returns:
Dictionary with profile information
"""
pass
class BaseExporter(ABC):
"""
Abstract base class for data exporters.
Exporters handle writing cleaned data to various formats
(HDF5, Parquet, CSV).
"""
def __init__(self, config: Config):
"""
Initialize exporter with configuration.
Args:
config: Configuration object
"""
self.config = config
@abstractmethod
def export(self, data: pd.DataFrame, output_path: str | Path, **kwargs) -> None:
"""
Export data to output file.
Args:
data: DataFrame to export
output_path: Output file path
**kwargs: Format-specific parameters
"""
pass
class BaseQualityAssessor(ABC):
"""
Abstract base class for data quality assessment.
Quality assessors analyze cleaned data and compute
quality scores and metrics.
"""
def __init__(self, config: Config):
"""
Initialize quality assessor with configuration.
Args:
config: Configuration object
"""
self.config = config
@abstractmethod
def assess(self, data: pd.DataFrame) -> Dict[str, Any]:
"""
Assess data quality and compute metrics.
Args:
data: DataFrame to assess
Returns:
Dictionary with quality metrics
"""
pass
@abstractmethod
def compute_quality_score(self, metrics: Dict[str, Any]) -> float:
"""
Compute overall quality score from metrics.
Args:
metrics: Quality metrics dictionary
Returns:
Quality score (0-10)
"""
pass |