File size: 5,800 Bytes
ba0fd6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python3
"""Validation & Diagnostic Visualization for iCCM CHW Triage Dataset."""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os

SCENARIOS = ['low_burden', 'moderate_burden', 'high_burden']


def load_scenarios(data_dir='data'):
    dfs = {}
    for sc in SCENARIOS:
        path = os.path.join(data_dir, f'iccm_{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('iCCM Community Health Worker Triage — Validation Report',
                 fontsize=16, fontweight='bold', y=0.98)
    df = dfs.get('moderate_burden', list(dfs.values())[0])

    # Panel 1: True diagnosis distribution
    ax = axes[0, 0]
    diags = ['malaria', 'pneumonia', 'diarrhoea', 'mixed', 'other_febrile']
    colors_d = ['#e74c3c', '#3498db', '#f39c12', '#9b59b6', '#95a5a6']
    counts = [((df['true_diagnosis'] == d).sum()) for d in diags]
    ax.bar(range(5), counts, color=colors_d)
    ax.set_xticks(range(5))
    ax.set_xticklabels([d.replace('_', ' ').title() for d in diags], fontsize=8)
    for i, v in enumerate(counts):
        ax.text(i, v + 30, f'{v/len(df)*100:.1f}%', ha='center', fontsize=9)
    ax.set_ylabel('Count')
    ax.set_title('True Diagnosis (Moderate Burden)')

    # Panel 2: CHW action distribution
    ax = axes[0, 1]
    actions = df['chw_action'].value_counts()
    colors_a = {'treat_at_community': '#2ecc71', 'refer_urgently': '#e74c3c',
                'treat_and_refer': '#f39c12', 'refer': '#e67e22'}
    ax.bar(range(len(actions)), actions.values,
           color=[colors_a.get(a, '#95a5a6') for a in actions.index])
    ax.set_xticks(range(len(actions)))
    ax.set_xticklabels([a.replace('_', '\n') for a in actions.index], fontsize=7)
    for i, v in enumerate(actions.values):
        ax.text(i, v + 30, f'{v/len(df)*100:.1f}%', ha='center', fontsize=9)
    ax.set_ylabel('Count')
    ax.set_title('CHW Action')

    # Panel 3: Symptom prevalence
    ax = axes[1, 0]
    syms = ['fever', 'cough', 'fast_breathing', 'diarrhoea', 'any_danger_sign']
    vals = [df[s].mean() * 100 for s in syms]
    ax.barh(range(5), vals, color='#3498db', alpha=0.8)
    ax.set_yticks(range(5))
    ax.set_yticklabels([s.replace('_', ' ').title() for s in syms])
    for i, v in enumerate(vals):
        ax.text(v + 0.5, i, f'{v:.1f}%', va='center', fontsize=10)
    ax.set_xlabel('Prevalence (%)')
    ax.set_title('Symptom & Sign Prevalence')

    # Panel 4: Treatment given
    ax = axes[1, 1]
    treatments = ['act_given', 'amoxicillin_given', 'ors_given', 'zinc_given']
    t_vals = [df[t].mean() * 100 for t in treatments]
    colors_t = ['#e74c3c', '#3498db', '#f39c12', '#2ecc71']
    ax.bar(range(4), t_vals, color=colors_t, alpha=0.8)
    ax.set_xticks(range(4))
    ax.set_xticklabels(['ACT', 'Amoxicillin', 'ORS', 'Zinc'])
    for i, v in enumerate(t_vals):
        ax.text(i, v + 0.5, f'{v:.1f}%', ha='center', fontsize=10)
    ax.set_ylabel('% of all cases')
    ax.set_title('Treatment Given')

    # Panel 5: Cross-scenario diagnosis rates
    ax = axes[2, 0]
    x = np.arange(len(diags))
    width = 0.25
    for i, sc in enumerate(SCENARIOS):
        if sc not in dfs:
            continue
        d = dfs[sc]
        rates = [(d['true_diagnosis'] == diag).mean() * 100 for diag in diags]
        ax.bar(x + i * width, rates, width, label=sc.replace('_', ' ').title(), alpha=0.8)
    ax.set_xticks(x + width)
    ax.set_xticklabels([d.replace('_', ' ').title() for d in diags], fontsize=7)
    ax.set_ylabel('Prevalence (%)')
    ax.set_title('Diagnosis Rates Across Scenarios')
    ax.legend(fontsize=8)

    # Panel 6: MUAC distribution
    ax = axes[2, 1]
    ax.hist(df['muac_cm'], bins=50, color='#9b59b6', alpha=0.7, edgecolor='white')
    ax.axvline(11.5, color='red', ls='--', lw=1.5, label='SAM <11.5')
    ax.axvline(12.5, color='orange', ls='--', lw=1.5, label='MAM <12.5')
    ax.set_xlabel('MUAC (cm)')
    ax.set_title(f'MUAC Distribution (SAM={( df["nutrition_status"]=="SAM").mean()*100:.1f}%)')
    ax.legend(fontsize=8)

    # Panel 7: Age distribution by diagnosis
    ax = axes[3, 0]
    for diag, color in [('malaria', '#e74c3c'), ('pneumonia', '#3498db'), ('diarrhoea', '#f39c12')]:
        sub = df[df['true_diagnosis'] == diag]['age_months']
        ax.hist(sub, bins=30, alpha=0.5, color=color, label=diag.title(), edgecolor='white')
    ax.set_xlabel('Age (months)')
    ax.set_title('Age Distribution by Diagnosis')
    ax.legend(fontsize=9)

    # Panel 8: Referral rate across scenarios
    ax = axes[3, 1]
    ref_rates = []
    ds_rates = []
    sam_rates = []
    for sc in SCENARIOS:
        if sc not in dfs:
            continue
        d = dfs[sc]
        ref_rates.append(np.mean(['refer' in str(a) for a in d['chw_action']]) * 100)
        ds_rates.append(d['any_danger_sign'].mean() * 100)
        sam_rates.append((d['nutrition_status'] == 'SAM').mean() * 100)
    x = np.arange(len(SCENARIOS))
    ax.bar(x - 0.2, ref_rates, 0.2, label='Referral Rate', color='#e74c3c', alpha=0.8)
    ax.bar(x, ds_rates, 0.2, label='Danger Signs', color='#f39c12', alpha=0.8)
    ax.bar(x + 0.2, sam_rates, 0.2, label='SAM', color='#9b59b6', alpha=0.8)
    ax.set_xticks(x)
    ax.set_xticklabels([s.replace('_', '\n').title() for s in SCENARIOS], fontsize=8)
    ax.set_ylabel('%')
    ax.set_title('Referral, Danger Signs, SAM Across Scenarios')
    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)