""" CardS (Sequential Card Test) dataset processor. Processes ESP sequential card finding test data with mixed row types: - Step rows: 4 columns (user_id, trial, response, timestamp) - Completion rows: 7 columns (user_id, trial, steps, response_array, target_image, timestamp) """ 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 CardSProcessor(BaseProcessor): """ Processes CardS (Sequential Card Test) data. Format: Mixed row types in same file - Step rows: user clicks on a card position (1-5) - Completion rows: trial finished, contains full response sequence """ BATCH_DELIMITER_CLEAN = False # mixed row formats (4 and 11 columns), no delimiter standardization # File discovery patterns FILE_PATTERNS = ['cardS*.dat'] # Column definitions for different row types COLUMNS_STEP = [ 'user_id', 'trial', 'response', 'timestamp' ] COLUMNS_COMPLETION = [ 'user_id', 'trial', 'steps', 'response_array', 'target_image', 'timestamp' ] # Unified output schema COLUMNS_UNIFIED = [ 'user_id', 'trial', 'row_type', 'response', 'steps', 'response_array', 'target_image', 'timestamp', 'file_date', 'source_file', 'source_row_number' ] def __init__(self, config: Config): """ Initialize CardS processor. Args: config: Configuration object """ super().__init__(config, 'cards') # 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_step': 0, 'rows_completion': 0, 'rows_valid': 0, 'rows_invalid': 0 } def extract_file_date(self, file_path: Path) -> Optional[datetime]: """ Extract date from filename (cardSYYMMDD.dat). Args: file_path: Path to file Returns: datetime object or None """ match = re.search(r'cardS(\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 parse_trial_number(self, trial_str: str) -> int: """ Parse trial number, removing '.' suffix if present. The '.' suffix indicates the first step of a trial. Args: trial_str: Trial string (e.g., "1.", "8.", "5") Returns: Integer trial number """ # Remove trailing '.' if present trial_clean = str(trial_str).rstrip('.') try: return int(trial_clean) except ValueError: return None def detect_row_type(self, row: pd.Series) -> str: """ Detect if row is a step or completion based on column count. Args: row: DataFrame row Returns: 'step' or 'completion' """ # Count non-null columns col_count = row.notna().sum() if col_count >= 6: # Completion rows have 6-7 columns return 'completion' else: # Step rows have 4 columns return 'step' def parse_response_array(self, array_str: str) -> List[int]: """ Parse comma-separated response array. Args: array_str: String like "0,4,5,3,2,0" Returns: List of integers """ if pd.isna(array_str) or not array_str: return [] try: return [int(x.strip()) for x in str(array_str).split(',')] except (ValueError, AttributeError): return [] def process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: """ Process a single CardS 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) # DON'T use delimiter cleaner - CardS has mixed row formats (4 and 11 columns) # which causes pandas to skip the 11-column rows as "bad lines" # Parse manually to handle variable column counts (4 vs 11) # Pandas read_csv skips rows with different column counts from io import StringIO import csv reader = csv.reader(StringIO(text), skipinitialspace=True) rows = list(reader) if not rows: self.errata_logger.log_error( 'empty_file', 'File is empty after CSV parsing - entire file omitted', file_path=str(file_path), scope='file' ) return None # Convert to DataFrame with max columns df = pd.DataFrame(rows) 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 row types based on column count # Step rows: user, trial, response, timestamp (4 columns) # Completion rows: user, trial, steps, [array values 0-5], image, timestamp (11 columns) # The response_array like "0,2,1,0,0,0" gets split into 6 separate columns file_date = self.extract_file_date(file_path) col_counts = df.notna().sum(axis=1) is_step = col_counts == 4 # Step rows have exactly 4 columns is_completion = col_counts >= 10 # Completion rows have 10-11 columns # Count row types self.stats['rows_step'] += is_step.sum() self.stats['rows_completion'] += is_completion.sum() # Create unified DataFrame result_df = pd.DataFrame(index=df.index) # Common columns for all rows result_df['user_id'] = df.iloc[:, 0] result_df['file_date'] = file_date # Add audit columns (source file and row numbers) result_df['source_file'] = file_path.name result_df['source_row_number'] = range(1, len(result_df) + 1) # Parse trial numbers (vectorized) - remove '.' suffix result_df['trial'] = df.iloc[:, 1].astype(str).str.rstrip('.').astype(float) # Process step rows (4 columns: user, trial, response, timestamp) result_df.loc[is_step, 'row_type'] = 'step' result_df.loc[is_step, 'response'] = df.loc[is_step].iloc[:, 2] result_df.loc[is_step, 'steps'] = None result_df.loc[is_step, 'response_array'] = None result_df.loc[is_step, 'target_image'] = None # Process completion rows (11 columns: user, trial, steps, arr0-arr5, image, timestamp) # Recombine the 6 array values back into comma-separated string result_df.loc[is_completion, 'row_type'] = 'completion' result_df.loc[is_completion, 'response'] = None result_df.loc[is_completion, 'steps'] = df.loc[is_completion].iloc[:, 2] # Recombine columns 3-8 into response_array (vectorized) if is_completion.any(): comp_df = df.loc[is_completion] result_df.loc[is_completion, 'response_array'] = ( comp_df.iloc[:, 3].astype(str) + ',' + comp_df.iloc[:, 4].astype(str) + ',' + comp_df.iloc[:, 5].astype(str) + ',' + comp_df.iloc[:, 6].astype(str) + ',' + comp_df.iloc[:, 7].astype(str) + ',' + comp_df.iloc[:, 8].astype(str) ) result_df.loc[is_completion, 'target_image'] = comp_df.iloc[:, 9].values # Parse timestamps: build a single raw series, parse once to avoid # tz-aware dtype conflicts from partial .loc assignments raw_ts = pd.Series(index=df.index, dtype='object') if is_step.any(): raw_ts.loc[is_step] = df.loc[is_step].iloc[:, 3].values if is_completion.any(): raw_ts.loc[is_completion] = df.loc[is_completion].iloc[:, 10].values result_df['timestamp'] = self.temporal_parser.parse_dates_vectorized( raw_ts, file_path=str(file_path) ) # Validate and clean result_df = self.validate_dataframe(result_df, file_path) # Ensure all unified columns exist for col in self.COLUMNS_UNIFIED: if col not in result_df.columns: result_df[col] = None # Reorder to unified schema result_df = result_df[self.COLUMNS_UNIFIED] self.stats['files_processed'] += 1 self.stats['rows_valid'] += len(result_df) return result_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) # Validate user_id length if 'user_id' in df.columns: 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 response range (1-5) for step rows if 'response' in df.columns: df['response'] = self.to_numeric_logged(df['response'], 'response', str(file_path)) step_rows = df['row_type'] == 'step' invalid_response = step_rows & ((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 (must be >= 1) if 'trial' in df.columns: df['trial'] = self.to_numeric_logged(df['trial'], 'trial', str(file_path)) invalid_trial = (df['trial'] < 1) if invalid_trial.any(): valid_mask &= ~invalid_trial self.errata_logger.log_error( 'trial_number_invalid', f'{invalid_trial.sum()} rows with trial < 1', file_path=str(file_path), scope='row' ) # Validate steps (1-5) for completion rows if 'steps' in df.columns: df['steps'] = self.to_numeric_logged(df['steps'], 'steps', str(file_path)) completion_rows = df['row_type'] == 'completion' invalid_steps = completion_rows & ((df['steps'] < 1) | (df['steps'] > 5)) if invalid_steps.any(): valid_mask &= ~invalid_steps self.errata_logger.log_error( 'steps_out_of_range', f'{invalid_steps.sum()} rows with steps not in 1-5', file_path=str(file_path), scope='row' ) # Convert numeric columns numeric_cols = ['trial', 'response', 'steps'] 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()