#!/usr/bin/env python3 """Validation & Diagnostic Visualization for Hearing Loss/Ear Disease Dataset.""" import pandas as pd import numpy as np import matplotlib.pyplot as plt import os SCENARIOS = ['ent_specialist_centre', 'district_hospital', 'rural_health_centre'] def load_scenarios(data_dir='data'): dfs = {} for sc in SCENARIOS: path = os.path.join(data_dir, f'ear_{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('Hearing Loss & Ear Disease — 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] conds = df['ear_condition'].value_counts() c_colors = ['#e74c3c', '#f39c12', '#3498db', '#9b59b6', '#2ecc71', '#e67e22', '#1abc9c', '#95a5a6', '#c0392b'] ax.barh(range(len(conds)), conds.values, color=c_colors[:len(conds)], alpha=0.8) ax.set_yticks(range(len(conds))) ax.set_yticklabels([s.replace('_', ' ').title() for s in conds.index], fontsize=7) ax.set_xlabel('Count') ax.set_title('Ear Conditions (CSOM #1)') ax = axes[0, 1] x = np.arange(len(SCENARIOS)) audio = [dfs[sc]['audiometry_done'].mean()*100 for sc in SCENARIOS if sc in dfs] ha = [dfs[sc]['hearing_aid_fitted'].mean()*100 for sc in SCENARIOS if sc in dfs] w = 0.3 ax.bar(x - w/2, audio, w, label='Audiometry', color='#3498db', alpha=0.8) ax.bar(x + w/2, ha, w, label='Hearing Aid', color='#2ecc71', alpha=0.8) ax.set_xticks(x) ax.set_xticklabels(['ENT Centre', 'District', 'Rural'], fontsize=9) ax.set_ylabel('Rate (%)') ax.set_title('Audiometry & Hearing Aid Access') ax.legend(fontsize=8) ax = axes[1, 0] sev = df['hearing_loss_severity'].value_counts() s_order = ['normal', 'mild', 'moderate', 'severe', 'profound'] vals = [sev.get(s, 0) for s in s_order] ax.bar(range(5), vals, color=['#2ecc71', '#f1c40f', '#f39c12', '#e74c3c', '#8e44ad'], alpha=0.8) ax.set_xticks(range(5)) ax.set_xticklabels(s_order, fontsize=9) ax.set_ylabel('Count') ax.set_title('Hearing Loss Severity') ax = axes[1, 1] hl_type = df[df['hearing_loss_type'] != 'none']['hearing_loss_type'].value_counts() if len(hl_type) > 0: ax.pie(hl_type.values, labels=[s.title() for s in hl_type.index], autopct='%1.0f%%', colors=['#3498db', '#e74c3c', '#f39c12'], startangle=90, textprops={'fontsize': 10}) ax.set_title('Hearing Loss Type') ax = axes[2, 0] children = df[df['child'] == 1] if len(children) > 0: impacts = ['speech_development_affected', 'school_performance_affected'] i_labels = ['Speech Affected', 'School Affected'] vals = [children[i].mean()*100 for i in impacts] ax.bar(range(2), vals, color=['#e74c3c', '#f39c12'], alpha=0.8) ax.set_xticks(range(2)) ax.set_xticklabels(i_labels, fontsize=9) for i, v in enumerate(vals): ax.text(i, v + 1, f'{v:.0f}%', ha='center', fontsize=10) ax.set_ylabel('Rate (%)') ax.set_title('Impact on Children') ax = axes[2, 1] risks = ['recurrent_ari', 'malnutrition', 'overcrowding', 'noise_exposure', 'traditional_ear_drops'] r_labels = ['Recurrent ARI', 'Malnutrition', 'Overcrowding', 'Noise', 'Trad. Drops'] vals = [df[r].mean()*100 for r in risks] ax.barh(range(5), vals, color='#3498db', alpha=0.7) ax.set_yticks(range(5)) ax.set_yticklabels(r_labels, fontsize=9) ax.set_xlabel('Prevalence (%)') ax.set_title('Risk Factors') ax = axes[3, 0] tx = ['antibiotics_given', 'ear_drops_given', 'ear_syringing', 'surgery_performed', 'hearing_aid_fitted'] t_labels = ['Antibiotics', 'Ear Drops', 'Syringing', 'Surgery', 'Hearing Aid'] for i, sc_name in enumerate(SCENARIOS): if sc_name in dfs: d = dfs[sc_name] vals = [d[t].mean()*100 for t in tx] ax.plot(range(5), vals, 'o-', label=sc_name.replace('_', ' ').title()[:10], color=colors[i], linewidth=2, markersize=5) ax.set_xticks(range(5)) ax.set_xticklabels(t_labels, fontsize=7, rotation=15) ax.set_ylabel('Rate (%)') ax.set_title('Treatment Cascade by Scenario') ax.legend(fontsize=7) ax = axes[3, 1] ref = [dfs[sc]['referred_ent'].mean()*100 for sc in SCENARIOS if sc in dfs] ref_c = [dfs[sc]['referral_completed'].mean()*100 for sc in SCENARIOS if sc in dfs] ax.bar(x - w/2, ref, w, label='Referred ENT', color='#f39c12', alpha=0.8) ax.bar(x + w/2, ref_c, w, label='Referral Done', color='#2ecc71', alpha=0.8) ax.set_xticks(x) ax.set_xticklabels(['ENT Centre', 'District', 'Rural'], fontsize=9) ax.set_ylabel('Rate (%)') ax.set_title('ENT Referral Gap (~20% completion)') ax.legend(fontsize=8) 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)