Kossisoroyce's picture
Upload folder using huggingface_hub
5c2eaba verified
Raw
History Blame Contribute Delete
4.99 kB
#!/usr/bin/env python3
"""Validation for Social Health Protection & Equity Dataset."""
import pandas as pd, numpy as np, matplotlib.pyplot as plt, os, glob
def load_scenarios(data_dir='data'):
dfs = {}
for f in sorted(glob.glob(os.path.join(data_dir, 'shp_*.csv'))):
name = os.path.basename(f).replace('.csv', '')[4:]
dfs[name] = pd.read_csv(f)
return dfs
def main():
dfs = load_scenarios()
if not dfs: return
all_df = pd.concat([df.assign(scenario=n) for n, df in dfs.items()], ignore_index=True)
fig, axes = plt.subplots(4, 2, figsize=(16, 20))
fig.suptitle('Social Health Protection & Equity — Validation Report', fontsize=14, fontweight='bold', y=0.98)
colors = {'strong_protection': '#2ecc71', 'moderate_protection': '#f39c12', 'weak_protection': '#e74c3c'}
labels = {'strong_protection': 'Strong (Rwanda/SA)', 'moderate_protection': 'Moderate (Kenya/Ghana)', 'weak_protection': 'Weak (Nigeria/DRC)'}
scenarios = list(dfs.keys())
ax = axes[0, 0]
metrics = ['SP Coverage', 'Insurance', 'Catastrophic', 'Unmet Need']
for i, s in enumerate(scenarios):
d = dfs[s]
vals = [d['has_social_protection'].mean()*100, d['has_health_insurance'].mean()*100, d['catastrophic_expenditure'].mean()*100, d['unmet_need'].mean()*100]
ax.bar(np.arange(len(metrics))+i*0.25, vals, 0.25, label=labels.get(s,s), color=colors[s], alpha=0.8)
ax.set_xticks(np.arange(len(metrics))+0.25); ax.set_xticklabels(metrics, fontsize=8); ax.set_ylabel('%'); ax.set_title('Panel 1: Key Metrics'); ax.legend(fontsize=7)
ax = axes[0, 1]
for s in scenarios:
rates = dfs[s].groupby('ses_quintile')['has_social_protection'].mean()*100
ax.plot(rates.index, rates.values, 'o-', label=labels.get(s,s), color=colors[s], lw=2)
ax.set_xlabel('SES Quintile (1=poorest)'); ax.set_ylabel('SP Coverage (%)'); ax.set_title('Panel 2: SP Coverage by Wealth'); ax.legend(fontsize=8)
ax = axes[1, 0]
for s in scenarios:
rates = dfs[s].groupby('ses_quintile')['catastrophic_expenditure'].mean()*100
ax.plot(rates.index, rates.values, 'o-', label=labels.get(s,s), color=colors[s], lw=2)
ax.set_xlabel('SES Quintile'); ax.set_ylabel('Catastrophic (%)'); ax.set_title('Panel 3: Catastrophic Expenditure by Wealth'); ax.legend(fontsize=8)
ax = axes[1, 1]
barriers = ['cost', 'distance', 'quality', 'availability']
for i, s in enumerate(scenarios):
unmet = dfs[s][dfs[s]['unmet_need']==1]
if len(unmet) == 0: continue
vals = [unmet['primary_barrier'].value_counts().get(b,0)/len(unmet)*100 for b in barriers]
ax.bar(np.arange(len(barriers))+i*0.25, vals, 0.25, label=labels.get(s,s), color=colors[s], alpha=0.8)
ax.set_xticks(np.arange(len(barriers))+0.25); ax.set_xticklabels(barriers, fontsize=8); ax.set_ylabel('% of Unmet Need'); ax.set_title('Panel 4: Barriers to Care'); ax.legend(fontsize=7)
ax = axes[2, 0]
for s in scenarios:
ax.hist(dfs[s]['financial_protection_score'], bins=30, alpha=0.5, label=labels.get(s,s), color=colors[s], density=True)
ax.set_xlabel('Financial Protection Score'); ax.set_title('Panel 5: Financial Protection Score'); ax.legend(fontsize=7)
ax = axes[2, 1]
for s in scenarios:
rates = dfs[s].groupby('ses_quintile')['sought_care'].mean()*100
ax.plot(rates.index, rates.values, 'o-', label=labels.get(s,s), color=colors[s], lw=2)
ax.set_xlabel('SES Quintile'); ax.set_ylabel('Utilisation (%)'); ax.set_title('Panel 6: Utilisation by Wealth'); ax.legend(fontsize=8)
ax = axes[3, 0]
for s in scenarios:
ax.hist(dfs[s].loc[dfs[s]['oop_spending_usd']>0, 'oop_spending_usd'].clip(upper=200), bins=40, alpha=0.5, label=labels.get(s,s), color=colors[s], density=True)
ax.set_xlabel('OOP Spending (USD)'); ax.set_title('Panel 7: OOP Distribution'); ax.legend(fontsize=7)
ax = axes[3, 1]
num_cols = ['ses_quintile', 'has_social_protection', 'has_health_insurance', 'oop_spending_usd', 'catastrophic_expenditure', 'unmet_need', 'financial_protection_score']
corr = all_df[num_cols].corr()
im = ax.imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1, aspect='auto')
ax.set_xticks(range(len(num_cols))); ax.set_yticks(range(len(num_cols)))
ax.set_xticklabels([c.replace('_','\n') for c in num_cols], fontsize=5, rotation=45, ha='right')
ax.set_yticklabels([c.replace('_','\n') for c in num_cols], fontsize=5)
ax.set_title('Panel 8: Correlation Heatmap'); fig.colorbar(im, ax=ax, fraction=0.046)
for i in range(len(num_cols)):
for j in range(len(num_cols)):
ax.text(j, i, f'{corr.iloc[i,j]:.2f}', ha='center', va='center', fontsize=4.5, color='white' if abs(corr.iloc[i,j])>0.5 else 'black')
plt.tight_layout(rect=[0,0,1,0.96]); plt.savefig('validation_report.png', dpi=150, bbox_inches='tight'); plt.close()
print("Saved validation_report.png")
if __name__ == '__main__':
main()