#!/usr/bin/env python3 """Validation & Diagnostic Visualization for Stroke Dataset.""" import pandas as pd import numpy as np import matplotlib.pyplot as plt import os SCENARIOS = ['tertiary_hospital', 'district_hospital', 'rural_facility'] def load_scenarios(data_dir='data'): dfs = {} for sc in SCENARIOS: path = os.path.join(data_dir, f'stroke_{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('Stroke & Cerebrovascular 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] x = np.arange(len(SCENARIOS)) mort = [(dfs[sc]['outcome_30_day'] == '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(['Tertiary', 'District', 'Rural'], fontsize=9) for i, v in enumerate(mort): ax.text(i, v + 0.5, f'{v:.1f}%', ha='center', fontsize=10) ax.set_ylabel('30-Day Mortality (%)') ax.set_title('30-Day Mortality (SSA pooled ~30%)') ax = axes[0, 1] types = ['ischaemic', 'intracerebral_haemorrhage', 'subarachnoid_haemorrhage'] t_labels = ['Ischaemic', 'ICH', 'SAH'] vals = [(df['stroke_type'] == t).mean() * 100 for t in types] t_colors = ['#3498db', '#e74c3c', '#f39c12'] ax.pie(vals, labels=t_labels, autopct='%1.0f%%', colors=t_colors, startangle=90, textprops={'fontsize': 10}) ax.set_title('Stroke Type (60% ischaemic, 32% ICH)') ax = axes[1, 0] risks = ['hypertension', 'diabetes', 'atrial_fibrillation', 'smoking', 'alcohol_heavy', 'prior_stroke', 'hiv_positive'] r_labels = ['HTN', 'DM', 'AF', 'Smoking', 'Alcohol', 'Prior Stroke', 'HIV'] vals = [df[r].mean() * 100 for r in risks] ax.barh(range(7), vals, color='#e74c3c', alpha=0.7) ax.set_yticks(range(7)) ax.set_yticklabels(r_labels, fontsize=8) for i, v in enumerate(vals): ax.text(v + 0.3, i, f'{v:.0f}%', va='center', fontsize=8) ax.set_xlabel('Prevalence (%)') ax.set_title('Risk Factors (HTN #1)') ax = axes[1, 1] for t, col, lab in [('ischaemic', '#3498db', 'Ischaemic'), ('intracerebral_haemorrhage', '#e74c3c', 'ICH')]: sub = df[df['stroke_type'] == t] m = (sub['outcome_30_day'] == 'died').mean() * 100 if len(sub) > 0 else 0 ax.bar(lab, m, color=col, alpha=0.8) ax.text(lab, m + 0.5, f'{m:.0f}%', ha='center', fontsize=10) ax.set_ylabel('30-Day Mortality (%)') ax.set_title('Mortality by Stroke Type (ICH > Ischaemic)') ax = axes[2, 0] for sc_name, col in zip(SCENARIOS, colors): if sc_name in dfs: d = dfs[sc_name] ax.hist(d['onset_to_arrival_hours'].clip(upper=72), bins=20, alpha=0.4, color=col, label=sc_name.replace('_', ' ').title()[:10], edgecolor='white') ax.set_xlabel('Hours from Onset to Arrival') ax.set_title('Presentation Delay') ax.legend(fontsize=7) ax = axes[2, 1] cascade = ['CT Scan', 'Antiplatelet', 'Thrombolysis', 'Statin', 'Physio'] for i, sc_name in enumerate(SCENARIOS): if sc_name in dfs: d = dfs[sc_name] vals = [d['ct_performed'].mean()*100, d['antiplatelet'].mean()*100, d['thrombolysis'].mean()*100, d['statin'].mean()*100, d['physiotherapy_started'].mean()*100] ax.plot(range(5), vals, 'o-', label=sc_name.replace('_', ' ').title()[:10], color=colors[i], linewidth=2, markersize=6) ax.set_xticks(range(5)) ax.set_xticklabels(cascade, fontsize=8) ax.set_ylabel('Rate (%)') ax.set_title('Treatment Cascade (thrombolysis near-zero SSA)') ax.legend(fontsize=7) ax = axes[3, 0] survived = df[df['outcome_30_day'] == 'survived'] if len(survived) > 0: mrs = survived['mrs_discharge'].value_counts().sort_index() ax.bar(mrs.index.astype(str), mrs.values, color='#3498db', alpha=0.8) ax.set_xlabel('Modified Rankin Scale') ax.set_ylabel('Count') ax.set_title('Disability at Discharge (mRS)') ax = axes[3, 1] died = df[df['outcome_30_day'] == 'died']['age_years'] surv = df[df['outcome_30_day'] == 'survived']['age_years'] ax.hist(surv, bins=20, alpha=0.5, color='#2ecc71', label='Survived', edgecolor='white') ax.hist(died, bins=20, alpha=0.7, color='#e74c3c', label='Died', edgecolor='white') ax.set_xlabel('Age (years)') ax.set_title('Age Distribution (mean ~59, younger than HICs)') 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)