""" HIV Treatment Cascade and Drug Resistance Dataset Generator for Nigeria This script generates synthetic datasets for HIV treatment cascade analysis and drug resistance surveillance in Nigeria, incorporating evidence-based parameters from recent studies and national program data. Variables included: - Geographic: state, lga, year, quarter, zone - Demographics: person_id (anonymized), age_years, age_group, sex, pregnancy_status - Key populations: key_population, kp_type - HIV cascade: hiv_status, date_of_diagnosis, days_since_diagnosis, ever_linked_to_care, date_of_art_initiation, months_on_art - Treatment: current_art_regimen, art_adherence_pct, missed_doses_last_month - Viral load: vl_test_done, vl_result, vl_suppressed, vl_suppression_threshold, vl_detectable - Drug resistance: dr_test_done, dr_test_method, num_drms_detected, high_level_risk_drugs, specific_drms, dr_category, transmitted_resistance_flag - Outcomes: treatment_outcome - Health system: facility_level, managing_authority, urban_rural, stockout_arv, stockout_rt_kits, cd4_count_cells_ul, who_clinical_stage - Prevention: tb_screening_done, tb_preventive_therapy, cervical_cancer_screening, mental_health_screening - Socioeconomic: household_wealth_quintile, education_level, distance_to_facility_km, transport_cost_ngn, stigma_experienced, disclosure_status, partner_notification_done, condom_use_at_last_sex Evidence Base: - NACA reports on HIV prevalence (1.3% among adults 15-49) and PLHIV estimate (1.9 million) - UNAIDS 95-95-95 targets progress (87-98-95 as of 2025) - HIV Drug Resistance Among Key Populations in Nigeria: 16.7% contained at least one DRM (2026) - DRM prevalence highest among PWID (21.6%) and North Central zone (25.8%) - 46% decline in new HIV infections (2025) - 95% of Nigerians on HIV treatment can no longer transmit virus (2025) """ import pandas as pd import numpy as np from datetime import datetime, timedelta import os import json class NigeriaHIVDatasetGenerator: def __init__(self, seed=42): """ Initialize the dataset generator with evidence-based parameters. Parameter Evidence Table: - HIV Prevalence: 1.3% among adults 15-49 years (NACA) [Source: NACA Nigeria Prevalence Rate] - PLHIV Estimate: 1.9 million people living with HIV in Nigeria [Source: NACA Nigeria Prevalence Rate] - 95-95-95 Progress: 87% know status, 98% on treatment, 95% virally suppressed (2025) [Source: NACA press conference, Nov 2025] - New Infections Decline: 46% drop in new HIV infections (2025) [Source: The Sun Nigeria, Nov 2025] - Transmission Risk: 95% of Nigerians on HIV treatment can no longer transmit virus (2025) [Source: Guardian Nigeria, Nov 2025] - HIV Drug Resistance: 16.7% of key populations contain at least one DRM (2026) [Source: PubMed PMID: 40931993, DOI: 10.1097/QAI.0000000000003763] - DRM by Population: Highest among PWID (21.6%) [Source: PubMed PMID: 40931993] - DRM by Zone: Highest in North Central (25.8%) [Source: PubMed PMID: 40931993] - Common DRMs: K103N, M41L, M184V [Source: PubMed PMID: 40931993] """ self.seed = seed np.random.seed(seed) # Geographic distribution based on Nigeria's 36 states + FTC self.states = [ 'Abia', 'Adamawa', 'Akwa Ibom', 'Anambra', 'Bauchi', 'Bayelsa', 'Benue', 'Borno', 'Cross River', 'Delta', 'Ebonyi', 'Edo', 'Ekiti', 'Enugu', 'Gombe', 'Imo', 'Jigawa', 'Kaduna', 'Kano', 'Katsina', 'Kebbi', 'Kogi', 'Kwara', 'Lagos', 'Nasarawa', 'Niger', 'Ogun', 'Ondo', 'Osun', 'Oyo', 'Plateau', 'Rivers', 'Sokoto', 'Taraba', 'Yobe', 'Zamfara', 'FCT Abuja' ] # Geopolitical zones self.zones = { 'North Central': ['Benue', 'Kogi', 'Kwara', 'Nasarawa', 'Niger', 'Plateau', 'FCT Abuja'], 'North East': ['Adamawa', 'Bauchi', 'Borno', 'Gombe', 'Taraba', 'Yobe'], 'North West': ['Jigawa', 'Kaduna', 'Kano', 'Katsina', 'Kebbi', 'Sokoto', 'Zamfara'], 'South East': ['Abia', 'Anambra', 'Ebonyi', 'Enugu', 'Imo'], 'South South': ['Akwa Ibom', 'Bayelsa', 'Cross River', 'Delta', 'Edo', 'Rivers'], 'South West': ['Ekiti', 'Lagos', 'Ogun', 'Ondo', 'Osun', 'Oyo'] } # Create reverse mapping self.state_to_zone = {} for zone, state_list in self.zones.items(): for state in state_list: self.state_to_zone[state] = zone # Local Government Areas (sample LGA names per state) self.lgas_by_state = { state: [f'{state}_LGA_{i+1}' for i in range(np.random.randint(5, 15))] for state in self.states } # Age groups self.age_groups = ['15-24', '25-34', '35-49', '50+'] self.age_group_ranges = { '15-24': (15, 24), '25-34': (25, 34), '35-49': (35, 49), '50+': (50, 80) } # Key population types self.kp_types = ['fsfw', 'msm', 'pid', 'tg', 'prisoners'] # ART regimens self.art_regimens = ['first_line', 'second_line', 'third_line'] # Facility levels self.facility_levels = ['primary', 'secondary', 'tertiary'] # Managing authorities self.managing_authorities = ['public', 'private', 'ngo', 'faith_based'] # Drug resistance mutations (common DRMs) self.common_drms = ['K103N', 'Y181C', 'M41L', 'M184V', 'T215Y', 'K101E', 'Y188L'] # DR categories self.dr_categories = ['none', 'low', 'intermediate', 'high'] # Treatment outcomes self.treatment_outcomes = ['suppressed', 'failed', 'defaulted', 'died', 'lost_to_followup'] # Education levels self.education_levels = ['none', 'primary', 'secondary', 'tertiary'] # Wealth quintiles self.wealth_quintiles = ['poorest', 'poorer', 'middle', 'richer', 'richest'] def generate_scenario(self, scenario_name, n_records): """Generate a dataset for a specific burden scenario.""" print(f"Generating {scenario_name} scenario with {n_records} records...") data = [] for i in range(n_records): # Generate record ID record_id = f'NGR-HIV-{scenario_name.upper()}-{i+1:06d}' # Generate geographic info state = np.random.choice(self.states) lga = np.random.choice(self.lgas_by_state[state]) zone = self.state_to_zone[state] # Generate time period (2018-2025) year = np.random.choice(range(2018, 2026)) quarter = np.random.choice([1, 2, 3, 4]) # Generate demographics age_group = np.random.choice(self.age_groups, p=[0.25, 0.35, 0.30, 0.10]) # Weighted toward younger ages age_min, age_max = self.age_group_ranges[age_group] age_years = np.random.randint(age_min, age_max + 1) sex = np.random.choice(['male', 'female'], p=[0.47, 0.53]) # Slightly more females # Pregnancy status (only for females 15-49) if sex == 'female' and 15 <= age_years <= 49: pregnancy_status = np.random.choice(['yes', 'no'], p=[0.08, 0.92]) # ~8% pregnancy rate else: pregnancy_status = 'not_applicable' # Key population status (based on NACA estimates) key_population = np.random.choice([True, False], p=[0.05, 0.95]) # ~5% KP prevalence if key_population: kp_type = np.random.choice(self.kp_types) else: kp_type = None # HIV status based on national prevalence (1.3%) # Adjust for key populations (higher prevalence) if key_population: # Higher HIV prevalence among key populations hiv_prob = 0.25 if kp_type == 'pid' else 0.20 # PWID have highest prevalence else: hiv_prob = 0.013 # General population prevalence hiv_status = 'positive' if np.random.random() < hiv_prob else 'negative' # Initialize HIV-specific variables date_of_diagnosis = None days_since_diagnosis = None ever_linked_to_care = None date_of_art_initiation = None months_on_art = None current_art_regimen = None art_adherence_pct = None missed_doses_last_month = None vl_test_done = None vl_result = None vl_suppressed = None vl_detectable = None vl_suppression_threshold = 1000 # Standard threshold dr_test_done = None dr_test_method = None num_drms_detected = None high_level_risk_drugs = None specific_drms = None dr_category = None transmitted_resistance_flag = None treatment_outcome = None # If HIV positive, generate treatment cascade if hiv_status == 'positive': # Date of diagnosis (within last 10 years) max_days_ago = 10 * 365 days_since_diagnosis = np.random.randint(0, max_days_ago) date_of_diagnosis = datetime.now() - timedelta(days=days_since_diagnosis) # Linkage to care (based on 98% of those who know status are on treatment) ever_linked_to_care = np.random.choice([True, False], p=[0.87, 0.13]) # 87% know status * 98% on treatment = ~85% linked if ever_linked_to_care: # ART initiation (some delay from diagnosis) init_delay_days = np.random.randint(0, min(365, days_since_diagnosis)) # Up to 1 year delay date_of_art_initiation = date_of_diagnosis + timedelta(days=init_delay_days) months_on_art = max(0, (datetime.now() - date_of_art_initiation).days // 30) # Current ART regimen (most on first-line) regimen_probs = [0.80, 0.15, 0.05] if months_on_art < 60 else [0.60, 0.30, 0.10] # Increase second/third line over time current_art_regimen = np.random.choice(self.art_regimens, p=regimen_probs) # ART adherence (based on viral suppression rates) if current_art_regimen == 'first_line': adherence_mean = 0.82 elif current_art_regimen == 'second_line': adherence_mean = 0.75 else: # third_line adherence_mean = 0.70 art_adherence_pct = np.clip(np.random.normal(adherence_mean, 0.15), 0, 1) missed_doses_last_month = np.random.poisson((1 - art_adherence_pct) * 30) # Based on non-adherence # Viral load testing (based on 95% suppression among those on treatment) vl_test_done = np.random.choice([True, False], p=[0.88, 0.12]) # 88% get VL tested if vl_test_done: # Viral load result (log-normal distribution) if np.random.random() < 0.95: # 95% suppressed among those tested and on treatment vl_result = np.random.lognormal(mean=3.0, sigma=0.5) # Mostly low copies vl_suppressed = True vl_detectable = np.random.choice([True, False], p=[0.10, 0.90]) # Some have low-level detectable else: vl_result = np.random.lognormal(mean=4.5, sigma=1.5) # Higher viral load vl_suppressed = False vl_detectable = True else: vl_result = None vl_suppressed = None vl_detectable = None # Drug resistance testing (done for those with detectable VL or treatment failure) dr_test_indication = (vl_test_done and vl_result and vl_result > 1000) or \ (not vl_suppressed and vl_test_done) or \ np.random.random() < 0.15 # 15% get resistance testing anyway dr_test_done = np.random.choice([True, False], p=[0.75 if dr_test_indication else 0.10, 0.25 if dr_test_indication else 0.90]) if dr_test_done: dr_test_method = 'genotyping' # DRM probability based on evidence base_drm_prob = 0.167 # Overall 16.7% from key populations study # Adjust for key populations if key_population: if kp_type == 'pid': # PWID base_drm_prob = 0.216 elif zone == 'North Central': base_drm_prob = 0.258 # Adjust for treatment duration and adherence if months_on_art > 60: # Longer treatment increases resistance risk base_drm_prob *= 1.5 if art_adherence_pct < 0.8: # Poor adherence increases resistance risk base_drm_prob *= 1.8 # Cap probability base_drm_prob = min(base_drm_prob, 0.60) has_drms = np.random.random() < base_drm_prob if has_drms: # Number of DRMs (1-4 typically) num_drms_detected = np.random.choice([1, 2, 3, 4], p=[0.5, 0.3, 0.15, 0.05]) # Select specific DRMs specific_drms_list = np.random.choice( self.common_drms, size=min(num_drms_detected, len(self.common_drms)), replace=False ).tolist() specific_drms = ','.join(specific_drms_list) # High-level risk drugs (based on DRMs present) high_level_drugs = [] drm_to_drugs = { 'K103N': ['efavirenz', 'nevirapine', 'etravirine'], 'Y181C': ['efavirenz', 'nevirapine', 'etravirine'], 'G190A': ['efavirenz', 'nevirapine'], 'M41L': ['zidovudine', 'stavudine'], 'M184V': ['lamivudine', 'emtricitabine'], 'T215Y': ['zidovudine', 'stavudine'] } for drm in specific_drms_list: if drm in drm_to_drugs: high_level_drugs.extend(drm_to_drugs[drm]) high_level_risk_drugs = ','.join(list(set(high_level_drugs))) if high_level_drugs else '' # Determine DR category if any(drm in ['K103N', 'Y181C', 'G190A'] for drm in specific_drms_list): dr_category = 'high' # High-level resistance to NNRTIs elif any(drm in ['M41L', 'M184V', 'T215Y'] for drm in specific_drms_list): dr_category = 'intermediate' # Intermediate resistance to NRTIs else: dr_category = 'low' # Transmitted resistance flag (more likely in recently diagnosed) transmitted_resistance_flag = np.random.random() < (0.3 if days_since_diagnosis < 365 else 0.1) else: num_drms_detected = 0 specific_drms = '' high_level_risk_drugs = '' dr_category = 'none' transmitted_resistance_flag = False else: num_drms_detected = None specific_drms = None high_level_risk_drugs = None dr_category = None transmitted_resistance_flag = None # Treatment outcome based on VL suppression and other factors if vl_suppressed == True: treatment_outcome = np.random.choice( ['suppressed', 'defaulted', 'lost_to_followup'], p=[0.85, 0.10, 0.05] ) else: treatment_outcome = np.random.choice( ['failed', 'defaulted', 'died', 'lost_to_followup'], p=[0.60, 0.25, 0.05, 0.10] ) else: # Not linked to care treatment_outcome = 'lost_to_followup' # Health system characteristics facility_level = np.random.choice( self.facility_levels, p=[0.50, 0.35, 0.15] # Mostly primary care ) managing_authority = np.random.choice( self.managing_authorities, p=[0.60, 0.20, 0.15, 0.05] # Mostly public ) urban_rural = np.random.choice(['urban', 'rural'], p=[0.45, 0.55]) # Stockouts (based on health system challenges) stockout_arv = np.random.choice([True, False], p=[0.12, 0.88]) # 12% ARV stockout rate stockout_rt_kits = np.random.choice([True, False], p=[0.18, 0.82]) # 18% RT kit stockout rate # Clinical indicators if hiv_status == 'positive' and ever_linked_to_care: # CD4 count (lower in untreated/advanced disease) if months_on_art == 0 or months_on_art is None: cd4_count = np.random.lognormal(mean=5.0, sigma=1.0) # Lower CD4 else: cd4_count = np.random.lognormal(mean=6.0, sigma=0.8) # Higher with treatment cd4_count_cells_ul = int(cd4_count) # WHO clinical stage stage_probs = [0.5, 0.3, 0.15, 0.05] if months_on_art > 12 else [0.3, 0.4, 0.2, 0.1] who_clinical_stage = np.random.choice([1, 2, 3, 4], p=stage_probs) else: cd4_count_cells_ul = None who_clinical_stage = None # Prevention services tb_screening_done = np.random.choice([True, False], p=[0.70, 0.30]) tb_preventive_therapy = np.random.choice([True, False], p=[0.25, 0.75]) if tb_screening_done else False cervical_cancer_screening = np.random.choice([True, False], p=[0.15, 0.85]) if sex == 'female' and age_years >= 30 else False mental_health_screening = np.random.choice([True, False], p=[0.30, 0.70]) # Socioeconomic factors household_wealth_quintile = np.random.choice(self.wealth_quintiles) education_level = np.random.choice(self.education_levels, p=[0.20, 0.35, 0.30, 0.15]) distance_to_facility_km = np.random.exponential(scale=5.0) # Most live close, some far distance_to_facility_km = min(distance_to_facility_km, 50) # Cap at 50km transport_cost_ngn = distance_to_facility_km * np.random.uniform(50, 200) # NGN per km stigma_experienced = np.random.choice([True, False], p=[0.35, 0.65]) disclosure_status = np.random.choice(['full', 'partial', 'none'], p=[0.40, 0.35, 0.25]) if hiv_status == 'positive' else 'not_applicable' partner_notification_done = np.random.choice([True, False], p=[0.50, 0.50]) if hiv_status == 'positive' and disclosure_status != 'none' else False condom_use_at_last_sex = np.random.choice([True, False], p=[0.60, 0.40]) if age_years >= 15 else False # Create person ID (anonymized) person_id = f'PID-{np.random.randint(1000000, 9999999)}' # Assemble record record = { 'record_id': record_id, 'state': state, 'lga': lga, 'year': year, 'quarter': quarter, 'zone': zone, 'person_id': person_id, 'age_years': age_years, 'age_group': age_group, 'sex': sex, 'pregnancy_status': pregnancy_status, 'key_population': key_population, 'kp_type': kp_type, 'hiv_status': hiv_status, 'date_of_diagnosis': date_of_diagnosis.strftime('%Y-%m-%d') if date_of_diagnosis else None, 'days_since_diagnosis': days_since_diagnosis, 'ever_linked_to_care': ever_linked_to_care, 'date_of_art_initiation': date_of_art_initiation.strftime('%Y-%m-%d') if date_of_art_initiation else None, 'months_on_art': months_on_art, 'current_art_regimen': current_art_regimen, 'art_adherence_pct': round(art_adherence_pct, 3) if art_adherence_pct is not None else None, 'missed_doses_last_month': missed_doses_last_month, 'vl_test_done': vl_test_done, 'vl_result': round(vl_result, 2) if vl_result is not None else None, 'vl_suppressed': vl_suppressed, 'vl_suppression_threshold': vl_suppression_threshold, 'vl_detectable': vl_detectable, 'dr_test_done': dr_test_done, 'dr_test_method': dr_test_method, 'num_drms_detected': num_drms_detected, 'high_level_risk_drugs': high_level_risk_drugs, 'specific_drms': specific_drms, 'dr_category': dr_category, 'transmitted_resistance_flag': transmitted_resistance_flag, 'treatment_outcome': treatment_outcome, 'facility_level': facility_level, 'managing_authority': managing_authority, 'urban_rural': urban_rural, 'stockout_arv': stockout_arv, 'stockout_rt_kits': stockout_rt_kits, 'cd4_count_cells_ul': cd4_count_cells_ul, 'who_clinical_stage': who_clinical_stage, 'tb_screening_done': tb_screening_done, 'tb_preventive_therapy': tb_preventive_therapy, 'cervical_cancer_screening': cervical_cancer_screening, 'mental_health_screening': mental_health_screening, 'household_wealth_quintile': household_wealth_quintile, 'education_level': education_level, 'distance_to_facility_km': round(distance_to_facility_km, 2), 'transport_cost_ngn': round(transport_cost_ngn, 2), 'stigma_experienced': stigma_experienced, 'disclosure_status': disclosure_status, 'partner_notification_done': partner_notification_done, 'condom_use_at_last_sex': condom_use_at_last_sex } data.append(record) return pd.DataFrame(data) def generate_all_scenarios(self): """Generate all three scenarios and save to CSV files.""" scenarios = { 'low_burden': 4000, 'moderate': 5000, 'high': 6000 } # Create output directory output_dir = '/Users/kossiso/CascadeProjects/malnutrition-dataset/nigeria-hiv-datasets/hiv-treatment-cascade-drug-resistance' os.makedirs(output_dir, exist_ok=True) for scenario_name, n_records in scenarios.items(): # Use different seeds for each scenario scenario_seed = 42 + list(scenarios.keys()).index(scenario_name) generator = NigeriaHIVDatasetGenerator(seed=scenario_seed) df = generator.generate_scenario(scenario_name, n_records) # Save to CSV output_path = os.path.join(output_dir, f'hiv_treatment_cascade_{scenario_name}.csv') df.to_csv(output_path, index=False) print(f"Saved {scenario_name} scenario to {output_path}") # Print summary statistics print(f"\n{scenario_name.upper()} SCENARIO SUMMARY:") print(f"Total records: {len(df)}") print(f"HIV positive: {df['hiv_status'].value_counts().get('positive', 0)} ({df['hiv_status'].value_counts().get('positive', 0)/len(df)*100:.1f}%)") if 'ever_linked_to_care' in df.columns: linked = df['ever_linked_to_care'].sum() print(f"Ever linked to care: {linked} ({linked/df['ever_linked_to_care'].notna().sum()*100:.1f}% of those with data)") if 'vl_suppressed' in df.columns: suppressed = df['vl_suppressed'].sum() print(f"Viral load suppressed: {suppressed} ({suppressed/df['vl_suppressed'].notna().sum()*100:.1f}% of those tested)") if 'dr_test_done' in df.columns: tested = df['dr_test_done'].sum() print(f"Drug resistance tests done: {tested} ({tested/len(df)*100:.1f}%)") if tested > 0: with_drms = df['num_drms_detected'].gt(0).sum() print(f"With DRMs detected: {with_drms} ({with_drms/tested*100:.1f}% of those tested)") if __name__ == "__main__": print("HIV Treatment Cascade and Drug Resistance Dataset Generator for Nigeria") print("=" * 70) generator = NigeriaHIVDatasetGenerator() generator.generate_all_scenarios() print("\nDataset generation complete!") print("Files saved to: /Users/kossiso/CascadeProjects/malnutrition-dataset/nigeria-hiv-datasets/hiv-treatment-cascade-drug-resistance/")