#!/usr/bin/env python3 """Validation & Diagnostic Visualization for Road Traffic Injury Dataset.""" import pandas as pd import numpy as np import matplotlib.pyplot as plt import os SCENARIOS = ['trauma_centre', 'district_hospital', 'rural_health_centre'] def load_scenarios(data_dir='data'): dfs = {} for sc in SCENARIOS: path = os.path.join(data_dir, f'rti_{sc}.csv') if os.path.exists(path): dfs[sc] = pd.read_csv(path) return dfs def make_report(dfs, output='validation_report.png'): fig, axes = plt.subplots(4, 2, figsize=(16, 22)) fig.suptitle('Road Traffic Injury & Trauma — Validation Report', fontsize=16, fontweight='bold', y=0.98) df = dfs.get('district_hospital', list(dfs.values())[0]) colors = ['#2ecc71', '#f39c12', '#e74c3c'] # Panel 1: Mortality across scenarios ax = axes[0, 0] x = np.arange(len(SCENARIOS)) mort = [(dfs[sc]['outcome'] == 'died').mean() * 100 for sc in SCENARIOS if sc in dfs] ax.bar(x, mort, color=colors, alpha=0.8) ax.set_xticks(x) ax.set_xticklabels(['Trauma Centre', 'District', 'Rural'], fontsize=9) for i, v in enumerate(mort): ax.text(i, v + 0.3, f'{v:.1f}%', ha='center', fontsize=10) ax.set_ylabel('Mortality (%)') ax.set_title('RTI Mortality (Africa: 26.6/100K)') # Panel 2: Road user type ax = axes[0, 1] users = df['road_user_type'].value_counts() u_colors = ['#e74c3c', '#3498db', '#f39c12', '#2ecc71', '#9b59b6', '#e67e22'] ax.pie(users.values, labels=[u.replace('_', ' ').title() for u in users.index], autopct='%1.1f%%', colors=u_colors[:len(users)], startangle=90, textprops={'fontsize': 8}) ax.set_title('Road User Type (WHO: Pedestrians >50% Africa)') # Panel 3: GCS vs mortality ax = axes[1, 0] gcs_cats = ['severe', 'moderate', 'mild'] gcs_mort = [] for g in gcs_cats: sub = df[df['gcs_category'] == g] gcs_mort.append((sub['outcome'] == 'died').mean() * 100 if len(sub) > 0 else 0) g_colors = ['#e74c3c', '#f39c12', '#2ecc71'] ax.bar(range(3), gcs_mort, color=g_colors, alpha=0.8) ax.set_xticks(range(3)) ax.set_xticklabels(['Severe (3-8)', 'Moderate (9-12)', 'Mild (13-15)']) for i, v in enumerate(gcs_mort): ax.text(i, v + 0.3, f'{v:.0f}%', ha='center', fontsize=9) ax.set_ylabel('Mortality (%)') ax.set_title('Mortality by GCS Category') # Panel 4: Body region ax = axes[1, 1] regions = df['primary_body_region'].value_counts() ax.barh(range(len(regions)), regions.values, color='#3498db', alpha=0.7) ax.set_yticks(range(len(regions))) ax.set_yticklabels([r.replace('_', ' ').title()[:15] for r in regions.index], fontsize=7) ax.set_xlabel('Count') ax.set_title('Primary Body Region (Head 28%, Extremity 32%)') # Panel 5: Ambulance & golden hour ax = axes[2, 0] amb = [(dfs[sc]['transport_mode'] == 'ambulance').mean() * 100 for sc in SCENARIOS if sc in dfs] gh = [dfs[sc]['within_golden_hour'].mean() * 100 for sc in SCENARIOS if sc in dfs] w = 0.3 ax.bar(x - w/2, amb, w, label='Ambulance', color='#3498db', alpha=0.8) ax.bar(x + w/2, gh, w, label='Golden Hour', color='#f39c12', alpha=0.8) ax.set_xticks(x) ax.set_xticklabels(['Trauma', 'District', 'Rural'], fontsize=9) ax.set_ylabel('Rate (%)') ax.set_title('Prehospital: Ambulance & Golden Hour') ax.legend(fontsize=8) # Panel 6: ISS distribution ax = axes[2, 1] for sc in SCENARIOS: if sc in dfs: ax.hist(dfs[sc]['iss'].clip(1, 50), bins=20, alpha=0.5, label=sc.replace('_', ' ').title()[:12], edgecolor='white') ax.axvline(x=16, color='red', linestyle='--', alpha=0.7, label='Severe (ISS≥16)') ax.set_xlabel('ISS') ax.set_title('Injury Severity Score Distribution') ax.legend(fontsize=7) # Panel 7: Age-sex distribution ax = axes[3, 0] males = df[df['sex'] == 'M']['age_years'] females = df[df['sex'] == 'F']['age_years'] ax.hist(males, bins=15, alpha=0.5, color='#3498db', label='Male', edgecolor='white') ax.hist(females, bins=15, alpha=0.5, color='#e74c3c', label='Female', edgecolor='white') ax.set_xlabel('Age (years)') ax.set_title('Age-Sex Distribution (Males 75%, peak 15-44y)') ax.legend(fontsize=8) # Panel 8: Disability at discharge ax = axes[3, 1] surv = df[df['outcome'] == 'survived'] if len(surv) > 0: dis = surv['disability_at_discharge'].value_counts() d_colors = ['#2ecc71', '#f39c12', '#e74c3c', '#9b59b6', '#3498db'] ax.pie(dis.values, labels=[d.replace('_', ' ').title() for d in dis.index], autopct='%1.1f%%', colors=d_colors[:len(dis)], startangle=90, textprops={'fontsize': 8}) ax.set_title('Disability at Discharge (Survivors)') plt.tight_layout(rect=[0, 0, 1, 0.97]) plt.savefig(output, dpi=150, bbox_inches='tight') print(f'Saved validation report to {output}') plt.close() if __name__ == '__main__': dfs = load_scenarios() if dfs: make_report(dfs)