| |
| """ |
| Literature-Informed Synthetic TB Screening & Symptom Dataset Generator |
| ====================================================================== |
| |
| Generates realistic synthetic datasets of patients undergoing tuberculosis |
| screening at LMIC health facilities, with demographic data, symptom profiles, |
| HIV co-infection status, diagnostic results (smear, GeneXpert, chest X-ray), |
| and TB classification. |
| |
| Target population: Adults and adolescents (≥15 years) presenting for TB |
| screening at facility-based care in TB-endemic LMIC settings. |
| |
| DAG (Sampling Order): |
| 1. age, sex (roots) |
| 2. hiv_status (scenario-dependent, age/sex-adjusted) |
| 3. bmi (conditional on age, TB status) |
| 4. true_tb_status (from prevalence, conditional on HIV) |
| 5. tb_type (pulmonary vs extrapulmonary) |
| 6. symptoms: cough, fever, night_sweats, weight_loss, hemoptysis |
| 7. smear_result, genexpert_result, cxr_finding (conditional on TB + test performance) |
| 8. tb_classification (derived) |
| |
| References: |
| ----------- |
| [1] WHO (2023). Global Tuberculosis Report 2023. Geneva. |
| [2] WHO (2021). WHO consolidated guidelines on tuberculosis: Module 3 - |
| Diagnosis: Rapid diagnostics for TB detection. Geneva. |
| [3] Corbett EL, et al. (2003). The growing burden of tuberculosis: global |
| trends and interactions with the HIV epidemic. Arch Intern Med, 163:1009. |
| [4] Steingart KR, et al. (2014). Xpert MTB/RIF assay for pulmonary TB and |
| rifampicin resistance in adults. Cochrane Database Syst Rev, 1:CD009593. |
| [5] Getahun H, et al. (2007). Diagnosis of smear-negative pulmonary TB in |
| people with HIV infection. Lancet Infect Dis, 7(4):238-246. |
| [6] WHO (2013). Systematic screening for active TB: principles and |
| recommendations. Geneva. |
| [7] van't Hoog AH, et al. (2012). Screening strategies for TB prevalence |
| surveys. PLoS One, 7(5):e36392. |
| [8] UNAIDS (2023). Global HIV & AIDS statistics fact sheet. |
| """ |
|
|
| import numpy as np |
| import pandas as pd |
| from scipy.stats import truncnorm |
| import argparse |
| import os |
|
|
| |
| |
| |
|
|
| SCENARIOS = { |
| 'low_tb_burden': { |
| 'description': 'Lower TB incidence LMIC (e.g., urban Latin America)', |
| 'tb_prevalence_screened': 0.05, |
| 'hiv_prevalence': 0.03, |
| 'hiv_tb_coinfection': 0.15, |
| 'mdr_rate': 0.03, |
| 'smear_positive_pct': 0.55, |
| }, |
| 'moderate_tb_burden': { |
| 'description': 'Moderate TB burden (e.g., Kenya, India, Philippines)', |
| 'tb_prevalence_screened': 0.12, |
| 'hiv_prevalence': 0.08, |
| 'hiv_tb_coinfection': 0.30, |
| 'mdr_rate': 0.05, |
| 'smear_positive_pct': 0.50, |
| }, |
| 'high_tb_burden': { |
| 'description': 'High TB/HIV burden (e.g., South Africa, Mozambique, DRC)', |
| 'tb_prevalence_screened': 0.22, |
| 'hiv_prevalence': 0.20, |
| 'hiv_tb_coinfection': 0.50, |
| 'mdr_rate': 0.08, |
| 'smear_positive_pct': 0.40, |
| }, |
| } |
|
|
| |
| |
| XPERT_SENSITIVITY_SMEAR_POS = 0.98 |
| XPERT_SENSITIVITY_SMEAR_NEG = 0.68 |
| XPERT_SENSITIVITY_HIV = 0.79 |
| XPERT_SPECIFICITY = 0.98 |
| XPERT_RIF_SENSITIVITY = 0.95 |
|
|
| |
| |
| SMEAR_SENSITIVITY = 0.60 |
| SMEAR_SENSITIVITY_HIV = 0.40 |
| SMEAR_SPECIFICITY = 0.98 |
|
|
| |
| |
| CXR_SENSITIVITY = 0.87 |
| CXR_SPECIFICITY = 0.70 |
|
|
| |
| |
| SYMPTOM_PROB_TB = { |
| 'cough_2weeks': 0.75, |
| 'fever': 0.65, |
| 'night_sweats': 0.55, |
| 'weight_loss': 0.60, |
| 'hemoptysis': 0.15, |
| 'chest_pain': 0.40, |
| 'fatigue': 0.70, |
| 'loss_of_appetite': 0.55, |
| } |
| SYMPTOM_PROB_NO_TB = { |
| 'cough_2weeks': 0.10, |
| 'fever': 0.15, |
| 'night_sweats': 0.05, |
| 'weight_loss': 0.08, |
| 'hemoptysis': 0.01, |
| 'chest_pain': 0.12, |
| 'fatigue': 0.20, |
| 'loss_of_appetite': 0.10, |
| } |
|
|
| |
| BMI_NORMAL = {'mean': 22.0, 'sd': 3.5} |
| BMI_TB = {'mean': 18.5, 'sd': 2.5} |
|
|
|
|
| |
| |
| |
|
|
| def trunc_normal(mean, sd, lo, hi, size, rng): |
| a, b = (lo - mean) / sd, (hi - mean) / sd |
| return truncnorm.rvs(a, b, loc=mean, scale=sd, size=size, |
| random_state=rng.integers(0, 2**31)) |
|
|
|
|
| |
| |
| |
|
|
| def generate_tb_dataset(n=10000, seed=42, scenario='moderate_tb_burden'): |
| rng = np.random.default_rng(seed) |
| sc = SCENARIOS[scenario] |
|
|
| |
| sex = rng.choice(['M', 'F'], size=n, p=[0.58, 0.42]) |
| age = trunc_normal(38, 14, 15, 85, n, rng).astype(int) |
|
|
| |
| hiv_status = np.zeros(n, dtype=int) |
| for i in range(n): |
| p_hiv = sc['hiv_prevalence'] |
| if 20 <= age[i] <= 45: |
| p_hiv *= 1.5 |
| if sex[i] == 'F' and 20 <= age[i] <= 35: |
| p_hiv *= 1.3 |
| hiv_status[i] = 1 if rng.random() < min(p_hiv, 0.50) else 0 |
|
|
| |
| true_tb = np.zeros(n, dtype=int) |
| for i in range(n): |
| p_tb = sc['tb_prevalence_screened'] |
| if hiv_status[i]: |
| p_tb *= 3.0 |
| if age[i] > 50: |
| p_tb *= 1.3 |
| if sex[i] == 'M': |
| p_tb *= 1.2 |
| true_tb[i] = 1 if rng.random() < min(p_tb, 0.60) else 0 |
|
|
| |
| tb_type = np.array(['none'] * n, dtype=object) |
| rifampicin_resistant = np.zeros(n, dtype=int) |
| for i in range(n): |
| if true_tb[i]: |
| |
| p_eptb = 0.25 if hiv_status[i] else 0.12 |
| tb_type[i] = 'extrapulmonary' if rng.random() < p_eptb else 'pulmonary' |
| rifampicin_resistant[i] = 1 if rng.random() < sc['mdr_rate'] else 0 |
|
|
| |
| bmi = np.zeros(n) |
| for i in range(n): |
| if true_tb[i]: |
| bmi[i] = rng.normal(BMI_TB['mean'], BMI_TB['sd']) |
| else: |
| bmi[i] = rng.normal(BMI_NORMAL['mean'], BMI_NORMAL['sd']) |
| bmi = np.clip(np.round(bmi, 1), 12.0, 45.0) |
|
|
| |
| symptoms = {} |
| for sym in SYMPTOM_PROB_TB: |
| symptoms[sym] = np.zeros(n, dtype=int) |
| for i in range(n): |
| p = SYMPTOM_PROB_TB[sym] if true_tb[i] else SYMPTOM_PROB_NO_TB[sym] |
| |
| if true_tb[i] and hiv_status[i] and sym in ('cough_2weeks', 'hemoptysis'): |
| p *= 0.80 |
| symptoms[sym][i] = 1 if rng.random() < p else 0 |
|
|
| |
| cough_duration_weeks = np.zeros(n, dtype=int) |
| for i in range(n): |
| if symptoms['cough_2weeks'][i]: |
| if true_tb[i]: |
| cough_duration_weeks[i] = max(2, rng.poisson(5)) |
| else: |
| cough_duration_weeks[i] = max(2, rng.poisson(3)) |
| cough_duration_weeks = np.clip(cough_duration_weeks, 0, 52) |
|
|
| |
| who_symptom_count = (symptoms['cough_2weeks'] + symptoms['fever'] + |
| symptoms['night_sweats'] + symptoms['weight_loss']) |
|
|
| |
| smear_result = np.zeros(n, dtype=int) |
| for i in range(n): |
| if true_tb[i] and tb_type[i] == 'pulmonary': |
| sens = SMEAR_SENSITIVITY_HIV if hiv_status[i] else SMEAR_SENSITIVITY |
| smear_result[i] = 1 if rng.random() < sens else 0 |
| elif true_tb[i] and tb_type[i] == 'extrapulmonary': |
| smear_result[i] = 1 if rng.random() < 0.10 else 0 |
| else: |
| smear_result[i] = 1 if rng.random() < (1 - SMEAR_SPECIFICITY) else 0 |
|
|
| |
| xpert_mtb = np.zeros(n, dtype=int) |
| xpert_rif_resistant = np.array(['N/A'] * n, dtype=object) |
| for i in range(n): |
| if true_tb[i] and tb_type[i] == 'pulmonary': |
| if smear_result[i]: |
| sens = XPERT_SENSITIVITY_SMEAR_POS |
| elif hiv_status[i]: |
| sens = XPERT_SENSITIVITY_HIV |
| else: |
| sens = XPERT_SENSITIVITY_SMEAR_NEG |
| xpert_mtb[i] = 1 if rng.random() < sens else 0 |
| elif true_tb[i] and tb_type[i] == 'extrapulmonary': |
| xpert_mtb[i] = 1 if rng.random() < 0.40 else 0 |
| else: |
| xpert_mtb[i] = 1 if rng.random() < (1 - XPERT_SPECIFICITY) else 0 |
|
|
| if xpert_mtb[i]: |
| if rifampicin_resistant[i]: |
| xpert_rif_resistant[i] = 'detected' if rng.random() < XPERT_RIF_SENSITIVITY else 'not_detected' |
| else: |
| xpert_rif_resistant[i] = 'not_detected' if rng.random() < 0.98 else 'detected' |
|
|
| |
| cxr_result = np.array(['normal'] * n, dtype=object) |
| for i in range(n): |
| if true_tb[i] and tb_type[i] == 'pulmonary': |
| if rng.random() < CXR_SENSITIVITY: |
| cxr_result[i] = rng.choice(['infiltrate', 'cavity', 'miliary', |
| 'pleural_effusion'], |
| p=[0.50, 0.25, 0.10, 0.15]) |
| elif true_tb[i] and tb_type[i] == 'extrapulmonary': |
| if rng.random() < 0.30: |
| cxr_result[i] = rng.choice(['infiltrate', 'pleural_effusion'], |
| p=[0.40, 0.60]) |
| else: |
| if rng.random() < (1 - CXR_SPECIFICITY): |
| cxr_result[i] = rng.choice(['old_tb_scar', 'other_pathology', |
| 'infiltrate'], |
| p=[0.40, 0.40, 0.20]) |
|
|
| cxr_abnormal = (cxr_result != 'normal').astype(int) |
|
|
| |
| tb_classification = np.array(['not_tb'] * n, dtype=object) |
| for i in range(n): |
| if true_tb[i]: |
| if tb_type[i] == 'pulmonary' and smear_result[i]: |
| tb_classification[i] = 'smear_positive_ptb' |
| elif tb_type[i] == 'pulmonary': |
| tb_classification[i] = 'smear_negative_ptb' |
| else: |
| tb_classification[i] = 'extrapulmonary_tb' |
|
|
| |
| treatment_outcome = np.array(['not_applicable'] * n, dtype=object) |
| for i in range(n): |
| if true_tb[i]: |
| if rifampicin_resistant[i]: |
| outcomes = ['cured', 'completed', 'failed', 'died', 'lost_to_followup'] |
| probs = [0.45, 0.15, 0.15, 0.15, 0.10] |
| elif hiv_status[i]: |
| outcomes = ['cured', 'completed', 'failed', 'died', 'lost_to_followup'] |
| probs = [0.50, 0.20, 0.05, 0.15, 0.10] |
| else: |
| outcomes = ['cured', 'completed', 'failed', 'died', 'lost_to_followup'] |
| probs = [0.65, 0.20, 0.03, 0.05, 0.07] |
| treatment_outcome[i] = rng.choice(outcomes, p=probs) |
|
|
| |
| df = pd.DataFrame({ |
| 'id': np.arange(1, n + 1), |
| 'age_years': age, |
| 'sex': sex, |
| 'bmi': bmi, |
| 'hiv_status': hiv_status, |
| 'cough_2weeks': symptoms['cough_2weeks'], |
| 'cough_duration_weeks': cough_duration_weeks, |
| 'fever': symptoms['fever'], |
| 'night_sweats': symptoms['night_sweats'], |
| 'weight_loss': symptoms['weight_loss'], |
| 'hemoptysis': symptoms['hemoptysis'], |
| 'chest_pain': symptoms['chest_pain'], |
| 'fatigue': symptoms['fatigue'], |
| 'loss_of_appetite': symptoms['loss_of_appetite'], |
| 'who_symptom_screen_count': who_symptom_count, |
| 'smear_result': smear_result, |
| 'xpert_mtb_detected': xpert_mtb, |
| 'xpert_rif_resistance': xpert_rif_resistant, |
| 'cxr_result': cxr_result, |
| 'cxr_abnormal': cxr_abnormal, |
| 'true_tb_status': true_tb, |
| 'tb_type': tb_type, |
| 'tb_classification': tb_classification, |
| 'rifampicin_resistant': rifampicin_resistant, |
| 'treatment_outcome': treatment_outcome, |
| }) |
|
|
| |
| tb_pos = true_tb.sum() |
| print(f"\n{'='*60}") |
| print(f"TB Screening — {scenario} (n={n}, seed={seed})") |
| print(f"{'='*60}") |
| print(f"\nTB prevalence: {tb_pos/n*100:.1f}%") |
| print(f"HIV+: {hiv_status.mean()*100:.1f}%") |
| print(f"TB-HIV co-infection: {(true_tb & hiv_status).sum()}/{tb_pos} " |
| f"({(true_tb & hiv_status).sum()/max(tb_pos,1)*100:.0f}%) of TB cases") |
| print(f"Pulmonary TB: {(tb_type=='pulmonary').sum()}") |
| print(f"Extrapulmonary TB: {(tb_type=='extrapulmonary').sum()}") |
| print(f"Smear+: {smear_result.sum()} ({smear_result.mean()*100:.1f}%)") |
| print(f"Xpert MTB+: {xpert_mtb.sum()} ({xpert_mtb.mean()*100:.1f}%)") |
| print(f"CXR abnormal: {cxr_abnormal.sum()} ({cxr_abnormal.mean()*100:.1f}%)") |
| print(f"MDR-TB: {rifampicin_resistant.sum()} ({rifampicin_resistant[true_tb==1].mean()*100:.1f}% of TB)") |
| print(f"Mean BMI (TB): {bmi[true_tb==1].mean():.1f}, (non-TB): {bmi[true_tb==0].mean():.1f}") |
|
|
| return df |
|
|
|
|
| |
| |
| |
|
|
| if __name__ == '__main__': |
| parser = argparse.ArgumentParser( |
| description='Generate synthetic TB screening dataset') |
| parser.add_argument('--scenario', type=str, default='moderate_tb_burden', |
| choices=list(SCENARIOS.keys())) |
| parser.add_argument('--n', type=int, default=10000) |
| parser.add_argument('--seed', type=int, default=42) |
| parser.add_argument('--output', type=str, default=None) |
| parser.add_argument('--all-scenarios', action='store_true') |
| args = parser.parse_args() |
|
|
| os.makedirs('data', exist_ok=True) |
|
|
| if args.all_scenarios: |
| for sc_name in SCENARIOS: |
| df = generate_tb_dataset(n=args.n, seed=args.seed, scenario=sc_name) |
| out = os.path.join('data', f'tb_{sc_name}.csv') |
| df.to_csv(out, index=False) |
| print(f" → Saved to {out}\n") |
| else: |
| df = generate_tb_dataset(n=args.n, seed=args.seed, scenario=args.scenario) |
| out = args.output or os.path.join('data', f'tb_{args.scenario}.csv') |
| df.to_csv(out, index=False) |
| print(f" → Saved to {out}") |
|
|