obstetric-fistula / generate_dataset.py
Kossisoroyce's picture
Upload folder using huggingface_hub
06881dd verified
Raw
History Blame Contribute Delete
11 kB
#!/usr/bin/env python3
"""
Literature-Informed Obstetric Fistula Dataset
==============================================
Generates realistic synthetic records of obstetric fistula patients
in sub-Saharan Africa, including risk factors, fistula characteristics,
social consequences, surgical repair, and outcomes.
References (web-searched):
-----------
[1] UNFPA 2024. Obstetric fistula caused by prolonged
obstructed labour without timely EmONC. SSA has 50%
of global burden. 50K-100K new cases/year.
[2] UNFPA WCARO 2024. West/Central Africa highest rates.
Social isolation, divorce, depression common.
[3] PMC 2024. Fistula repair failure in SSA. Repair
success 85-90% at specialized centres.
[4] PubMed 1999. Early marriage, young adolescents,
premature pregnancy → VVF. Sociomedical risk factors.
[5] PubMed 2018. Kitovu Hospital Uganda, highest fistula
rates globally. Incidence and causative factors.
[6] PubMed 2024. Systematic review repair outcomes.
Proportions of successful repair in LMICs.
"""
import numpy as np
import pandas as pd
import argparse
import os
SCENARIOS = {
'specialized_fistula_centre': {
'description': 'Dedicated fistula repair centre with '
'trained surgeon, physiotherapy, social '
'support (e.g., Addis Ababa Fistula Hospital, '
'Kitovu Uganda)',
'repair_available': True,
'specialist_surgeon': True,
'physiotherapy': True,
'social_support': True,
'repair_success': 0.90,
},
'district_hospital': {
'description': 'District hospital with visiting fistula '
'surgeon, basic repair capability, limited '
'follow-up (e.g., district hospitals DRC, '
'Malawi, Tanzania)',
'repair_available': True,
'specialist_surgeon': False,
'physiotherapy': False,
'social_support': False,
'repair_success': 0.70,
},
'no_surgical_access': {
'description': 'Rural community with no surgical access, '
'traditional remedies, referral barriers '
'(e.g., rural Niger, Chad, South Sudan)',
'repair_available': False,
'specialist_surgeon': False,
'physiotherapy': False,
'social_support': False,
'repair_success': 0.0,
},
}
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. Demographics ──
rec['age_at_presentation'] = max(14, min(65, int(rng.normal(28, 8))))
rec['age_at_fistula_onset'] = max(13, min(rec['age_at_presentation'],
int(rng.normal(20, 5))))
rec['years_living_with_fistula'] = max(0,
rec['age_at_presentation'] - rec['age_at_fistula_onset'])
rec['age_at_marriage'] = max(10, min(30, int(rng.normal(16, 3))))
rec['child_marriage'] = 1 if rec['age_at_marriage'] < 18 else 0
rec['age_at_first_pregnancy'] = max(rec['age_at_marriage'],
min(35, int(rng.normal(17, 3))))
rec['education'] = rng.choice(
['none', 'primary', 'secondary', 'tertiary'],
p=[0.45, 0.35, 0.15, 0.05])
rec['rural'] = 1 if rng.random() < 0.80 else 0
rec['parity'] = max(0, min(12, int(rng.exponential(2.5))))
rec['height_cm'] = max(140, min(180, int(rng.normal(157, 6))))
rec['short_stature'] = 1 if rec['height_cm'] < 150 else 0
rec['bmi'] = round(max(14, min(35, rng.normal(20, 3))), 1)
# ── 2. Obstetric history ──
rec['labour_duration_hours'] = max(6, min(120, int(rng.exponential(24) + 12)))
rec['prolonged_labour'] = 1 if rec['labour_duration_hours'] > 24 else 0
rec['obstructed_labour'] = 1 if rec['labour_duration_hours'] > 18 and rng.random() < 0.85 else 0
rec['caesarean_performed'] = 0
if rec['obstructed_labour']:
rec['caesarean_performed'] = 1 if rng.random() < 0.15 else 0
rec['skilled_birth_attendant'] = 1 if rng.random() < 0.20 else 0
rec['place_of_delivery'] = rng.choice(
['home', 'health_centre', 'hospital'],
p=[0.60, 0.25, 0.15])
rec['stillbirth'] = 1 if rng.random() < 0.70 else 0
rec['neonatal_death'] = 0
if not rec['stillbirth']:
rec['neonatal_death'] = 1 if rng.random() < 0.15 else 0
# ── 3. Fistula characteristics ──
rec['fistula_type'] = rng.choice(
['vesicovaginal', 'rectovaginal', 'combined'],
p=[0.80, 0.10, 0.10])
rec['fistula_size'] = rng.choice(
['small', 'medium', 'large', 'extensive'],
p=[0.20, 0.35, 0.30, 0.15])
rec['urethral_involvement'] = 1 if rng.random() < 0.25 else 0
rec['circumferential_defect'] = 1 if rec['fistula_size'] == 'extensive' and rng.random() < 0.40 else 0
rec['scarring_severity'] = rng.choice(
['mild', 'moderate', 'severe'],
p=[0.25, 0.40, 0.35])
rec['vaginal_stenosis'] = 1 if rec['scarring_severity'] == 'severe' and rng.random() < 0.40 else 0
rec['foot_drop'] = 1 if rec['prolonged_labour'] and rng.random() < 0.10 else 0
# ── 4. Social consequences [1][2] ──
rec['divorced_separated'] = 1 if rng.random() < 0.55 else 0
rec['social_isolation'] = 1 if rng.random() < 0.65 else 0
rec['depression'] = 1 if rng.random() < 0.60 else 0
rec['anxiety'] = 1 if rng.random() < 0.45 else 0
rec['economic_impact'] = rng.choice(
['none', 'mild', 'severe'],
p=[0.10, 0.30, 0.60])
rec['unable_to_work'] = 1 if rng.random() < 0.50 else 0
rec['skin_excoriation'] = 1 if rng.random() < 0.70 else 0
rec['recurrent_uti'] = 1 if rng.random() < 0.50 else 0
rec['malodour'] = 1 if rng.random() < 0.80 else 0
# ── 5. Care seeking ──
rec['delay_to_presentation_years'] = rec['years_living_with_fistula']
rec['previous_repair_attempts'] = max(0, min(5, int(rng.exponential(0.5))))
rec['traditional_remedy_tried'] = 1 if rng.random() < 0.35 else 0
rec['barrier_to_care'] = rng.choice(
['cost', 'distance', 'awareness', 'stigma', 'no_service', 'none'],
p=[0.20, 0.20, 0.15, 0.15, 0.20, 0.10])
rec['referred_by'] = rng.choice(
['self', 'ngo', 'health_worker', 'community', 'media'],
p=[0.30, 0.25, 0.20, 0.15, 0.10])
# ── 6. Surgical repair [3][6] ──
rec['repair_performed'] = 0
if sc['repair_available']:
rec['repair_performed'] = 1 if rng.random() < 0.85 else 0
rec['repair_technique'] = 'none'
if rec['repair_performed']:
rec['repair_technique'] = rng.choice(
['transvaginal', 'transabdominal', 'combined'],
p=[0.75, 0.15, 0.10])
rec['graft_used'] = 0
if rec['repair_performed'] and rec['fistula_size'] in ('large', 'extensive'):
rec['graft_used'] = 1 if rng.random() < 0.20 else 0
rec['catheter_days'] = 0
if rec['repair_performed']:
rec['catheter_days'] = max(7, min(28, int(rng.normal(14, 3))))
rec['repair_successful'] = 0
if rec['repair_performed']:
success_prob = sc['repair_success']
if rec['fistula_size'] == 'extensive':
success_prob *= 0.60
elif rec['fistula_size'] == 'large':
success_prob *= 0.80
if rec['previous_repair_attempts'] > 0:
success_prob *= 0.85
if rec['circumferential_defect']:
success_prob *= 0.50
rec['repair_successful'] = 1 if rng.random() < success_prob else 0
rec['residual_incontinence'] = 0
if rec['repair_successful']:
rec['residual_incontinence'] = 1 if rng.random() < 0.15 else 0
rec['complication_post_repair'] = 0
if rec['repair_performed']:
rec['complication_post_repair'] = 1 if rng.random() < 0.10 else 0
# ── 7. Rehabilitation ──
rec['physiotherapy_received'] = 0
if rec['repair_performed'] and sc['physiotherapy']:
rec['physiotherapy_received'] = 1 if rng.random() < 0.70 else 0
rec['social_reintegration_support'] = 0
if rec['repair_performed'] and sc['social_support']:
rec['social_reintegration_support'] = 1 if rng.random() < 0.60 else 0
rec['livelihood_support'] = 0
if rec['social_reintegration_support']:
rec['livelihood_support'] = 1 if rng.random() < 0.40 else 0
rec['continence_at_3_months'] = 0
if rec['repair_successful'] and not rec['residual_incontinence']:
rec['continence_at_3_months'] = 1 if rng.random() < 0.90 else 0
rec['returned_to_community'] = 0
if rec['repair_successful']:
rec['returned_to_community'] = 1 if rng.random() < 0.75 else 0
records.append(rec)
df = pd.DataFrame(records)
print(f"\n{'='*65}")
print(f"Obstetric Fistula — {scenario} (n={n}, seed={seed})")
print(f"{'='*65}")
print(f"\n Repair performed: {df['repair_performed'].mean()*100:.1f}%")
print(f" Repair success: {df[df['repair_performed']==1]['repair_successful'].mean()*100:.1f}%" if df['repair_performed'].sum() > 0 else " No repairs")
print(f" Stillbirth: {df['stillbirth'].mean()*100:.1f}%")
print(f" Divorced: {df['divorced_separated'].mean()*100:.1f}%")
print(f" Depression: {df['depression'].mean()*100:.1f}%")
print(f" Mean years with fistula: {df['years_living_with_fistula'].mean():.1f}")
return df
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Generate obstetric fistula 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'fistula_{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'fistula_{args.scenario}.csv')
df.to_csv(out, index=False)
print(f" -> Saved to {out}")