medical-oxygen-supply / generate_dataset.py
Kossisoroyce's picture
Upload folder using huggingface_hub
d76d275 verified
Raw
History Blame Contribute Delete
15.2 kB
#!/usr/bin/env python3
"""
Literature-Informed Medical Oxygen Supply Dataset
====================================================
Generates realistic synthetic facility-level observations of medical
oxygen availability, delivery systems, equipment status, and patient
outcomes across three tiers of healthcare in sub-Saharan Africa.
Each record represents ONE facility observation for ONE monthly period.
Epidemiological Parameterization (web-searched):
-------------------------------------------------
[1] Oxygen Hub / ITT (2021). Closing the medical oxygen gap in SSA.
Most SSA countries have <10% of volume needed. PSA vs LOX
trade-offs. Decentralized hub-and-spoke model proposed.
[2] PMC (2022). Oxygen inequity in COVID-19 pandemic and beyond.
Ghana, Senegal SPRINT pilot. UNICEF workgroups. PMC9972372.
[3] PMC (2022). Comprehensive approach to medical oxygen ecosystem.
165 PSA plants needing repair globally; 151 in SSA. PMC9771461.
[4] PMC (2021). Oxygen delivery systems for adults in SSA. Scoping
review. Hypoxemia prevalence 11-89%. High mortality among
hypoxemic patients. PMC8109278.
[5] BMC Health Services Research (2025). Design and maintenance of
oxygen concentrators in SSA. WHO distributed >30,000 OCs.
Maintenance challenges documented. doi:10.1186/s12913-025-12315-6
[6] PMC (2024). Functional availability of medical oxygen for
pneumonia management. ~50% of facilities in resource-limited
settings had no or inconsistent oxygen. PMC11082622.
[7] WHO (2023). Essential medicines list — medical oxygen included.
Pulse oximetry essential for identifying hypoxemia.
"""
import numpy as np
import pandas as pd
import argparse
import os
OXYGEN_SOURCES = [
'PSA_plant_onsite', 'LOX_bulk_tank', 'oxygen_concentrator',
'cylinder_piped', 'cylinder_portable', 'none'
]
PATIENT_CONDITIONS = [
'pneumonia_child', 'pneumonia_adult', 'neonatal_respiratory',
'COPD_exacerbation', 'COVID19_severe', 'severe_malaria',
'heart_failure', 'surgical_anaesthesia', 'trauma',
'asthma_severe', 'sepsis', 'other_hypoxemia'
]
SHORTAGE_CAUSES = [
'cylinder_delivery_delay', 'PSA_plant_breakdown', 'concentrator_malfunction',
'power_outage', 'empty_cylinders_not_collected', 'funding_for_refill',
'no_oxygen_source', 'demand_surge', 'supplier_stockout',
'piping_system_leak', 'regulator_valve_failure',
]
SCENARIOS = {
'referral_hospital': {
'description': (
'Urban referral/teaching hospital with PSA plant or LOX '
'bulk tank, piped oxygen system, pulse oximetry, ICU, '
'biomedical technician. Analogous to Muhimbili (TZ), '
'Kenyatta (KE), Mulago (UG).'
),
'facility_level': 'referral_hospital',
'has_piped_system': True,
'has_icu': True,
'has_pulse_oximeter': True,
'has_biomedical_tech': True,
'oxygen_source_probs': [0.25, 0.30, 0.20, 0.20, 0.05, 0.00],
'oxygen_available_rate': 0.82,
'sufficient_quantity_rate': 0.65,
'concentrator_functional_rate': 0.70,
'pulse_ox_functional_rate': 0.85,
'cylinder_refill_days': 5,
'mortality_hypoxic_untreated': 0.35,
},
'district_hospital': {
'description': (
'District hospital with oxygen concentrators and/or '
'cylinders, limited pulse oximetry, no ICU, clinical '
'officer manages oxygen. Analogous to district hospitals '
'in Malawi, Rwanda, Mozambique.'
),
'facility_level': 'district_hospital',
'has_piped_system': False,
'has_icu': False,
'has_pulse_oximeter': False,
'has_biomedical_tech': False,
'oxygen_source_probs': [0.02, 0.05, 0.35, 0.15, 0.30, 0.13],
'oxygen_available_rate': 0.50,
'sufficient_quantity_rate': 0.35,
'concentrator_functional_rate': 0.45,
'pulse_ox_functional_rate': 0.40,
'cylinder_refill_days': 21,
'mortality_hypoxic_untreated': 0.45,
},
'rural_health_centre': {
'description': (
'Rural health centre with no permanent oxygen source, '
'occasional cylinder if available, no pulse oximetry, '
'nurse-managed. Analogous to health centres in Niger, '
'DRC, South Sudan, rural Ethiopia.'
),
'facility_level': 'rural_health_centre',
'has_piped_system': False,
'has_icu': False,
'has_pulse_oximeter': False,
'has_biomedical_tech': False,
'oxygen_source_probs': [0.00, 0.00, 0.08, 0.02, 0.20, 0.70],
'oxygen_available_rate': 0.12,
'sufficient_quantity_rate': 0.08,
'concentrator_functional_rate': 0.15,
'pulse_ox_functional_rate': 0.08,
'cylinder_refill_days': 45,
'mortality_hypoxic_untreated': 0.55,
},
}
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. Facility characteristics ──
rec['facility_level'] = sc['facility_level']
rec['facility_id'] = f"O2_{rng.integers(1, 200):04d}"
rec['region_type'] = rng.choice(
['urban', 'peri_urban', 'rural'],
p=[0.10, 0.15, 0.75] if scenario == 'rural_health_centre'
else ([0.55, 0.25, 0.20] if scenario == 'referral_hospital'
else [0.20, 0.35, 0.45]))
rec['bed_count'] = max(5, int(rng.normal(
250 if scenario == 'referral_hospital' else
(60 if scenario == 'district_hospital' else 12), 40)))
rec['has_icu'] = 1 if sc['has_icu'] else (1 if rng.random() < 0.02 else 0)
rec['has_nicu'] = 1 if sc['has_icu'] else (1 if rng.random() < 0.05 else 0)
rec['has_piped_oxygen'] = 1 if sc['has_piped_system'] else (
1 if rng.random() < 0.05 else 0)
rec['has_biomedical_technician'] = 1 if sc['has_biomedical_tech'] else (
1 if rng.random() < 0.05 else 0)
# ── 2. Oxygen source & equipment [1][3][5] ──
rec['primary_oxygen_source'] = rng.choice(
OXYGEN_SOURCES, p=sc['oxygen_source_probs'])
rec['concentrator_count'] = 0
if rec['primary_oxygen_source'] == 'oxygen_concentrator' or rng.random() < 0.20:
rec['concentrator_count'] = max(0, int(rng.poisson(
5 if scenario == 'referral_hospital' else
(2 if scenario == 'district_hospital' else 0.3))))
rec['concentrator_functional'] = 0
if rec['concentrator_count'] > 0:
func_rate = sc['concentrator_functional_rate']
rec['concentrator_functional'] = max(0, min(
rec['concentrator_count'],
int(rec['concentrator_count'] * rng.normal(func_rate, 0.2))))
rec['concentrator_mean_age_years'] = max(0, round(rng.exponential(
3 if scenario == 'referral_hospital' else
(5 if scenario == 'district_hospital' else 8)), 1))
rec['concentrator_maintenance_available'] = 1 if rec['has_biomedical_technician'] else (
1 if rng.random() < 0.10 else 0)
rec['cylinder_count_full'] = max(0, int(rng.poisson(
10 if scenario == 'referral_hospital' else
(3 if scenario == 'district_hospital' else 0.5))))
rec['cylinder_count_empty'] = max(0, int(rng.poisson(
5 if scenario == 'referral_hospital' else
(4 if scenario == 'district_hospital' else 1))))
rec['days_since_cylinder_refill'] = max(0, int(rng.exponential(
sc['cylinder_refill_days'])))
rec['PSA_plant_functional'] = 0
if rec['primary_oxygen_source'] == 'PSA_plant_onsite':
rec['PSA_plant_functional'] = 1 if rng.random() < 0.55 else 0
# ── 3. Pulse oximetry [4][6][7] ──
rec['pulse_oximeter_available'] = 1 if sc['has_pulse_oximeter'] else (
1 if rng.random() < (0.35 if scenario == 'district_hospital' else 0.05) else 0)
rec['pulse_oximeter_functional'] = 0
if rec['pulse_oximeter_available']:
rec['pulse_oximeter_functional'] = 1 if rng.random() < sc['pulse_ox_functional_rate'] else 0
rec['SpO2_screening_routine'] = 0
if rec['pulse_oximeter_functional']:
rec['SpO2_screening_routine'] = 1 if rng.random() < (
0.70 if scenario == 'referral_hospital' else
(0.30 if scenario == 'district_hospital' else 0.05)) else 0
# ── 4. Oxygen availability [1][6] ──
rec['oxygen_available_today'] = 1 if rng.random() < sc['oxygen_available_rate'] else 0
rec['oxygen_sufficient_for_demand'] = 0
if rec['oxygen_available_today']:
rec['oxygen_sufficient_for_demand'] = 1 if rng.random() < sc['sufficient_quantity_rate'] / sc['oxygen_available_rate'] else 0
rec['oxygen_stockout_days_last_month'] = 0
if not rec['oxygen_available_today']:
rec['oxygen_stockout_days_last_month'] = max(1, min(30,
int(rng.exponential(12))))
elif rng.random() < 0.20:
rec['oxygen_stockout_days_last_month'] = max(1, min(15,
int(rng.exponential(5))))
rec['shortage_cause'] = 'not_applicable'
if not rec['oxygen_available_today'] or rec['oxygen_stockout_days_last_month'] > 0:
if scenario == 'rural_health_centre':
cause_p = [0.15, 0.02, 0.05, 0.12, 0.05, 0.10, 0.35, 0.08, 0.05, 0.01, 0.02]
elif scenario == 'district_hospital':
cause_p = [0.25, 0.05, 0.18, 0.15, 0.08, 0.08, 0.05, 0.06, 0.04, 0.03, 0.03]
else:
cause_p = [0.10, 0.20, 0.15, 0.15, 0.05, 0.05, 0.02, 0.15, 0.05, 0.05, 0.03]
rec['shortage_cause'] = rng.choice(SHORTAGE_CAUSES, p=cause_p)
# ── 5. Reporting period ──
rec['year'] = rng.choice([2021, 2022, 2023, 2024],
p=[0.15, 0.25, 0.30, 0.30])
rec['month'] = rng.integers(1, 13)
# ── 6. Patient demand & utilisation ──
rec['patients_needing_oxygen'] = max(0, int(rng.poisson(
40 if scenario == 'referral_hospital' else
(12 if scenario == 'district_hospital' else 3))))
rec['primary_condition'] = rng.choice(PATIENT_CONDITIONS,
p=[0.15, 0.12, 0.12, 0.08, 0.10, 0.08, 0.06, 0.08, 0.06, 0.05, 0.05, 0.05])
rec['patients_received_oxygen'] = 0
if rec['oxygen_available_today'] and rec['patients_needing_oxygen'] > 0:
coverage = rng.normal(
0.80 if scenario == 'referral_hospital' else
(0.45 if scenario == 'district_hospital' else 0.10), 0.15)
rec['patients_received_oxygen'] = max(0, min(
rec['patients_needing_oxygen'],
int(rec['patients_needing_oxygen'] * np.clip(coverage, 0, 1))))
rec['patients_untreated_hypoxemia'] = max(0,
rec['patients_needing_oxygen'] - rec['patients_received_oxygen'])
rec['flow_rate_adequate'] = 0
if rec['patients_received_oxygen'] > 0:
rec['flow_rate_adequate'] = 1 if rng.random() < (
0.75 if scenario == 'referral_hospital' else
(0.40 if scenario == 'district_hospital' else 0.15)) else 0
# ── 7. Outcomes ──
rec['deaths_hypoxemia_related'] = 0
if rec['patients_untreated_hypoxemia'] > 0:
mort_rate = sc['mortality_hypoxic_untreated']
rec['deaths_hypoxemia_related'] = max(0,
int(rng.binomial(rec['patients_untreated_hypoxemia'], mort_rate)))
rec['referred_for_oxygen'] = 0
if not rec['oxygen_available_today'] and rec['patients_needing_oxygen'] > 0:
rec['referred_for_oxygen'] = max(0, int(
rec['patients_needing_oxygen'] * rng.normal(0.30, 0.15)))
# ── 8. Cost & logistics ──
rec['monthly_oxygen_cost_usd'] = max(0, round(rng.normal(
800 if scenario == 'referral_hospital' else
(200 if scenario == 'district_hospital' else 30),
150 if scenario == 'referral_hospital' else
(80 if scenario == 'district_hospital' else 20)), 0))
rec['distance_to_refill_km'] = max(0, round(rng.exponential(
15 if scenario == 'referral_hospital' else
(50 if scenario == 'district_hospital' else 120)), 0))
rec['transport_available_for_cylinders'] = 1 if rng.random() < (
0.85 if scenario == 'referral_hospital' else
(0.40 if scenario == 'district_hospital' else 0.10)) else 0
# ── 9. Power supply (critical for concentrators/PSA) ──
rec['power_source'] = rng.choice(
['grid_reliable', 'grid_unreliable', 'generator_only', 'solar', 'none'],
p=[0.40, 0.30, 0.15, 0.10, 0.05] if scenario == 'referral_hospital'
else ([0.10, 0.35, 0.15, 0.15, 0.25] if scenario == 'district_hospital'
else [0.02, 0.10, 0.05, 0.08, 0.75]))
rec['power_outage_hours_last_week'] = max(0, int(rng.exponential(
5 if scenario == 'referral_hospital' else
(15 if scenario == 'district_hospital' else 60))))
records.append(rec)
df = pd.DataFrame(records)
print(f"\n{'='*65}")
print(f"Medical Oxygen Supply — {scenario} (n={n}, seed={seed})")
print(f"{'='*65}")
print(f"\n Oxygen available today: {df['oxygen_available_today'].mean()*100:.1f}%")
print(f" Sufficient for demand: {df['oxygen_sufficient_for_demand'].mean()*100:.1f}%")
print(f" Pulse oximeter functional: {df['pulse_oximeter_functional'].mean()*100:.1f}%")
print(f" Patients needing O2 (mean): {df['patients_needing_oxygen'].mean():.1f}")
print(f" Patients received O2 (mean): {df['patients_received_oxygen'].mean():.1f}")
print(f" Deaths hypoxemia (mean): {df['deaths_hypoxemia_related'].mean():.2f}")
return df
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Generate medical oxygen supply 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'oxygen_{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'oxygen_{args.scenario}.csv')
df.to_csv(out, index=False)
print(f" -> Saved to {out}")