#!/usr/bin/env python3 """Validation & Diagnostic Visualization for Preterm/KMC Dataset.""" import pandas as pd import numpy as np import matplotlib.pyplot as plt import os SCENARIOS = ['nicu', 'special_care_nursery', 'postnatal_ward'] def load_scenarios(data_dir='data'): dfs = {} for sc in SCENARIOS: path = os.path.join(data_dir, f'preterm_{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('Preterm Birth & Kangaroo Mother Care — Validation Report', fontsize=16, fontweight='bold', y=0.98) df = dfs.get('special_care_nursery', list(dfs.values())[0]) colors = ['#2ecc71', '#f39c12', '#e74c3c'] ax = axes[0, 0] x = np.arange(len(SCENARIOS)) mort = [dfs[sc]['neonatal_death'].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(['NICU', 'SCN', 'Postnatal'], fontsize=9) for i, v in enumerate(mort): ax.text(i, v + 0.5, f'{v:.1f}%', ha='center', fontsize=10) ax.set_ylabel('Neonatal Mortality (%)') ax.set_title('Neonatal Mortality (preterm = leading U5 cause)') ax = axes[0, 1] kmc = df[df['kmc_initiated'] == 1] no_kmc = df[df['kmc_initiated'] == 0] if len(kmc) > 0 and len(no_kmc) > 0: m_k = kmc['neonatal_death'].mean() * 100 m_n = no_kmc['neonatal_death'].mean() * 100 ax.bar(['KMC', 'No KMC'], [m_k, m_n], color=['#2ecc71', '#e74c3c'], alpha=0.8) for i, v in enumerate([m_k, m_n]): ax.text(i, v + 0.5, f'{v:.1f}%', ha='center', fontsize=10) ax.set_ylabel('Mortality (%)') ax.set_title('KMC Effect on Mortality (reduces 25-40%)') ax = axes[1, 0] ga_bins = [24, 28, 32, 34, 37] ga_labels = ['24-27', '28-31', '32-33', '34-36'] df_copy = df.copy() df_copy['ga_bin'] = pd.cut(df_copy['gestational_age_weeks'], bins=ga_bins, labels=ga_labels, right=False) ga_mort = df_copy.groupby('ga_bin', observed=True)['neonatal_death'].mean() * 100 ax.bar(range(len(ga_mort)), ga_mort.values, color=['#e74c3c', '#f39c12', '#3498db', '#2ecc71'], alpha=0.8) ax.set_xticks(range(len(ga_mort))) ax.set_xticklabels(ga_mort.index, fontsize=9) for i, v in enumerate(ga_mort.values): ax.text(i, v + 0.5, f'{v:.0f}%', ha='center', fontsize=9) ax.set_ylabel('Mortality (%)') ax.set_title('Mortality by Gestational Age') ax = axes[1, 1] cascade = ['KMC', 'KMC <24h', 'EBF', 'CPAP', 'Surfactant', 'Steroids'] for i, sc_name in enumerate(SCENARIOS): if sc_name in dfs: d = dfs[sc_name] vals = [d['kmc_initiated'].mean()*100, d['kmc_within_24h'].mean()*100, d['exclusive_breastfeeding'].mean()*100, d['cpap_given'].mean()*100, d['surfactant_given'].mean()*100, d['antenatal_steroids'].mean()*100] ax.plot(range(6), vals, 'o-', label=sc_name.replace('_', ' ').title()[:10], color=colors[i], linewidth=2, markersize=6) ax.set_xticks(range(6)) ax.set_xticklabels(cascade, fontsize=7, rotation=20) ax.set_ylabel('Rate (%)') ax.set_title('Intervention Cascade') ax.legend(fontsize=7) ax = axes[2, 0] complications = ['rds', 'neonatal_sepsis', 'jaundice', 'hypothermia', 'apnoea', 'nec', 'ivh'] c_labels = ['RDS', 'Sepsis', 'Jaundice', 'Hypothermia', 'Apnoea', 'NEC', 'IVH'] vals = [df[c].mean() * 100 for c in complications] ax.barh(range(7), vals, color='#e74c3c', alpha=0.7) ax.set_yticks(range(7)) ax.set_yticklabels(c_labels, fontsize=8) for i, v in enumerate(vals): ax.text(v + 0.3, i, f'{v:.1f}%', va='center', fontsize=8) ax.set_xlabel('Rate (%)') ax.set_title('Complications') ax = axes[2, 1] ax.hist(df['birth_weight_g'], bins=30, color='#3498db', alpha=0.7, edgecolor='white') ax.axvline(1500, color='red', linestyle='--', linewidth=2, label='VLBW <1500g') ax.axvline(1000, color='darkred', linestyle='--', linewidth=2, label='ELBW <1000g') ax.set_xlabel('Birth Weight (g)') ax.set_title('Birth Weight Distribution') ax.legend(fontsize=8) ax = axes[3, 0] kmc_hrs = df[df['kmc_initiated'] == 1] if len(kmc_hrs) > 0: ax.hist(kmc_hrs['kmc_hours_per_day'], bins=15, color='#2ecc71', alpha=0.7, edgecolor='white') ax.axvline(8, color='red', linestyle='--', linewidth=2, label='WHO: 8+ hrs/day') ax.set_xlabel('KMC Hours per Day') ax.set_title('KMC Duration (WHO: 8+ hrs/day)') ax.legend(fontsize=8) ax = axes[3, 1] steroids = df[df['antenatal_steroids'] == 1] no_steroids = df[df['antenatal_steroids'] == 0] cats = ['RDS', 'Mortality'] if len(steroids) > 0 and len(no_steroids) > 0: vs = [steroids['rds'].mean()*100, steroids['neonatal_death'].mean()*100] vn = [no_steroids['rds'].mean()*100, no_steroids['neonatal_death'].mean()*100] w = 0.3 ax.bar(np.arange(2) - w/2, vn, w, label='No Steroids', color='#e74c3c', alpha=0.8) ax.bar(np.arange(2) + w/2, vs, w, label='Steroids', color='#2ecc71', alpha=0.8) ax.set_xticks(np.arange(2)) ax.set_xticklabels(cats, fontsize=9) ax.set_ylabel('Rate (%)') ax.set_title('Antenatal Steroids Effect') 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)