#!/usr/bin/env python3 """Validation & Diagnostic Visualization for DS-TB Treatment Cascade Dataset.""" import pandas as pd import numpy as np import matplotlib.pyplot as plt import os SCENARIOS = ['urban_dots_centre', 'district_hospital', 'rural_health_post'] def load_scenarios(data_dir='data'): dfs = {} for sc in SCENARIOS: path = os.path.join(data_dir, f'tb_{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('Drug-Sensitive TB Treatment Cascade — 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)) success = [dfs[sc]['treatment_success'].mean()*100 for sc in SCENARIOS if sc in dfs] ax.bar(x, success, color=colors, alpha=0.8) ax.set_xticks(x) ax.set_xticklabels(['Urban DOTS', 'District', 'Rural'], fontsize=9) for i, v in enumerate(success): ax.text(i, v + 0.5, f'{v:.0f}%', ha='center', fontsize=10) ax.set_ylabel('Treatment Success (%)') ax.set_title('Treatment Success (WHO target ≥85%)') ax = axes[0, 1] outcomes = df['treatment_outcome'].value_counts() o_colors = ['#2ecc71', '#3498db', '#e74c3c', '#f39c12', '#9b59b6', '#95a5a6'] ax.pie(outcomes.values, labels=[s.replace('_', ' ').title() for s in outcomes.index], autopct='%1.0f%%', colors=o_colors[:len(outcomes)], startangle=90, textprops={'fontsize': 8}) ax.set_title('Treatment Outcomes') ax = axes[1, 0] cascade = ['Tx Started', 'Intensive', 'Continuation', 'Success'] for i, sc_name in enumerate(SCENARIOS): if sc_name in dfs: d = dfs[sc_name] vals = [d['treatment_started'].mean()*100, d['intensive_phase_completed'].mean()*100, d['continuation_phase_completed'].mean()*100, d['treatment_success'].mean()*100] ax.plot(range(4), vals, 'o-', label=sc_name.replace('_', ' ').title()[:12], color=colors[i], linewidth=2, markersize=6) ax.set_xticks(range(4)) ax.set_xticklabels(cascade, fontsize=9) ax.set_ylabel('Rate (%)') ax.set_title('Treatment Cascade (drop-off at each stage)') ax.legend(fontsize=7) ax = axes[1, 1] hiv_pos = df[df['hiv_positive'] == 1] hiv_neg = df[df['hiv_positive'] == 0] cats = ['Tx Success', 'Died', 'LTFU'] if len(hiv_pos) > 0 and len(hiv_neg) > 0: vp = [hiv_pos['treatment_success'].mean()*100, hiv_pos['died_during_treatment'].mean()*100, (hiv_pos['treatment_outcome'] == 'lost_to_followup').mean()*100] vn = [hiv_neg['treatment_success'].mean()*100, hiv_neg['died_during_treatment'].mean()*100, (hiv_neg['treatment_outcome'] == 'lost_to_followup').mean()*100] w = 0.3 ax.bar(np.arange(3) - w/2, vp, w, label='HIV+', color='#e74c3c', alpha=0.8) ax.bar(np.arange(3) + w/2, vn, w, label='HIV-', color='#2ecc71', alpha=0.8) ax.set_xticks(np.arange(3)) ax.set_xticklabels(cats, fontsize=9) ax.set_ylabel('Rate (%)') ax.set_title('TB-HIV Coinfection Impact (~35%)') ax.legend(fontsize=8) ax = axes[2, 0] diag = df['diagnostic_method'].value_counts() ax.bar(range(len(diag)), diag.values, color=['#3498db', '#f39c12', '#e74c3c'][:len(diag)], alpha=0.8) ax.set_xticks(range(len(diag))) ax.set_xticklabels([s.replace('_', ' ').title() for s in diag.index], fontsize=8) ax.set_ylabel('Count') ax.set_title('Diagnostic Method (GeneXpert rollout)') ax = axes[2, 1] ax.hist(df['diagnosis_delay_days'], bins=30, color='#f39c12', alpha=0.7, edgecolor='white') ax.axvline(30, color='red', linestyle='--', linewidth=2, label='30 days') ax.set_xlabel('Delay (days)') ax.set_title('Diagnostic Delay') ax.legend(fontsize=8) ax = axes[3, 0] ltfu = [dfs[sc][dfs[sc]['treatment_outcome'] == 'lost_to_followup'].shape[0] / max(1, dfs[sc]['treatment_started'].sum()) * 100 for sc in SCENARIOS if sc in dfs] died = [dfs[sc]['died_during_treatment'].mean()*100 for sc in SCENARIOS if sc in dfs] w = 0.3 ax.bar(x - w/2, ltfu, w, label='LTFU', color='#f39c12', alpha=0.8) ax.bar(x + w/2, died, w, label='Died', color='#e74c3c', alpha=0.8) ax.set_xticks(x) ax.set_xticklabels(['Urban DOTS', 'District', 'Rural'], fontsize=9) ax.set_ylabel('Rate (%)') ax.set_title('LTFU & Mortality') ax.legend(fontsize=8) ax = axes[3, 1] dot_y = df[df['dot_received'] == 1] dot_n = df[df['dot_received'] == 0] if len(dot_y) > 0 and len(dot_n) > 0: ax.hist(dot_y['adherence_rate'], bins=20, alpha=0.6, label='DOT', color='#2ecc71') ax.hist(dot_n['adherence_rate'], bins=20, alpha=0.6, label='No DOT', color='#e74c3c') ax.set_xlabel('Adherence Rate') ax.set_title('Adherence: DOT vs Self-Administered') 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)