#!/usr/bin/env python3 """Validation & Diagnostic Visualization for Asthma/COPD Dataset.""" import pandas as pd import numpy as np import matplotlib.pyplot as plt import os SCENARIOS = ['urban_respiratory_clinic', 'district_hospital', 'rural_health_centre'] def load_scenarios(data_dir='data'): dfs = {} for sc in SCENARIOS: path = os.path.join(data_dir, f'respiratory_{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('Asthma & COPD — Validation Report', fontsize=16, fontweight='bold', y=0.98) df = dfs.get('district_hospital', list(dfs.values())[0]) colors = ['#2ecc71', '#f39c12', '#e74c3c'] ax = axes[0, 0] x = np.arange(len(SCENARIOS)) mort = [dfs[sc]['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(['Urban Clinic', 'District', 'Rural'], fontsize=9) for i, v in enumerate(mort): ax.text(i, v + 0.05, f'{v:.2f}%', ha='center', fontsize=10) ax.set_ylabel('Mortality (%)') ax.set_title('Mortality by Scenario') ax = axes[0, 1] diag = df['diagnosis'].value_counts() d_colors = ['#3498db', '#e74c3c', '#f39c12', '#9b59b6'] ax.pie(diag.values, labels=[s.replace('_', ' ').title() for s in diag.index], autopct='%1.0f%%', colors=d_colors[:len(diag)], startangle=90, textprops={'fontsize': 9}) ax.set_title('Diagnosis Distribution (asthma ~50%)') ax = axes[1, 0] risks = ['biomass_fuel_cooking', 'tobacco_smoking', 'occupational_dust', 'outdoor_air_pollution', 'tb_history', 'family_history_asthma'] r_labels = ['Biomass', 'Tobacco', 'Dust', 'Outdoor AP', 'TB Hx', 'Family Hx'] vals = [df[r].mean()*100 for r in risks] ax.barh(range(6), vals, color='#3498db', alpha=0.7) ax.set_yticks(range(6)) ax.set_yticklabels(r_labels, fontsize=9) for i, v in enumerate(vals): ax.text(v + 0.5, i, f'{v:.0f}%', va='center', fontsize=9) ax.set_xlabel('Prevalence (%)') ax.set_title('Risk Factors (biomass = #1)') ax = axes[1, 1] inhaler = [dfs[sc]['inhaler_prescribed'].mean()*100 for sc in SCENARIOS if sc in dfs] ax.bar(x, inhaler, color=colors, alpha=0.8) ax.set_xticks(x) ax.set_xticklabels(['Urban Clinic', 'District', 'Rural'], fontsize=9) for i, v in enumerate(inhaler): ax.text(i, v + 1, f'{v:.0f}%', ha='center', fontsize=10) ax.set_ylabel('Rate (%)') ax.set_title('Inhaler Access (0% rural)') ax = axes[2, 0] sev = df['severity'].value_counts() s_order = ['mild', 'moderate', 'severe'] vals = [sev.get(s, 0) for s in s_order] ax.bar(range(3), vals, color=['#2ecc71', '#f39c12', '#e74c3c'], alpha=0.8) ax.set_xticks(range(3)) ax.set_xticklabels(['Mild', 'Moderate', 'Severe'], fontsize=9) ax.set_ylabel('Count') ax.set_title('Severity Distribution') ax = axes[2, 1] spir = [dfs[sc]['spirometry_done'].mean()*100 for sc in SCENARIOS if sc in dfs] clin = [dfs[sc]['clinical_diagnosis_only'].mean()*100 for sc in SCENARIOS if sc in dfs] w = 0.3 ax.bar(x - w/2, spir, w, label='Spirometry', color='#3498db', alpha=0.8) ax.bar(x + w/2, clin, w, label='Clinical Only', color='#e74c3c', alpha=0.8) ax.set_xticks(x) ax.set_xticklabels(['Urban Clinic', 'District', 'Rural'], fontsize=9) ax.set_ylabel('Rate (%)') ax.set_title('Diagnostic Approach (spirometry rare)') ax.legend(fontsize=8) ax = axes[3, 0] users = df[df['inhaler_prescribed'] == 1] if len(users) > 0: tech = users['inhaler_technique_correct'].mean() * 100 ax.bar(['Correct', 'Incorrect'], [tech, 100 - tech], color=['#2ecc71', '#e74c3c'], alpha=0.8) ax.text(0, tech + 1, f'{tech:.0f}%', ha='center', fontsize=10) ax.set_ylabel('Rate (%)') ax.set_title('Inhaler Technique (~35% correct)') ax = axes[3, 1] exac = [dfs[sc]['exacerbations_past_year'].mean() for sc in SCENARIOS if sc in dfs] hosp = [dfs[sc]['hospitalised_exacerbation'].mean()*100 for sc in SCENARIOS if sc in dfs] ax2 = ax.twinx() ax.bar(x - 0.15, exac, 0.3, color='#f39c12', alpha=0.8, label='Mean Exacerbations') ax2.bar(x + 0.15, hosp, 0.3, color='#e74c3c', alpha=0.8, label='Hospitalised (%)') ax.set_xticks(x) ax.set_xticklabels(['Urban Clinic', 'District', 'Rural'], fontsize=9) ax.set_ylabel('Mean Exacerbations/yr') ax2.set_ylabel('Hospitalised (%)') ax.set_title('Exacerbations & Hospitalisations') 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)