""" Card (Basic Card Test) dataset processor. Processes ESP basic card guessing test data with two schema versions: - Old format (pre 2006-01-10): 14-15 columns, uses seed2 instead of trperrun - New format (post 2006-01-10): 14-15 columns, uses trperrun parameter The Card test is a simple 1-in-5 ESP card guessing test with bias influence. User sees 5 face-down cards and selects one, trying to find the hidden target. """ 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 CardProcessor(BaseProcessor): """ Processes Card (Basic Card Test) data. Schema versions: - v1 (pre 2006-01-10): Uses seed2 in column 3 - v2 (post 2006-01-10): Uses trperrun in column 3 Format: 14-15 columns - user_id, condition, seed1, seed2/trperrun, x, y, bias, - (unused), target1, target2, response, cumulative_hits, - trial_number, timestamp, [target_image] """ # Schema change date (from Perl comment: "beginning 1/10/06") SCHEMA_CHANGE_DATE = datetime(2006, 1, 10) # Column definitions for both schemas # Actual format from data inspection and Perl code line 28: # ($trpr, $tar, $res, $nhit, $trn, $tim) = @l[3, 8, 9, 10, 11, 12] # Columns: user, condition, seed1, seed2/trperrun, x, y, bias, # ?, target2, response, cumulative_hits, trial_number, timestamp, image # Note: target1 appears to be in column 7 based on data COLUMNS_OLD = [ 'user_id', 'condition', 'seed1', 'seed2', 'x', 'y', 'bias', 'target1', 'target2', 'response', 'cumulative_hits', 'trial_number', 'timestamp', 'target_image' ] COLUMNS_NEW = [ 'user_id', 'condition', 'seed1', 'trperrun', 'x', 'y', 'bias', 'target1', 'target2', 'response', 'cumulative_hits', 'trial_number', 'timestamp', 'target_image' ] COLUMNS_UNIFIED = [ 'user_id', 'condition', 'seed1', 'trperrun', 'x', 'y', 'bias', 'target1', 'target2', 'response', 'cumulative_hits', 'trial_number', 'is_hit', 'timestamp', 'target_image', 'file_date', 'schema_version', 'source_file', 'source_row_number' ] # File discovery patterns FILE_PATTERNS = ['card[0-9]*.dat'] # Known cheaters to filter (from Perl code line 45) KNOWN_CHEATERS = {'241758', 'hodedo', '857142', '142857'} def __init__(self, config: Config): """ Initialize Card processor. Args: config: Configuration object """ super().__init__(config, 'card') # Initialize cleaners self.encoding_cleaner = EncodingCleaner(config, self.errata_logger) self.delimiter_cleaner = DelimiterCleaner(config, self.errata_logger) self.temporal_parser = TemporalParser(config, self.errata_logger) # Statistics self.stats = { 'files_processed': 0, 'files_failed': 0, 'rows_total': 0, 'rows_valid': 0, 'rows_invalid': 0, 'rows_cheaters_filtered': 0, 'schema_v1_files': 0, 'schema_v2_files': 0 } def extract_file_date(self, file_path: Path) -> Optional[datetime]: """ Extract date from filename (cardYYMMDD.dat). Args: file_path: Path to file Returns: datetime object or None """ match = re.search(r'card(\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) -> str: """ Detect schema version based on file date. Args: file_path: Path to file Returns: 'v1' or 'v2' """ file_date = self.extract_file_date(file_path) if not file_date: return 'v2' # Default to newer format # Make schema change date timezone-aware for comparison schema_change_aware = self.temporal_parser.timezone.localize(self.SCHEMA_CHANGE_DATE) if file_date >= schema_change_aware: return 'v2' else: return 'v1' def is_cheater_in_2001(self, user_id: str, timestamp_str: str) -> bool: """ Check if user is a known cheater from 2001. Implements Perl logic: if ($l[12]=~/2001/ && ($user eq "...")) Args: user_id: User identifier timestamp_str: Timestamp string Returns: True if known cheater from 2001 """ if user_id not in self.KNOWN_CHEATERS: return False # Check if timestamp contains "2001" return '2001' in str(timestamp_str) def process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: """ Process a single Card 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: # Use pre-cleaned text if available, otherwise clean inline 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)) # Pre-validate lines so bad rows are logged before being removed 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 # Detect schema version schema_version = self.detect_schema_version(file_path) column_count = len(df.columns) # Handle trailing commas that create empty 15th column if column_count == 15: # Drop the last column if it's all empty (trailing comma artifact) if df.iloc[:, -1].isna().all() or (df.iloc[:, -1].astype(str).str.strip() == '').all(): df = df.iloc[:, :-1] column_count = 14 # Assign column names if column_count == 14: if schema_version == 'v1': df.columns = self.COLUMNS_OLD self.stats['schema_v1_files'] += 1 else: df.columns = self.COLUMNS_NEW self.stats['schema_v2_files'] += 1 else: self.errata_logger.log_error( 'insufficient_columns', f'Unexpected column count: {column_count} (expected 14) - entire file omitted', file_path=str(file_path), scope='file' ) return None # Normalize column 3: rename seed2 to trperrun for v1 if schema_version == 'v1' and 'seed2' in df.columns: df = df.rename(columns={'seed2': 'trperrun'}) # Add metadata file_date = self.extract_file_date(file_path) df['file_date'] = file_date df['schema_version'] = schema_version # Add audit columns (source file and row numbers) df['source_file'] = file_path.name df['source_row_number'] = range(1, len(df) + 1) # Calculate is_hit (target2 == response) df['is_hit'] = (df['target2'] == df['response']).astype(int) # Filter known cheaters from 2001 (vectorized) if 'user_id' in df.columns and 'timestamp' in df.columns: is_known_cheater = df['user_id'].astype(str).isin(self.KNOWN_CHEATERS) has_2001 = df['timestamp'].astype(str).str.contains('2001', na=False) cheater_mask = is_known_cheater & has_2001 cheater_count = cheater_mask.sum() if cheater_count > 0: self.stats['rows_cheaters_filtered'] += cheater_count self.errata_logger.log_error( 'known_cheaters_filtered', f'Filtered {cheater_count} rows from known 2001 cheaters', file_path=str(file_path), scope='row' ) df = df[~cheater_mask] # Filter test users test_user_mask = df['user_id'].astype(str).str.startswith('_test99') if test_user_mask.any(): df = df[~test_user_mask] # Validate and clean df = self.validate_dataframe(df, file_path) # Ensure all unified columns exist AFTER validation for col in self.COLUMNS_UNIFIED: if col not in df.columns: df[col] = None # Reorder to unified schema df = df[self.COLUMNS_UNIFIED] # Update stats 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()}, ) self.stats['files_failed'] += 1 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) # Validate user_id length 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' ) # Validate target1 range (1-5) if 'target1' in df.columns: df['target1'] = self.to_numeric_logged(df['target1'], 'target1', str(file_path)) invalid_target1 = (df['target1'] < 1) | (df['target1'] > 5) if invalid_target1.any(): valid_mask &= ~invalid_target1 self.errata_logger.log_error( 'target1_out_of_range', f'{invalid_target1.sum()} rows with target1 not in 1-5', file_path=str(file_path), scope='row' ) # Validate target2 range (1-5) - actual target after bias if 'target2' in df.columns: df['target2'] = self.to_numeric_logged(df['target2'], 'target2', str(file_path)) invalid_target2 = (df['target2'] < 1) | (df['target2'] > 5) if invalid_target2.any(): valid_mask &= ~invalid_target2 self.errata_logger.log_error( 'target2_out_of_range', f'{invalid_target2.sum()} rows with target2 not in 1-5', file_path=str(file_path), scope='row' ) # Validate response range (1-5) if 'response' in df.columns: df['response'] = self.to_numeric_logged(df['response'], 'response', str(file_path)) invalid_response = (df['response'] < 1) | (df['response'] > 5) if invalid_response.any(): valid_mask &= ~invalid_response self.errata_logger.log_error( 'response_out_of_range', f'{invalid_response.sum()} rows with response not in 1-5', file_path=str(file_path), scope='row' ) # Validate trial_number (1-100) 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) | (df['trial_number'] > 100) if invalid_trial.any(): valid_mask &= ~invalid_trial self.errata_logger.log_error( 'trial_number_invalid', f'{invalid_trial.sum()} rows with trial_number not in 1-100', file_path=str(file_path), scope='row' ) # Validate cumulative_hits <= trial_number if 'cumulative_hits' in df.columns and 'trial_number' in df.columns: df['cumulative_hits'] = self.to_numeric_logged(df['cumulative_hits'], 'cumulative_hits', str(file_path)) invalid_hits = df['cumulative_hits'] > df['trial_number'] if invalid_hits.any(): valid_mask &= ~invalid_hits self.errata_logger.log_error( 'cumulative_hits_exceeds_trials', f'{invalid_hits.sum()} rows with cumulative_hits > trial_number', file_path=str(file_path), scope='row' ) # Validate hit logic: if is_hit=1, then cumulative_hits must be >= 1 if 'is_hit' in df.columns and 'cumulative_hits' in df.columns: invalid_hit_logic = (df['is_hit'] == 1) & (df['cumulative_hits'] < 1) if invalid_hit_logic.any(): valid_mask &= ~invalid_hit_logic self.errata_logger.log_error( 'hit_logic_violation', f'{invalid_hit_logic.sum()} rows with is_hit=1 but cumulative_hits < 1', file_path=str(file_path), scope='row' ) # Parse timestamps (vectorized with per-row fallback) if 'timestamp' in df.columns: df['timestamp'] = self.temporal_parser.parse_dates_vectorized( df['timestamp'], file_path=str(file_path) ) # Convert numeric columns numeric_cols = [ 'condition', 'seed1', 'trperrun', 'x', 'y', 'bias', 'target1', 'target2', 'response', 'cumulative_hits', 'trial_number', 'is_hit' ] for col in numeric_cols: if col in df.columns: df[col] = self.to_numeric_logged(df[col], col, str(file_path)) # Filter to valid rows 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()