#!/usr/bin/env python3 """Validation & Diagnostic Visualization for Childhood Immunisation Dataset.""" import pandas as pd import numpy as np import matplotlib.pyplot as plt import os SCENARIOS = ['high_coverage', 'moderate_coverage', 'low_coverage'] def load_scenarios(data_dir='data'): dfs = {} for sc in SCENARIOS: path = os.path.join(data_dir, f'immunisation_{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('Childhood Immunisation Coverage — Validation Report', fontsize=16, fontweight='bold', y=0.98) df = dfs.get('moderate_coverage', list(dfs.values())[0]) elig = df[df['age_months'] >= 4] # Old enough for primary series # Panel 1: Immunisation status ax = axes[0, 0] status_counts = df['immunisation_status'].value_counts() colors = {'fully_immunised': '#2ecc71', 'partially_immunised': '#f39c12', 'zero_dose': '#e74c3c'} order = ['fully_immunised', 'partially_immunised', 'zero_dose'] vals = [status_counts.get(s, 0) for s in order] ax.bar(range(3), vals, color=[colors[s] for s in order]) ax.set_xticks(range(3)) ax.set_xticklabels(['Fully\nImmunised', 'Partially\nImmunised', 'Zero\nDose']) for i, v in enumerate(vals): ax.text(i, v + 50, f'{v/len(df)*100:.1f}%', ha='center', fontsize=10) ax.set_ylabel('Count') ax.set_title('Immunisation Status (Moderate Coverage)') # Panel 2: Vaccine coverage cascade ax = axes[0, 1] vaccines = ['bcg', 'penta1', 'penta2', 'penta3', 'mcv1', 'mcv2'] elig_ages = [1, 2, 3, 4, 10, 16] coverages = [] for v, min_age in zip(vaccines, elig_ages): sub = df[df['age_months'] >= min_age] coverages.append(sub[v].mean() * 100 if len(sub) > 0 else 0) bars = ax.bar(range(len(vaccines)), coverages, color='#3498db', alpha=0.8) ax.set_xticks(range(len(vaccines))) ax.set_xticklabels([v.upper() for v in vaccines]) for i, v in enumerate(coverages): ax.text(i, v + 1, f'{v:.0f}%', ha='center', fontsize=9) ax.set_ylabel('Coverage (%)') ax.set_title('Vaccine Coverage Cascade (age-eligible)') ax.set_ylim(0, 105) # Panel 3: Penta3 coverage by SES quintile across scenarios ax = axes[1, 0] x = np.arange(5) width = 0.25 for i, sc in enumerate(SCENARIOS): if sc not in dfs: continue d = dfs[sc] elig_d = d[d['age_months'] >= 4] rates = [] for q in range(1, 6): sub = elig_d[elig_d['ses_quintile'] == q] rates.append(sub['penta3'].mean() * 100 if len(sub) > 0 else 0) ax.bar(x + i * width, rates, width, label=sc.replace('_', ' ').title(), alpha=0.8) ax.set_xticks(x + width) ax.set_xticklabels([f'Q{q}' for q in range(1, 6)]) ax.set_ylabel('Penta3 Coverage (%)') ax.set_title('Penta3 Coverage by Wealth Quintile') ax.legend(fontsize=8) # Panel 4: Coverage by urban/rural ax = axes[1, 1] for rt in ['urban', 'rural']: sub = elig[elig['region_type'] == rt] if len(sub) == 0: continue covs = [sub[v].mean() * 100 for v in ['bcg', 'penta1', 'penta3', 'mcv1']] ax.plot(['BCG', 'Penta1', 'Penta3', 'MCV1'], covs, 'o-', label=rt.title(), linewidth=2, markersize=8) ax.set_ylabel('Coverage (%)') ax.set_title('Coverage by Urban/Rural') ax.legend(fontsize=10) ax.set_ylim(0, 100) # Panel 5: Distance vs total doses ax = axes[2, 0] sample = df.sample(min(3000, len(df)), random_state=42) ax.scatter(sample['distance_to_facility_km'], sample['total_basic_doses'], alpha=0.3, s=8, c='#3498db') ax.set_xlabel('Distance to Facility (km)') ax.set_ylabel('Total Basic Doses Received') ax.set_title('Distance vs Doses Received') # Panel 6: Cross-scenario zero-dose and fully immunised ax = axes[2, 1] metrics = ['zero_dose', 'fully_immunised'] x = np.arange(len(SCENARIOS)) width = 0.35 for i, m in enumerate(metrics): rates = [] for sc in SCENARIOS: if sc in dfs: d = dfs[sc] rates.append(d[d['age_months'] >= 1][m].mean() * 100) else: rates.append(0) color = '#e74c3c' if m == 'zero_dose' else '#2ecc71' ax.bar(x + i * width, rates, width, label=m.replace('_', ' ').title(), color=color, alpha=0.8) ax.set_xticks(x + width / 2) ax.set_xticklabels([s.replace('_', '\n').title() for s in SCENARIOS], fontsize=8) ax.set_ylabel('%') ax.set_title('Zero-Dose & Fully Immunised Across Scenarios') ax.legend(fontsize=9) # Panel 7: Dropout rates across scenarios ax = axes[3, 0] for sc in SCENARIOS: if sc not in dfs: continue d = dfs[sc] elig_d = d[d['age_months'] >= 4] if len(elig_d) == 0: continue p13 = elig_d['dropout_penta1_penta3'].mean() * 100 elig_mcv = d[d['age_months'] >= 10] pm = elig_mcv['dropout_penta1_mcv1'].mean() * 100 if len(elig_mcv) > 0 else 0 ax.bar([f'{sc.replace("_", chr(10)).title()}\nPenta1→3', f'{sc.replace("_", chr(10)).title()}\nPenta1→MCV1'], [p13, pm], alpha=0.7) ax.set_ylabel('Dropout Rate (%)') ax.set_title('Dropout Rates') # Panel 8: Coverage by maternal education ax = axes[3, 1] edu_order = ['none', 'primary', 'secondary', 'tertiary'] for v, color in [('penta3', '#3498db'), ('mcv1', '#e74c3c')]: covs = [] for edu in edu_order: sub = elig[elig['maternal_education'] == edu] covs.append(sub[v].mean() * 100 if len(sub) > 0 else 0) ax.plot(edu_order, covs, 'o-', label=v.upper(), linewidth=2, markersize=8, color=color) ax.set_xlabel('Maternal Education') ax.set_ylabel('Coverage (%)') ax.set_title('Coverage by Maternal Education') ax.legend(fontsize=10) 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 not dfs: print('No data files found in data/') else: make_report(dfs)