File size: 7,310 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 | """
Process full Location dataset and export to Parquet.
Processes all Location (Remote Viewing Coordinates) files and exports cleaned data.
"""
import sys
import argparse
from pathlib import Path
from datetime import datetime
sys.path.insert(0, str(Path(__file__).parent.parent))
from src.core.config import Config
from src.core.output_lock import seal_output, unlock_for_write
from src.processors.location_processor import LocationProcessor
def main():
parser = argparse.ArgumentParser(description='Process Location dataset')
parser.add_argument('--audit', action='store_true',
help='Include source_file and source_row_number columns in output')
parser.add_argument('--data-dir',
help='Override raw data directory (default: data/)')
args = parser.parse_args()
print("="*70)
print("Location Full Dataset Processing")
print("="*70)
print()
start_time = datetime.now()
# Load config
config = Config('config/cleaning_config.yaml')
# Override audit mode if --audit flag is provided
if args.audit:
config.set('processing.audit_mode', True)
print("Audit mode: ENABLED (including source_file and source_row_number columns)")
print()
# Override data directory if --data-dir flag is provided
if args.data_dir:
config.set('directories.raw_data', args.data_dir)
# Create output directory
output_dir = config.output_dir / 'parquet'
output_dir.mkdir(parents=True, exist_ok=True)
output_file = output_dir / 'location_cleaned.parquet'
print(f"Output file: {output_file}")
print()
# Create processor
processor = LocationProcessor(config)
# Get file count
all_files = processor.get_file_list()
print(f"Total files to process: {len(all_files)}")
print()
# Process all files
print("Processing all Location files...")
print()
try:
df = processor.process()
# Get statistics
stats = processor.get_stats()
print()
print("="*70)
print("✓ Processing Complete!")
print("="*70)
print()
print("Processing Statistics:")
print(f" Files processed: {stats['files_processed']:,}")
print(f" Files failed: {stats['files_failed']:,}")
success_rate = (stats['files_processed'] / len(all_files)) * 100
print(f" Success rate: {success_rate:.1f}%")
print()
print(f" Total rows: {len(df):,}")
print(f" Valid rows: {stats['rows_valid']:,}")
print()
# Data quality metrics
if len(df) > 0:
completeness = df.notna().sum() / len(df)
avg_completeness = completeness.mean() * 100
# Date range
if 'timestamp' in df.columns and df['timestamp'].notna().any():
date_col = pd.to_datetime(df['timestamp'], errors='coerce')
min_date = date_col.min()
max_date = date_col.max()
date_span = (max_date - min_date).days
print("Data Quality:")
print(f" Completeness (avg): {avg_completeness:.1f}%")
missing_ts = df['timestamp'].isna().sum()
print(f" Missing timestamps: {missing_ts:,} ({missing_ts/len(df)*100:.1f}%)")
print()
print(f"Date range: {min_date} to {max_date}")
print(f"Span: {date_span:,} days")
print()
# User statistics
if 'user_id' in df.columns:
unique_users = df['user_id'].nunique()
print("User Statistics:")
print(f" Unique users: {unique_users:,}")
# Calculate trials per user
if 'trial_number' in df.columns:
trials_per_user = df.groupby('user_id')['trial_number'].max().mean()
print(f" Trials per user (mean): {trials_per_user:.0f}")
print()
# Coordinate statistics
if 'x_guess' in df.columns and 'x_target' in df.columns:
print("Coordinate Statistics:")
# Calculate distance (Euclidean)
df['distance'] = ((df['x_guess'] - df['x_target'])**2 +
(df['y_guess'] - df['y_target'])**2)**0.5
avg_distance = df['distance'].mean()
print(f" Average distance from target: {avg_distance:.1f} pixels")
# Z-score statistics
if 'z_score' in df.columns:
avg_z = df['z_score'].mean()
print(f" Average z-score: {avg_z:.3f}")
print()
processing_time = datetime.now() - start_time
print(f"Processing time: {processing_time}")
if len(df) > 0:
rows_per_sec = len(df) / processing_time.total_seconds()
print(f"Speed: {rows_per_sec:.0f} rows/second")
print()
# Export to Parquet
print("Exporting to Parquet...")
unlock_for_write(output_file)
df.to_parquet(output_file, compression='snappy', engine='pyarrow', index=False)
seal_output(output_file)
# Get file size
file_size_mb = output_file.stat().st_size / (1024 * 1024)
print(f"✓ Exported to: {output_file}")
print(f" File size: {file_size_mb:.1f} MB")
print()
# Calculate compression ratio (estimate)
if len(df) > 0:
# Rough estimate: 150 bytes per row uncompressed
est_uncompressed = (len(df) * 150) / (1024 * 1024)
compression_ratio = est_uncompressed / file_size_mb
print(f" Compression ratio: {compression_ratio:.1f}x")
print()
# Error summary
errata_log = Path(f"logs/errata/location_{datetime.now().strftime('%Y%m%d_%H%M%S')}_errata.jsonl")
if errata_log.exists():
print("Error Summary:")
import json
error_types = {}
total_errors = 0
with open(errata_log, 'r') as f:
for line in f:
try:
data = json.loads(line)
if data.get('type') == 'error':
error_type = data.get('error_type', 'unknown')
error_types[error_type] = error_types.get(error_type, 0) + 1
total_errors += 1
except:
pass
print(f" Total errors: {total_errors}")
files_with_errors = stats['files_failed']
print(f" Files with errors: {files_with_errors}")
if error_types:
print(f" Error types:")
for error_type, count in sorted(error_types.items(), key=lambda x: x[1], reverse=True):
print(f" - {error_type}: {count}")
print(f" Errata log: {errata_log}")
print()
print("="*70)
print("✓ Location Dataset Processing Complete!")
print("="*70)
except Exception as e:
print(f"\n❌ Error during processing: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == '__main__':
import pandas as pd
main()
|