""" Users dataset processor for Psi survey data. Processes two types of user survey files: 1. users14.dat (2000-2015): Fixed format with variable commas in username/location fields 2. questions.dat (2014-2022): Similar format with email field and different timestamp format Common schema: - Username, Timestamp, Email, City, State, Coordinates, Country - Psi1-15: Psi test responses (15 questions) - Hemi1-10: Hemispheric dominance questions (10 questions) - HowFind: How user found the survey (text field) - na_count_Psi_and_Hemi: Count of NAs in Psi and Hemi columns Data cleaning rules: - Usernames and location fields can contain commas (dirty data before Psi1) - Remove duplicate usernames: keep row with fewest NAs, then prefer oldest date - Column 32 (HowFind) format changed in Sept 2002 from yes/no to descriptive text """ from pathlib import Path from typing import List, Dict, Any, Optional from datetime import datetime import pandas as pd import re import csv from io import StringIO 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 from ..cleaners.location_parser import LocationParser class UsersProcessor(BaseProcessor): """ Processes user survey data from two time periods. Handles: - users14.dat: 2000-2015 data with basic timestamp format - questions.dat: 2014-2022 data with Wed Jan 1 format and email field Both formats have extremely dirty user-entered data before Psi1 column. Username and location fields can contain commas. """ BATCH_DELIMITER_CLEAN = False # dirty comma fields, no delimiter standardization # File discovery patterns FILE_PATTERNS = ['users14*.dat', 'questions*.dat'] # Column definitions for unified schema COLUMNS_UNIFIED = [ 'username', 'timestamp', 'email', 'city', 'state', 'coordinates', 'country' ] + [f'psi_{i:02d}' for i in range(1, 16)] + [ # Psi1-15 f'hemi_{i:02d}' for i in range(1, 11) # Hemi1-10 ] + ['how_find', 'na_count_psi_and_hemi', 'source_file', 'source_row_number', 'file_type'] # Psi and Hemi column names PSI_COLUMNS = [f'psi_{i:02d}' for i in range(1, 16)] HEMI_COLUMNS = [f'hemi_{i:02d}' for i in range(1, 11)] def __init__(self, config: Config): """Initialize Users processor. Args: config: Configuration object """ super().__init__(config, 'users') # 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) self.location_parser = LocationParser(config, self.errata_logger) # Statistics self.stats = { 'files_processed': 0, 'files_failed': 0, 'rows_total': 0, 'rows_valid': 0, 'rows_invalid': 0, 'users14_rows': 0, 'questions_rows': 0, 'duplicates_removed': 0, 'na_usernames_count': 0 } def detect_file_type(self, file_path: Path) -> str: """ Detect whether file is users14 or questions format. Args: file_path: Path to file Returns: 'users14' or 'questions' """ if 'users14' in file_path.name.lower(): return 'users14' elif 'questions' in file_path.name.lower(): return 'questions' else: # Try to detect from first line with open(file_path, 'r', encoding='utf-8', errors='replace') as f: first_line = f.readline() # questions.dat has "Wed Jan" style dates if 'Wed ' in first_line or 'Mon ' in first_line or 'Tue ' in first_line: return 'questions' else: return 'users14' def parse_dirty_csv_line(self, line: str, expected_clean_cols: int = 25) -> tuple: """ Parse CSV line by finding clean numeric data working backwards. Strategy: 1. Split by comma 2. Work backwards to find 25 contiguous numeric columns (Psi1-15, Hemi1-10) 3. Everything before = dirty user data (username, timestamp, location fields) 4. Everything after = HowFind + na_count (for users14 only) The Psi and Hemi columns should only contain values 1-5 or be empty. We use this as an anchor to identify where the clean data starts. Args: line: Raw CSV line expected_clean_cols: Number of expected columns from Psi1 onwards (default 25) Returns: Tuple of (dirty_part, clean_part, tail_part) - dirty_part: List of user-entered fields before Psi1 - clean_part: List of 25 Psi/Hemi columns - tail_part: List of fields after Hemi10 (HowFind, na_count) """ def is_valid_response(val: str) -> bool: """Check if value is valid Psi/Hemi response (1-5 or empty).""" val = val.strip() return val == '' or val in ['1', '2', '3', '4', '5'] # Split by comma parts = line.split(',') # Need at least 25 columns for Psi/Hemi if len(parts) < expected_clean_cols: return parts, [], [] # Search backwards for 25 contiguous valid response columns # Start from a reasonable position (need at least some dirty fields) min_dirty_fields = 2 # At minimum: username, timestamp for i in range(len(parts) - expected_clean_cols, min_dirty_fields - 1, -1): window = parts[i:i + expected_clean_cols] # Check if all values in window are valid responses if len(window) == expected_clean_cols and all(is_valid_response(v) for v in window): # Found the clean section! dirty_part = parts[:i] # Everything before Psi1 clean_part = parts[i:i + expected_clean_cols] # Psi1-15 + Hemi1-10 tail_part = parts[i + expected_clean_cols:] # HowFind + na_count return dirty_part, clean_part, tail_part # Fallback: couldn't find clean section, return original split # This will be caught by validation later return parts, [], [] def process_users14_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: """ Process users14.dat format file (2000-2015). Format: Username, Timestamp, City, State, Coordinates, Country, Psi1-15, Hemi1-10, HowFind, na_count Args: file_path: Path to file pre_cleaned_text: Pre-cleaned text from parallel batch cleaning. Returns: DataFrame or None """ 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) # Parse lines manually due to dirty commas lines = text.strip().split('\n') parsed_rows = [] for line_num, line in enumerate(lines, 1): if not line.strip(): continue # Parse with dirty comma handling # Expected: variable dirty fields + 25 clean Psi/Hemi fields + tail fields dirty_part, clean_part, tail_part = self.parse_dirty_csv_line(line, expected_clean_cols=25) # Validate we found the clean section if len(clean_part) != 25: self.errata_logger.log_error( 'parse_failed', f'Line {line_num}: Could not identify clean Psi/Hemi section', file_path=str(file_path), line_number=line_num ) continue # Map dirty fields to schema # Expected dirty fields for users14: Username, Timestamp, Location # Location is a single comma-separated string containing city, state, coords, country username = dirty_part[0].strip() if len(dirty_part) > 0 else None timestamp = dirty_part[1].strip() if len(dirty_part) > 1 else None # Everything after timestamp is the location string location_str = ','.join(dirty_part[2:]) if len(dirty_part) > 2 else None # Parse location string location = self.location_parser.parse_location(location_str) if location_str else { 'city': None, 'state': None, 'coordinates': None, 'country': None } row = { 'username': username, 'timestamp': timestamp, 'email': None, # Not in users14 'city': location['city'], 'state': location['state'], 'coordinates': location['coordinates'], 'country': location['country'], } # Psi1-15 (first 15 of clean_part) for i in range(15): row[f'psi_{i+1:02d}'] = clean_part[i].strip() if clean_part[i].strip() else None # Hemi1-10 (next 10 of clean_part) for i in range(10): row[f'hemi_{i+1:02d}'] = clean_part[15 + i].strip() if clean_part[15 + i].strip() else None # HowFind and na_count from tail row['how_find'] = tail_part[0].strip() if len(tail_part) > 0 else None row['na_count_psi_and_hemi'] = tail_part[1].strip() if len(tail_part) > 1 else None # If HowFind has multiple parts (due to commas in text), join them if len(tail_part) > 2: row['how_find'] = ','.join([t.strip() for t in tail_part[:-1]]) row['na_count_psi_and_hemi'] = tail_part[-1].strip() row['source_file'] = file_path.name row['source_row_number'] = line_num row['file_type'] = 'users14' parsed_rows.append(row) if not parsed_rows: self.errata_logger.log_error( 'empty_file', 'No valid rows parsed', file_path=str(file_path) ) return None df = pd.DataFrame(parsed_rows) 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 process_questions_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: """ Process questions.dat format file (2014-2022). Format: Username, Timestamp, Email, City, State, Coordinates, Country, Psi1-15, Hemi1-10, HowFind Timestamp format: "Wed Jan 1 00:33:44 2014" Args: file_path: Path to file pre_cleaned_text: Pre-cleaned text from parallel batch cleaning. Returns: DataFrame or None """ 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) # Parse lines manually due to dirty commas lines = text.strip().split('\n') parsed_rows = [] for line_num, line in enumerate(lines, 1): if not line.strip(): continue # Parse with dirty comma handling # Expected: variable dirty fields + 25 clean Psi/Hemi fields + tail fields dirty_part, clean_part, tail_part = self.parse_dirty_csv_line(line, expected_clean_cols=25) # Validate we found the clean section if len(clean_part) != 25: self.errata_logger.log_error( 'parse_failed', f'Line {line_num}: Could not identify clean Psi/Hemi section', file_path=str(file_path), line_number=line_num ) continue # Map dirty fields to schema # Expected dirty fields for questions: Username, Timestamp, Email, Location # Location is a single comma-separated string containing city, state, coords, country username = dirty_part[0].strip() if len(dirty_part) > 0 else None timestamp = dirty_part[1].strip() if len(dirty_part) > 1 else None email = dirty_part[2].strip() if len(dirty_part) > 2 else None # Everything after email is the location string location_str = ','.join(dirty_part[3:]) if len(dirty_part) > 3 else None # Parse location string location = self.location_parser.parse_location(location_str) if location_str else { 'city': None, 'state': None, 'coordinates': None, 'country': None } row = { 'username': username, 'timestamp': timestamp, 'email': email, 'city': location['city'], 'state': location['state'], 'coordinates': location['coordinates'], 'country': location['country'], } # Psi1-15 (first 15 of clean_part) for i in range(15): row[f'psi_{i+1:02d}'] = clean_part[i].strip() if clean_part[i].strip() else None # Hemi1-10 (next 10 of clean_part) for i in range(10): row[f'hemi_{i+1:02d}'] = clean_part[15 + i].strip() if clean_part[15 + i].strip() else None # HowFind from tail (can contain commas, so join all tail parts) row['how_find'] = ','.join([t.strip() for t in tail_part]) if tail_part else None # na_count not in questions.dat - will be calculated later row['na_count_psi_and_hemi'] = None row['source_file'] = file_path.name row['source_row_number'] = line_num row['file_type'] = 'questions' parsed_rows.append(row) if not parsed_rows: self.errata_logger.log_error( 'empty_file', 'No valid rows parsed', file_path=str(file_path) ) return None df = pd.DataFrame(parsed_rows) 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 process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: """ Process a single user data 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 """ file_type = self.detect_file_type(file_path) if file_type == 'users14': df = self.process_users14_file(file_path, pre_cleaned_text=pre_cleaned_text) else: df = self.process_questions_file(file_path, pre_cleaned_text=pre_cleaned_text) if df is None or df.empty: self.stats['files_failed'] += 1 return None # Validate and clean df = self.validate_dataframe(df, file_path) if df.empty: self.stats['files_failed'] += 1 return None # Track stats self.stats['files_processed'] += 1 if file_type == 'users14': self.stats['users14_rows'] += len(df) else: self.stats['questions_rows'] += len(df) return df 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) # Track NA usernames (June 18 2025: these are now kept, not removed) if 'username' in df.columns: na_usernames = df['username'].isna() | (df['username'].str.lower().str.strip() == 'na') self.stats['na_usernames_count'] += na_usernames.sum() # Parse timestamps if 'timestamp' in df.columns: df['timestamp'] = self.temporal_parser.parse_dates_vectorized( df['timestamp'], file_path=str(file_path) ) # Convert Psi columns to numeric for col in self.PSI_COLUMNS: if col in df.columns: df[col] = self.to_numeric_logged(df[col], col, str(file_path)) # Convert Hemi columns to numeric for col in self.HEMI_COLUMNS: if col in df.columns: df[col] = self.to_numeric_logged(df[col], col, str(file_path)) # Calculate na_count_psi_and_hemi if not present if 'na_count_psi_and_hemi' not in df.columns or df['na_count_psi_and_hemi'].isna().all(): psi_hemi_cols = self.PSI_COLUMNS + self.HEMI_COLUMNS existing_cols = [col for col in psi_hemi_cols if col in df.columns] df['na_count_psi_and_hemi'] = df[existing_cols].isna().sum(axis=1) else: df['na_count_psi_and_hemi'] = self.to_numeric_logged(df['na_count_psi_and_hemi'], 'na_count_psi_and_hemi', str(file_path)) # Ensure all unified columns exist for col in self.COLUMNS_UNIFIED: if col not in df.columns: df[col] = None # Reorder to unified schema df = df[self.COLUMNS_UNIFIED] invalid_count = initial_count - len(df) if invalid_count > 0: self.errata_logger.log_file_summary( str(file_path), 'partial', initial_count, len(df), invalid_count ) return df def remove_duplicates(self, df: pd.DataFrame) -> pd.DataFrame: """ Remove duplicate usernames using deduplication rules: 1. Keep row with fewest NAs in Psi and Hemi columns 2. If tied on NAs, keep oldest timestamp Args: df: Input DataFrame Returns: Deduplicated DataFrame """ initial_count = len(df) # Track per-file duplicate stats before deduplication print("\nPer-file duplicate analysis:") print("-" * 50) # Count duplicates within each file type if 'file_type' in df.columns: for file_type in df['file_type'].unique(): file_df = df[df['file_type'] == file_type] file_dupes = len(file_df) - file_df['username'].nunique() print(f" {file_type}: {len(file_df):,} rows, {file_dupes:,} internal duplicates") # Count cross-file duplicates total_rows = len(df) unique_usernames = df['username'].nunique() total_dupes = total_rows - unique_usernames print(f"\nCross-file analysis:") print(f" Total rows: {total_rows:,}") print(f" Unique usernames: {unique_usernames:,}") print(f" Total duplicates to remove: {total_dupes:,}") print() # Sort by username, na_count (ascending), timestamp (ascending) df_sorted = df.sort_values( by=['username', 'na_count_psi_and_hemi', 'timestamp'], ascending=[True, True, True] ) # Keep first row per username (fewest NAs, then oldest) # Track which file types are kept vs removed kept_indices = df_sorted.groupby('username').head(1).index df_dedup = df_sorted.loc[kept_indices].reset_index(drop=True) # Analyze what was kept vs removed by file type if 'file_type' in df.columns: print("Deduplication results by file type:") removed_df = df[~df.index.isin(kept_indices)] for file_type in df['file_type'].unique(): kept_count = (df_dedup['file_type'] == file_type).sum() removed_count = (removed_df['file_type'] == file_type).sum() original_count = (df['file_type'] == file_type).sum() print(f" {file_type}: kept {kept_count:,} / {original_count:,}, removed {removed_count:,}") print() duplicates_removed = initial_count - len(df_dedup) self.stats['duplicates_removed'] = duplicates_removed if duplicates_removed > 0: self.errata_logger.log_error( 'duplicates_removed', f'Removed {duplicates_removed} duplicate username entries', file_path='combined_data' ) # Log detail for a sample of discarded duplicates so the dedup # policy can be audited without changing the output schema. removed_df = df_sorted[~df_sorted.index.isin(kept_indices)] compare_cols = self.PSI_COLUMNS + self.HEMI_COLUMNS + ['timestamp', 'city', 'state', 'country'] compare_cols = [c for c in compare_cols if c in df.columns] sample_users = removed_df['username'].unique()[:50] for uname in sample_users: kept_row = df_dedup[df_dedup['username'] == uname] removed_rows = removed_df[removed_df['username'] == uname] if kept_row.empty or removed_rows.empty: continue kept_vals = kept_row[compare_cols].iloc[0] for _, rem_row in removed_rows.iterrows(): diffs = {} for col in compare_cols: k, r = kept_vals[col], rem_row[col] if str(k) != str(r): diffs[col] = {'kept': str(k), 'removed': str(r)} if diffs: self.errata_logger.log_error( 'duplicate_detail', f"Discarded row for '{uname}' differs in {len(diffs)} field(s)", file_path='combined_data', scope='row', context={'differing_fields': diffs}, ) return df_dedup def process(self, max_files: Optional[int] = None) -> pd.DataFrame: """ Process all user data files. Args: max_files: Optional limit on number of files to process Returns: Combined DataFrame """ files = self.get_file_list() if max_files: files = files[:max_files] print(f"Processing {len(files)} user data files...") # Parallel batch cleaning (encoding only, no delimiter cleaning) cleaned_texts = self._batch_clean_files(files, use_delimiter_cleaner=False) print(f"Successfully cleaned {len(cleaned_texts)}/{len(files)} files") dfs = [] try: from tqdm import tqdm iterator = tqdm(files, desc="Processing user files") except ImportError: iterator = files for file_path in iterator: pre_cleaned = cleaned_texts.get(file_path) if pre_cleaned is None: continue df = self.process_file(file_path, pre_cleaned_text=pre_cleaned) if df is not None and not df.empty: dfs.append(df) if not dfs: raise ProcessorError("No valid data processed") print("Combining files...") combined = pd.concat(dfs, ignore_index=True) self.stats['rows_total'] = len(combined) # Log unique usernames before deduplication unique_usernames_before = combined['username'].nunique() print(f"\nBefore deduplication:") print(f" Total rows: {len(combined):,}") print(f" Unique usernames: {unique_usernames_before:,}") print() # Remove duplicates print("Removing duplicate usernames...") combined = self.remove_duplicates(combined) # Log unique usernames after deduplication unique_usernames_after = combined['username'].nunique() print(f"After deduplication:") print(f" Total rows: {len(combined):,}") print(f" Unique usernames: {unique_usernames_after:,}") print() self.stats['rows_valid'] = len(combined) # 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() # Close errata logger self.errata_logger.close() return combined def get_stats(self) -> Dict[str, Any]: """Get processing statistics.""" return self.stats.copy()