#!/usr/bin/env python3 """ Literature-Informed Synthetic HIV/ART Treatment Cascade Dataset Generator ========================================================================= Generates realistic synthetic records of people living with HIV (PLHIV) across the treatment cascade in sub-Saharan African settings, including diagnosis status, ART regimen, CD4 count trajectories, viral load, adherence, regimen switches, PMTCT, retention in care, and outcomes. Target population: PLHIV aged 15-65 years in facility-based ART programmes across sub-Saharan Africa. DAG (Sampling Order): 1. age, sex (roots) 2. cascade_stage: undiagnosed / diagnosed_not_on_ART / on_ART 3. years_on_art, art_regimen, regimen_line 4. cd4_at_diagnosis, cd4_current (conditional on ART duration, adherence) 5. viral_load (conditional on ART, adherence) 6. adherence_category (conditional on age, sex, scenario) 7. who_clinical_stage (conditional on CD4, VL) 8. tb_coinfection, pregnancy/pmtct (conditional on sex, age) 9. outcome: alive_in_care / ltfu / transferred / died References: ----------- [1] UNAIDS (2023). Global AIDS Update. 90-90-90 targets. 25.6M on ART in eastern/southern Africa; 86% of PLHIV know status, 89% of diagnosed on ART, 92% of those on ART suppressed. [2] Hakim J, et al. (2020). Sociodemographic heterogeneity across HIV treatment cascade in SSA. Systematic review, 92 studies. Ages 15-24: cascade 60-49-81; ≥25: 70-63-91; Men: 66-72-85; Women: 79-76-89. PMID: 32153117 [3] WHO (2019). Updated recommendations on first-line and second-line ART. TDF/3TC/DTG preferred first-line. ATV/r or LPV/r-based second-line. [4] IeDEA Consortium (multiple). CD4 at ART initiation in SSA: median ~200-350 cells/µL. Late presenters (<200): 30-50% in many settings. [5] Bock P, et al. (Lancet HIV 2022). Viral load monitoring cascade in SSA. VL testing coverage 60-85%; suppression 85-92% among tested. [6] Onoya D, et al. (2021). 12-month retention in care: 75-85% in well-performing programmes; 50-65% in weaker systems. [7] WHO (2007/2014). WHO clinical staging of HIV/AIDS. Stage 1: asymptomatic; Stage 2: mild; Stage 3: advanced; Stage 4: severe. [8] Gupta RK, et al. (Lancet Infect Dis 2018). HIV drug resistance in SSA. Pre-treatment NNRTI resistance 10-15%; acquired resistance ~5-10%. [9] Dzangare J, et al. (2023). Implementation of DTG-based first-line regimens. DTG retention aRR 1.09; VL suppression higher vs EFV. PMID: 37001536 [10] Shroufi A, et al. (2021). TLD as second-line after NNRTI failure. High suppression despite baseline NRTI resistance. PMID: 33973876 [11] UNAIDS (2022). PMTCT: 82% of pregnant women with HIV received ART globally; mother-to-child transmission rate ~3-5% in SSA with ART. """ import numpy as np import pandas as pd from scipy.stats import truncnorm import argparse import os # ============================================================ # SECTION 1: Literature-Informed Parameters # ============================================================ SCENARIOS = { 'high_performing': { 'description': 'Well-resourced ART programme (e.g., Botswana, Rwanda, ' 'eSwatini). Near 90-90-90 achievement.', # Treatment cascade [1][2] 'pct_diagnosed': 0.90, 'pct_on_art_if_diagnosed': 0.89, 'pct_suppressed_if_on_art': 0.92, # Retention [6] 'retention_12mo': 0.85, 'ltfu_annual_rate': 0.08, # CD4 at initiation [4] 'cd4_init_mean': 320, 'cd4_init_sd': 180, 'late_presenter_pct': 0.25, # CD4 <200 # Adherence 'good_adherence_pct': 0.75, 'moderate_adherence_pct': 0.18, # Regimen [3][9] 'dtg_based_pct': 0.80, 'efv_based_pct': 0.12, 'second_line_pct': 0.06, 'third_line_pct': 0.02, # TB co-infection 'tb_coinfection_pct': 0.08, # Mortality 'annual_mortality_on_art': 0.015, 'annual_mortality_not_on_art': 0.08, }, 'moderate_performing': { 'description': 'Average SSA ART programme (e.g., Kenya, Tanzania, ' 'Zambia). Partial 90-90-90 achievement.', 'pct_diagnosed': 0.80, 'pct_on_art_if_diagnosed': 0.78, 'pct_suppressed_if_on_art': 0.88, 'retention_12mo': 0.78, 'ltfu_annual_rate': 0.12, 'cd4_init_mean': 250, 'cd4_init_sd': 170, 'late_presenter_pct': 0.35, 'good_adherence_pct': 0.65, 'moderate_adherence_pct': 0.22, 'dtg_based_pct': 0.65, 'efv_based_pct': 0.22, 'second_line_pct': 0.10, 'third_line_pct': 0.03, 'tb_coinfection_pct': 0.12, 'annual_mortality_on_art': 0.025, 'annual_mortality_not_on_art': 0.10, }, 'low_performing': { 'description': 'Weak ART programme (e.g., Nigeria, DRC, Chad). ' 'Low cascade achievement, high LTFU.', 'pct_diagnosed': 0.65, 'pct_on_art_if_diagnosed': 0.62, 'pct_suppressed_if_on_art': 0.80, 'retention_12mo': 0.60, 'ltfu_annual_rate': 0.22, 'cd4_init_mean': 180, 'cd4_init_sd': 150, 'late_presenter_pct': 0.50, 'good_adherence_pct': 0.50, 'moderate_adherence_pct': 0.25, 'dtg_based_pct': 0.45, 'efv_based_pct': 0.32, 'second_line_pct': 0.18, 'third_line_pct': 0.05, 'tb_coinfection_pct': 0.18, 'annual_mortality_on_art': 0.04, 'annual_mortality_not_on_art': 0.14, }, } # --- CD4 Recovery on ART --- # [4] IeDEA: ~100-150 cells/µL gain in first year, slower after CD4_RECOVERY_YEAR1 = 120 # cells/µL/year CD4_RECOVERY_LATER = 50 # cells/µL/year after year 1 # --- Viral Load Parameters --- # Suppressed (<1000 copies/mL per WHO; <50 = undetectable) # Untreated: 10,000-1,000,000 copies/mL [1] VL_SUPPRESSED = {'mean_log': 1.3, 'sd_log': 0.4} # ~20 copies/mL VL_LOW_LEVEL = {'mean_log': 2.5, 'sd_log': 0.5} # ~300 copies/mL VL_FAILING = {'mean_log': 4.0, 'sd_log': 0.8} # ~10,000 copies/mL VL_UNTREATED = {'mean_log': 4.5, 'sd_log': 0.7} # ~30,000 copies/mL # --- ART Regimens --- # [3] WHO 2019 recommended REGIMENS = { 'first_line_dtg': 'TDF/3TC/DTG', 'first_line_efv': 'TDF/3TC/EFV', 'second_line': 'AZT/3TC/ATV-r', 'third_line': 'DRV-r/DTG/AZT/3TC', } # --- WHO Clinical Staging [7] --- # Stage determined by CD4 and opportunistic infections WHO_STAGE_BY_CD4 = { 'stage_1': {'cd4_min': 500, 'prob_if_above': 0.70}, 'stage_2': {'cd4_range': (350, 500), 'prob_in_range': 0.50}, 'stage_3': {'cd4_range': (200, 350), 'prob_in_range': 0.55}, 'stage_4': {'cd4_max': 200, 'prob_if_below': 0.40}, } # ============================================================ # SECTION 2: Utility Functions # ============================================================ def trunc_normal(mean, sd, lo, hi, size, rng): if sd <= 0: return np.full(size, mean) 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)) # ============================================================ # SECTION 3: Main Generator # ============================================================ def generate_hiv_dataset(n=10000, seed=42, scenario='moderate_performing'): rng = np.random.default_rng(seed) sc = SCENARIOS[scenario] # ── Step 1: Demographics ── # Age: 15-65, peak in 25-45 (highest HIV prevalence) age_years = np.zeros(n) for i in range(n): r = rng.random() if r < 0.15: age_years[i] = rng.uniform(15, 24) elif r < 0.45: age_years[i] = rng.uniform(25, 34) elif r < 0.75: age_years[i] = rng.uniform(35, 44) elif r < 0.92: age_years[i] = rng.uniform(45, 54) else: age_years[i] = rng.uniform(55, 65) age_years = np.round(age_years, 0).astype(int) # Sex: ~60% female in SSA HIV populations [2] sex = rng.choice(['M', 'F'], size=n, p=[0.40, 0.60]) # ── Step 2: Treatment Cascade Stage ── # [1][2] UNAIDS cascade cascade_stage = np.array(['undiagnosed'] * n, dtype=object) for i in range(n): # Diagnosis probability [2] — age/sex adjusted diag_prob = sc['pct_diagnosed'] if age_years[i] < 25: diag_prob *= 0.75 # [2] Youth lower diagnosis if sex[i] == 'M': diag_prob *= 0.88 # [2] Men lower diagnosis if rng.random() < diag_prob: # On ART probability art_prob = sc['pct_on_art_if_diagnosed'] if age_years[i] < 25: art_prob *= 0.70 # [2] Youth lower ART uptake if sex[i] == 'M': art_prob *= 0.90 if rng.random() < art_prob: cascade_stage[i] = 'on_ART' else: cascade_stage[i] = 'diagnosed_not_on_ART' # ── Step 3: ART Duration & Regimen ── years_on_art = np.zeros(n) art_regimen = np.array(['none'] * n, dtype=object) regimen_line = np.zeros(n, dtype=int) ever_switched = np.zeros(n, dtype=int) for i in range(n): if cascade_stage[i] != 'on_ART': continue # Duration: 0.5-15 years, skewed toward shorter years_on_art[i] = rng.exponential(4.0) years_on_art[i] = np.clip(years_on_art[i], 0.1, 18.0) # Regimen assignment [3][9] reg_roll = rng.random() if reg_roll < sc['dtg_based_pct']: art_regimen[i] = REGIMENS['first_line_dtg'] regimen_line[i] = 1 elif reg_roll < sc['dtg_based_pct'] + sc['efv_based_pct']: art_regimen[i] = REGIMENS['first_line_efv'] regimen_line[i] = 1 elif reg_roll < (sc['dtg_based_pct'] + sc['efv_based_pct'] + sc['second_line_pct']): art_regimen[i] = REGIMENS['second_line'] regimen_line[i] = 2 ever_switched[i] = 1 else: art_regimen[i] = REGIMENS['third_line'] regimen_line[i] = 3 ever_switched[i] = 1 years_on_art = np.round(years_on_art, 1) # ── Step 4: CD4 Count ── # [4] CD4 at diagnosis and current cd4_at_diagnosis = np.zeros(n, dtype=int) cd4_current = np.zeros(n, dtype=int) for i in range(n): # CD4 at diagnosis [4] if rng.random() < sc['late_presenter_pct']: # Late presenter: CD4 <200 cd4_at_diagnosis[i] = max(10, int(rng.normal(120, 60))) else: cd4_at_diagnosis[i] = max(50, int(rng.normal( sc['cd4_init_mean'], sc['cd4_init_sd']))) cd4_at_diagnosis[i] = min(cd4_at_diagnosis[i], 1200) # Current CD4 if cascade_stage[i] == 'on_ART': # Recovery: ~120/yr year 1, ~50/yr after [4] yrs = years_on_art[i] if yrs <= 1: recovery = CD4_RECOVERY_YEAR1 * yrs else: recovery = CD4_RECOVERY_YEAR1 + CD4_RECOVERY_LATER * (yrs - 1) # Add noise recovery *= rng.normal(1.0, 0.3) cd4_current[i] = int(cd4_at_diagnosis[i] + max(recovery, 0)) cd4_current[i] = min(cd4_current[i], 1500) elif cascade_stage[i] == 'diagnosed_not_on_ART': # Declining ~50-100 cells/yr untreated decline = rng.normal(75, 30) * rng.uniform(0.5, 3.0) cd4_current[i] = max(10, int(cd4_at_diagnosis[i] - decline)) else: # Undiagnosed — assign based on natural history cd4_current[i] = max(10, int(rng.normal(350, 200))) cd4_at_diagnosis[i] = 0 # Not yet diagnosed # ── Step 5: Adherence ── adherence_category = np.array(['unknown'] * n, dtype=object) adherence_pct = np.zeros(n) for i in range(n): if cascade_stage[i] != 'on_ART': continue good_prob = sc['good_adherence_pct'] mod_prob = sc['moderate_adherence_pct'] # [2] Youth and men have lower adherence if age_years[i] < 25: good_prob *= 0.75 mod_prob *= 1.2 if sex[i] == 'M': good_prob *= 0.90 roll = rng.random() total = good_prob + mod_prob if roll < good_prob / (total + (1 - total)): adherence_category[i] = 'good' adherence_pct[i] = rng.uniform(90, 100) elif roll < (good_prob + mod_prob) / (total + (1 - total)): adherence_category[i] = 'moderate' adherence_pct[i] = rng.uniform(70, 90) else: adherence_category[i] = 'poor' adherence_pct[i] = rng.uniform(30, 70) adherence_pct = np.round(adherence_pct, 0).astype(int) # ── Step 6: Viral Load ── viral_load = np.zeros(n, dtype=int) vl_suppressed = np.zeros(n, dtype=int) for i in range(n): if cascade_stage[i] == 'on_ART': if adherence_category[i] == 'good': # [1][5] ~92% suppressed if rng.random() < sc['pct_suppressed_if_on_art']: log_vl = rng.normal(VL_SUPPRESSED['mean_log'], VL_SUPPRESSED['sd_log']) else: log_vl = rng.normal(VL_LOW_LEVEL['mean_log'], VL_LOW_LEVEL['sd_log']) elif adherence_category[i] == 'moderate': if rng.random() < 0.65: log_vl = rng.normal(VL_SUPPRESSED['mean_log'], VL_SUPPRESSED['sd_log']) else: log_vl = rng.normal(VL_FAILING['mean_log'], VL_FAILING['sd_log']) else: # poor if rng.random() < 0.25: log_vl = rng.normal(VL_LOW_LEVEL['mean_log'], VL_LOW_LEVEL['sd_log']) else: log_vl = rng.normal(VL_FAILING['mean_log'], VL_FAILING['sd_log']) else: # Not on ART log_vl = rng.normal(VL_UNTREATED['mean_log'], VL_UNTREATED['sd_log']) log_vl = np.clip(log_vl, 0.5, 7.0) viral_load[i] = int(10 ** log_vl) vl_suppressed[i] = 1 if viral_load[i] < 1000 else 0 # WHO threshold # ── Step 7: WHO Clinical Stage [7] ── who_stage = np.zeros(n, dtype=int) for i in range(n): cd4 = cd4_current[i] if cd4 >= 500: who_stage[i] = 1 if rng.random() < 0.80 else 2 elif cd4 >= 350: roll = rng.random() if roll < 0.40: who_stage[i] = 1 elif roll < 0.80: who_stage[i] = 2 else: who_stage[i] = 3 elif cd4 >= 200: roll = rng.random() if roll < 0.20: who_stage[i] = 2 elif roll < 0.70: who_stage[i] = 3 else: who_stage[i] = 4 else: roll = rng.random() if roll < 0.15: who_stage[i] = 3 else: who_stage[i] = 4 # ── Step 8: Co-morbidities ── # TB co-infection tb_coinfection = np.zeros(n, dtype=int) for i in range(n): tb_prob = sc['tb_coinfection_pct'] if cd4_current[i] < 200: tb_prob *= 3.0 elif cd4_current[i] < 350: tb_prob *= 1.5 tb_coinfection[i] = 1 if rng.random() < min(tb_prob, 0.5) else 0 # Pregnancy / PMTCT [11] pregnant = np.zeros(n, dtype=int) on_pmtct = np.zeros(n, dtype=int) for i in range(n): if sex[i] == 'F' and 15 <= age_years[i] <= 45: if rng.random() < 0.06: pregnant[i] = 1 if cascade_stage[i] == 'on_ART': on_pmtct[i] = 1 elif rng.random() < 0.82: # [11] 82% PMTCT coverage on_pmtct[i] = 1 # ── Step 9: VL monitoring ── # [5] VL test done in last 12 months vl_test_done = np.zeros(n, dtype=int) for i in range(n): if cascade_stage[i] == 'on_ART': vl_test_prob = 0.80 if scenario == 'high_performing' else ( 0.65 if scenario == 'moderate_performing' else 0.45) vl_test_done[i] = 1 if rng.random() < vl_test_prob else 0 # ── Step 10: Outcome ── outcome = np.array(['alive_in_care'] * n, dtype=object) for i in range(n): if cascade_stage[i] == 'undiagnosed': if rng.random() < sc['annual_mortality_not_on_art']: outcome[i] = 'died' else: outcome[i] = 'undiagnosed' elif cascade_stage[i] == 'diagnosed_not_on_ART': if rng.random() < sc['annual_mortality_not_on_art']: outcome[i] = 'died' elif rng.random() < sc['ltfu_annual_rate']: outcome[i] = 'ltfu' else: outcome[i] = 'pre_art_care' else: # on_ART mort = sc['annual_mortality_on_art'] if cd4_current[i] < 100: mort *= 4.0 elif cd4_current[i] < 200: mort *= 2.0 if tb_coinfection[i]: mort *= 2.5 if not vl_suppressed[i]: mort *= 1.8 if rng.random() < min(mort, 0.30): outcome[i] = 'died' elif rng.random() < sc['ltfu_annual_rate']: outcome[i] = 'ltfu' elif rng.random() < 0.03: outcome[i] = 'transferred' else: outcome[i] = 'alive_in_care' # ── Assemble DataFrame ── df = pd.DataFrame({ 'id': np.arange(1, n + 1), 'age_years': age_years, 'sex': sex, 'cascade_stage': cascade_stage, 'years_on_art': years_on_art, 'art_regimen': art_regimen, 'regimen_line': regimen_line, 'ever_switched_regimen': ever_switched, 'cd4_at_diagnosis': cd4_at_diagnosis, 'cd4_current': cd4_current, 'adherence_category': adherence_category, 'adherence_pct': adherence_pct, 'viral_load_copies_ml': viral_load, 'vl_suppressed': vl_suppressed, 'vl_test_done_12mo': vl_test_done, 'who_clinical_stage': who_stage, 'tb_coinfection': tb_coinfection, 'pregnant': pregnant, 'on_pmtct': on_pmtct, 'outcome': outcome, }) # ── Print Summary ── print(f"\n{'='*65}") print(f"HIV/ART Treatment Cascade — {scenario} (n={n}, seed={seed})") print(f"{'='*65}") for stage in ['undiagnosed', 'diagnosed_not_on_ART', 'on_ART']: ct = (cascade_stage == stage).sum() print(f" {stage}: {ct} ({ct/n*100:.1f}%)") on_art = df[df['cascade_stage'] == 'on_ART'] print(f"\n On ART (n={len(on_art)}):") print(f" VL suppressed (<1000): {on_art['vl_suppressed'].mean()*100:.1f}%") print(f" CD4 current: {on_art['cd4_current'].mean():.0f} ± " f"{on_art['cd4_current'].std():.0f}") print(f" Years on ART: {on_art['years_on_art'].mean():.1f}") print(f" Good adherence: {(on_art['adherence_category']=='good').mean()*100:.1f}%") for reg in ['TDF/3TC/DTG', 'TDF/3TC/EFV', 'AZT/3TC/ATV-r', 'DRV-r/DTG/AZT/3TC']: ct = (on_art['art_regimen'] == reg).sum() if ct > 0: print(f" {reg}: {ct} ({ct/len(on_art)*100:.1f}%)") print(f"\n TB co-infection: {tb_coinfection.sum()} " f"({tb_coinfection.mean()*100:.1f}%)") print(f" Pregnant: {pregnant.sum()}") print(f" On PMTCT: {on_pmtct.sum()}") died = (outcome == 'died').sum() ltfu = (outcome == 'ltfu').sum() print(f"\n Deaths: {died} ({died/n*100:.1f}%)") print(f" LTFU: {ltfu} ({ltfu/n*100:.1f}%)") # Population-level viral suppression pop_suppressed = vl_suppressed.sum() / n * 100 print(f" Population-level VL suppression: {pop_suppressed:.1f}%") return df # ============================================================ # SECTION 4: CLI Entry Point # ============================================================ if __name__ == '__main__': parser = argparse.ArgumentParser( description='Generate synthetic HIV/ART treatment cascade dataset') parser.add_argument('--scenario', type=str, default='moderate_performing', 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_hiv_dataset(n=args.n, seed=args.seed, scenario=sc_name) out = os.path.join('data', f'hiv_art_{sc_name}.csv') df.to_csv(out, index=False) print(f" → Saved to {out}\n") else: df = generate_hiv_dataset(n=args.n, seed=args.seed, scenario=args.scenario) out = args.output or os.path.join('data', f'hiv_art_{args.scenario}.csv') df.to_csv(out, index=False) print(f" → Saved to {out}")