Download src/processors/location_processor.py from instNoeticSciences/GotPsi: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/src/processors/location_processor.py
- Command line
-
hf download hf://datasets/instNoeticSciences/GotPsi/src/processors/location_processor.py
-
curl -L -o location_processor.py https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/src/processors/location_processor.py
12.8 kB
| """ | |
| Location (Remote Viewing Coordinates) dataset processor. | |
| Processes remote viewing coordinate guessing data: | |
| - Format: 10 columns (user_id, timestamp, trial, x_guess, y_guess, x_target, y_target, count, z_score, seed) | |
| - Timestamp: comma-separated format (e.g., "Sun,Jan,1,00:02:45,2017") | |
| - Count offset: +100000 applied in Perl code | |
| """ | |
| 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 LocationProcessor(BaseProcessor): | |
| """ | |
| Processes Location (Remote Viewing Coordinates) data. | |
| Format: 10 columns with comma-separated timestamp | |
| - Coordinates: 300x300 grid (0-299 range) | |
| - Count has +100000 offset that needs to be removed | |
| """ | |
| BATCH_DELIMITER_CLEAN = False # timestamps are comma-separated, don't standardize delimiters | |
| # File discovery patterns | |
| FILE_PATTERNS = ['loc*.dat'] | |
| # Column definitions | |
| COLUMNS = [ | |
| 'user_id', 'timestamp', 'trial_number', 'x_guess', 'y_guess', | |
| 'x_target', 'y_target', 'count', 'z_score', 'seed' | |
| ] | |
| # Unified output schema | |
| COLUMNS_UNIFIED = [ | |
| 'user_id', 'timestamp', 'trial_number', | |
| 'x_guess', 'y_guess', 'x_target', 'y_target', | |
| 'count', 'z_score', 'seed', 'file_date', 'source_file', 'source_row_number' | |
| ] | |
| def __init__(self, config: Config): | |
| """ | |
| Initialize Location processor. | |
| Args: | |
| config: Configuration object | |
| """ | |
| super().__init__(config, 'location') | |
| # 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 | |
| } | |
| def extract_file_date(self, file_path: Path) -> Optional[datetime]: | |
| """ | |
| Extract date from filename (locYYMMDD.dat). | |
| Args: | |
| file_path: Path to file | |
| Returns: | |
| datetime object or None | |
| """ | |
| match = re.search(r'loc(\d{6})\.dat', file_path.name) | |
| if not match: | |
| return None | |
| return self.temporal_parser.extract_date_from_filename(file_path.name) | |
| def parse_comma_separated_timestamp(self, ts_str: str, file_path: str) -> Optional[datetime]: | |
| """ | |
| Parse comma-separated timestamp format. | |
| The Perl code replaces spaces with commas: | |
| "Sun Jan 1 00:02:45 2017" -> "Sun,Jan,1,00:02:45,2017" | |
| Args: | |
| ts_str: Comma-separated timestamp string | |
| file_path: Source file path for error logging | |
| Returns: | |
| datetime object or None | |
| """ | |
| if pd.isna(ts_str) or not ts_str: | |
| return None | |
| try: | |
| # Replace commas back to spaces | |
| space_format = str(ts_str).replace(',', ' ') | |
| # Parse using temporal parser | |
| return self.temporal_parser.parse_date(space_format, file_path=file_path) | |
| except Exception: | |
| return None | |
| def process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: | |
| """ | |
| Process a single Location 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 - timestamps are comma-separated | |
| # Parse manually with csv.reader to handle comma-separated timestamps | |
| 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 | |
| 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 | |
| # Column 1 is always day-of-week (Mon, Tue, etc.) — drop it. | |
| # After removal: user, month, day, time, year, trial, xg, yg, xt, yt, count, zscore, [seed] | |
| df = df.drop(columns=[1]).reset_index(drop=True) | |
| df.columns = range(df.shape[1]) | |
| # Check column count (should be 12 or 13 after dropping day-of-week) | |
| # 12 cols: no seed column, 13 cols: with seed column | |
| col_count = df.shape[1] | |
| if col_count < 12: | |
| self.errata_logger.log_error( | |
| 'insufficient_columns', | |
| f'Expected 12-13 columns, found {col_count} - entire file omitted', | |
| file_path=str(file_path), | |
| scope='file' | |
| ) | |
| return None | |
| # Get file date | |
| file_date = self.extract_file_date(file_path) | |
| # Create result DataFrame | |
| result_df = pd.DataFrame() | |
| # Map columns (12-13 after dropping day-of-week): | |
| # user, month, day, time, year, trial, xg, yg, xt, yt, count, zscore, [seed] | |
| result_df['user_id'] = df.iloc[:, 0] | |
| result_df['trial_number'] = self.to_numeric_logged(df.iloc[:, 5], 'trial_number', str(file_path)) | |
| result_df['x_guess'] = self.to_numeric_logged(df.iloc[:, 6], 'x_guess', str(file_path)) | |
| result_df['y_guess'] = self.to_numeric_logged(df.iloc[:, 7], 'y_guess', str(file_path)) | |
| result_df['x_target'] = self.to_numeric_logged(df.iloc[:, 8], 'x_target', str(file_path)) | |
| result_df['y_target'] = self.to_numeric_logged(df.iloc[:, 9], 'y_target', str(file_path)) | |
| result_df['count'] = self.to_numeric_logged(df.iloc[:, 10], 'count', str(file_path)) | |
| result_df['z_score'] = self.to_numeric_logged(df.iloc[:, 11], 'z_score', str(file_path)) | |
| # Seed column only exists in newer files (13 columns after drop) | |
| if col_count >= 13: | |
| result_df['seed'] = self.to_numeric_logged(df.iloc[:, 12], 'seed', str(file_path)) | |
| else: | |
| result_df['seed'] = None | |
| 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) | |
| # Reconstruct timestamp from columns 1-4 (month, date, time, year) | |
| # Day-of-week has been removed, so now: user, month, date, time, year, ... | |
| ts_strings = ( | |
| df.iloc[:, 1].astype(str) + ' ' + | |
| df.iloc[:, 2].astype(str) + ' ' + | |
| df.iloc[:, 3].astype(str) + ' ' + | |
| df.iloc[:, 4].astype(str) | |
| ) | |
| result_df['timestamp'] = self.temporal_parser.parse_dates_vectorized( | |
| ts_strings, file_path=str(file_path) | |
| ) | |
| # Remove count offset (+100000) - but only if count > 100000 | |
| result_df.loc[result_df['count'] > 100000, 'count'] = result_df['count'] - 100000 | |
| # 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 trial number (must be >= 1) | |
| 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) | |
| 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 coordinates (0-299 range for 300x300 grid) | |
| coord_cols = ['x_guess', 'y_guess', 'x_target', 'y_target'] | |
| for col in coord_cols: | |
| if col in df.columns: | |
| df[col] = self.to_numeric_logged(df[col], col, str(file_path)) | |
| invalid_coord = (df[col] < 0) | (df[col] > 299) | |
| if invalid_coord.any(): | |
| valid_mask &= ~invalid_coord | |
| self.errata_logger.log_error( | |
| f'{col}_out_of_range', | |
| f'{invalid_coord.sum()} rows with {col} not in 0-299', | |
| file_path=str(file_path), | |
| scope='row' | |
| ) | |
| # Validate count (should be >= 0 after offset removal) | |
| if 'count' in df.columns: | |
| df['count'] = self.to_numeric_logged(df['count'], 'count', str(file_path)) | |
| invalid_count = df['count'] < 0 | |
| if invalid_count.any(): | |
| valid_mask &= ~invalid_count | |
| self.errata_logger.log_error( | |
| 'count_invalid', | |
| f'{invalid_count.sum()} rows with count < 0', | |
| file_path=str(file_path), | |
| scope='row' | |
| ) | |
| # Convert numeric columns | |
| numeric_cols = ['trial_number', 'x_guess', 'y_guess', 'x_target', 'y_target', | |
| 'count', 'z_score', 'seed'] | |
| 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() | |