#!/usr/bin/env python3 """Validation & Diagnostic Visualization for Obstetric Fistula Dataset.""" import pandas as pd import numpy as np import matplotlib.pyplot as plt import os SCENARIOS = ['specialized_fistula_centre', 'district_hospital', 'no_surgical_access'] def load_scenarios(data_dir='data'): dfs = {} for sc in SCENARIOS: path = os.path.join(data_dir, f'fistula_{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('Obstetric Fistula — 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)) repair = [dfs[sc]['repair_performed'].mean()*100 for sc in SCENARIOS if sc in dfs] success = [] for sc in SCENARIOS: if sc in dfs: d = dfs[sc] rep = d[d['repair_performed'] == 1] success.append(rep['repair_successful'].mean()*100 if len(rep) > 0 else 0) w = 0.3 ax.bar(x - w/2, repair, w, label='Repair Performed', color='#3498db', alpha=0.8) ax.bar(x + w/2, success, w, label='Repair Success', color='#2ecc71', alpha=0.8) ax.set_xticks(x) ax.set_xticklabels(['Specialist', 'District', 'No Access'], fontsize=9) ax.set_ylabel('Rate (%)') ax.set_title('Repair Access & Success (85-90% at specialist)') ax.legend(fontsize=8) ax = axes[0, 1] ft = df['fistula_type'].value_counts() c_colors = ['#e74c3c', '#f39c12', '#9b59b6'] ax.pie(ft.values, labels=[s.replace('_', ' ').upper() for s in ft.index], autopct='%1.0f%%', colors=c_colors[:len(ft)], startangle=90, textprops={'fontsize': 9}) ax.set_title('Fistula Type (VVF = 80%)') ax = axes[1, 0] social = ['divorced_separated', 'social_isolation', 'depression', 'unable_to_work', 'skin_excoriation', 'malodour'] s_labels = ['Divorced', 'Isolated', 'Depression', 'Unable Work', 'Excoriation', 'Malodour'] vals = [df[s].mean()*100 for s in social] ax.barh(range(6), vals, color='#9b59b6', alpha=0.7) ax.set_yticks(range(6)) ax.set_yticklabels(s_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('Social Consequences (devastating)') ax = axes[1, 1] ax.hist(df['years_living_with_fistula'], bins=20, color='#e74c3c', alpha=0.7, edgecolor='white') ax.set_xlabel('Years Living with Fistula') ax.set_title('Duration Before Presentation') ax = axes[2, 0] risks = ['child_marriage', 'short_stature', 'prolonged_labour', 'obstructed_labour', 'stillbirth'] r_labels = ['Child Marriage', 'Short Stature', 'Prolonged Labour', 'Obstructed Labour', 'Stillbirth'] vals = [df[r].mean()*100 for r in risks] ax.bar(range(5), vals, color=['#e74c3c', '#f39c12', '#9b59b6', '#3498db', '#e67e22'], alpha=0.8) ax.set_xticks(range(5)) ax.set_xticklabels(r_labels, fontsize=7, rotation=15) for i, v in enumerate(vals): ax.text(i, v + 0.5, f'{v:.0f}%', ha='center', fontsize=8) ax.set_ylabel('Prevalence (%)') ax.set_title('Risk Factors (obstructed labour = key cause)') ax = axes[2, 1] barriers = df[df['barrier_to_care'] != 'none']['barrier_to_care'].value_counts() if len(barriers) > 0: ax.barh(range(len(barriers)), barriers.values, color='#3498db', alpha=0.8) ax.set_yticks(range(len(barriers))) ax.set_yticklabels([s.replace('_', ' ').title() for s in barriers.index], fontsize=9) ax.set_xlabel('Count') ax.set_title('Barriers to Care') ax = axes[3, 0] sizes = ['small', 'medium', 'large', 'extensive'] rep_d = df[df['repair_performed'] == 1] if len(rep_d) > 0: size_success = [] for sz in sizes: sz_d = rep_d[rep_d['fistula_size'] == sz] size_success.append(sz_d['repair_successful'].mean()*100 if len(sz_d) > 0 else 0) ax.bar(range(4), size_success, color=['#2ecc71', '#f39c12', '#e74c3c', '#9b59b6'], alpha=0.8) ax.set_xticks(range(4)) ax.set_xticklabels(sizes, fontsize=9) for i, v in enumerate(size_success): ax.text(i, v + 1, f'{v:.0f}%', ha='center', fontsize=9) ax.set_ylabel('Success Rate (%)') ax.set_title('Repair Success by Fistula Size') ax = axes[3, 1] ax.hist(df['age_at_fistula_onset'], bins=20, color='#f39c12', alpha=0.7, edgecolor='white', label='Onset') ax.hist(df['age_at_presentation'], bins=20, color='#3498db', alpha=0.5, edgecolor='white', label='Presentation') ax.set_xlabel('Age (years)') ax.set_title('Age at Onset vs Presentation') 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)