#!/usr/bin/env python3 """ Literature-Informed Drug-Sensitive TB Treatment Cascade Dataset ================================================================ Generates realistic synthetic records of drug-sensitive TB patients in sub-Saharan Africa, including diagnosis, treatment regimen, adherence, HIV coinfection, and treatment outcomes. References (web-searched): ----------- [1] WHO 2024. Global TB Report. 10.8M new cases 2023, 1.25M deaths. SSA disproportionate burden. [2] Frontiers 2025. TB burden in 22 SSA countries. High incidence, drug resistance emerging. [3] WHO 2022. DS-TB treatment: 2HRZE/4HR (6 months). Treatment success target >=85%. [4] PubMed 2022. GeneXpert rollout in DRC, Nigeria, SA. Improvements in diagnosis but treatment gaps remain. [5] ScienceDirect 2025. Multi-month dispensing TB meds. Treatment success rate varies 75-88% in SSA. [6] PubMed 2024. Subclinical TB linkage to care. Loss to follow-up significant. """ import numpy as np import pandas as pd import argparse import os SCENARIOS = { 'urban_dots_centre': { 'description': 'Urban DOTS centre with GeneXpert, ' 'daily DOT, HIV testing, ART integration ' '(e.g., Johannesburg, Nairobi, Dar es Salaam)', 'genexpert_available': True, 'culture_available': True, 'dot_available': True, 'art_integrated': True, 'treatment_success': 0.85, 'ltfu_rate': 0.08, }, 'district_hospital': { 'description': 'District hospital with smear microscopy, ' 'GeneXpert referral, community DOT ' '(e.g., district hospitals Malawi, Uganda)', 'genexpert_available': False, 'culture_available': False, 'dot_available': True, 'art_integrated': True, 'treatment_success': 0.78, 'ltfu_rate': 0.15, }, 'rural_health_post': { 'description': 'Rural health post with smear microscopy ' 'only, drug supply challenges, no DOT ' '(e.g., rural DRC, CAR, South Sudan)', 'genexpert_available': False, 'culture_available': False, 'dot_available': False, 'art_integrated': False, 'treatment_success': 0.65, 'ltfu_rate': 0.25, }, } def generate_dataset(n=10000, seed=42, scenario='district_hospital'): rng = np.random.default_rng(seed) sc = SCENARIOS[scenario] records = [] for idx in range(n): rec = {'id': idx + 1} # ── 1. Demographics ── rec['age'] = max(5, min(85, int(rng.normal(35, 14)))) rec['sex'] = rng.choice(['M', 'F'], p=[0.58, 0.42]) rec['child'] = 1 if rec['age'] < 15 else 0 rec['education'] = rng.choice( ['none', 'primary', 'secondary', 'tertiary'], p=[0.20, 0.35, 0.35, 0.10]) rec['urban'] = 1 if rng.random() < 0.45 else 0 rec['bmi'] = round(max(12, min(35, rng.normal(19.5, 3.5))), 1) rec['underweight'] = 1 if rec['bmi'] < 18.5 else 0 # ── 2. Risk factors ── rec['hiv_positive'] = 1 if rng.random() < 0.35 else 0 rec['on_art'] = 0 if rec['hiv_positive']: rec['on_art'] = 1 if rng.random() < (0.80 if sc['art_integrated'] else 0.45) else 0 rec['cd4_count'] = 0 if rec['hiv_positive']: rec['cd4_count'] = max(10, min(1000, int(rng.normal(250, 150)))) rec['diabetes'] = 0 if rec['age'] >= 30: rec['diabetes'] = 1 if rng.random() < 0.06 else 0 rec['smoker'] = 0 if rec['age'] >= 15: rec['smoker'] = 1 if rng.random() < 0.15 else 0 rec['alcohol_use'] = 0 if rec['age'] >= 15: rec['alcohol_use'] = 1 if rng.random() < 0.20 else 0 rec['previous_tb'] = 1 if rng.random() < 0.12 else 0 rec['household_tb_contact'] = 1 if rng.random() < 0.25 else 0 rec['mining_exposure'] = 0 if rec['sex'] == 'M': rec['mining_exposure'] = 1 if rng.random() < 0.05 else 0 # ── 3. Presentation ── rec['tb_type'] = rng.choice( ['pulmonary', 'extrapulmonary'], p=[0.85, 0.15]) rec['symptom_duration_weeks'] = max(1, min(52, int(rng.exponential(6) + 2))) rec['cough'] = 1 if rec['tb_type'] == 'pulmonary' and rng.random() < 0.90 else ( 1 if rng.random() < 0.30 else 0) rec['weight_loss'] = 1 if rng.random() < 0.70 else 0 rec['night_sweats'] = 1 if rng.random() < 0.55 else 0 rec['fever'] = 1 if rng.random() < 0.60 else 0 rec['haemoptysis'] = 0 if rec['tb_type'] == 'pulmonary': rec['haemoptysis'] = 1 if rng.random() < 0.15 else 0 rec['cavitary_disease'] = 0 if rec['tb_type'] == 'pulmonary': rec['cavitary_disease'] = 1 if rng.random() < 0.30 else 0 # ── 4. Diagnosis [4] ── rec['diagnostic_method'] = 'clinical' if rec['tb_type'] == 'pulmonary': if sc['genexpert_available']: rec['diagnostic_method'] = rng.choice( ['genexpert', 'smear_microscopy', 'clinical'], p=[0.60, 0.25, 0.15]) else: rec['diagnostic_method'] = rng.choice( ['smear_microscopy', 'clinical'], p=[0.60, 0.40]) rec['smear_positive'] = 0 if rec['tb_type'] == 'pulmonary': rec['smear_positive'] = 1 if rng.random() < 0.55 else 0 rec['chest_xray_done'] = 1 if rng.random() < (0.70 if rec['urban'] else 0.30) else 0 rec['culture_done'] = 0 if sc['culture_available']: rec['culture_done'] = 1 if rng.random() < 0.30 else 0 rec['dst_done'] = 0 if rec['diagnostic_method'] == 'genexpert' or rec['culture_done']: rec['dst_done'] = 1 if rng.random() < 0.80 else 0 rec['rifampicin_sensitive'] = 1 rec['diagnosis_delay_days'] = max(1, min(180, int(rng.exponential(30) + 7))) rec['hiv_tested_at_tb_diagnosis'] = 0 if sc['art_integrated']: rec['hiv_tested_at_tb_diagnosis'] = 1 if rng.random() < 0.85 else 0 else: rec['hiv_tested_at_tb_diagnosis'] = 1 if rng.random() < 0.40 else 0 # ── 5. Treatment [3][5] ── rec['treatment_regimen'] = '2HRZE_4HR' if rec['child'] and rec['age'] < 8: rec['treatment_regimen'] = '2HRZ_4HR' rec['treatment_started'] = 1 if rng.random() < 0.92 else 0 rec['treatment_start_delay_days'] = 0 if rec['treatment_started']: rec['treatment_start_delay_days'] = max(0, min(60, int(rng.exponential(5)))) rec['dot_received'] = 0 if rec['treatment_started'] and sc['dot_available']: rec['dot_received'] = 1 if rng.random() < 0.70 else 0 rec['cotrimoxazole_prophylaxis'] = 0 if rec['hiv_positive'] and rec['treatment_started']: rec['cotrimoxazole_prophylaxis'] = 1 if rng.random() < 0.75 else 0 rec['intensive_phase_completed'] = 0 if rec['treatment_started']: rec['intensive_phase_completed'] = 1 if rng.random() < (0.97 - sc['ltfu_rate'] * 0.3) else 0 rec['sputum_conversion_2_months'] = 0 if rec['intensive_phase_completed'] and rec['smear_positive']: rec['sputum_conversion_2_months'] = 1 if rng.random() < 0.80 else 0 rec['continuation_phase_completed'] = 0 if rec['intensive_phase_completed']: rec['continuation_phase_completed'] = 1 if rng.random() < (0.97 - sc['ltfu_rate'] * 0.6) else 0 rec['adherence_rate'] = 0.0 if rec['treatment_started']: base = 0.85 if rec['dot_received'] else 0.70 rec['adherence_rate'] = round(min(1.0, max(0.2, rng.normal(base, 0.12))), 2) rec['side_effects'] = 0 if rec['treatment_started']: rec['side_effects'] = 1 if rng.random() < 0.25 else 0 rec['hepatotoxicity'] = 0 if rec['side_effects']: rec['hepatotoxicity'] = 1 if rng.random() < 0.15 else 0 rec['peripheral_neuropathy'] = 0 if rec['side_effects']: rec['peripheral_neuropathy'] = 1 if rng.random() < 0.20 else 0 # ── 6. Treatment outcome [1][5] ── rec['treatment_outcome'] = 'not_evaluated' if rec['treatment_started']: if rec['continuation_phase_completed']: if rng.random() < sc['treatment_success']: rec['treatment_outcome'] = 'cured' if rec['smear_positive'] else 'completed' else: rec['treatment_outcome'] = rng.choice(['failed', 'relapsed'], p=[0.60, 0.40]) elif rec['intensive_phase_completed'] and not rec['continuation_phase_completed']: rec['treatment_outcome'] = 'lost_to_followup' else: rec['treatment_outcome'] = rng.choice( ['lost_to_followup', 'failed'], p=[0.80, 0.20]) rec['died_during_treatment'] = 0 if rec['treatment_started']: mort = 0.04 if rec['hiv_positive'] and not rec['on_art']: mort *= 3 if rec['underweight']: mort *= 1.5 if rec['age'] > 60: mort *= 1.5 rec['died_during_treatment'] = 1 if rng.random() < min(mort, 0.25) else 0 if rec['died_during_treatment']: rec['treatment_outcome'] = 'died' rec['treatment_success'] = 1 if rec['treatment_outcome'] in ('cured', 'completed') else 0 records.append(rec) df = pd.DataFrame(records) print(f"\n{'='*65}") print(f"DS-TB Cascade — {scenario} (n={n}, seed={seed})") print(f"{'='*65}") print(f"\n TB-HIV coinfection: {df['hiv_positive'].mean()*100:.1f}%") print(f" Treatment started: {df['treatment_started'].mean()*100:.1f}%") print(f" Treatment success: {df['treatment_success'].mean()*100:.1f}%") print(f" LTFU: {(df['treatment_outcome']=='lost_to_followup').mean()*100:.1f}%") print(f" Died: {df['died_during_treatment'].mean()*100:.1f}%") print(f" Smear positive: {df['smear_positive'].mean()*100:.1f}%") return df if __name__ == '__main__': parser = argparse.ArgumentParser( description='Generate DS-TB treatment cascade dataset') parser.add_argument('--scenario', type=str, default='district_hospital', 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_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_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}")