File size: 26,410 Bytes
9deebf2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | """
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()
|