road-traffic-injury-trauma / generate_dataset.py
Kossisoroyce's picture
Upload folder using huggingface_hub
8b50a57 verified
Raw
History Blame Contribute Delete
15 kB
#!/usr/bin/env python3
"""
Literature-Informed Road Traffic Injury & Trauma Dataset
=========================================================
Generates realistic synthetic records of road traffic injury patients
presenting to emergency departments in sub-Saharan Africa, including
injury mechanism, severity, prehospital care, emergency management,
and outcomes.
Target population: Road traffic injury patients of all ages presenting
to health facilities across SSA.
DAG (Sampling Order):
1. demographics: age, sex, road_user_type
2. injury: mechanism, body_region, severity (GCS, ISS), fractures
3. prehospital: time_to_facility, transport, first_aid, referral
4. emergency_care: imaging, blood, surgery, ICU
5. complications: infection, VTE, organ_failure
6. outcome: survived/died, disability, LOS
References (web-searched):
-----------
[1] WHO Global Status Report on Road Safety (2023). 1.35M road
deaths/yr. Africa highest rate: 26.6/100K vs 17.4 global.
90% in LMICs. Pedestrians/cyclists >50% in Africa.
[2] Galvagno SM, et al. (2019). Prehospital trauma: <10% arrive
within golden hour in many SSA settings.
[3] Zafar SN, et al. (Lancet 2018). Trauma care Africa: mortality
30-40% for severe injuries (ISS>15). TBI leading cause of death.
[4] WHO (2024). Road traffic injuries fact sheet. Young adults
15-44y most affected. Males 3x female risk.
[5] Chalya PL, et al. (BMC Public Health 2012). Tanzania Bugando:
RTI mortality 11.2%. Pedestrians 41%, motorcyclists 28%.
Head injury 44%, extremity 38%.
[6] Hyder AA, et al. (Bull WHO 2017). Cost of RTI in LMICs:
1-3% of GDP. Disability burden enormous.
[7] Mwandri M, et al. (World J Emerg Surg 2020). Trauma in SSA:
GCS on admission strongest predictor of mortality.
[8] Mock C, et al. (Bull WHO 2012). Strengthening prehospital
trauma care could prevent 54% of trauma deaths.
"""
import numpy as np
import pandas as pd
import argparse
import os
SCENARIOS = {
'trauma_centre': {
'description': 'Urban trauma centre with CT, ICU, neurosurgery, '
'orthopaedics, blood bank (e.g., Muhimbili, '
'Chris Hani Baragwanath, Kenyatta)',
'ct_available': True,
'icu_available': True,
'neurosurgery_available': True,
'blood_bank': True,
'ambulance_rate': 0.40,
'golden_hour_rate': 0.25,
'mortality': 0.08,
},
'district_hospital': {
'description': 'District hospital with basic X-ray, limited '
'surgery, no ICU (e.g., district hospitals '
'Tanzania, Malawi, Uganda)',
'ct_available': False,
'icu_available': False,
'neurosurgery_available': False,
'blood_bank': False,
'ambulance_rate': 0.10,
'golden_hour_rate': 0.10,
'mortality': 0.18,
},
'rural_health_centre': {
'description': 'Rural health centre, no imaging, no surgery, '
'stabilise and refer (e.g., rural Nigeria, '
'DRC, South Sudan)',
'ct_available': False,
'icu_available': False,
'neurosurgery_available': False,
'blood_bank': False,
'ambulance_rate': 0.03,
'golden_hour_rate': 0.03,
'mortality': 0.32,
},
}
ROAD_USER_TYPES = {
'pedestrian': 0.38,
'motorcyclist': 0.22,
'motor_vehicle_occupant': 0.18,
'cyclist': 0.10,
'passenger_minibus': 0.08,
'other': 0.04,
}
def generate_dataset(n=10000, seed=42, scenario='district_hospital'):
rng = np.random.default_rng(seed)
sc = SCENARIOS[scenario]
users = list(ROAD_USER_TYPES.keys())
user_p = list(ROAD_USER_TYPES.values())
records = []
for idx in range(n):
rec = {'id': idx + 1}
# ── Step 1: Demographics [4][5] ──
r = rng.random()
if r < 0.08:
rec['age_years'] = rng.integers(0, 15)
elif r < 0.40:
rec['age_years'] = rng.integers(15, 30)
elif r < 0.65:
rec['age_years'] = rng.integers(30, 45)
elif r < 0.85:
rec['age_years'] = rng.integers(45, 60)
else:
rec['age_years'] = rng.integers(60, 80)
rec['sex'] = rng.choice(['M', 'F'], p=[0.75, 0.25])
rec['road_user_type'] = rng.choice(users, p=user_p)
if rec['age_years'] < 15:
rec['road_user_type'] = rng.choice(
['pedestrian', 'cyclist', 'passenger_minibus'],
p=[0.60, 0.20, 0.20])
rec['helmet_use'] = 0
if rec['road_user_type'] == 'motorcyclist':
rec['helmet_use'] = 1 if rng.random() < 0.25 else 0
rec['seatbelt_use'] = 0
if rec['road_user_type'] == 'motor_vehicle_occupant':
rec['seatbelt_use'] = 1 if rng.random() < 0.15 else 0
rec['alcohol_involved'] = 1 if rng.random() < 0.25 else 0
rec['time_of_day'] = rng.choice(
['morning_6_12', 'afternoon_12_18', 'evening_18_24', 'night_0_6'],
p=[0.20, 0.30, 0.30, 0.20])
rec['road_type'] = rng.choice(
['highway', 'urban_road', 'rural_road', 'intersection'],
p=[0.25, 0.30, 0.30, 0.15])
# ── Step 2: Injury [5] ──
rec['primary_body_region'] = rng.choice(
['head_neck', 'chest', 'abdomen', 'upper_extremity',
'lower_extremity', 'spine', 'pelvis', 'multiple'],
p=[0.28, 0.10, 0.08, 0.12, 0.20, 0.06, 0.04, 0.12])
if rec['road_user_type'] in ('pedestrian', 'cyclist'):
if rng.random() < 0.35:
rec['primary_body_region'] = 'head_neck'
rec['tbi'] = 1 if rec['primary_body_region'] == 'head_neck' else 0
if rec['primary_body_region'] == 'multiple' and rng.random() < 0.40:
rec['tbi'] = 1
# GCS
if rec['tbi']:
gcs_roll = rng.random()
if gcs_roll < 0.25:
rec['gcs'] = rng.integers(3, 9)
elif gcs_roll < 0.50:
rec['gcs'] = rng.integers(9, 13)
else:
rec['gcs'] = rng.integers(13, 16)
else:
rec['gcs'] = rng.choice([14, 15], p=[0.20, 0.80])
rec['gcs_category'] = 'mild'
if rec['gcs'] <= 8:
rec['gcs_category'] = 'severe'
elif rec['gcs'] <= 12:
rec['gcs_category'] = 'moderate'
# ISS
if rec['primary_body_region'] == 'multiple':
rec['iss'] = max(9, int(rng.normal(25, 10)))
elif rec['tbi'] and rec['gcs'] <= 8:
rec['iss'] = max(16, int(rng.normal(30, 10)))
elif rec['primary_body_region'] in ('chest', 'abdomen'):
rec['iss'] = max(4, int(rng.normal(16, 8)))
else:
rec['iss'] = max(1, int(rng.normal(10, 6)))
rec['iss'] = min(rec['iss'], 75)
rec['iss_category'] = 'minor'
if rec['iss'] >= 25:
rec['iss_category'] = 'critical'
elif rec['iss'] >= 16:
rec['iss_category'] = 'severe'
elif rec['iss'] >= 9:
rec['iss_category'] = 'moderate'
rec['fracture'] = 0
if rec['primary_body_region'] in ('upper_extremity', 'lower_extremity', 'pelvis'):
rec['fracture'] = 1 if rng.random() < 0.70 else 0
elif rec['primary_body_region'] == 'multiple':
rec['fracture'] = 1 if rng.random() < 0.50 else 0
else:
rec['fracture'] = 1 if rng.random() < 0.15 else 0
rec['open_fracture'] = 0
if rec['fracture']:
rec['open_fracture'] = 1 if rng.random() < 0.30 else 0
rec['internal_bleeding'] = 0
if rec['primary_body_region'] in ('abdomen', 'chest', 'pelvis', 'multiple'):
rec['internal_bleeding'] = 1 if rng.random() < 0.25 else 0
rec['spinal_cord_injury'] = 0
if rec['primary_body_region'] == 'spine':
rec['spinal_cord_injury'] = 1 if rng.random() < 0.35 else 0
# ── Step 3: Prehospital [2][8] ──
tp = np.array([sc['ambulance_rate'], 0.30, 0.10, 0.20, 0.05, 0.35 - sc['ambulance_rate']])
tp = np.maximum(tp, 0.01)
tp = tp / tp.sum()
rec['transport_mode'] = rng.choice(
['ambulance', 'private_vehicle', 'police', 'bystander',
'walked', 'motorcycle_taxi'], p=tp)
rec['time_to_facility_hours'] = max(0.25, round(rng.exponential(3), 1))
rec['time_to_facility_hours'] = min(rec['time_to_facility_hours'], 48)
rec['within_golden_hour'] = 1 if rec['time_to_facility_hours'] <= 1.0 else 0
rec['prehospital_first_aid'] = 1 if rng.random() < 0.20 else 0
rec['cervical_spine_immobilised'] = 0
if rec['transport_mode'] == 'ambulance':
rec['cervical_spine_immobilised'] = 1 if rng.random() < 0.50 else 0
rec['referred_from_other'] = 1 if rng.random() < 0.25 else 0
# ── Step 4: Emergency Care ──
rec['xray_done'] = 1 if rng.random() < 0.70 else 0
rec['ct_done'] = 0
if sc['ct_available'] and (rec['tbi'] or rec['iss'] >= 16):
rec['ct_done'] = 1 if rng.random() < 0.65 else 0
rec['ultrasound_fast'] = 0
if rec['internal_bleeding'] or rec['primary_body_region'] in ('abdomen', 'pelvis'):
rec['ultrasound_fast'] = 1 if rng.random() < 0.40 else 0
rec['blood_transfusion'] = 0
if rec['internal_bleeding'] or rec['iss'] >= 25:
if sc['blood_bank']:
rec['blood_transfusion'] = 1 if rng.random() < 0.45 else 0
else:
rec['blood_transfusion'] = 1 if rng.random() < 0.10 else 0
rec['surgery_performed'] = 0
rec['surgery_type'] = 'none'
if rec['internal_bleeding'] and rng.random() < 0.50:
rec['surgery_performed'] = 1
rec['surgery_type'] = 'laparotomy'
elif rec['tbi'] and rec['gcs'] <= 8 and sc['neurosurgery_available']:
rec['surgery_performed'] = 1 if rng.random() < 0.30 else 0
if rec['surgery_performed']:
rec['surgery_type'] = 'craniotomy'
elif rec['fracture']:
rec['surgery_performed'] = 1 if rng.random() < 0.35 else 0
if rec['surgery_performed']:
rec['surgery_type'] = rng.choice(
['orif', 'external_fixation', 'amputation'],
p=[0.50, 0.35, 0.15])
rec['icu_admission'] = 0
if sc['icu_available'] and (rec['gcs'] <= 8 or rec['iss'] >= 25):
rec['icu_admission'] = 1 if rng.random() < 0.40 else 0
rec['intubated'] = 0
if rec['gcs'] <= 8:
rec['intubated'] = 1 if rng.random() < (0.60 if sc['icu_available'] else 0.10) else 0
rec['tetanus_given'] = 1 if rng.random() < 0.65 else 0
rec['antibiotics_given'] = 1 if (rec['open_fracture'] or rec['surgery_performed']) else 0
# ── Step 5: Complications ──
rec['wound_infection'] = 0
if rec['open_fracture'] or rec['surgery_performed']:
rec['wound_infection'] = 1 if rng.random() < 0.15 else 0
rec['sepsis'] = 0
if rec['wound_infection'] or (rec['icu_admission'] and rng.random() < 0.10):
rec['sepsis'] = 1 if rng.random() < 0.25 else 0
rec['vte'] = 0
if rec['fracture'] and rec['primary_body_region'] in ('lower_extremity', 'pelvis'):
rec['vte'] = 1 if rng.random() < 0.05 else 0
# ── Step 6: Outcome [3][7] ──
mort = sc['mortality']
if rec['gcs'] <= 8:
mort *= 4.0
elif rec['gcs'] <= 12:
mort *= 2.0
if rec['iss'] >= 25:
mort *= 2.5
if rec['internal_bleeding'] and not rec['blood_transfusion']:
mort *= 2.0
if not rec['within_golden_hour'] and rec['iss'] >= 16:
mort *= 1.5
if rec['age_years'] > 60:
mort *= 1.5
if rec['age_years'] < 5:
mort *= 1.3
if rec['surgery_performed'] and rec['internal_bleeding']:
mort *= 0.50
if rec['icu_admission']:
mort *= 0.70
rec['outcome'] = 'died' if rng.random() < min(mort, 0.80) else 'survived'
if rec['outcome'] == 'died':
rec['length_of_stay_days'] = max(0, rng.integers(0, 7))
elif rec['iss'] >= 16:
rec['length_of_stay_days'] = max(3, int(rng.normal(18, 10)))
else:
rec['length_of_stay_days'] = max(1, int(rng.normal(5, 3)))
rec['disability_at_discharge'] = 'none'
if rec['outcome'] == 'survived':
if rec['spinal_cord_injury']:
rec['disability_at_discharge'] = 'paralysis'
elif rec['surgery_type'] == 'amputation':
rec['disability_at_discharge'] = 'amputation'
elif rec['tbi'] and rec['gcs'] <= 12:
rec['disability_at_discharge'] = 'cognitive_impairment'
elif rec['fracture']:
rec['disability_at_discharge'] = 'mobility_limitation'
records.append(rec)
df = pd.DataFrame(records)
print(f"\n{'='*65}")
print(f"Road Traffic Injury — {scenario} (n={n}, seed={seed})")
print(f"{'='*65}")
print(f"\n Male: {(df['sex']=='M').mean()*100:.1f}%")
print(f" Pedestrians: {(df['road_user_type']=='pedestrian').mean()*100:.1f}%")
print(f" TBI: {df['tbi'].mean()*100:.1f}%")
print(f" Severe (ISS≥16): {(df['iss']>=16).mean()*100:.1f}%")
print(f" Within golden hour: {df['within_golden_hour'].mean()*100:.1f}%")
print(f" Ambulance: {(df['transport_mode']=='ambulance').mean()*100:.1f}%")
died = (df['outcome'] == 'died').sum()
print(f" Mortality: {died} ({died/n*100:.1f}%)")
return df
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Generate synthetic road traffic injury 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'rti_{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'rti_{args.scenario}.csv')
df.to_csv(out, index=False)
print(f" → Saved to {out}")