Kossisoroyce commited on
Commit
e0d61de
·
verified ·
1 Parent(s): 1af6630

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ task_categories:
4
+ - tabular-classification
5
+ language:
6
+ - en
7
+ tags:
8
+ - healthcare
9
+ - stroke
10
+ - cerebrovascular
11
+ - hypertension
12
+ - neurology
13
+ - thrombolysis
14
+ - sub-saharan-africa
15
+ - lmic
16
+ pretty_name: "Stroke & Cerebrovascular Disease (Type, Severity, Treatment, Disability)"
17
+ size_categories:
18
+ - 10K<n<100K
19
+ configs:
20
+ - config_name: tertiary_hospital
21
+ data_files: data/stroke_tertiary_hospital.csv
22
+ - config_name: district_hospital
23
+ data_files: data/stroke_district_hospital.csv
24
+ default: true
25
+ - config_name: rural_facility
26
+ data_files: data/stroke_rural_facility.csv
27
+ ---
28
+
29
+ # Stroke & Cerebrovascular Disease Dataset
30
+
31
+ ## Abstract
32
+
33
+ This dataset provides **30,000 simulated stroke records** (10,000 per scenario) of adults presenting with acute stroke in sub-Saharan Africa. Each record contains 50+ variables including risk factors, stroke type, severity (NIHSS, GCS), imaging, treatment, complications, and outcomes (30-day mortality, mRS). Three settings: tertiary hospital (28% mortality), district hospital (41%), and rural facility (57%).
34
+
35
+ ## 1. Introduction
36
+
37
+ Stroke in Africa has an annual incidence up to 316/100K person-years, with 30-day case fatality rates of ~30% (range 18-40%) and 90-day mortality reaching 50% at some centres. Approximately 60% of strokes are ischaemic and 32% haemorrhagic — a higher proportion of haemorrhagic stroke than in HICs. Mean age at onset is ~59 years, 10 years younger than Western populations. Hypertension is the dominant risk factor with BP control rates <10% in many SSA populations. CT scanning and thrombolysis are virtually unavailable outside tertiary centres.
38
+
39
+ **This dataset is entirely simulated. It must not be used for clinical decision-making.**
40
+
41
+ ## 2. Methodology
42
+
43
+ ### 2.1 Parameterization
44
+
45
+ | Parameter | Value | Source |
46
+ | --- | --- | --- |
47
+ | Incidence (Africa) | Up to 316/100K | Frontiers Stroke 2025 |
48
+ | 30-day CFR (SSA pooled) | ~30% | PLOS Glob PH 2024 |
49
+ | 90-day mortality | ~50% | Muhimbili 2018 |
50
+ | Ischaemic / ICH / SAH | 60% / 32% / 8% | Sierra Leone 2021 |
51
+ | Mean age | 59 years | Sierra Leone 2021 |
52
+ | Hypertension prevalence | 75% | PMC 2015 |
53
+ | BP control rate | <10% | PMC 2015 |
54
+ | Recurrence rate | 9-25% | PMC 2024 |
55
+
56
+ ### 2.2 Scenario Design
57
+
58
+ | Scenario | CT | Thrombolysis | Stroke Unit | 30-Day Mortality |
59
+ | --- | --- | --- | --- | --- |
60
+ | Tertiary hospital | Yes | Limited | Yes | 28% |
61
+ | District hospital | No | No | No | 41% |
62
+ | Rural facility | No | No | No | 57% |
63
+
64
+ ## 3. Schema
65
+
66
+ | Column | Type | Description |
67
+ | --- | --- | --- |
68
+ | id | int | Unique identifier |
69
+ | age_years | int | Patient age |
70
+ | sex | categorical | M / F |
71
+ | hypertension | binary | Hypertension |
72
+ | systolic_bp | int | Systolic BP (mmHg) |
73
+ | diastolic_bp | int | Diastolic BP (mmHg) |
74
+ | diabetes | binary | Diabetes |
75
+ | atrial_fibrillation | binary | AF |
76
+ | smoking | binary | Current smoker |
77
+ | alcohol_heavy | binary | Heavy alcohol |
78
+ | prior_stroke | binary | Prior stroke |
79
+ | stroke_type | categorical | ischaemic / intracerebral_haemorrhage / subarachnoid_haemorrhage |
80
+ | ischaemic_subtype | categorical | large_vessel / small_vessel / cardioembolic / undetermined |
81
+ | nihss_score | int | NIHSS (0-42) |
82
+ | gcs_score | int | GCS (3-15) |
83
+ | hemiparesis | binary | Hemiparesis |
84
+ | aphasia | binary | Aphasia |
85
+ | dysphagia | binary | Dysphagia |
86
+ | onset_to_arrival_hours | int | Time to presentation |
87
+ | ct_performed | binary | CT scan done |
88
+ | thrombolysis | binary | Thrombolysis given |
89
+ | antiplatelet | binary | Antiplatelet |
90
+ | statin | binary | Statin |
91
+ | physiotherapy_started | binary | Early physiotherapy |
92
+ | aspiration_pneumonia | binary | Aspiration pneumonia |
93
+ | outcome_30_day | categorical | survived / died |
94
+ | mrs_discharge | int | Modified Rankin Scale (0-5) |
95
+ | disability | categorical | none / mild / moderate / severe |
96
+ | hospital_days | int | Hospital stay |
97
+
98
+ ## 4. Validation
99
+
100
+ <p align="center">
101
+ <img src="validation_report.png" alt="Validation Report" width="100%">
102
+ </p>
103
+
104
+ Key validation checks:
105
+
106
+ - **Mortality gradient**: 28% → 41% → 57% ✓
107
+ - **Stroke type**: 60% ischaemic, 32% ICH ✓
108
+ - **Hypertension**: 75% prevalence ✓
109
+ - **CT access**: 80% tertiary vs 0% district/rural ✓
110
+ - **ICH mortality > ischaemic** ✓
111
+ - **Mean age ~59** ✓
112
+
113
+ ## 5. Usage
114
+
115
+ ```python
116
+ from datasets import load_dataset
117
+ dataset = load_dataset("electricsheepafrica/stroke-cerebrovascular-disease", "district_hospital")
118
+ df = dataset["train"].to_pandas()
119
+ ```
120
+
121
+ ## 6. Limitations
122
+
123
+ - **Simulated**: Not from real stroke registries.
124
+ - **No neuroimaging**: No actual CT/MRI data.
125
+ - **No longitudinal**: 30-day outcome only, no long-term follow-up.
126
+ - **No rehabilitation**: Limited rehab outcome data.
127
+ - **Simplified**: No detailed vascular territory mapping.
128
+
129
+ ## 7. References
130
+
131
+ 1. Frontiers Stroke (2025). Strategic action plan for stroke in Africa.
132
+ 2. PLOS Glob Public Health (2024). 30-day stroke CFR in SSA.
133
+ 3. PubMed (2021). Stroke register Sierra Leone.
134
+ 4. PubMed (2020). Predictors of stroke mortality Uganda.
135
+ 5. PubMed (2018). Stroke at Muhimbili Tanzania.
136
+ 6. PMC (2015). Burden of stroke in Africa.
137
+ 7. PMC (2024). Stroke recurrence in SSA.
138
+
139
+ ## Citation
140
+
141
+ ```bibtex
142
+ @dataset{esa_stroke_2025,
143
+ title={Stroke and Cerebrovascular Disease Dataset},
144
+ author={Electric Sheep Africa},
145
+ year={2025},
146
+ publisher={Hugging Face},
147
+ url={https://huggingface.co/datasets/electricsheepafrica/stroke-cerebrovascular-disease}
148
+ }
149
+ ```
150
+
151
+ ## License
152
+
153
+ [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/)
data/stroke_district_hospital.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/stroke_rural_facility.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/stroke_tertiary_hospital.csv ADDED
The diff for this file is too large to render. See raw diff
 
generate_dataset.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Literature-Informed Stroke & Cerebrovascular Disease Dataset
4
+ ==============================================================
5
+
6
+ Generates realistic synthetic records of stroke patients in
7
+ sub-Saharan Africa, including risk factors, stroke type, severity,
8
+ imaging, treatment, and outcomes.
9
+
10
+ Target population: Adults presenting with acute stroke to SSA
11
+ health facilities.
12
+
13
+ References (web-searched):
14
+ -----------
15
+ [1] Frontiers Stroke 2025. Africa stroke incidence up to
16
+ 316/100K person-years. 3-year fatality rate reaching 84%.
17
+ [2] PLOS Glob Public Health 2024. 30-day in-hospital stroke
18
+ CFR in SSA: pooled ~30% (range 18-40%).
19
+ [3] Sierra Leone stroke register 2021. 60% ischaemic, 22%
20
+ ICH, 3% SAH, 15% undetermined. Mean age 59.
21
+ [4] Uganda cohort 2020. Low consciousness at admission,
22
+ severity, haemorrhagic type predict 30/90-day mortality.
23
+ [5] Muhimbili Tanzania 2018. 90-day mortality 50%.
24
+ Thrombolysis virtually unavailable in SSA.
25
+ [6] PMC 2015. Hypertension is #1 risk factor. BP control
26
+ rates <10% in many SSA populations.
27
+ [7] Stroke recurrence SSA 2024. Recurrence 9.4-25%.
28
+ Hypertension, alcohol, prior stroke main risk factors.
29
+ """
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+ import argparse
34
+ import os
35
+
36
+ SCENARIOS = {
37
+ 'tertiary_hospital': {
38
+ 'description': 'Tertiary hospital with CT/MRI, stroke unit, '
39
+ 'physiotherapy, some thrombolysis capability '
40
+ '(e.g., Muhimbili Tanzania, UCH Ibadan, KBTH Ghana)',
41
+ 'ct_available': True,
42
+ 'mri_available': True,
43
+ 'thrombolysis_available': True,
44
+ 'stroke_unit': True,
45
+ 'physiotherapy': True,
46
+ 'mortality_mod': 0.7,
47
+ },
48
+ 'district_hospital': {
49
+ 'description': 'District hospital, no CT, clinical diagnosis, '
50
+ 'basic BP management, no stroke unit '
51
+ '(e.g., district hospitals Malawi, Uganda)',
52
+ 'ct_available': False,
53
+ 'mri_available': False,
54
+ 'thrombolysis_available': False,
55
+ 'stroke_unit': False,
56
+ 'physiotherapy': False,
57
+ 'mortality_mod': 1.0,
58
+ },
59
+ 'rural_facility': {
60
+ 'description': 'Rural facility, no imaging, delayed referral, '
61
+ 'minimal management '
62
+ '(e.g., rural DRC, Chad, South Sudan)',
63
+ 'ct_available': False,
64
+ 'mri_available': False,
65
+ 'thrombolysis_available': False,
66
+ 'stroke_unit': False,
67
+ 'physiotherapy': False,
68
+ 'mortality_mod': 1.5,
69
+ },
70
+ }
71
+
72
+
73
+ def generate_dataset(n=10000, seed=42, scenario='district_hospital'):
74
+ rng = np.random.default_rng(seed)
75
+ sc = SCENARIOS[scenario]
76
+
77
+ records = []
78
+
79
+ for idx in range(n):
80
+ rec = {'id': idx + 1}
81
+
82
+ # ── 1. Demographics [3] ──
83
+ rec['age_years'] = max(18, min(95, int(rng.normal(59, 14))))
84
+ rec['sex'] = rng.choice(['M', 'F'], p=[0.52, 0.48])
85
+ rec['rural'] = 1 if rng.random() < 0.60 else 0
86
+
87
+ # ── 2. Risk factors [6][7] ──
88
+ rec['hypertension'] = 1 if rng.random() < 0.75 else 0
89
+ rec['bp_on_treatment'] = 0
90
+ if rec['hypertension']:
91
+ rec['bp_on_treatment'] = 1 if rng.random() < 0.30 else 0
92
+ rec['bp_controlled'] = 0
93
+ if rec['bp_on_treatment']:
94
+ rec['bp_controlled'] = 1 if rng.random() < 0.25 else 0
95
+
96
+ rec['systolic_bp'] = max(90, min(260, int(rng.normal(
97
+ 160 if rec['hypertension'] and not rec['bp_controlled'] else 130, 25))))
98
+ rec['diastolic_bp'] = max(50, min(150, int(rng.normal(
99
+ 95 if rec['hypertension'] and not rec['bp_controlled'] else 80, 15))))
100
+
101
+ rec['diabetes'] = 1 if rng.random() < 0.20 else 0
102
+ rec['atrial_fibrillation'] = 1 if rng.random() < 0.08 else 0
103
+ rec['smoking'] = 1 if rng.random() < 0.15 else 0
104
+ rec['alcohol_heavy'] = 1 if rng.random() < 0.20 else 0
105
+ rec['hiv_positive'] = 1 if rng.random() < 0.08 else 0
106
+ rec['bmi'] = round(max(15, min(45, rng.normal(26, 5))), 1)
107
+ rec['prior_stroke'] = 1 if rng.random() < 0.12 else 0
108
+ rec['prior_tia'] = 1 if rng.random() < 0.05 else 0
109
+ rec['sickle_cell'] = 1 if rng.random() < 0.03 else 0
110
+
111
+ # ── 3. Stroke characteristics [3] ──
112
+ rec['stroke_type'] = rng.choice(
113
+ ['ischaemic', 'intracerebral_haemorrhage', 'subarachnoid_haemorrhage'],
114
+ p=[0.60, 0.32, 0.08])
115
+
116
+ if rec['stroke_type'] == 'ischaemic':
117
+ rec['ischaemic_subtype'] = rng.choice(
118
+ ['large_vessel', 'small_vessel', 'cardioembolic', 'undetermined'],
119
+ p=[0.30, 0.25, 0.15, 0.30])
120
+ else:
121
+ rec['ischaemic_subtype'] = 'n/a'
122
+
123
+ rec['nihss_score'] = max(0, min(42, int(rng.exponential(8))))
124
+ rec['gcs_score'] = max(3, min(15, int(rng.normal(
125
+ 12 if rec['nihss_score'] < 15 else 8, 3))))
126
+
127
+ rec['hemiparesis'] = 1 if rng.random() < 0.75 else 0
128
+ rec['aphasia'] = 1 if rng.random() < 0.30 else 0
129
+ rec['dysphagia'] = 1 if rng.random() < 0.35 else 0
130
+ rec['visual_field_defect'] = 1 if rng.random() < 0.15 else 0
131
+ rec['neglect'] = 1 if rng.random() < 0.10 else 0
132
+
133
+ rec['onset_to_arrival_hours'] = max(1, int(rng.exponential(
134
+ 24 if scenario == 'rural_facility' else 12)))
135
+
136
+ # ── 4. Diagnosis ──
137
+ rec['ct_performed'] = 0
138
+ if sc['ct_available']:
139
+ rec['ct_performed'] = 1 if rng.random() < 0.80 else 0
140
+
141
+ rec['mri_performed'] = 0
142
+ if sc['mri_available'] and rec['ct_performed']:
143
+ rec['mri_performed'] = 1 if rng.random() < 0.20 else 0
144
+
145
+ rec['ecg_done'] = 1 if rng.random() < (0.70 if sc['stroke_unit'] else 0.30) else 0
146
+ rec['echo_done'] = 1 if rng.random() < (0.30 if sc['ct_available'] else 0.05) else 0
147
+ rec['clinical_diagnosis_only'] = 1 if not rec['ct_performed'] else 0
148
+
149
+ # ── 5. Treatment [5] ──
150
+ rec['thrombolysis'] = 0
151
+ if (sc['thrombolysis_available'] and rec['stroke_type'] == 'ischaemic'
152
+ and rec['onset_to_arrival_hours'] <= 4.5):
153
+ rec['thrombolysis'] = 1 if rng.random() < 0.10 else 0
154
+
155
+ rec['antiplatelet'] = 0
156
+ if rec['stroke_type'] == 'ischaemic':
157
+ rec['antiplatelet'] = 1 if rng.random() < (0.75 if sc['ct_available'] else 0.40) else 0
158
+
159
+ rec['anticoagulant'] = 0
160
+ if rec['atrial_fibrillation'] and rec['stroke_type'] == 'ischaemic':
161
+ rec['anticoagulant'] = 1 if rng.random() < 0.20 else 0
162
+
163
+ rec['antihypertensive_acute'] = 1 if rec['systolic_bp'] > 180 and rng.random() < 0.60 else 0
164
+ rec['statin'] = 1 if rng.random() < (0.40 if sc['stroke_unit'] else 0.10) else 0
165
+ rec['surgical_evacuation'] = 0
166
+ if rec['stroke_type'] == 'intracerebral_haemorrhage' and sc['ct_available']:
167
+ rec['surgical_evacuation'] = 1 if rng.random() < 0.05 else 0
168
+
169
+ rec['nasogastric_feeding'] = 0
170
+ if rec['dysphagia']:
171
+ rec['nasogastric_feeding'] = 1 if rng.random() < (0.50 if sc['stroke_unit'] else 0.15) else 0
172
+
173
+ rec['physiotherapy_started'] = 0
174
+ if sc['physiotherapy']:
175
+ rec['physiotherapy_started'] = 1 if rng.random() < 0.50 else 0
176
+
177
+ rec['dvt_prophylaxis'] = 1 if rng.random() < (0.40 if sc['stroke_unit'] else 0.05) else 0
178
+
179
+ # ── 6. Complications ──
180
+ rec['aspiration_pneumonia'] = 0
181
+ if rec['dysphagia'] and not rec['nasogastric_feeding']:
182
+ rec['aspiration_pneumonia'] = 1 if rng.random() < 0.25 else 0
183
+
184
+ rec['dvt_pe'] = 1 if rng.random() < (0.03 if rec['dvt_prophylaxis'] else 0.08) else 0
185
+ rec['pressure_ulcer'] = 1 if rng.random() < 0.10 else 0
186
+ rec['seizure'] = 1 if rng.random() < 0.08 else 0
187
+ rec['haemorrhagic_transformation'] = 0
188
+ if rec['stroke_type'] == 'ischaemic':
189
+ rec['haemorrhagic_transformation'] = 1 if rng.random() < 0.05 else 0
190
+
191
+ # ── 7. Outcome [2][4][5] ──
192
+ base_mort = 0.25
193
+ if rec['stroke_type'] == 'intracerebral_haemorrhage':
194
+ base_mort = 0.40
195
+ elif rec['stroke_type'] == 'subarachnoid_haemorrhage':
196
+ base_mort = 0.45
197
+
198
+ mort = base_mort * sc['mortality_mod']
199
+ if rec['gcs_score'] <= 8:
200
+ mort *= 1.8
201
+ if rec['nihss_score'] > 20:
202
+ mort *= 1.5
203
+ if rec['thrombolysis']:
204
+ mort *= 0.6
205
+ if rec['aspiration_pneumonia']:
206
+ mort *= 1.5
207
+ if rec['age_years'] > 75:
208
+ mort *= 1.3
209
+
210
+ rec['outcome_30_day'] = 'died' if rng.random() < min(mort, 0.80) else 'survived'
211
+
212
+ rec['mrs_discharge'] = 5
213
+ if rec['outcome_30_day'] == 'survived':
214
+ if rec['nihss_score'] < 5:
215
+ rec['mrs_discharge'] = rng.choice([0, 1, 2, 3], p=[0.10, 0.25, 0.35, 0.30])
216
+ elif rec['nihss_score'] < 15:
217
+ rec['mrs_discharge'] = rng.choice([2, 3, 4], p=[0.20, 0.45, 0.35])
218
+ else:
219
+ rec['mrs_discharge'] = rng.choice([3, 4, 5], p=[0.15, 0.45, 0.40])
220
+
221
+ rec['disability'] = 'none' if rec['mrs_discharge'] <= 1 else (
222
+ 'mild' if rec['mrs_discharge'] == 2 else (
223
+ 'moderate' if rec['mrs_discharge'] == 3 else 'severe'))
224
+
225
+ rec['hospital_days'] = max(1, min(60, int(rng.exponential(10))))
226
+ if rec['outcome_30_day'] == 'died':
227
+ rec['hospital_days'] = max(1, min(30, int(rng.exponential(5))))
228
+
229
+ records.append(rec)
230
+
231
+ df = pd.DataFrame(records)
232
+
233
+ print(f"\n{'='*65}")
234
+ print(f"Stroke — {scenario} (n={n}, seed={seed})")
235
+ print(f"{'='*65}")
236
+ print(f"\n Ischaemic: {(df['stroke_type']=='ischaemic').mean()*100:.1f}%")
237
+ print(f" Haemorrhagic: {(df['stroke_type']=='intracerebral_haemorrhage').mean()*100:.1f}%")
238
+ print(f" Hypertension: {df['hypertension'].mean()*100:.1f}%")
239
+ print(f" CT performed: {df['ct_performed'].mean()*100:.1f}%")
240
+ died = (df['outcome_30_day']=='died').mean()*100
241
+ print(f" 30-day mortality: {died:.1f}%")
242
+
243
+ return df
244
+
245
+
246
+ if __name__ == '__main__':
247
+ parser = argparse.ArgumentParser(
248
+ description='Generate stroke dataset')
249
+ parser.add_argument('--scenario', type=str, default='district_hospital',
250
+ choices=list(SCENARIOS.keys()))
251
+ parser.add_argument('--n', type=int, default=10000)
252
+ parser.add_argument('--seed', type=int, default=42)
253
+ parser.add_argument('--output', type=str, default=None)
254
+ parser.add_argument('--all-scenarios', action='store_true')
255
+ args = parser.parse_args()
256
+
257
+ os.makedirs('data', exist_ok=True)
258
+
259
+ if args.all_scenarios:
260
+ for sc_name in SCENARIOS:
261
+ df = generate_dataset(n=args.n, seed=args.seed, scenario=sc_name)
262
+ out = os.path.join('data', f'stroke_{sc_name}.csv')
263
+ df.to_csv(out, index=False)
264
+ print(f" → Saved to {out}\n")
265
+ else:
266
+ df = generate_dataset(n=args.n, seed=args.seed, scenario=args.scenario)
267
+ out = args.output or os.path.join('data', f'stroke_{args.scenario}.csv')
268
+ df.to_csv(out, index=False)
269
+ print(f" → Saved to {out}")
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ numpy>=1.24
2
+ pandas>=2.0
3
+ matplotlib>=3.7
validate_dataset.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validation & Diagnostic Visualization for Stroke Dataset."""
3
+
4
+ import pandas as pd
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+ import os
8
+
9
+ SCENARIOS = ['tertiary_hospital', 'district_hospital', 'rural_facility']
10
+
11
+
12
+ def load_scenarios(data_dir='data'):
13
+ dfs = {}
14
+ for sc in SCENARIOS:
15
+ path = os.path.join(data_dir, f'stroke_{sc}.csv')
16
+ if os.path.exists(path):
17
+ dfs[sc] = pd.read_csv(path)
18
+ return dfs
19
+
20
+
21
+ def make_report(dfs, output='validation_report.png'):
22
+ fig, axes = plt.subplots(4, 2, figsize=(16, 22))
23
+ fig.suptitle('Stroke & Cerebrovascular Disease — Validation Report',
24
+ fontsize=16, fontweight='bold', y=0.98)
25
+ df = dfs.get('district_hospital', list(dfs.values())[0])
26
+ colors = ['#2ecc71', '#f39c12', '#e74c3c']
27
+
28
+ ax = axes[0, 0]
29
+ x = np.arange(len(SCENARIOS))
30
+ mort = [(dfs[sc]['outcome_30_day'] == 'died').mean() * 100 for sc in SCENARIOS if sc in dfs]
31
+ ax.bar(x, mort, color=colors, alpha=0.8)
32
+ ax.set_xticks(x)
33
+ ax.set_xticklabels(['Tertiary', 'District', 'Rural'], fontsize=9)
34
+ for i, v in enumerate(mort):
35
+ ax.text(i, v + 0.5, f'{v:.1f}%', ha='center', fontsize=10)
36
+ ax.set_ylabel('30-Day Mortality (%)')
37
+ ax.set_title('30-Day Mortality (SSA pooled ~30%)')
38
+
39
+ ax = axes[0, 1]
40
+ types = ['ischaemic', 'intracerebral_haemorrhage', 'subarachnoid_haemorrhage']
41
+ t_labels = ['Ischaemic', 'ICH', 'SAH']
42
+ vals = [(df['stroke_type'] == t).mean() * 100 for t in types]
43
+ t_colors = ['#3498db', '#e74c3c', '#f39c12']
44
+ ax.pie(vals, labels=t_labels, autopct='%1.0f%%', colors=t_colors,
45
+ startangle=90, textprops={'fontsize': 10})
46
+ ax.set_title('Stroke Type (60% ischaemic, 32% ICH)')
47
+
48
+ ax = axes[1, 0]
49
+ risks = ['hypertension', 'diabetes', 'atrial_fibrillation', 'smoking',
50
+ 'alcohol_heavy', 'prior_stroke', 'hiv_positive']
51
+ r_labels = ['HTN', 'DM', 'AF', 'Smoking', 'Alcohol', 'Prior Stroke', 'HIV']
52
+ vals = [df[r].mean() * 100 for r in risks]
53
+ ax.barh(range(7), vals, color='#e74c3c', alpha=0.7)
54
+ ax.set_yticks(range(7))
55
+ ax.set_yticklabels(r_labels, fontsize=8)
56
+ for i, v in enumerate(vals):
57
+ ax.text(v + 0.3, i, f'{v:.0f}%', va='center', fontsize=8)
58
+ ax.set_xlabel('Prevalence (%)')
59
+ ax.set_title('Risk Factors (HTN #1)')
60
+
61
+ ax = axes[1, 1]
62
+ for t, col, lab in [('ischaemic', '#3498db', 'Ischaemic'),
63
+ ('intracerebral_haemorrhage', '#e74c3c', 'ICH')]:
64
+ sub = df[df['stroke_type'] == t]
65
+ m = (sub['outcome_30_day'] == 'died').mean() * 100 if len(sub) > 0 else 0
66
+ ax.bar(lab, m, color=col, alpha=0.8)
67
+ ax.text(lab, m + 0.5, f'{m:.0f}%', ha='center', fontsize=10)
68
+ ax.set_ylabel('30-Day Mortality (%)')
69
+ ax.set_title('Mortality by Stroke Type (ICH > Ischaemic)')
70
+
71
+ ax = axes[2, 0]
72
+ for sc_name, col in zip(SCENARIOS, colors):
73
+ if sc_name in dfs:
74
+ d = dfs[sc_name]
75
+ ax.hist(d['onset_to_arrival_hours'].clip(upper=72), bins=20,
76
+ alpha=0.4, color=col,
77
+ label=sc_name.replace('_', ' ').title()[:10], edgecolor='white')
78
+ ax.set_xlabel('Hours from Onset to Arrival')
79
+ ax.set_title('Presentation Delay')
80
+ ax.legend(fontsize=7)
81
+
82
+ ax = axes[2, 1]
83
+ cascade = ['CT Scan', 'Antiplatelet', 'Thrombolysis', 'Statin', 'Physio']
84
+ for i, sc_name in enumerate(SCENARIOS):
85
+ if sc_name in dfs:
86
+ d = dfs[sc_name]
87
+ vals = [d['ct_performed'].mean()*100, d['antiplatelet'].mean()*100,
88
+ d['thrombolysis'].mean()*100, d['statin'].mean()*100,
89
+ d['physiotherapy_started'].mean()*100]
90
+ ax.plot(range(5), vals, 'o-', label=sc_name.replace('_', ' ').title()[:10],
91
+ color=colors[i], linewidth=2, markersize=6)
92
+ ax.set_xticks(range(5))
93
+ ax.set_xticklabels(cascade, fontsize=8)
94
+ ax.set_ylabel('Rate (%)')
95
+ ax.set_title('Treatment Cascade (thrombolysis near-zero SSA)')
96
+ ax.legend(fontsize=7)
97
+
98
+ ax = axes[3, 0]
99
+ survived = df[df['outcome_30_day'] == 'survived']
100
+ if len(survived) > 0:
101
+ mrs = survived['mrs_discharge'].value_counts().sort_index()
102
+ ax.bar(mrs.index.astype(str), mrs.values, color='#3498db', alpha=0.8)
103
+ ax.set_xlabel('Modified Rankin Scale')
104
+ ax.set_ylabel('Count')
105
+ ax.set_title('Disability at Discharge (mRS)')
106
+
107
+ ax = axes[3, 1]
108
+ died = df[df['outcome_30_day'] == 'died']['age_years']
109
+ surv = df[df['outcome_30_day'] == 'survived']['age_years']
110
+ ax.hist(surv, bins=20, alpha=0.5, color='#2ecc71', label='Survived', edgecolor='white')
111
+ ax.hist(died, bins=20, alpha=0.7, color='#e74c3c', label='Died', edgecolor='white')
112
+ ax.set_xlabel('Age (years)')
113
+ ax.set_title('Age Distribution (mean ~59, younger than HICs)')
114
+ ax.legend(fontsize=8)
115
+
116
+ plt.tight_layout(rect=[0, 0, 1, 0.97])
117
+ plt.savefig(output, dpi=150, bbox_inches='tight')
118
+ print(f'Saved validation report to {output}')
119
+ plt.close()
120
+
121
+
122
+ if __name__ == '__main__':
123
+ dfs = load_scenarios()
124
+ if dfs:
125
+ make_report(dfs)
validation_report.png ADDED

Git LFS Details

  • SHA256: ce1ee5c32b0d0118efb65e2b7b67a2a0e7df0f8d6296af38d34b050e9b65add9
  • Pointer size: 131 Bytes
  • Size of remote file: 338 kB