Kossisoroyce commited on
Commit
e8a8762
·
verified ·
1 Parent(s): 455b318

Initial release: Synthetic TB Screening v1.0

Browse files
README.md ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ task_categories:
4
+ - tabular-classification
5
+ - tabular-regression
6
+ language:
7
+ - en
8
+ tags:
9
+ - synthetic
10
+ - healthcare
11
+ - tuberculosis
12
+ - tb
13
+ - genexpert
14
+ - smear-microscopy
15
+ - chest-xray
16
+ - hiv-tb
17
+ - mdr-tb
18
+ - who-guidelines
19
+ - lmic
20
+ pretty_name: "Synthetic TB Screening & Symptom Dataset (GeneXpert, Smear, CXR)"
21
+ size_categories:
22
+ - 10K<n<100K
23
+ configs:
24
+ - config_name: low_tb_burden
25
+ data_files: data/tb_low_tb_burden.csv
26
+ - config_name: moderate_tb_burden
27
+ data_files: data/tb_moderate_tb_burden.csv
28
+ default: true
29
+ - config_name: high_tb_burden
30
+ data_files: data/tb_high_tb_burden.csv
31
+ ---
32
+
33
+ # Synthetic TB Screening & Symptom Dataset (GeneXpert, Smear, CXR)
34
+
35
+ ## Abstract
36
+
37
+ This dataset provides **30,000 synthetic records** (10,000 per scenario) of patients undergoing TB screening at LMIC health facilities. Each record contains 25 variables including demographics, HIV status, BMI, 8 symptom indicators, WHO symptom screen score, diagnostic results (smear microscopy, GeneXpert MTB/RIF with rifampicin resistance, chest X-ray), TB classification, and treatment outcome. Diagnostic test performance (sensitivity, specificity) is modelled from Cochrane reviews and WHO product evaluations. Three burden scenarios (low, moderate, high) span TB prevalence from 6% to 35% among screened patients, with HIV co-infection rates from 10% to 46%.
38
+
39
+ **This dataset is entirely synthetic. It must not be used for clinical decision-making.**
40
+
41
+ ## 2. Methodology
42
+
43
+ ### 2.1 Diagnostic Test Performance
44
+
45
+ | Test | Sensitivity | Specificity | Source |
46
+ | --- | --- | --- | --- |
47
+ | Smear microscopy | 60% (40% if HIV+) | 98% | Getahun et al., Lancet ID 2007 |
48
+ | GeneXpert (smear+) | 98% | 98% | Steingart et al., Cochrane 2014 |
49
+ | GeneXpert (smear-) | 68% (79% HIV+) | 98% | Steingart et al., 2014 |
50
+ | GeneXpert RIF resistance | 95% sensitivity | 98% specificity | WHO 2021 |
51
+ | Chest X-ray | 87% | 70% | van't Hoog et al., PLoS One 2012 |
52
+
53
+ ### 2.2 Scenario Design
54
+
55
+ | Scenario | TB Prevalence | HIV+ | TB-HIV Co-infection | MDR-TB | Smear+ |
56
+ | --- | --- | --- | --- | --- | --- |
57
+ | Low burden | 6.4% | 4.1% | 10% of TB cases | 3.1% | 5.4% |
58
+ | Moderate burden | 17.2% | 10.8% | 26% of TB cases | 4.8% | 10.4% |
59
+ | High burden | 35.1% | 27.5% | 46% of TB cases | 8.1% | 16.8% |
60
+
61
+ ## 3. Schema
62
+
63
+ | Column | Type | Description |
64
+ | --- | --- | --- |
65
+ | age_years | int | Age (15-85) |
66
+ | sex | categorical | M/F (M:F ratio ~1.4:1 per WHO) |
67
+ | bmi | float | Body mass index |
68
+ | hiv_status | binary | HIV serostatus |
69
+ | cough_2weeks, fever, night_sweats, weight_loss | binary | WHO symptom screen |
70
+ | hemoptysis, chest_pain, fatigue, loss_of_appetite | binary | Additional symptoms |
71
+ | cough_duration_weeks | int | Duration of cough |
72
+ | who_symptom_screen_count | int (0-4) | Number of WHO screening symptoms |
73
+ | smear_result | binary | Sputum smear microscopy |
74
+ | xpert_mtb_detected | binary | GeneXpert MTB detected |
75
+ | xpert_rif_resistance | categorical | detected / not_detected / N/A |
76
+ | cxr_result | categorical | normal / infiltrate / cavity / miliary / pleural_effusion / old_tb_scar / other_pathology |
77
+ | cxr_abnormal | binary | Any CXR abnormality |
78
+ | true_tb_status | binary | Ground truth TB status |
79
+ | tb_type | categorical | none / pulmonary / extrapulmonary |
80
+ | tb_classification | categorical | not_tb / smear_positive_ptb / smear_negative_ptb / extrapulmonary_tb |
81
+ | rifampicin_resistant | binary | Drug resistance status |
82
+ | treatment_outcome | categorical | cured / completed / failed / died / lost_to_followup / not_applicable |
83
+
84
+ ## 4. Validation
85
+
86
+ <p align="center">
87
+ <img src="validation_report.png" alt="Validation Report" width="100%">
88
+ </p>
89
+
90
+ ## 5. Usage
91
+
92
+ ```python
93
+ from datasets import load_dataset
94
+ dataset = load_dataset("electricsheepafrica/synthetic-tb-screening-symptoms-genexpert-WHO", "moderate_tb_burden")
95
+ df = dataset["train"].to_pandas()
96
+ ```
97
+
98
+ ## 6. Limitations
99
+
100
+ - **Synthetic**: Not for clinical use or diagnostic algorithm validation.
101
+ - **No paediatric TB**: Only adults ≥15 years; paediatric TB has different presentation.
102
+ - **Simplified CXR**: CXR findings are categorical; no image data.
103
+ - **No treatment timeline**: Outcomes are assigned, not modelled over time.
104
+ - **Single sputum sample**: Real diagnosis often requires multiple specimens.
105
+
106
+ ## 7. References
107
+
108
+ 1. WHO (2023). Global Tuberculosis Report 2023. Geneva.
109
+ 2. WHO (2021). Consolidated guidelines on TB: Rapid diagnostics. Geneva.
110
+ 3. Corbett EL, et al. (2003). TB and the HIV epidemic. *Arch Intern Med*, 163:1009.
111
+ 4. Steingart KR, et al. (2014). Xpert MTB/RIF for pulmonary TB. *Cochrane*, CD009593.
112
+ 5. Getahun H, et al. (2007). Smear-negative pulmonary TB in HIV. *Lancet ID*, 7(4):238-246.
113
+ 6. WHO (2013). Systematic screening for active TB. Geneva.
114
+ 7. van't Hoog AH, et al. (2012). Screening strategies for TB. *PLoS One*, 7(5):e36392.
115
+
116
+ ## Citation
117
+
118
+ ```bibtex
119
+ @dataset{esa_tb_2025,
120
+ title={Synthetic TB Screening and Symptom Dataset},
121
+ author={Electric Sheep Africa},
122
+ year={2025},
123
+ publisher={Hugging Face},
124
+ url={https://huggingface.co/datasets/electricsheepafrica/synthetic-tb-screening-symptoms-genexpert-WHO}
125
+ }
126
+ ```
127
+
128
+ ## License
129
+
130
+ [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/)
data/tb_high_tb_burden.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/tb_low_tb_burden.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/tb_moderate_tb_burden.csv ADDED
The diff for this file is too large to render. See raw diff
 
generate_dataset.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Literature-Informed Synthetic TB Screening & Symptom Dataset Generator
4
+ ======================================================================
5
+
6
+ Generates realistic synthetic datasets of patients undergoing tuberculosis
7
+ screening at LMIC health facilities, with demographic data, symptom profiles,
8
+ HIV co-infection status, diagnostic results (smear, GeneXpert, chest X-ray),
9
+ and TB classification.
10
+
11
+ Target population: Adults and adolescents (≥15 years) presenting for TB
12
+ screening at facility-based care in TB-endemic LMIC settings.
13
+
14
+ DAG (Sampling Order):
15
+ 1. age, sex (roots)
16
+ 2. hiv_status (scenario-dependent, age/sex-adjusted)
17
+ 3. bmi (conditional on age, TB status)
18
+ 4. true_tb_status (from prevalence, conditional on HIV)
19
+ 5. tb_type (pulmonary vs extrapulmonary)
20
+ 6. symptoms: cough, fever, night_sweats, weight_loss, hemoptysis
21
+ 7. smear_result, genexpert_result, cxr_finding (conditional on TB + test performance)
22
+ 8. tb_classification (derived)
23
+
24
+ References:
25
+ -----------
26
+ [1] WHO (2023). Global Tuberculosis Report 2023. Geneva.
27
+ [2] WHO (2021). WHO consolidated guidelines on tuberculosis: Module 3 -
28
+ Diagnosis: Rapid diagnostics for TB detection. Geneva.
29
+ [3] Corbett EL, et al. (2003). The growing burden of tuberculosis: global
30
+ trends and interactions with the HIV epidemic. Arch Intern Med, 163:1009.
31
+ [4] Steingart KR, et al. (2014). Xpert MTB/RIF assay for pulmonary TB and
32
+ rifampicin resistance in adults. Cochrane Database Syst Rev, 1:CD009593.
33
+ [5] Getahun H, et al. (2007). Diagnosis of smear-negative pulmonary TB in
34
+ people with HIV infection. Lancet Infect Dis, 7(4):238-246.
35
+ [6] WHO (2013). Systematic screening for active TB: principles and
36
+ recommendations. Geneva.
37
+ [7] van't Hoog AH, et al. (2012). Screening strategies for TB prevalence
38
+ surveys. PLoS One, 7(5):e36392.
39
+ [8] UNAIDS (2023). Global HIV & AIDS statistics fact sheet.
40
+ """
41
+
42
+ import numpy as np
43
+ import pandas as pd
44
+ from scipy.stats import truncnorm
45
+ import argparse
46
+ import os
47
+
48
+ # ============================================================
49
+ # SECTION 1: Literature-Informed Parameters
50
+ # ============================================================
51
+
52
+ SCENARIOS = {
53
+ 'low_tb_burden': {
54
+ 'description': 'Lower TB incidence LMIC (e.g., urban Latin America)',
55
+ 'tb_prevalence_screened': 0.05, # WHO 2023: 3-8% among symptomatic screened
56
+ 'hiv_prevalence': 0.03,
57
+ 'hiv_tb_coinfection': 0.15, # 10-20% of TB is HIV+ in low-HIV settings
58
+ 'mdr_rate': 0.03, # WHO 2023: 2-5% new cases
59
+ 'smear_positive_pct': 0.55, # ~50-60% of PTB is smear+
60
+ },
61
+ 'moderate_tb_burden': {
62
+ 'description': 'Moderate TB burden (e.g., Kenya, India, Philippines)',
63
+ 'tb_prevalence_screened': 0.12, # WHO 2023: 8-15% among presumptive TB
64
+ 'hiv_prevalence': 0.08,
65
+ 'hiv_tb_coinfection': 0.30, # Corbett 2003: 25-40% in SSA
66
+ 'mdr_rate': 0.05,
67
+ 'smear_positive_pct': 0.50,
68
+ },
69
+ 'high_tb_burden': {
70
+ 'description': 'High TB/HIV burden (e.g., South Africa, Mozambique, DRC)',
71
+ 'tb_prevalence_screened': 0.22, # WHO 2023: 15-30% in high-burden
72
+ 'hiv_prevalence': 0.20,
73
+ 'hiv_tb_coinfection': 0.50, # Corbett 2003: 40-60% in high HIV
74
+ 'mdr_rate': 0.08, # WHO 2023: up to 10% in hotspots
75
+ 'smear_positive_pct': 0.40, # Lower smear+ in HIV coinfection
76
+ },
77
+ }
78
+
79
+ # --- GeneXpert Performance ---
80
+ # Source: Steingart 2014, WHO 2021
81
+ XPERT_SENSITIVITY_SMEAR_POS = 0.98 # Smear-positive PTB
82
+ XPERT_SENSITIVITY_SMEAR_NEG = 0.68 # Smear-negative PTB
83
+ XPERT_SENSITIVITY_HIV = 0.79 # HIV-associated TB (pooled)
84
+ XPERT_SPECIFICITY = 0.98
85
+ XPERT_RIF_SENSITIVITY = 0.95 # For rifampicin resistance detection
86
+
87
+ # --- Smear Microscopy Performance ---
88
+ # Source: Getahun 2007
89
+ SMEAR_SENSITIVITY = 0.60 # Overall
90
+ SMEAR_SENSITIVITY_HIV = 0.40 # Reduced in HIV+
91
+ SMEAR_SPECIFICITY = 0.98
92
+
93
+ # --- CXR Performance ---
94
+ # Source: van't Hoog 2012
95
+ CXR_SENSITIVITY = 0.87 # For active PTB
96
+ CXR_SPECIFICITY = 0.70 # Many false positives (old TB, other pathology)
97
+
98
+ # --- Symptom Profiles ---
99
+ # Source: WHO 2013 systematic screening guidelines, van't Hoog 2012
100
+ SYMPTOM_PROB_TB = {
101
+ 'cough_2weeks': 0.75, # Cough ≥2 weeks
102
+ 'fever': 0.65,
103
+ 'night_sweats': 0.55,
104
+ 'weight_loss': 0.60,
105
+ 'hemoptysis': 0.15,
106
+ 'chest_pain': 0.40,
107
+ 'fatigue': 0.70,
108
+ 'loss_of_appetite': 0.55,
109
+ }
110
+ SYMPTOM_PROB_NO_TB = {
111
+ 'cough_2weeks': 0.10,
112
+ 'fever': 0.15,
113
+ 'night_sweats': 0.05,
114
+ 'weight_loss': 0.08,
115
+ 'hemoptysis': 0.01,
116
+ 'chest_pain': 0.12,
117
+ 'fatigue': 0.20,
118
+ 'loss_of_appetite': 0.10,
119
+ }
120
+
121
+ # --- BMI ---
122
+ BMI_NORMAL = {'mean': 22.0, 'sd': 3.5}
123
+ BMI_TB = {'mean': 18.5, 'sd': 2.5} # TB patients often underweight
124
+
125
+
126
+ # ============================================================
127
+ # SECTION 2: Utility Functions
128
+ # ============================================================
129
+
130
+ def trunc_normal(mean, sd, lo, hi, size, rng):
131
+ a, b = (lo - mean) / sd, (hi - mean) / sd
132
+ return truncnorm.rvs(a, b, loc=mean, scale=sd, size=size,
133
+ random_state=rng.integers(0, 2**31))
134
+
135
+
136
+ # ============================================================
137
+ # SECTION 3: Main Generator
138
+ # ============================================================
139
+
140
+ def generate_tb_dataset(n=10000, seed=42, scenario='moderate_tb_burden'):
141
+ rng = np.random.default_rng(seed)
142
+ sc = SCENARIOS[scenario]
143
+
144
+ # ── Step 1: Demographics ──
145
+ sex = rng.choice(['M', 'F'], size=n, p=[0.58, 0.42]) # TB M:F ~1.4:1 (WHO 2023)
146
+ age = trunc_normal(38, 14, 15, 85, n, rng).astype(int)
147
+
148
+ # ── Step 2: HIV status ──
149
+ hiv_status = np.zeros(n, dtype=int)
150
+ for i in range(n):
151
+ p_hiv = sc['hiv_prevalence']
152
+ if 20 <= age[i] <= 45:
153
+ p_hiv *= 1.5 # Peak HIV age
154
+ if sex[i] == 'F' and 20 <= age[i] <= 35:
155
+ p_hiv *= 1.3 # Higher in young women in SSA
156
+ hiv_status[i] = 1 if rng.random() < min(p_hiv, 0.50) else 0
157
+
158
+ # ── Step 3: True TB status ──
159
+ true_tb = np.zeros(n, dtype=int)
160
+ for i in range(n):
161
+ p_tb = sc['tb_prevalence_screened']
162
+ if hiv_status[i]:
163
+ p_tb *= 3.0 # HIV is strongest risk factor (Corbett 2003)
164
+ if age[i] > 50:
165
+ p_tb *= 1.3
166
+ if sex[i] == 'M':
167
+ p_tb *= 1.2
168
+ true_tb[i] = 1 if rng.random() < min(p_tb, 0.60) else 0
169
+
170
+ # ── Step 4: TB type and drug resistance ──
171
+ tb_type = np.array(['none'] * n, dtype=object)
172
+ rifampicin_resistant = np.zeros(n, dtype=int)
173
+ for i in range(n):
174
+ if true_tb[i]:
175
+ # ~85% pulmonary, ~15% extrapulmonary (higher in HIV+)
176
+ p_eptb = 0.25 if hiv_status[i] else 0.12
177
+ tb_type[i] = 'extrapulmonary' if rng.random() < p_eptb else 'pulmonary'
178
+ rifampicin_resistant[i] = 1 if rng.random() < sc['mdr_rate'] else 0
179
+
180
+ # ── Step 5: BMI ──
181
+ bmi = np.zeros(n)
182
+ for i in range(n):
183
+ if true_tb[i]:
184
+ bmi[i] = rng.normal(BMI_TB['mean'], BMI_TB['sd'])
185
+ else:
186
+ bmi[i] = rng.normal(BMI_NORMAL['mean'], BMI_NORMAL['sd'])
187
+ bmi = np.clip(np.round(bmi, 1), 12.0, 45.0)
188
+
189
+ # ── Step 6: Symptoms ──
190
+ symptoms = {}
191
+ for sym in SYMPTOM_PROB_TB:
192
+ symptoms[sym] = np.zeros(n, dtype=int)
193
+ for i in range(n):
194
+ p = SYMPTOM_PROB_TB[sym] if true_tb[i] else SYMPTOM_PROB_NO_TB[sym]
195
+ # HIV+ TB patients may have fewer respiratory symptoms
196
+ if true_tb[i] and hiv_status[i] and sym in ('cough_2weeks', 'hemoptysis'):
197
+ p *= 0.80
198
+ symptoms[sym][i] = 1 if rng.random() < p else 0
199
+
200
+ # Cough duration (weeks)
201
+ cough_duration_weeks = np.zeros(n, dtype=int)
202
+ for i in range(n):
203
+ if symptoms['cough_2weeks'][i]:
204
+ if true_tb[i]:
205
+ cough_duration_weeks[i] = max(2, rng.poisson(5))
206
+ else:
207
+ cough_duration_weeks[i] = max(2, rng.poisson(3))
208
+ cough_duration_weeks = np.clip(cough_duration_weeks, 0, 52)
209
+
210
+ # Number of WHO screening symptoms (cough ≥2wk, fever, night sweats, weight loss)
211
+ who_symptom_count = (symptoms['cough_2weeks'] + symptoms['fever'] +
212
+ symptoms['night_sweats'] + symptoms['weight_loss'])
213
+
214
+ # ── Step 7: Smear microscopy ──
215
+ smear_result = np.zeros(n, dtype=int)
216
+ for i in range(n):
217
+ if true_tb[i] and tb_type[i] == 'pulmonary':
218
+ sens = SMEAR_SENSITIVITY_HIV if hiv_status[i] else SMEAR_SENSITIVITY
219
+ smear_result[i] = 1 if rng.random() < sens else 0
220
+ elif true_tb[i] and tb_type[i] == 'extrapulmonary':
221
+ smear_result[i] = 1 if rng.random() < 0.10 else 0 # Very low for EPTB
222
+ else:
223
+ smear_result[i] = 1 if rng.random() < (1 - SMEAR_SPECIFICITY) else 0
224
+
225
+ # ── Step 8: GeneXpert MTB/RIF ──
226
+ xpert_mtb = np.zeros(n, dtype=int)
227
+ xpert_rif_resistant = np.array(['N/A'] * n, dtype=object)
228
+ for i in range(n):
229
+ if true_tb[i] and tb_type[i] == 'pulmonary':
230
+ if smear_result[i]:
231
+ sens = XPERT_SENSITIVITY_SMEAR_POS
232
+ elif hiv_status[i]:
233
+ sens = XPERT_SENSITIVITY_HIV
234
+ else:
235
+ sens = XPERT_SENSITIVITY_SMEAR_NEG
236
+ xpert_mtb[i] = 1 if rng.random() < sens else 0
237
+ elif true_tb[i] and tb_type[i] == 'extrapulmonary':
238
+ xpert_mtb[i] = 1 if rng.random() < 0.40 else 0
239
+ else:
240
+ xpert_mtb[i] = 1 if rng.random() < (1 - XPERT_SPECIFICITY) else 0
241
+
242
+ if xpert_mtb[i]:
243
+ if rifampicin_resistant[i]:
244
+ xpert_rif_resistant[i] = 'detected' if rng.random() < XPERT_RIF_SENSITIVITY else 'not_detected'
245
+ else:
246
+ xpert_rif_resistant[i] = 'not_detected' if rng.random() < 0.98 else 'detected'
247
+
248
+ # ── Step 9: Chest X-ray ──
249
+ cxr_result = np.array(['normal'] * n, dtype=object)
250
+ for i in range(n):
251
+ if true_tb[i] and tb_type[i] == 'pulmonary':
252
+ if rng.random() < CXR_SENSITIVITY:
253
+ cxr_result[i] = rng.choice(['infiltrate', 'cavity', 'miliary',
254
+ 'pleural_effusion'],
255
+ p=[0.50, 0.25, 0.10, 0.15])
256
+ elif true_tb[i] and tb_type[i] == 'extrapulmonary':
257
+ if rng.random() < 0.30:
258
+ cxr_result[i] = rng.choice(['infiltrate', 'pleural_effusion'],
259
+ p=[0.40, 0.60])
260
+ else:
261
+ if rng.random() < (1 - CXR_SPECIFICITY):
262
+ cxr_result[i] = rng.choice(['old_tb_scar', 'other_pathology',
263
+ 'infiltrate'],
264
+ p=[0.40, 0.40, 0.20])
265
+
266
+ cxr_abnormal = (cxr_result != 'normal').astype(int)
267
+
268
+ # ── Step 10: TB classification ──
269
+ tb_classification = np.array(['not_tb'] * n, dtype=object)
270
+ for i in range(n):
271
+ if true_tb[i]:
272
+ if tb_type[i] == 'pulmonary' and smear_result[i]:
273
+ tb_classification[i] = 'smear_positive_ptb'
274
+ elif tb_type[i] == 'pulmonary':
275
+ tb_classification[i] = 'smear_negative_ptb'
276
+ else:
277
+ tb_classification[i] = 'extrapulmonary_tb'
278
+
279
+ # ── Step 11: Treatment outcome (simplified) ──
280
+ treatment_outcome = np.array(['not_applicable'] * n, dtype=object)
281
+ for i in range(n):
282
+ if true_tb[i]:
283
+ if rifampicin_resistant[i]:
284
+ outcomes = ['cured', 'completed', 'failed', 'died', 'lost_to_followup']
285
+ probs = [0.45, 0.15, 0.15, 0.15, 0.10]
286
+ elif hiv_status[i]:
287
+ outcomes = ['cured', 'completed', 'failed', 'died', 'lost_to_followup']
288
+ probs = [0.50, 0.20, 0.05, 0.15, 0.10]
289
+ else:
290
+ outcomes = ['cured', 'completed', 'failed', 'died', 'lost_to_followup']
291
+ probs = [0.65, 0.20, 0.03, 0.05, 0.07]
292
+ treatment_outcome[i] = rng.choice(outcomes, p=probs)
293
+
294
+ # ── Assemble DataFrame ──
295
+ df = pd.DataFrame({
296
+ 'id': np.arange(1, n + 1),
297
+ 'age_years': age,
298
+ 'sex': sex,
299
+ 'bmi': bmi,
300
+ 'hiv_status': hiv_status,
301
+ 'cough_2weeks': symptoms['cough_2weeks'],
302
+ 'cough_duration_weeks': cough_duration_weeks,
303
+ 'fever': symptoms['fever'],
304
+ 'night_sweats': symptoms['night_sweats'],
305
+ 'weight_loss': symptoms['weight_loss'],
306
+ 'hemoptysis': symptoms['hemoptysis'],
307
+ 'chest_pain': symptoms['chest_pain'],
308
+ 'fatigue': symptoms['fatigue'],
309
+ 'loss_of_appetite': symptoms['loss_of_appetite'],
310
+ 'who_symptom_screen_count': who_symptom_count,
311
+ 'smear_result': smear_result,
312
+ 'xpert_mtb_detected': xpert_mtb,
313
+ 'xpert_rif_resistance': xpert_rif_resistant,
314
+ 'cxr_result': cxr_result,
315
+ 'cxr_abnormal': cxr_abnormal,
316
+ 'true_tb_status': true_tb,
317
+ 'tb_type': tb_type,
318
+ 'tb_classification': tb_classification,
319
+ 'rifampicin_resistant': rifampicin_resistant,
320
+ 'treatment_outcome': treatment_outcome,
321
+ })
322
+
323
+ # ── Print summary ──
324
+ tb_pos = true_tb.sum()
325
+ print(f"\n{'='*60}")
326
+ print(f"TB Screening — {scenario} (n={n}, seed={seed})")
327
+ print(f"{'='*60}")
328
+ print(f"\nTB prevalence: {tb_pos/n*100:.1f}%")
329
+ print(f"HIV+: {hiv_status.mean()*100:.1f}%")
330
+ print(f"TB-HIV co-infection: {(true_tb & hiv_status).sum()}/{tb_pos} "
331
+ f"({(true_tb & hiv_status).sum()/max(tb_pos,1)*100:.0f}%) of TB cases")
332
+ print(f"Pulmonary TB: {(tb_type=='pulmonary').sum()}")
333
+ print(f"Extrapulmonary TB: {(tb_type=='extrapulmonary').sum()}")
334
+ print(f"Smear+: {smear_result.sum()} ({smear_result.mean()*100:.1f}%)")
335
+ print(f"Xpert MTB+: {xpert_mtb.sum()} ({xpert_mtb.mean()*100:.1f}%)")
336
+ print(f"CXR abnormal: {cxr_abnormal.sum()} ({cxr_abnormal.mean()*100:.1f}%)")
337
+ print(f"MDR-TB: {rifampicin_resistant.sum()} ({rifampicin_resistant[true_tb==1].mean()*100:.1f}% of TB)")
338
+ print(f"Mean BMI (TB): {bmi[true_tb==1].mean():.1f}, (non-TB): {bmi[true_tb==0].mean():.1f}")
339
+
340
+ return df
341
+
342
+
343
+ # ============================================================
344
+ # SECTION 4: CLI Entry Point
345
+ # ============================================================
346
+
347
+ if __name__ == '__main__':
348
+ parser = argparse.ArgumentParser(
349
+ description='Generate synthetic TB screening dataset')
350
+ parser.add_argument('--scenario', type=str, default='moderate_tb_burden',
351
+ choices=list(SCENARIOS.keys()))
352
+ parser.add_argument('--n', type=int, default=10000)
353
+ parser.add_argument('--seed', type=int, default=42)
354
+ parser.add_argument('--output', type=str, default=None)
355
+ parser.add_argument('--all-scenarios', action='store_true')
356
+ args = parser.parse_args()
357
+
358
+ os.makedirs('data', exist_ok=True)
359
+
360
+ if args.all_scenarios:
361
+ for sc_name in SCENARIOS:
362
+ df = generate_tb_dataset(n=args.n, seed=args.seed, scenario=sc_name)
363
+ out = os.path.join('data', f'tb_{sc_name}.csv')
364
+ df.to_csv(out, index=False)
365
+ print(f" → Saved to {out}\n")
366
+ else:
367
+ df = generate_tb_dataset(n=args.n, seed=args.seed, scenario=args.scenario)
368
+ out = args.output or os.path.join('data', f'tb_{args.scenario}.csv')
369
+ df.to_csv(out, index=False)
370
+ print(f" → Saved to {out}")
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ numpy>=1.24
2
+ pandas>=2.0
3
+ scipy>=1.10
4
+ matplotlib>=3.7
validate_dataset.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validation & Diagnostic Visualization for TB Screening Dataset."""
3
+
4
+ import pandas as pd
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+ import os
8
+
9
+ SCENARIOS = ['low_tb_burden', 'moderate_tb_burden', 'high_tb_burden']
10
+
11
+
12
+ def load_scenarios(data_dir='data'):
13
+ dfs = {}
14
+ for sc in SCENARIOS:
15
+ path = os.path.join(data_dir, f'tb_{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('TB Screening & Symptom Data — Validation Report',
24
+ fontsize=16, fontweight='bold', y=0.98)
25
+ df = dfs.get('moderate_tb_burden', list(dfs.values())[0])
26
+
27
+ # Panel 1: TB classification
28
+ ax = axes[0, 0]
29
+ order = ['not_tb', 'smear_positive_ptb', 'smear_negative_ptb', 'extrapulmonary_tb']
30
+ colors = ['#2ecc71', '#e74c3c', '#f39c12', '#9b59b6']
31
+ counts = df['tb_classification'].value_counts().reindex(order).fillna(0)
32
+ ax.bar(range(4), counts.values, color=colors)
33
+ ax.set_xticks(range(4))
34
+ ax.set_xticklabels(['Not TB', 'Smear+ PTB', 'Smear- PTB', 'EPTB'], fontsize=9)
35
+ for i, v in enumerate(counts.values):
36
+ ax.text(i, v + 30, f'{v/len(df)*100:.1f}%', ha='center', fontsize=10)
37
+ ax.set_ylabel('Count')
38
+ ax.set_title('TB Classification (Moderate Burden)')
39
+
40
+ # Panel 2: Symptom prevalence TB vs non-TB
41
+ ax = axes[0, 1]
42
+ syms = ['cough_2weeks', 'fever', 'night_sweats', 'weight_loss', 'hemoptysis', 'fatigue']
43
+ tb = df[df['true_tb_status'] == 1]
44
+ no_tb = df[df['true_tb_status'] == 0]
45
+ x = np.arange(len(syms))
46
+ ax.barh(x - 0.2, [tb[s].mean()*100 for s in syms], 0.4, label='TB+', color='#e74c3c', alpha=0.8)
47
+ ax.barh(x + 0.2, [no_tb[s].mean()*100 for s in syms], 0.4, label='No TB', color='#3498db', alpha=0.8)
48
+ ax.set_yticks(x)
49
+ ax.set_yticklabels([s.replace('_', ' ').title() for s in syms], fontsize=8)
50
+ ax.set_xlabel('Prevalence (%)')
51
+ ax.set_title('Symptom Prevalence: TB+ vs No TB')
52
+ ax.legend(fontsize=9)
53
+
54
+ # Panel 3: BMI distribution by TB status
55
+ ax = axes[1, 0]
56
+ ax.hist(no_tb['bmi'], bins=40, alpha=0.6, color='#3498db', label='No TB', edgecolor='white')
57
+ ax.hist(tb['bmi'], bins=40, alpha=0.6, color='#e74c3c', label='TB+', edgecolor='white')
58
+ ax.axvline(18.5, color='black', ls='--', lw=1, label='Underweight <18.5')
59
+ ax.set_xlabel('BMI')
60
+ ax.set_title('BMI Distribution by TB Status')
61
+ ax.legend(fontsize=8)
62
+
63
+ # Panel 4: Diagnostic cascade
64
+ ax = axes[1, 1]
65
+ metrics = ['True TB+', 'CXR Abnormal', 'Xpert MTB+', 'Smear+']
66
+ vals = [(df['true_tb_status']==1).sum(), df['cxr_abnormal'].sum(),
67
+ df['xpert_mtb_detected'].sum(), df['smear_result'].sum()]
68
+ ax.barh(range(4), vals, color=['#2ecc71', '#f39c12', '#9b59b6', '#e74c3c'], alpha=0.8)
69
+ ax.set_yticks(range(4))
70
+ ax.set_yticklabels(metrics)
71
+ for i, v in enumerate(vals):
72
+ ax.text(v + 20, i, f'{v/len(df)*100:.1f}%', va='center', fontsize=10)
73
+ ax.set_xlabel('Count')
74
+ ax.set_title('Diagnostic Cascade')
75
+
76
+ # Panel 5: Cross-scenario TB prevalence
77
+ ax = axes[2, 0]
78
+ x = np.arange(3)
79
+ width = 0.2
80
+ for i, sc in enumerate(SCENARIOS):
81
+ if sc not in dfs:
82
+ continue
83
+ d = dfs[sc]
84
+ tb_r = d['true_tb_status'].mean() * 100
85
+ hiv_r = d['hiv_status'].mean() * 100
86
+ mdr_r = d[d['true_tb_status']==1]['rifampicin_resistant'].mean() * 100 if d['true_tb_status'].sum() > 0 else 0
87
+ ax.bar(x[0] + i*width, tb_r, width, alpha=0.8, label=sc.replace('_', ' ').title() if i == 0 else '')
88
+ ax.bar(x[1] + i*width, hiv_r, width, alpha=0.8)
89
+ ax.bar(x[2] + i*width, mdr_r, width, alpha=0.8)
90
+ ax.set_xticks(x + width)
91
+ ax.set_xticklabels(['TB Prevalence', 'HIV Prevalence', 'MDR-TB (of TB)'])
92
+ ax.set_ylabel('%')
93
+ ax.set_title('Key Rates Across Scenarios')
94
+ ax.legend(fontsize=8)
95
+
96
+ # Panel 6: HIV-TB co-infection
97
+ ax = axes[2, 1]
98
+ hiv_pos = df[df['hiv_status']==1]
99
+ hiv_neg = df[df['hiv_status']==0]
100
+ tb_hiv_pos = hiv_pos['true_tb_status'].mean()*100
101
+ tb_hiv_neg = hiv_neg['true_tb_status'].mean()*100
102
+ ax.bar([0, 1], [tb_hiv_neg, tb_hiv_pos], color=['#3498db', '#e74c3c'], alpha=0.8)
103
+ ax.set_xticks([0, 1])
104
+ ax.set_xticklabels(['HIV-', 'HIV+'])
105
+ ax.set_ylabel('TB Prevalence (%)')
106
+ ax.set_title(f'TB Prevalence by HIV Status')
107
+ for i, v in enumerate([tb_hiv_neg, tb_hiv_pos]):
108
+ ax.text(i, v + 0.5, f'{v:.1f}%', ha='center', fontsize=11)
109
+
110
+ # Panel 7: WHO symptom screen count distribution
111
+ ax = axes[3, 0]
112
+ for status, color, label in [(1, '#e74c3c', 'TB+'), (0, '#3498db', 'No TB')]:
113
+ sub = df[df['true_tb_status']==status]['who_symptom_screen_count']
114
+ ax.hist(sub, bins=range(0, 6), alpha=0.6, color=color, label=label, edgecolor='white')
115
+ ax.set_xlabel('WHO Symptom Screen Count (0-4)')
116
+ ax.set_title('WHO Symptom Screen Score')
117
+ ax.legend(fontsize=10)
118
+
119
+ # Panel 8: Treatment outcomes (TB cases only)
120
+ ax = axes[3, 1]
121
+ tb_cases = df[df['true_tb_status']==1]
122
+ if len(tb_cases) > 0:
123
+ outcomes = ['cured', 'completed', 'failed', 'died', 'lost_to_followup']
124
+ out_colors = ['#2ecc71', '#27ae60', '#f39c12', '#e74c3c', '#95a5a6']
125
+ counts_out = tb_cases['treatment_outcome'].value_counts().reindex(outcomes).fillna(0)
126
+ ax.bar(range(5), counts_out.values, color=out_colors)
127
+ ax.set_xticks(range(5))
128
+ ax.set_xticklabels([o.replace('_', '\n').title() for o in outcomes], fontsize=8)
129
+ for i, v in enumerate(counts_out.values):
130
+ ax.text(i, v + 5, f'{v/len(tb_cases)*100:.0f}%', ha='center', fontsize=9)
131
+ ax.set_ylabel('Count')
132
+ ax.set_title('Treatment Outcomes (TB cases)')
133
+
134
+ plt.tight_layout(rect=[0, 0, 1, 0.97])
135
+ plt.savefig(output, dpi=150, bbox_inches='tight')
136
+ print(f'Saved validation report to {output}')
137
+ plt.close()
138
+
139
+
140
+ if __name__ == '__main__':
141
+ dfs = load_scenarios()
142
+ if dfs:
143
+ make_report(dfs)
validation_report.png ADDED

Git LFS Details

  • SHA256: 23ba3d806a5454cedd6233e596546c8f30e3bf1a6b6bb7e5131e47aba67f9c89
  • Pointer size: 131 Bytes
  • Size of remote file: 278 kB