| """ |
| RVQ (Quick Remote Viewing) dataset processor. |
| |
| Processes quick remote viewing test data with 5-choice image selection. |
| Format: 14-15 columns with user, timestamp, trial info, target/response, and 5 image filenames. |
| |
| Very similar to Card test but with 5 images instead of 1 target image. |
| """ |
|
|
| 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 RVQProcessor(BaseProcessor): |
| """ |
| Processes RVQ (Quick Remote Viewing) data. |
| |
| Format: 14-15 columns (15 with trailing comma) |
| - user_id, timestamp, condition, unused, trial_number, is_hit, cumulative_hits, |
| - target (1-5), response (1-5), image_0, image_1, image_2, image_3, image_4 |
| |
| User sees 5 images and selects which one is the target. |
| Similar to Card test but with images instead of abstract cards. |
| """ |
|
|
| |
| FILE_PATTERNS = ['rvq[0-9]*.dat'] |
|
|
| |
| COLUMNS = [ |
| 'user_id', 'timestamp', 'condition', 'unused', 'trial_number', |
| 'is_hit', 'cumulative_hits', 'target', 'response', |
| 'image_0', 'image_1', 'image_2', 'image_3', 'image_4' |
| ] |
|
|
| COLUMNS_UNIFIED = [ |
| 'user_id', 'timestamp', 'condition', 'trial_number', |
| 'is_hit', 'cumulative_hits', 'target', 'response', |
| 'image_0', 'image_1', 'image_2', 'image_3', 'image_4', |
| 'file_date', 'source_file', 'source_row_number' |
| ] |
|
|
| def __init__(self, config: Config): |
| """ |
| Initialize RVQ processor. |
| |
| Args: |
| config: Configuration object |
| """ |
| super().__init__(config, 'rvq') |
|
|
| |
| 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 |
| } |
|
|
| def extract_file_date(self, file_path: Path) -> Optional[datetime]: |
| """ |
| Extract date from filename (rvqYYMMDD.dat). |
| |
| Args: |
| file_path: Path to file |
| |
| Returns: |
| datetime object or None |
| """ |
| match = re.search(r'rvq(\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 process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: |
| """ |
| Process a single RVQ 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 |
|
|
| column_count = len(df.columns) |
|
|
| |
| if column_count == 15: |
| |
| |
| col_15_data = df.iloc[:, -1].astype(str).str.strip() |
| empty_count = (col_15_data.isna() | (col_15_data == '')).sum() |
| empty_ratio = empty_count / len(df) if len(df) > 0 else 0 |
|
|
| if empty_ratio >= 0.95: |
| df = df.iloc[:, :-1] |
| column_count = 14 |
|
|
| |
| if column_count == 14: |
| df.columns = self.COLUMNS |
| 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 |
|
|
| |
| file_date = self.extract_file_date(file_path) |
| df['file_date'] = file_date |
|
|
| |
| df['source_file'] = file_path.name |
| df['source_row_number'] = range(1, len(df) + 1) |
|
|
| |
| |
| |
| |
|
|
| |
| if 'unused' in df.columns: |
| df = df.drop(columns=['unused']) |
|
|
| |
| 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()}, |
| ) |
| 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) |
|
|
|
|
| |
| 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' |
| ) |
|
|
| |
| if 'target' in df.columns: |
| df['target'] = self.to_numeric_logged(df['target'], 'target', str(file_path)) |
| invalid_target = (df['target'] < 1) | (df['target'] > 5) |
| if invalid_target.any(): |
| valid_mask &= ~invalid_target |
| self.errata_logger.log_error( |
| 'target_out_of_range', |
| f'{invalid_target.sum()} rows with target not in 1-5', |
| file_path=str(file_path), |
| scope='row' |
| ) |
|
|
| |
| 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' |
| ) |
|
|
| |
| 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' |
| ) |
|
|
| |
| 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' |
| ) |
|
|
| |
| |
| if 'is_hit' in df.columns and 'cumulative_hits' in df.columns: |
| df['is_hit'] = self.to_numeric_logged(df['is_hit'], 'is_hit', str(file_path)) |
| 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' |
| ) |
|
|
| |
| if 'is_hit' in df.columns and 'target' in df.columns and 'response' in df.columns: |
| calculated_hit = (df['target'] == df['response']).astype(int) |
| hit_mismatch = df['is_hit'] != calculated_hit |
| if hit_mismatch.any(): |
| |
| self.errata_logger.log_error( |
| 'hit_calculation_mismatch', |
| f'{hit_mismatch.sum()} rows where is_hit field does not match target==response', |
| file_path=str(file_path), |
| scope='row' |
| ) |
| |
| df['is_hit'] = calculated_hit |
|
|
| |
| if 'timestamp' in df.columns: |
| df['timestamp'] = self.temporal_parser.parse_dates_vectorized( |
| df['timestamp'], file_path=str(file_path) |
| ) |
|
|
| |
| numeric_cols = [ |
| 'condition', 'trial_number', 'is_hit', 'cumulative_hits', |
| 'target', 'response' |
| ] |
|
|
| 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() |
|
|