| """ |
| CardD (Card Draw Test) dataset processor. |
| |
| Processes ESP card drawing test data with two schema versions: |
| - Old format (pre 2006-06-22): 14-15 columns, combined Markov bits |
| - New format (post 2006-06-22): 15-16 columns, separate Markov bits, optional image_filename |
| """ |
|
|
| from pathlib import Path |
| from typing import List, Dict, Any, Optional |
| from datetime import datetime |
| import pandas as pd |
| import re |
|
|
| from ..core.base_classes import BaseProcessor |
| from ..core.config import Config |
| from ..core.exceptions import ProcessorError |
| from ..cleaners.encoding_cleaner import EncodingCleaner |
| from ..cleaners.delimiter_cleaner import DelimiterCleaner |
| from ..cleaners.temporal_parser import TemporalParser |
|
|
|
|
| class CardDProcessor(BaseProcessor): |
| """ |
| Processes CardD (Card Draw Test) data. |
| |
| Schema versions: |
| - v1 (pre 2006-06-22): Markov bits combined in single 32-bit word |
| - v2 (post 2006-06-22): Markov bits in separate words |
| """ |
|
|
| |
| FILE_PATTERNS = ['cardD*.dat'] |
|
|
| |
| SCHEMA_CHANGE_DATE = datetime(2006, 6, 22) |
|
|
| |
| COLUMNS_OLD = [ |
| 'user_id', 'target_bit', 'cards_done', 'cards_hit', |
| 'markov_stages', 'markov_output', 'markov_prob', |
| 'markov_bits_combined', |
| 'card_number', 'is_hit', 'run_hits', 'trial_number', |
| 'timestamp', 'target_image', 'extra' |
| ] |
|
|
| COLUMNS_NEW = [ |
| 'user_id', 'target_bit', 'cards_done', 'cards_hit', |
| 'markov_stages', 'markov_output', 'markov_prob', |
| 'markov_bits_main', 'markov_bits_aux', |
| 'card_number', 'is_hit', 'run_hits', 'trial_number', |
| 'timestamp', 'image_filename', 'target_image', 'extra' |
| ] |
|
|
| COLUMNS_UNIFIED = [ |
| 'user_id', 'target_bit', 'cards_done', 'cards_hit', |
| 'markov_stages', 'markov_output', 'markov_prob', |
| 'markov_bits_main', 'markov_bits_aux', |
| 'card_number', 'is_hit', 'run_hits', 'trial_number', |
| 'timestamp', 'image_filename', 'target_image', |
| 'file_date', 'schema_version', 'source_file', 'source_row_number' |
| ] |
|
|
| def __init__(self, config: Config): |
| """ |
| Initialize CardD processor. |
| |
| Args: |
| config: Configuration object |
| """ |
| super().__init__(config, 'cardd') |
|
|
| |
| self.encoding_cleaner = EncodingCleaner(config, self.errata_logger) |
| self.delimiter_cleaner = DelimiterCleaner(config, self.errata_logger) |
| self.temporal_parser = TemporalParser(config, self.errata_logger) |
|
|
| |
| self.stats = { |
| 'files_processed': 0, |
| 'files_failed': 0, |
| 'rows_total': 0, |
| 'rows_valid': 0, |
| 'rows_invalid': 0, |
| 'schema_v1_files': 0, |
| 'schema_v2_files': 0 |
| } |
|
|
| def extract_file_date(self, file_path: Path) -> Optional[datetime]: |
| """ |
| Extract date from filename (cardDYYMMDD.dat). |
| |
| Args: |
| file_path: Path to file |
| |
| Returns: |
| datetime object or None |
| """ |
| match = re.search(r'cardD(\d{6})\.dat', file_path.name) |
| if not match: |
| return None |
|
|
| date_str = match.group(1) |
| return self.temporal_parser.extract_date_from_filename(file_path.name) |
|
|
| def detect_schema_version(self, file_path: Path, df: pd.DataFrame) -> tuple: |
| """ |
| Detect schema version based on file date and column count distribution. |
| |
| Checks first, middle, and last rows to detect mixed schemas. |
| |
| Args: |
| file_path: Path to file |
| df: DataFrame with raw data (no headers) |
| |
| Returns: |
| Tuple of (primary_version, is_mixed) |
| - primary_version: 'v1' or 'v2' |
| - is_mixed: True if file contains both schemas |
| """ |
| file_date = self.extract_file_date(file_path) |
|
|
| |
| schema_change_aware = self.temporal_parser.timezone.localize(self.SCHEMA_CHANGE_DATE) |
|
|
| |
| sample_indices = [0, len(df) // 2, len(df) - 1] if len(df) > 2 else [0] |
| column_counts = [] |
|
|
| for idx in sample_indices: |
| if idx < len(df): |
| |
| col_count = df.iloc[idx].notna().sum() |
| column_counts.append(col_count) |
|
|
| unique_counts = set(column_counts) |
| is_mixed = len(unique_counts) > 1 |
|
|
| |
| max_col_count = max(column_counts) |
|
|
| if file_date and file_date >= schema_change_aware: |
| primary_version = 'v2' |
| elif max_col_count >= 15: |
| primary_version = 'v2' |
| else: |
| primary_version = 'v1' |
|
|
| return primary_version, is_mixed |
|
|
| def unpack_markov_bits_old(self, combined: int, n_stages: int) -> tuple: |
| """ |
| Unpack combined Markov bits (old format). |
| |
| In old format, both main and aux chains stored in one 32-bit word: |
| - Main chain: lower n_stages bits |
| - Aux chain: next n_stages bits |
| |
| Args: |
| combined: Combined 32-bit value |
| n_stages: Number of Markov stages |
| |
| Returns: |
| Tuple of (main_bits, aux_bits) |
| """ |
| mask = (1 << n_stages) - 1 |
| main_bits = combined & mask |
| aux_bits = (combined >> n_stages) & mask |
| return main_bits, aux_bits |
|
|
| def _process_mixed_schema_file(self, df: pd.DataFrame, file_path: Path) -> Optional[pd.DataFrame]: |
| """ |
| Process a file with mixed schema versions (row-by-row). |
| |
| Args: |
| df: Raw DataFrame with no headers |
| file_path: Source file path |
| |
| Returns: |
| Processed DataFrame or None |
| """ |
| processed_rows = [] |
| file_date = self.extract_file_date(file_path) |
|
|
| for idx, row in df.iterrows(): |
| try: |
| |
| col_count = row.notna().sum() |
|
|
| |
| if col_count >= 15: |
| |
| schema = 'v2' |
| columns = self.COLUMNS_NEW[:col_count] |
| elif col_count >= 14: |
| |
| schema = 'v1' |
| columns = self.COLUMNS_OLD[:col_count] |
| else: |
| |
| continue |
|
|
| |
| row_dict = {} |
| for i, col_name in enumerate(columns): |
| if i < len(row): |
| row_dict[col_name] = row.iloc[i] |
|
|
| |
| if schema == 'v1' and 'markov_bits_combined' in row_dict: |
| try: |
| n_stages = int(row_dict.get('markov_stages', 0)) |
| combined = int(row_dict['markov_bits_combined']) |
| main_bits, aux_bits = self.unpack_markov_bits_old(combined, n_stages) |
| row_dict['markov_bits_main'] = main_bits |
| row_dict['markov_bits_aux'] = aux_bits |
| del row_dict['markov_bits_combined'] |
| except (ValueError, TypeError): |
| |
| continue |
|
|
| |
| row_dict['file_date'] = file_date |
| row_dict['schema_version'] = schema |
|
|
| |
| row_dict['source_file'] = file_path.name |
| row_dict['source_row_number'] = idx + 1 |
|
|
| |
| if 'extra' in row_dict: |
| del row_dict['extra'] |
|
|
| processed_rows.append(row_dict) |
|
|
| except Exception as e: |
| import traceback |
| self.errata_logger.log_error( |
| 'row_processing_failed', |
| f'Row {idx}: {type(e).__name__}: {e}', |
| file_path=str(file_path), |
| scope='row', |
| line_number=idx, |
| context={'traceback': traceback.format_exc()}, |
| ) |
| continue |
|
|
| if not processed_rows: |
| return None |
|
|
| |
| result_df = pd.DataFrame(processed_rows) |
|
|
| |
| result_df = self.validate_dataframe(result_df, file_path) |
|
|
| |
| for col in self.COLUMNS_UNIFIED: |
| if col not in result_df.columns: |
| result_df[col] = None |
|
|
| |
| result_df = result_df[self.COLUMNS_UNIFIED] |
|
|
| return result_df |
|
|
| def process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: |
| """ |
| Process a single CardD file. |
| |
| Args: |
| file_path: Path to file |
| pre_cleaned_text: Pre-cleaned text from parallel batch cleaning. |
| If None, cleans the file inline (backward compat). |
| |
| Returns: |
| DataFrame or None if processing fails |
| """ |
| try: |
| |
| if pre_cleaned_text is not None: |
| text = pre_cleaned_text |
| else: |
| text = self.encoding_cleaner.clean(file_path) |
| text = self.delimiter_cleaner.clean(text, file_path=str(file_path)) |
|
|
| |
| text = self.pre_validate_csv_lines(text, file_path=str(file_path)) |
|
|
| from io import BytesIO |
| df = pd.read_csv(BytesIO(text.encode('utf-8')), header=None, on_bad_lines='skip', engine='pyarrow') |
|
|
| if df.empty: |
| self.errata_logger.log_error( |
| 'empty_file', |
| 'File is empty or has no valid rows - entire file omitted', |
| file_path=str(file_path), |
| scope='file' |
| ) |
| return None |
|
|
| |
| schema_version, is_mixed = self.detect_schema_version(file_path, df) |
|
|
| if is_mixed: |
| self.errata_logger.log_error( |
| 'mixed_schema_detected', |
| f'File contains mixed schema versions (v1 and v2)', |
| file_path=str(file_path), |
| scope='row' |
| ) |
| |
| return self._process_mixed_schema_file(df, file_path) |
|
|
| |
| column_count = len(df.columns) |
|
|
| |
| if schema_version == 'v1': |
| if column_count >= 14: |
| df.columns = self.COLUMNS_OLD[:column_count] |
| self.stats['schema_v1_files'] += 1 |
| else: |
| self.errata_logger.log_error( |
| 'insufficient_columns', |
| f'Too few columns: {column_count} - entire file omitted', |
| file_path=str(file_path), |
| scope='file' |
| ) |
| return None |
| else: |
| if column_count >= 15: |
| df.columns = self.COLUMNS_NEW[:column_count] |
| self.stats['schema_v2_files'] += 1 |
| else: |
| self.errata_logger.log_error( |
| 'insufficient_columns', |
| f'Too few columns: {column_count} - entire file omitted', |
| file_path=str(file_path), |
| scope='file' |
| ) |
| return None |
|
|
| |
| if schema_version == 'v1' and 'markov_bits_combined' in df.columns: |
| df[['markov_bits_main', 'markov_bits_aux']] = df.apply( |
| lambda row: pd.Series( |
| self.unpack_markov_bits_old( |
| row['markov_bits_combined'], |
| row['markov_stages'] |
| ) |
| ), |
| axis=1 |
| ) |
| df = df.drop(columns=['markov_bits_combined']) |
|
|
| |
| file_date = self.extract_file_date(file_path) |
| df['file_date'] = file_date |
| df['schema_version'] = schema_version |
|
|
| |
| df['source_file'] = file_path.name |
| df['source_row_number'] = range(1, len(df) + 1) |
|
|
| |
| if 'extra' in df.columns: |
| df = df.drop(columns=['extra']) |
|
|
| |
| df = self.validate_dataframe(df, file_path) |
|
|
| |
| for col in self.COLUMNS_UNIFIED: |
| if col not in df.columns: |
| df[col] = None |
|
|
| |
| df = df[self.COLUMNS_UNIFIED] |
|
|
| self.stats['files_processed'] += 1 |
| self.stats['rows_valid'] += len(df) |
| return df |
|
|
| except Exception as e: |
| import traceback |
| self.errata_logger.log_error( |
| 'file_processing_failed', |
| f'{type(e).__name__}: {e} - entire file omitted', |
| file_path=str(file_path), |
| scope='file', |
| context={'traceback': traceback.format_exc()}, |
| ) |
| return None |
|
|
| def validate_dataframe(self, df: pd.DataFrame, file_path: Path) -> pd.DataFrame: |
| """ |
| Validate and clean DataFrame. |
| |
| Args: |
| df: Input DataFrame |
| file_path: Source file path |
| |
| Returns: |
| Cleaned DataFrame |
| """ |
| initial_count = len(df) |
| valid_mask = pd.Series([True] * len(df), index=df.index) |
|
|
|
|
| |
| long_users = df['user_id'].str.len() > 64 |
| if long_users.any(): |
| valid_mask &= ~long_users |
| self.errata_logger.log_error( |
| 'user_id_too_long', |
| f'{long_users.sum()} rows with user_id > 64 chars', |
| file_path=str(file_path), |
| scope='row' |
| ) |
|
|
| |
| if 'card_number' in df.columns: |
| df['card_number'] = self.to_numeric_logged(df['card_number'], 'card_number', str(file_path)) |
| invalid_card = (df['card_number'] < 0) | (df['card_number'] > 4) |
| if invalid_card.any(): |
| valid_mask &= ~invalid_card |
| self.errata_logger.log_error( |
| 'card_number_out_of_range', |
| f'{invalid_card.sum()} rows with card_number not in 0-4', |
| file_path=str(file_path), |
| scope='row' |
| ) |
|
|
| |
| if 'trial_number' in df.columns: |
| df['trial_number'] = self.to_numeric_logged(df['trial_number'], 'trial_number', str(file_path)) |
| invalid_trial = (df['trial_number'] < 1) |
| if invalid_trial.any(): |
| valid_mask &= ~invalid_trial |
| self.errata_logger.log_error( |
| 'trial_number_invalid', |
| f'{invalid_trial.sum()} rows with trial_number < 1', |
| file_path=str(file_path), |
| scope='row' |
| ) |
|
|
| |
| for col in ['cards_done', 'cards_hit']: |
| if col in df.columns: |
| df[col] = self.to_numeric_logged(df[col], col, str(file_path)) |
| invalid = (df[col] < 0) | (df[col] > 5) |
| if invalid.any(): |
| valid_mask &= ~invalid |
|
|
| |
| if 'timestamp' in df.columns: |
| df['timestamp'] = self.temporal_parser.parse_dates_vectorized( |
| df['timestamp'], file_path=str(file_path) |
| ) |
|
|
| |
| numeric_cols = [ |
| 'target_bit', 'cards_done', 'cards_hit', 'markov_stages', |
| 'markov_output', 'markov_prob', 'markov_bits_main', 'markov_bits_aux', |
| 'card_number', 'is_hit', 'run_hits', 'trial_number' |
| ] |
|
|
| for col in numeric_cols: |
| if col in df.columns: |
| df[col] = self.to_numeric_logged(df[col], col, str(file_path)) |
|
|
| |
| df_valid = df[valid_mask].copy() |
|
|
| invalid_count = initial_count - len(df_valid) |
| if invalid_count > 0: |
| self.errata_logger.log_file_summary( |
| str(file_path), |
| 'partial', |
| initial_count, |
| len(df_valid), |
| invalid_count |
| ) |
|
|
| return df_valid |
|
|
| def get_stats(self) -> Dict[str, Any]: |
| """Get processing statistics.""" |
| return self.stats.copy() |