#!/usr/bin/env python3 """Audit: Users (Survey Responses) dataset.""" import sys sys.path.insert(0, str(__import__('pathlib').Path(__file__).resolve().parent)) from _common import * def main(): output_dir = setup_output_dir('users') print_section('USERS DATASET AUDIT') print(f'Audit started: {datetime.now()}') df = load_parquet('users') # --- Overview --- print_section('DATASET OVERVIEW') df.info() # --- Missing data --- print_section('MISSING DATA SUMMARY') missing = df.isnull().sum() missing_pct = (missing / len(df) * 100).round(2) missing_df = pd.DataFrame({ 'Missing Count': missing, 'Missing %': missing_pct }).sort_values('Missing %', ascending=False) print(missing_df[missing_df['Missing Count'] > 0]) # --- Psi/Hemi summaries --- psi_cols = [f'psi_{i:02d}' for i in range(1, 16)] hemi_cols = [f'hemi_{i:02d}' for i in range(1, 11)] print_section('SURVEY QUESTION SUMMARIES') print('PSI QUESTIONS SUMMARY (1-5 scale)') print(df[psi_cols].describe()) print('\nHEMI QUESTIONS SUMMARY (1-5 scale)') print(df[hemi_cols].describe()) # --- Temporal --- df['timestamp'] = pd.to_datetime(df['timestamp']) df['date'] = df['timestamp'].dt.date df['year'] = df['timestamp'].dt.year df['month'] = df['timestamp'].dt.to_period('M') print_section('TEMPORAL ANALYSIS') print(f'First record: {df["timestamp"].min()}') print(f'Last record: {df["timestamp"].max()}') print(f'Time span: {(df["timestamp"].max() - df["timestamp"].min()).days} days') print(f'Years: {df["year"].min()} to {df["year"].max()}') yearly_counts = df['year'].value_counts().sort_index() print('\nYEARLY DISTRIBUTION') print(yearly_counts) plt.figure(figsize=(14, 6)) yearly_counts.plot(kind='bar', color='steelblue') plt.title('Users Dataset Audit - Yearly Distribution', fontsize=14, fontweight='bold') plt.xlabel('Year') plt.ylabel('Number of Users') plt.xticks(rotation=45) plt.grid(axis='y', alpha=0.3) plt.tight_layout() save_fig(output_dir, 'yearly_distribution') # Monthly continuity monthly_counts = df.groupby('month').size() plt.figure(figsize=(16, 6)) monthly_counts.plot(kind='line', marker='o', markersize=3) plt.title('Survey Responses by Month (Temporal Continuity Check)', fontsize=14, fontweight='bold') plt.xlabel('Month') plt.ylabel('Number of Users') plt.grid(alpha=0.3) plt.tight_layout() save_fig(output_dir, 'monthly_continuity') all_months = pd.period_range(start=monthly_counts.index.min(), end=monthly_counts.index.max(), freq='M') missing_months = all_months.difference(monthly_counts.index) if len(missing_months) > 0: print(f'\n{len(missing_months)} months with ZERO responses:') for month in missing_months[:10]: print(f' - {month}') if len(missing_months) > 10: print(f' ... and {len(missing_months) - 10} more') else: print('\nNo missing months - data is temporally continuous') # --- Deduplication check --- print_section('DEDUPLICATION CHECK') uid_col = 'username_hash' if 'username_hash' in df.columns else 'username' print(f'Total rows: {len(df):,}') print(f'Unique {uid_col}: {df[uid_col].nunique():,}') if 'username' in df.columns: duplicates = df[df.duplicated(subset=['username'], keep=False)] if len(duplicates) > 0: print(f'\nCRITICAL: Found {len(duplicates)} duplicate username records!') print(duplicates[['username', 'timestamp', 'na_count_psi_and_hemi']].head(20)) else: print('\nPASS: No duplicate usernames found') hash_duplicates = df[df.duplicated(subset=[uid_col], keep=False)] if len(hash_duplicates) > 0: print(f'\nCRITICAL: Found {len(hash_duplicates)} duplicate {uid_col} records!') else: print(f'PASS: All {uid_col} values are unique') # --- Survey completeness --- print_section('SURVEY COMPLETENESS') na_dist = df['na_count_psi_and_hemi'].value_counts().sort_index() complete_surveys = int((df['na_count_psi_and_hemi'] == 0).sum()) complete_pct = complete_surveys / len(df) * 100 print(f'Complete surveys (0 NAs): {complete_surveys:,} ({complete_pct:.1f}%)') print(f'Partial surveys (1+ NAs): {len(df) - complete_surveys:,} ({100 - complete_pct:.1f}%)') print(f'\nNA Count Distribution (0 = complete, 25 = all questions skipped):') print(na_dist.head(10)) plt.figure(figsize=(12, 5)) na_dist.plot(kind='bar', color='coral') plt.title('Survey Completeness Distribution', fontsize=14, fontweight='bold') plt.xlabel('Number of Unanswered Questions') plt.ylabel('Number of Users') plt.tight_layout() save_fig(output_dir, 'survey_completeness') # Question-by-question completion psi_completion = {col: (df[col].notna().sum() / len(df) * 100) for col in psi_cols} hemi_completion = {col: (df[col].notna().sum() / len(df) * 100) for col in hemi_cols} print('\nPSI QUESTION COMPLETION RATES') for col, rate in psi_completion.items(): print(f'{col}: {rate:.1f}%') print('\nHEMI QUESTION COMPLETION RATES') for col, rate in hemi_completion.items(): print(f'{col}: {rate:.1f}%') fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 5)) ax1.bar(range(len(psi_completion)), list(psi_completion.values()), color='skyblue') ax1.set_title('Psi Question Completion Rates', fontweight='bold') ax1.set_xlabel('Question Number') ax1.set_ylabel('Completion Rate (%)') ax1.set_ylim(0, 100) ax1.axhline(y=90, color='green', linestyle='--', alpha=0.5, label='90% threshold') ax1.legend() ax2.bar(range(len(hemi_completion)), list(hemi_completion.values()), color='lightcoral') ax2.set_title('Hemi Question Completion Rates', fontweight='bold') ax2.set_xlabel('Question Number') ax2.set_ylabel('Completion Rate (%)') ax2.set_ylim(0, 100) ax2.axhline(y=90, color='green', linestyle='--', alpha=0.5, label='90% threshold') ax2.legend() plt.tight_layout() save_fig(output_dir, 'question_completion_rates') # --- File type distribution --- if 'file_type' in df.columns: print_section('FILE TYPE DISTRIBUTION') file_type_dist = df['file_type'].value_counts() print(file_type_dist) plt.figure(figsize=(8, 5)) file_type_dist.plot(kind='bar', color=['steelblue', 'darkorange']) plt.title('Source File Type Distribution', fontsize=14, fontweight='bold') plt.xlabel('File Type') plt.ylabel('Number of Records') plt.xticks(rotation=0) plt.tight_layout() save_fig(output_dir, 'file_type_distribution') print('\nFILE TYPE BY YEAR') file_type_year = df.groupby(['year', 'file_type']).size().unstack(fill_value=0) print(file_type_year) file_type_year.plot(kind='bar', stacked=True, figsize=(14, 6)) plt.title('File Type Distribution by Year', fontsize=14, fontweight='bold') plt.xlabel('Year') plt.ylabel('Number of Records') plt.legend(title='File Type') plt.tight_layout() save_fig(output_dir, 'file_type_by_year') # --- Location data quality --- print_section('LOCATION DATA QUALITY') location_cols = ['state', 'coordinates', 'country'] has_any_location = 0 for col in location_cols: if col in df.columns: filled = df[col].notna().sum() pct = filled / len(df) * 100 print(f'{col:12s}: {filled:6,} filled ({pct:5.1f}%)') has_any_location = int(df[location_cols].notna().any(axis=1).sum()) has_all_location = int(df[location_cols].notna().all(axis=1).sum()) print(f'\nUsers with ANY location data: {has_any_location:,} ({has_any_location / len(df) * 100:.1f}%)') print(f'Users with ALL location data: {has_all_location:,} ({has_all_location / len(df) * 100:.1f}%)') if 'country' in df.columns and df['country'].notna().any(): print('\nTOP 20 COUNTRIES') top_countries = df['country'].value_counts().head(20) print(top_countries) plt.figure(figsize=(12, 6)) top_countries.plot(kind='barh', color='teal') plt.title('Top 20 Countries by User Count', fontsize=14, fontweight='bold') plt.xlabel('Number of Users') plt.ylabel('Country') plt.gca().invert_yaxis() plt.tight_layout() save_fig(output_dir, 'top_countries') # --- Validation --- print_section('RESPONSE VALIDATION') print('Psi/Hemi responses must be 1-5 or NULL') all_survey_cols = psi_cols + hemi_cols invalid_responses = {} for col in all_survey_cols: invalid = df[(df[col].notna()) & ((df[col] < 1) | (df[col] > 5))] if len(invalid) > 0: invalid_responses[col] = len(invalid) if invalid_responses: print('FAIL: Found invalid responses (not in 1-5 range):') for col, count in invalid_responses.items(): print(f' {col}: {count} invalid values') else: print('PASS: All Psi/Hemi responses are in valid range (1-5)') # na_count consistency print('\nna_count_psi_and_hemi should match actual NAs') actual_na_count = df[all_survey_cols].isnull().sum(axis=1) reported_na_count = df['na_count_psi_and_hemi'] mismatch = (actual_na_count != reported_na_count) mismatch_count = int(mismatch.sum()) if mismatch_count > 0: print(f'WARNING: {mismatch_count} rows with na_count mismatch') sample = df[mismatch][['username_hash', 'na_count_psi_and_hemi']].head(10).copy() sample['actual_na_count'] = actual_na_count[mismatch].head(10).values print(sample) else: print('PASS: All na_count_psi_and_hemi values match actual NA counts') # --- Summary --- standard_audit_summary('Users Dataset', df, extra_lines=[ f'Complete Surveys: {complete_surveys:,} ({complete_pct:.1f}%)', f'Location Coverage: {has_any_location / len(df) * 100:.1f}%', ]) if __name__ == '__main__': main()