#!/usr/bin/env python3 """ Literature-Informed Synthetic Childhood Immunisation Coverage & Dropout Dataset =============================================================================== Generates realistic synthetic datasets of childhood immunisation records for children aged 0-23 months in LMIC settings, with vaccine-specific coverage, dropout indicators, and demographic/contextual variables. Target population: Children aged 0-23 months eligible for routine EPI vaccines in LMIC facility and community settings. DAG (Sampling Order): 1. sex (root) 2. age_months (root) 3. region_type (root: urban/rural) 4. ses_quintile (root: 1-5) 5. maternal_education (root) 6. distance_to_facility_km (conditional on region_type) 7. base_access_probability (conditional on ses, region, distance, education) 8. Individual vaccine doses (conditional on age, access probability, schedule) 9. Derived: fully_immunised, dropout indicators, zero-dose status References: ----------- [1] WHO/UNICEF (2023). WHO/UNICEF Estimates of National Immunization Coverage (WUENIC). Geneva/New York. [2] WHO (2023). Global Immunization Data. Immunization Dashboard. [3] Gavi (2023). Zero-dose children: Key data and analytics. [4] DHS Program. Demographic and Health Surveys, vaccination module, multiple countries 2015-2023. [5] Restrepo-Méndez MC, et al. (2016). Inequalities in full immunization coverage: trends in low- and middle-income countries. Bull WHO, 94:794-805. [6] WHO (2022). Immunization Agenda 2030. Geneva. [7] Arsenault C, et al. (2017). Equity in antenatal care quality: an analysis of 91 national household surveys. Lancet Global Health, 5(11):e1079-e1088. [8] WHO (2023). WHO recommendations for routine immunization - summary tables. """ import numpy as np import pandas as pd import argparse import os # ============================================================ # SECTION 1: Literature-Informed Parameters # ============================================================ # --- EPI Schedule (WHO Expanded Programme on Immunization) --- # Source: WHO (2023) Routine immunization summary tables # Format: vaccine -> {dose: eligible_age_weeks} EPI_SCHEDULE = { 'bcg': {1: 0}, # At birth 'opv': {0: 0, 1: 6, 2: 10, 3: 14}, # OPV0 at birth, then 6/10/14 weeks 'penta': {1: 6, 2: 10, 3: 14}, # DTP-HepB-Hib at 6/10/14 weeks 'pcv': {1: 6, 2: 10, 3: 14}, # Pneumococcal conjugate 'rota': {1: 6, 2: 10}, # Rotavirus (2-dose schedule) 'measles':{1: 39, 2: 65}, # MCV1 at 9 months, MCV2 at 15 months 'ipv': {1: 14}, # Inactivated polio at 14 weeks } # Convert weeks to months for age eligibility def weeks_to_months(w): return w / 4.33 # --- Coverage Levels by Scenario --- # Source: WUENIC 2023, DHS pooled estimates # These are BASE coverage probabilities for each antigen (dose 1 or single dose) SCENARIOS = { 'high_coverage': { 'description': 'Well-performing LMIC (e.g., Rwanda, Bangladesh urban)', 'bcg_coverage': 0.96, # WUENIC 2023: 85-99% 'penta1_coverage': 0.95, # WUENIC: 90-98% 'penta3_coverage': 0.88, # WUENIC: 82-95% 'mcv1_coverage': 0.90, # WUENIC: 85-95% 'mcv2_coverage': 0.78, # WUENIC: 60-85% 'zero_dose_rate': 0.03, # Gavi 2023: 2-5% in high-coverage 'dropout_penta13': 0.07, # 5-10% 'urban_pct': 0.45, }, 'moderate_coverage': { 'description': 'Average LMIC (e.g., Kenya, Ghana, Senegal)', 'bcg_coverage': 0.89, 'penta1_coverage': 0.87, 'penta3_coverage': 0.78, 'mcv1_coverage': 0.80, 'mcv2_coverage': 0.55, 'zero_dose_rate': 0.10, # Gavi 2023: 8-15% 'dropout_penta13': 0.12, 'urban_pct': 0.35, }, 'low_coverage': { 'description': 'Under-performing / conflict (e.g., CAR, South Sudan, Chad)', 'bcg_coverage': 0.68, 'penta1_coverage': 0.65, 'penta3_coverage': 0.48, 'mcv1_coverage': 0.52, 'mcv2_coverage': 0.28, 'zero_dose_rate': 0.25, # Gavi 2023: 20-35% in fragile states 'dropout_penta13': 0.25, 'urban_pct': 0.25, }, } # --- Equity Gradients --- # Source: Restrepo-Méndez 2016, DHS equity analyses # Coverage ratio: richest quintile / poorest quintile # Typical equity ratio: 1.2-2.5x depending on setting SES_COVERAGE_MULTIPLIER = { 1: 0.65, # Poorest quintile 2: 0.80, 3: 1.00, # Middle (reference) 4: 1.15, 5: 1.30, # Richest quintile } EDUCATION_COVERAGE_MULTIPLIER = { 'none': 0.70, 'primary': 0.85, 'secondary': 1.05, 'tertiary': 1.20, } REGION_COVERAGE_MULTIPLIER = { 'urban': 1.10, 'rural': 0.90, } # Maternal education distribution by SES (DHS patterns) EDUCATION_BY_SES = { 1: {'none': 0.50, 'primary': 0.35, 'secondary': 0.13, 'tertiary': 0.02}, 2: {'none': 0.30, 'primary': 0.40, 'secondary': 0.25, 'tertiary': 0.05}, 3: {'none': 0.15, 'primary': 0.35, 'secondary': 0.40, 'tertiary': 0.10}, 4: {'none': 0.08, 'primary': 0.25, 'secondary': 0.47, 'tertiary': 0.20}, 5: {'none': 0.03, 'primary': 0.12, 'secondary': 0.45, 'tertiary': 0.40}, } # ============================================================ # SECTION 2: Utility Functions # ============================================================ def compute_individual_access(ses, region, education, distance, scenario_base, rng): """Compute individual-level access probability from equity determinants.""" base = scenario_base ses_mult = SES_COVERAGE_MULTIPLIER[ses] edu_mult = EDUCATION_COVERAGE_MULTIPLIER[education] reg_mult = REGION_COVERAGE_MULTIPLIER[region] # Distance penalty: each km reduces probability slightly dist_penalty = max(0, 1.0 - distance * 0.012) # Individual random effect (unobserved factors) individual_effect = rng.normal(1.0, 0.08) p = base * ses_mult * edu_mult * reg_mult * dist_penalty * individual_effect return np.clip(p, 0.01, 0.99) def vaccine_received(age_months, eligible_age_months, access_prob, prev_dose_received, rng): """Determine if a vaccine dose was received given age, eligibility, access.""" if age_months < eligible_age_months: return 0 # Too young if not prev_dose_received: return 0 # Can't get dose 3 without dose 2 (sequential) # Timeliness decay: probability decreases if very late months_since_eligible = age_months - eligible_age_months timeliness_factor = 1.0 if months_since_eligible < 3 else 0.90 p = access_prob * timeliness_factor return 1 if rng.random() < p else 0 # ============================================================ # SECTION 3: Main Generator # ============================================================ def generate_immunisation_dataset(n=10000, seed=42, scenario='moderate_coverage'): rng = np.random.default_rng(seed) sc = SCENARIOS[scenario] # ── Step 1: Sex ── sex = rng.choice(['M', 'F'], size=n, p=[0.512, 0.488]) # ── Step 2: Age (months, 0-23) ── age_months = rng.uniform(0, 23.9, n) age_months = np.round(age_months, 1) # ── Step 3: Region type ── region_type = rng.choice(['urban', 'rural'], size=n, p=[sc['urban_pct'], 1 - sc['urban_pct']]) # ── Step 4: SES quintile ── ses_quintile = rng.choice([1, 2, 3, 4, 5], size=n, p=[0.20, 0.20, 0.20, 0.20, 0.20]) # ── Step 5: Maternal education (conditional on SES) ── maternal_education = np.empty(n, dtype=object) for i in range(n): dist = EDUCATION_BY_SES[ses_quintile[i]] maternal_education[i] = rng.choice( list(dist.keys()), p=list(dist.values())) # ── Step 6: Distance to facility ── distance_km = np.zeros(n) for i in range(n): if region_type[i] == 'urban': distance_km[i] = rng.exponential(2.0) # Mean 2km urban else: distance_km[i] = rng.exponential(8.0) # Mean 8km rural distance_km = np.clip(np.round(distance_km, 1), 0.1, 80.0) # ── Step 7: Individual access probability ── # Base coverage used as the "system" level factor base_cov = (sc['bcg_coverage'] + sc['penta1_coverage'] + sc['mcv1_coverage']) / 3.0 access_prob = np.zeros(n) for i in range(n): access_prob[i] = compute_individual_access( ses_quintile[i], region_type[i], maternal_education[i], distance_km[i], base_cov, rng) # ── Step 8: Vaccine doses ── # Zero-dose children: some children never enter the system is_zero_dose = rng.random(n) < (sc['zero_dose_rate'] / access_prob) is_zero_dose = is_zero_dose & (rng.random(n) < 0.5) # Soften to realistic rate # BCG (birth dose) bcg = np.zeros(n, dtype=int) for i in range(n): if is_zero_dose[i]: continue if age_months[i] >= 0: bcg[i] = 1 if rng.random() < access_prob[i] * 1.05 else 0 # OPV (0, 1, 2, 3) opv0 = np.zeros(n, dtype=int) opv1 = np.zeros(n, dtype=int) opv2 = np.zeros(n, dtype=int) opv3 = np.zeros(n, dtype=int) for i in range(n): if is_zero_dose[i]: continue opv0[i] = vaccine_received(age_months[i], 0, access_prob[i] * 0.95, True, rng) opv1[i] = vaccine_received(age_months[i], weeks_to_months(6), access_prob[i], bool(opv0[i]) or rng.random() < 0.3, rng) opv2[i] = vaccine_received(age_months[i], weeks_to_months(10), access_prob[i] * 0.97, bool(opv1[i]), rng) opv3[i] = vaccine_received(age_months[i], weeks_to_months(14), access_prob[i] * 0.94, bool(opv2[i]), rng) # Penta (1, 2, 3) penta1 = np.zeros(n, dtype=int) penta2 = np.zeros(n, dtype=int) penta3 = np.zeros(n, dtype=int) for i in range(n): if is_zero_dose[i]: continue penta1[i] = vaccine_received(age_months[i], weeks_to_months(6), access_prob[i], True, rng) penta2[i] = vaccine_received(age_months[i], weeks_to_months(10), access_prob[i] * 0.97, bool(penta1[i]), rng) penta3[i] = vaccine_received(age_months[i], weeks_to_months(14), access_prob[i] * 0.93, bool(penta2[i]), rng) # PCV (1, 2, 3) pcv1 = np.zeros(n, dtype=int) pcv2 = np.zeros(n, dtype=int) pcv3 = np.zeros(n, dtype=int) for i in range(n): if is_zero_dose[i]: continue pcv1[i] = vaccine_received(age_months[i], weeks_to_months(6), access_prob[i], True, rng) pcv2[i] = vaccine_received(age_months[i], weeks_to_months(10), access_prob[i] * 0.97, bool(pcv1[i]), rng) pcv3[i] = vaccine_received(age_months[i], weeks_to_months(14), access_prob[i] * 0.93, bool(pcv2[i]), rng) # Rotavirus (1, 2) rota1 = np.zeros(n, dtype=int) rota2 = np.zeros(n, dtype=int) for i in range(n): if is_zero_dose[i]: continue rota1[i] = vaccine_received(age_months[i], weeks_to_months(6), access_prob[i], True, rng) rota2[i] = vaccine_received(age_months[i], weeks_to_months(10), access_prob[i] * 0.96, bool(rota1[i]), rng) # IPV (1 dose at 14 weeks) ipv1 = np.zeros(n, dtype=int) for i in range(n): if is_zero_dose[i]: continue ipv1[i] = vaccine_received(age_months[i], weeks_to_months(14), access_prob[i], True, rng) # Measles (MCV1 at 9mo, MCV2 at 15mo) mcv1 = np.zeros(n, dtype=int) mcv2 = np.zeros(n, dtype=int) for i in range(n): if is_zero_dose[i]: continue mcv1[i] = vaccine_received(age_months[i], 9.0, access_prob[i] * 0.95, True, rng) mcv2[i] = vaccine_received(age_months[i], 15.0, access_prob[i] * 0.85, bool(mcv1[i]), rng) # ── Step 9: Derived indicators ── # Total doses received (out of basic schedule: BCG, Penta1-3, OPV1-3, MCV1 = 8) total_basic_doses = bcg + penta1 + penta2 + penta3 + opv1 + opv2 + opv3 + mcv1 # Fully immunised for age (all age-appropriate vaccines received) fully_immunised = np.zeros(n, dtype=int) for i in range(n): if age_months[i] < weeks_to_months(6): # Only BCG expected fully_immunised[i] = int(bcg[i] == 1) elif age_months[i] < weeks_to_months(14): # BCG + first round (Penta1, OPV1, PCV1, Rota1) fully_immunised[i] = int(bcg[i] and penta1[i] and opv1[i]) elif age_months[i] < 9: # All primary series fully_immunised[i] = int(bcg[i] and penta3[i] and opv3[i] and pcv3[i]) elif age_months[i] < 15: # Primary + MCV1 fully_immunised[i] = int(bcg[i] and penta3[i] and opv3[i] and mcv1[i]) else: # Full schedule including MCV2 fully_immunised[i] = int(bcg[i] and penta3[i] and opv3[i] and mcv1[i] and mcv2[i]) # Dropout: Penta1 to Penta3 dropout_penta13 = np.zeros(n, dtype=int) for i in range(n): if penta1[i] == 1 and penta3[i] == 0 and age_months[i] >= weeks_to_months(14): dropout_penta13[i] = 1 # Dropout: Penta1 to MCV1 dropout_penta1_mcv1 = np.zeros(n, dtype=int) for i in range(n): if penta1[i] == 1 and mcv1[i] == 0 and age_months[i] >= 9: dropout_penta1_mcv1[i] = 1 # Zero-dose: no vaccines at all despite being old enough for BCG zero_dose = ((bcg + opv0 + penta1 + pcv1 + rota1) == 0).astype(int) # Immunisation status category imm_status = np.where( zero_dose == 1, 'zero_dose', np.where(fully_immunised == 1, 'fully_immunised', 'partially_immunised')) # ── Assemble DataFrame ── df = pd.DataFrame({ 'id': np.arange(1, n + 1), 'sex': sex, 'age_months': age_months, 'region_type': region_type, 'ses_quintile': ses_quintile, 'maternal_education': maternal_education, 'distance_to_facility_km': distance_km, 'bcg': bcg, 'opv0': opv0, 'opv1': opv1, 'opv2': opv2, 'opv3': opv3, 'penta1': penta1, 'penta2': penta2, 'penta3': penta3, 'pcv1': pcv1, 'pcv2': pcv2, 'pcv3': pcv3, 'rota1': rota1, 'rota2': rota2, 'ipv1': ipv1, 'mcv1': mcv1, 'mcv2': mcv2, 'total_basic_doses': total_basic_doses, 'fully_immunised': fully_immunised, 'dropout_penta1_penta3': dropout_penta13, 'dropout_penta1_mcv1': dropout_penta1_mcv1, 'zero_dose': zero_dose, 'immunisation_status': imm_status, }) # ── Print summary ── # Filter to age-eligible for meaningful stats elig_penta = df[df['age_months'] >= weeks_to_months(14) + 1] elig_mcv1 = df[df['age_months'] >= 10] elig_mcv2 = df[df['age_months'] >= 16] print(f"\n{'='*60}") print(f"Childhood Immunisation — {scenario} (n={n}, seed={seed})") print(f"{'='*60}") print(f"\nCoverage (age-eligible children):") print(f" BCG: {df[df['age_months']>=1]['bcg'].mean()*100:.1f}%") if len(elig_penta) > 0: print(f" Penta1: {elig_penta['penta1'].mean()*100:.1f}%") print(f" Penta3: {elig_penta['penta3'].mean()*100:.1f}%") if len(elig_mcv1) > 0: print(f" MCV1: {elig_mcv1['mcv1'].mean()*100:.1f}%") if len(elig_mcv2) > 0: print(f" MCV2: {elig_mcv2['mcv2'].mean()*100:.1f}%") print(f"\nDropout (Penta1→Penta3): " f"{elig_penta['dropout_penta1_penta3'].mean()*100:.1f}%" if len(elig_penta) > 0 else "") print(f"Zero-dose (no vaccines, age≥1mo): " f"{df[df['age_months']>=1]['zero_dose'].mean()*100:.1f}%") print(f"Fully immunised for age: {df['fully_immunised'].mean()*100:.1f}%") # Equity: coverage by SES quintile if len(elig_penta) > 0: print(f"\nPenta3 by SES quintile:") for q in range(1, 6): sub = elig_penta[elig_penta['ses_quintile'] == q] if len(sub) > 0: print(f" Q{q}: {sub['penta3'].mean()*100:.1f}%") return df # ============================================================ # SECTION 4: CLI Entry Point # ============================================================ if __name__ == '__main__': parser = argparse.ArgumentParser( description='Generate synthetic childhood immunisation dataset') parser.add_argument('--scenario', type=str, default='moderate_coverage', 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_immunisation_dataset(n=args.n, seed=args.seed, scenario=sc_name) out = os.path.join('data', f'immunisation_{sc_name}.csv') df.to_csv(out, index=False) print(f" → Saved to {out}\n") else: df = generate_immunisation_dataset(n=args.n, seed=args.seed, scenario=args.scenario) out = args.output or os.path.join('data', f'immunisation_{args.scenario}.csv') df.to_csv(out, index=False) print(f" → Saved to {out}")