prostate-cancer / generate_dataset.py
Kossisoroyce's picture
Upload folder using huggingface_hub
f2bf984 verified
Raw
History Blame Contribute Delete
10.6 kB
#!/usr/bin/env python3
"""
Literature-Informed Prostate Cancer Dataset
=============================================
Generates realistic synthetic records of prostate cancer patients
in sub-Saharan Africa, including presentation, diagnosis, staging,
treatment access, and survival outcomes.
References (web-searched):
-----------
[1] PMC 2022. PCa screening/diagnosis/treatment in SSA.
Inconsistent PSA screening. Late presentation.
[2] PMC 2023. Public awareness PCa screening South Africa.
Black men disproportionately aggressive disease.
[3] BJUI 2024. Global viewpoints PCa in SSA. High
incidence and mortality. PSA not readily available.
[4] PMC 2021. PCa survival SSA by stage. Poor survival,
high proportions late stage.
[5] PubMed 2023. PCa management barriers in SSA.
Screening, diagnosis, curative Tx not available.
[6] PubMed 2018. Radiotherapy PCa Ghana. Emphasis on
curative treatment at tertiary centres.
[7] PubMed 2024. Radiotherapy access barriers SSA.
"""
import numpy as np
import pandas as pd
import argparse
import os
SCENARIOS = {
'tertiary_oncology': {
'description': 'Tertiary oncology centre with PSA, biopsy, '
'CT/MRI, radiotherapy, surgery, ADT '
'(e.g., Groote Schuur, LUTH, Kenyatta)',
'psa_available': True,
'biopsy_available': True,
'imaging_available': True,
'radiotherapy_available': True,
'surgery_available': True,
'early_stage_proportion': 0.35,
'five_year_survival': 0.55,
},
'district_hospital': {
'description': 'District hospital with PSA, DRE, limited '
'biopsy, no radiotherapy, ADT only '
'(e.g., district hospitals Uganda, Malawi)',
'psa_available': True,
'biopsy_available': False,
'imaging_available': False,
'radiotherapy_available': False,
'surgery_available': False,
'early_stage_proportion': 0.15,
'five_year_survival': 0.30,
},
'rural_health_centre': {
'description': 'Rural health centre, clinical diagnosis '
'only, no PSA, referral for all treatment '
'(e.g., rural DRC, Niger, CAR)',
'psa_available': False,
'biopsy_available': False,
'imaging_available': False,
'radiotherapy_available': False,
'surgery_available': False,
'early_stage_proportion': 0.05,
'five_year_survival': 0.15,
},
}
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'] = max(40, min(95, int(rng.normal(67, 9))))
rec['education'] = rng.choice(
['none', 'primary', 'secondary', 'tertiary'],
p=[0.25, 0.30, 0.30, 0.15])
rec['urban'] = 1 if rng.random() < 0.40 else 0
rec['family_history_pca'] = 1 if rng.random() < 0.10 else 0
rec['bmi'] = round(max(15, min(40, rng.normal(24, 4))), 1)
rec['hiv_positive'] = 1 if rng.random() < 0.06 else 0
rec['diabetes'] = 1 if rng.random() < 0.08 else 0
rec['hypertension'] = 1 if rng.random() < 0.30 else 0
# ── 2. Presentation ──
rec['presenting_symptom'] = rng.choice(
['luts', 'bone_pain', 'urinary_retention', 'haematuria',
'weight_loss', 'incidental', 'screening'],
p=[0.30, 0.20, 0.15, 0.10, 0.10, 0.05, 0.10])
rec['symptom_duration_months'] = max(1, min(36, int(rng.exponential(6) + 2)))
rec['traditional_medicine_first'] = 1 if rng.random() < 0.25 else 0
# ── 3. Diagnosis [1][3] ──
rec['dre_performed'] = 1 if rng.random() < 0.70 else 0
rec['dre_suspicious'] = 0
if rec['dre_performed']:
rec['dre_suspicious'] = 1 if rng.random() < 0.65 else 0
rec['psa_tested'] = 0
if sc['psa_available']:
rec['psa_tested'] = 1 if rng.random() < 0.80 else 0
rec['psa_level'] = 0.0
if rec['psa_tested']:
rec['psa_level'] = round(max(0.5, min(5000,
rng.lognormal(3.5, 1.5))), 1)
rec['psa_elevated'] = 1 if rec['psa_level'] > 4.0 else 0
rec['biopsy_performed'] = 0
if sc['biopsy_available'] and (rec['psa_elevated'] or rec['dre_suspicious']):
rec['biopsy_performed'] = 1 if rng.random() < 0.60 else 0
rec['gleason_score'] = 0
if rec['biopsy_performed']:
rec['gleason_score'] = rng.choice(
[6, 7, 8, 9, 10],
p=[0.15, 0.30, 0.25, 0.20, 0.10])
rec['gleason_group'] = 0
if rec['gleason_score'] == 6:
rec['gleason_group'] = 1
elif rec['gleason_score'] == 7:
rec['gleason_group'] = rng.choice([2, 3])
elif rec['gleason_score'] == 8:
rec['gleason_group'] = 4
elif rec['gleason_score'] >= 9:
rec['gleason_group'] = 5
# ── 4. Staging [4] ──
rec['stage'] = 'unknown'
if rng.random() < sc['early_stage_proportion']:
rec['stage'] = rng.choice(['I', 'II'], p=[0.30, 0.70])
else:
rec['stage'] = rng.choice(['III', 'IV'], p=[0.35, 0.65])
rec['metastatic'] = 1 if rec['stage'] == 'IV' else 0
rec['bone_metastases'] = 0
if rec['metastatic']:
rec['bone_metastases'] = 1 if rng.random() < 0.80 else 0
rec['lymph_node_metastases'] = 0
if rec['metastatic']:
rec['lymph_node_metastases'] = 1 if rng.random() < 0.40 else 0
rec['ct_scan_done'] = 0
if sc['imaging_available']:
rec['ct_scan_done'] = 1 if rng.random() < 0.50 else 0
rec['bone_scan_done'] = 0
if sc['imaging_available']:
rec['bone_scan_done'] = 1 if rng.random() < 0.30 else 0
# ── 5. Treatment [5][6][7] ──
rec['treatment_received'] = 'none'
if sc['surgery_available'] and rec['stage'] in ('I', 'II'):
rec['treatment_received'] = rng.choice(
['radical_prostatectomy', 'radiotherapy', 'adt', 'watchful_waiting'],
p=[0.25, 0.25, 0.30, 0.20])
elif sc['radiotherapy_available'] and rec['stage'] == 'III':
rec['treatment_received'] = rng.choice(
['radiotherapy_adt', 'adt_only', 'none'],
p=[0.40, 0.45, 0.15])
elif rec['stage'] == 'IV':
if sc['psa_available']:
rec['treatment_received'] = rng.choice(
['adt_only', 'adt_chemo', 'palliative', 'none'],
p=[0.45, 0.10, 0.25, 0.20])
else:
rec['treatment_received'] = rng.choice(
['adt_only', 'palliative', 'none'],
p=[0.30, 0.20, 0.50])
else:
if sc['psa_available']:
rec['treatment_received'] = rng.choice(
['adt_only', 'palliative', 'none'],
p=[0.40, 0.20, 0.40])
else:
rec['treatment_received'] = rng.choice(
['palliative', 'none'], p=[0.30, 0.70])
rec['adt_type'] = 'none'
if 'adt' in rec['treatment_received']:
rec['adt_type'] = rng.choice(
['surgical_castration', 'lhrh_agonist', 'antiandrogen'],
p=[0.40, 0.35, 0.25])
rec['pain_management'] = 0
if rec['bone_metastases'] or rec['treatment_received'] == 'palliative':
rec['pain_management'] = 1 if rng.random() < 0.50 else 0
rec['treatment_delay_months'] = max(0, min(24,
int(rng.exponential(3))))
rec['referral_needed'] = 0
if not sc['surgery_available'] and rec['stage'] in ('I', 'II', 'III'):
rec['referral_needed'] = 1 if rng.random() < 0.70 else 0
rec['referral_completed'] = 0
if rec['referral_needed']:
rec['referral_completed'] = 1 if rng.random() < 0.30 else 0
# ── 6. Outcome ──
base_mort = 1.0 - sc['five_year_survival']
if rec['stage'] == 'IV':
mort = base_mort * 1.3
elif rec['stage'] == 'III':
mort = base_mort * 0.8
else:
mort = base_mort * 0.3
if rec['treatment_received'] == 'none':
mort *= 1.5
if rec['age'] > 75:
mort *= 1.2
rec['died_within_2_years'] = 1 if rng.random() < min(mort, 0.80) else 0
rec['quality_of_life'] = rng.choice(
['good', 'moderate', 'poor'],
p=[0.20, 0.40, 0.40] if rec['metastatic'] else [0.40, 0.40, 0.20])
rec['castration_resistant'] = 0
if 'adt' in rec['treatment_received']:
rec['castration_resistant'] = 1 if rng.random() < 0.30 else 0
records.append(rec)
df = pd.DataFrame(records)
print(f"\n{'='*65}")
print(f"Prostate Cancer — {scenario} (n={n}, seed={seed})")
print(f"{'='*65}")
print(f"\n Stage IV: {(df['stage']=='IV').mean()*100:.1f}%")
print(f" PSA tested: {df['psa_tested'].mean()*100:.1f}%")
print(f" No treatment: {(df['treatment_received']=='none').mean()*100:.1f}%")
print(f" 2-yr mortality: {df['died_within_2_years'].mean()*100:.1f}%")
return df
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Generate prostate cancer 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'pca_{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'pca_{args.scenario}.csv')
df.to_csv(out, index=False)
print(f" -> Saved to {out}")