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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#!/usr/bin/env python3
"""
Literature-Informed Synthetic Snakebite Envenomation Dataset Generator
======================================================================

Generates realistic synthetic records of snakebite envenomation cases
presenting to health facilities in sub-Saharan Africa, including snake
species, envenomation syndrome, severity grading, clinical features,
antivenom treatment, complications, and outcomes.

Target population: Snakebite victims aged 1-80 years presenting to
health facilities across SSA.

DAG (Sampling Order):
  1. age, sex, occupation, location (roots)
  2. snake_species (conditional on region/habitat)
  3. envenomation_syndrome: cytotoxic / hemotoxic / neurotoxic / dry bite
  4. severity: mild / moderate / severe
  5. clinical_features: swelling, coagulopathy, neurotoxicity, necrosis
  6. treatment: antivenom, wound care, fasciotomy
  7. complications: compartment syndrome, AKI, necrosis, amputation
  8. outcome: survived / died / disability

References:
-----------
[1]  Chippaux JP (Toxicon 2011). SSA: ~315,000 envenomations/yr,
     ~32,000 deaths, ~7,000 amputations. Case fatality 6-10%.
[2]  WHO (2019). Snakebite envenoming strategy. NTD category A since
     2017. Target: halve deaths/disability by 2030.
[3]  Habib AG, et al. (PLoS NTD 2015). Echis ocellatus envenoming in
     Nigeria: coagulopathy in 70-80%, local swelling 90%+.
     EchiTab antivenom efficacy.
[4]  Warrell DA (Lancet 2010). Snake bite. Clinical features by species:
     Bitis arietans: massive local swelling, necrosis, coagulopathy.
     Naja: necrosis, neurotoxicity. Dendroaspis: rapid neurotoxicity.
     Echis: coagulopathy, haemorrhage, renal failure.
[5]  Harrison RA, et al. (PLoS NTD 2009). Snakebite: disease of poverty.
     Agricultural workers, children at highest risk.
[6]  Kasturiratne A, et al. (PLoS Med 2008). Global burden: 1.2-5.5M
     bites/yr, 421,000-1.8M envenomations, 20,000-94,000 deaths.
[7]  Gutierrez JM, et al. (Nat Rev Dis Primers 2017). Snakebite
     envenoming comprehensive review. Antivenom sole specific treatment.
[8]  Schioldann E, et al. (PLoS NTD 2018). Antivenom availability in
     SSA: <2% of need met. Mean time to treatment 6-24 hours.
"""

import numpy as np
import pandas as pd
import argparse
import os

# ============================================================
# SECTION 1: Literature-Informed Parameters
# ============================================================

SCENARIOS = {
    'referral_hospital': {
        'description': 'Tertiary/referral hospital with antivenom stock, '
                       'surgical capacity (e.g., Kaltungo Nigeria, Kilifi Kenya)',
        # Snake species distribution [1][3][4]
        'species_probs': {
            'echis_ocellatus': 0.30,     # Carpet viper
            'bitis_arietans': 0.25,      # Puff adder
            'naja_nigricollis': 0.15,    # Black-necked spitting cobra
            'naja_haje': 0.08,           # Egyptian cobra
            'dendroaspis_polylepis': 0.05, # Black mamba
            'dendroaspis_viridis': 0.03, # Green mamba
            'causus_rhombeatus': 0.04,   # Night adder
            'atractaspis_spp': 0.03,     # Burrowing asp
            'unknown_unidentified': 0.07,
        },
        'dry_bite_rate': 0.20,           # No envenomation
        'antivenom_available': 0.70,
        'antivenom_given_if_needed': 0.80,
        'surgical_capacity': 0.90,
        'time_to_facility_hrs_mean': 4,
        'case_fatality': 0.04,
    },
    'district_hospital': {
        'description': 'District hospital, intermittent antivenom supply, '
                       'basic surgical (e.g., district hospitals Ghana, Tanzania)',
        'species_probs': {
            'echis_ocellatus': 0.28,
            'bitis_arietans': 0.28,
            'naja_nigricollis': 0.14,
            'naja_haje': 0.06,
            'dendroaspis_polylepis': 0.04,
            'dendroaspis_viridis': 0.02,
            'causus_rhombeatus': 0.06,
            'atractaspis_spp': 0.03,
            'unknown_unidentified': 0.09,
        },
        'dry_bite_rate': 0.20,
        'antivenom_available': 0.35,
        'antivenom_given_if_needed': 0.60,
        'surgical_capacity': 0.50,
        'time_to_facility_hrs_mean': 8,
        'case_fatality': 0.08,
    },
    'rural_health_centre': {
        'description': 'Rural PHC/health centre, no antivenom, referral '
                       'needed for severe cases (e.g., rural DRC, Niger, Chad)',
        'species_probs': {
            'echis_ocellatus': 0.30,
            'bitis_arietans': 0.30,
            'naja_nigricollis': 0.12,
            'naja_haje': 0.05,
            'dendroaspis_polylepis': 0.05,
            'dendroaspis_viridis': 0.02,
            'causus_rhombeatus': 0.05,
            'atractaspis_spp': 0.02,
            'unknown_unidentified': 0.09,
        },
        'dry_bite_rate': 0.20,
        'antivenom_available': 0.05,
        'antivenom_given_if_needed': 0.20,
        'surgical_capacity': 0.10,
        'time_to_facility_hrs_mean': 16,
        'case_fatality': 0.14,
    },
}

# Envenomation syndrome by species [4]
SYNDROME_BY_SPECIES = {
    'echis_ocellatus': {'hemotoxic': 0.70, 'cytotoxic': 0.25, 'mixed': 0.05},
    'bitis_arietans': {'cytotoxic': 0.60, 'hemotoxic': 0.30, 'mixed': 0.10},
    'naja_nigricollis': {'cytotoxic': 0.55, 'neurotoxic': 0.35, 'mixed': 0.10},
    'naja_haje': {'neurotoxic': 0.60, 'cytotoxic': 0.30, 'mixed': 0.10},
    'dendroaspis_polylepis': {'neurotoxic': 0.85, 'mixed': 0.15},
    'dendroaspis_viridis': {'neurotoxic': 0.80, 'mixed': 0.20},
    'causus_rhombeatus': {'cytotoxic': 0.90, 'hemotoxic': 0.10},
    'atractaspis_spp': {'cytotoxic': 0.70, 'cardiotoxic': 0.30},
    'unknown_unidentified': {'cytotoxic': 0.45, 'hemotoxic': 0.30,
                              'neurotoxic': 0.15, 'mixed': 0.10},
}


def sample_categorical(probs_dict, rng):
    labels = list(probs_dict.keys())
    probs = np.array(list(probs_dict.values()))
    probs = probs / probs.sum()
    return rng.choice(labels, p=probs)


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}

        # ── Step 1: Demographics [5] ──
        r = rng.random()
        if r < 0.15:
            rec['age_years'] = rng.integers(1, 10)
        elif r < 0.30:
            rec['age_years'] = rng.integers(10, 18)
        elif r < 0.65:
            rec['age_years'] = rng.integers(18, 40)
        elif r < 0.85:
            rec['age_years'] = rng.integers(40, 60)
        else:
            rec['age_years'] = rng.integers(60, 80)

        rec['sex'] = rng.choice(['M', 'F'], p=[0.65, 0.35])  # Male predominance [5]

        if rec['age_years'] >= 18:
            rec['occupation'] = rng.choice(
                ['farmer', 'herder', 'hunter', 'trader', 'student', 'other'],
                p=[0.45, 0.15, 0.10, 0.10, 0.10, 0.10])
        else:
            rec['occupation'] = rng.choice(['student', 'child', 'herder'],
                                           p=[0.40, 0.45, 0.15])

        rec['bite_location'] = rng.choice(
            ['foot', 'ankle', 'lower_leg', 'hand', 'forearm', 'other'],
            p=[0.30, 0.20, 0.15, 0.20, 0.10, 0.05])

        rec['activity_at_bite'] = rng.choice(
            ['farming', 'walking', 'sleeping', 'herding', 'collecting_firewood', 'other'],
            p=[0.35, 0.25, 0.15, 0.10, 0.10, 0.05])

        # Time to facility [8]
        rec['time_to_facility_hours'] = max(0.5, round(
            rng.exponential(sc['time_to_facility_hrs_mean']), 1))
        rec['time_to_facility_hours'] = min(rec['time_to_facility_hours'], 72)

        # Traditional treatment before hospital
        rec['traditional_treatment_first'] = 1 if rng.random() < 0.40 else 0
        if rec['traditional_treatment_first']:
            rec['time_to_facility_hours'] *= 1.5

        # ── Step 2: Snake Species [1][4] ──
        rec['snake_species'] = sample_categorical(sc['species_probs'], rng)

        # ── Step 3: Envenomation & Syndrome ──
        rec['dry_bite'] = 1 if rng.random() < sc['dry_bite_rate'] else 0

        if rec['dry_bite']:
            rec['envenomation_syndrome'] = 'none'
            rec['severity'] = 'none'
        else:
            syndrome_probs = SYNDROME_BY_SPECIES.get(
                rec['snake_species'],
                {'cytotoxic': 0.50, 'hemotoxic': 0.30, 'neurotoxic': 0.20})
            rec['envenomation_syndrome'] = sample_categorical(syndrome_probs, rng)

            # Severity grading
            sev_roll = rng.random()
            if sev_roll < 0.30:
                rec['severity'] = 'mild'
            elif sev_roll < 0.70:
                rec['severity'] = 'moderate'
            else:
                rec['severity'] = 'severe'

            # Mamba bites more often severe
            if rec['snake_species'].startswith('dendroaspis'):
                if rng.random() < 0.4:
                    rec['severity'] = 'severe'

        # ── Step 4: Clinical Features [3][4] ──
        rec['local_swelling'] = 0
        rec['local_necrosis'] = 0
        rec['coagulopathy'] = 0
        rec['inr_elevated'] = 0
        rec['bleeding'] = 0
        rec['neurotoxicity'] = 0
        rec['ptosis'] = 0
        rec['respiratory_failure'] = 0
        rec['acute_kidney_injury'] = 0
        rec['compartment_syndrome'] = 0

        if not rec['dry_bite']:
            # Local effects
            if rec['envenomation_syndrome'] in ('cytotoxic', 'mixed'):
                rec['local_swelling'] = 1 if rng.random() < 0.92 else 0
                if rec['severity'] == 'severe':
                    rec['local_necrosis'] = 1 if rng.random() < 0.45 else 0
                    rec['compartment_syndrome'] = 1 if rng.random() < 0.15 else 0
                elif rec['severity'] == 'moderate':
                    rec['local_necrosis'] = 1 if rng.random() < 0.15 else 0
            elif rec['envenomation_syndrome'] == 'hemotoxic':
                rec['local_swelling'] = 1 if rng.random() < 0.85 else 0

            # Hemotoxic effects [3]
            if rec['envenomation_syndrome'] in ('hemotoxic', 'mixed'):
                rec['coagulopathy'] = 1 if rng.random() < 0.75 else 0
                if rec['coagulopathy']:
                    rec['inr_elevated'] = 1
                    rec['bleeding'] = 1 if rng.random() < 0.40 else 0
                rec['acute_kidney_injury'] = 1 if rng.random() < 0.20 else 0

            # Neurotoxic effects [4]
            if rec['envenomation_syndrome'] in ('neurotoxic', 'mixed'):
                rec['neurotoxicity'] = 1 if rng.random() < 0.80 else 0
                if rec['neurotoxicity']:
                    rec['ptosis'] = 1 if rng.random() < 0.70 else 0
                    if rec['severity'] == 'severe':
                        rec['respiratory_failure'] = 1 if rng.random() < 0.35 else 0

            # Delayed presentation worsens everything
            if rec['time_to_facility_hours'] > 12:
                if not rec['compartment_syndrome'] and rec['local_swelling']:
                    rec['compartment_syndrome'] = 1 if rng.random() < 0.10 else 0
                if not rec['acute_kidney_injury'] and rec['coagulopathy']:
                    rec['acute_kidney_injury'] = 1 if rng.random() < 0.15 else 0

        # ── Step 5: Treatment [7][8] ──
        rec['antivenom_given'] = 0
        rec['antivenom_vials'] = 0
        rec['antivenom_reaction'] = 0
        rec['wound_care'] = 0
        rec['fasciotomy'] = 0
        rec['blood_transfusion'] = 0
        rec['mechanical_ventilation'] = 0
        rec['dialysis'] = 0
        rec['amputation'] = 0
        rec['antibiotics_given'] = 0

        if not rec['dry_bite']:
            # Antivenom
            needs_antivenom = rec['severity'] in ('moderate', 'severe')
            if needs_antivenom:
                av_available = rng.random() < sc['antivenom_available']
                if av_available:
                    rec['antivenom_given'] = 1 if rng.random() < sc['antivenom_given_if_needed'] else 0

            if rec['antivenom_given']:
                if rec['severity'] == 'severe':
                    rec['antivenom_vials'] = rng.integers(3, 10)
                else:
                    rec['antivenom_vials'] = rng.integers(1, 5)
                rec['antivenom_reaction'] = 1 if rng.random() < 0.15 else 0

            # Wound care
            rec['wound_care'] = 1 if rng.random() < 0.85 else 0
            rec['antibiotics_given'] = 1 if rng.random() < 0.70 else 0

            # Surgery
            if rec['compartment_syndrome'] and rng.random() < sc['surgical_capacity']:
                rec['fasciotomy'] = 1

            if rec['local_necrosis'] and rec['severity'] == 'severe':
                if rec['time_to_facility_hours'] > 24 or not rec['antivenom_given']:
                    rec['amputation'] = 1 if rng.random() < 0.12 else 0

            # Supportive
            if rec['bleeding'] and rng.random() < 0.30:
                rec['blood_transfusion'] = 1
            if rec['respiratory_failure'] and rng.random() < sc['surgical_capacity']:
                rec['mechanical_ventilation'] = 1
            if rec['acute_kidney_injury'] and rec['severity'] == 'severe':
                if rng.random() < 0.15:
                    rec['dialysis'] = 1

        # ── Step 6: Outcome ──
        mort = 0.005  # Dry bite / mild
        if not rec['dry_bite']:
            if rec['severity'] == 'severe':
                mort = sc['case_fatality'] * 2.5
            elif rec['severity'] == 'moderate':
                mort = sc['case_fatality']
            else:
                mort = sc['case_fatality'] * 0.3

            # Antivenom protective
            if rec['antivenom_given']:
                mort *= 0.40

            # Delayed presentation increases mortality
            if rec['time_to_facility_hours'] > 12:
                mort *= 1.5
            if rec['time_to_facility_hours'] > 24:
                mort *= 1.5

            # Specific high-risk features
            if rec['respiratory_failure']:
                if not rec['mechanical_ventilation']:
                    mort = min(mort * 3, 0.80)
            if rec['acute_kidney_injury'] and rec['severity'] == 'severe':
                mort *= 1.5

            # Children more vulnerable
            if rec['age_years'] < 10:
                mort *= 1.5

        if rng.random() < min(mort, 0.70):
            rec['outcome'] = 'died'
        elif rec['amputation']:
            rec['outcome'] = 'survived_with_disability'
        elif rec['local_necrosis'] or rec['compartment_syndrome']:
            rec['outcome'] = 'survived_with_sequelae'
        else:
            rec['outcome'] = 'survived_full_recovery'

        # Hospital days
        if rec['outcome'] == 'died':
            rec['hospital_days'] = max(0, rng.integers(0, 7))
        elif rec['dry_bite'] or rec['severity'] in ('none', 'mild'):
            rec['hospital_days'] = rng.integers(1, 3)
        elif rec['severity'] == 'moderate':
            rec['hospital_days'] = rng.integers(2, 8)
        else:
            rec['hospital_days'] = rng.integers(5, 21)

        records.append(rec)

    df = pd.DataFrame(records)

    # ── Print Summary ──
    print(f"\n{'='*65}")
    print(f"Snakebite Envenomation — {scenario} (n={n}, seed={seed})")
    print(f"{'='*65}")

    print(f"\n  Dry bites: {df['dry_bite'].sum()} ({df['dry_bite'].mean()*100:.1f}%)")
    env = df[df['dry_bite'] == 0]
    print(f"  Envenomated: {len(env)}")

    print(f"\n  Top species:")
    for sp, ct in df['snake_species'].value_counts().head(5).items():
        print(f"    {sp}: {ct} ({ct/n*100:.1f}%)")

    print(f"\n  Syndrome (envenomated):")
    for syn, ct in env['envenomation_syndrome'].value_counts().items():
        print(f"    {syn}: {ct} ({ct/len(env)*100:.1f}%)")

    print(f"\n  Severity (envenomated):")
    for sev in ['mild', 'moderate', 'severe']:
        ct = (env['severity'] == sev).sum()
        print(f"    {sev}: {ct} ({ct/len(env)*100:.1f}%)")

    print(f"\n  Antivenom given: {df['antivenom_given'].sum()} "
          f"({df['antivenom_given'].mean()*100:.1f}%)")
    print(f"  Mean time to facility: {df['time_to_facility_hours'].mean():.1f} hrs")
    print(f"  Traditional treatment first: {df['traditional_treatment_first'].mean()*100:.1f}%")

    died = (df['outcome'] == 'died').sum()
    amp = df['amputation'].sum()
    print(f"\n  Deaths: {died} ({died/n*100:.1f}%)")
    print(f"  Amputations: {amp}")

    return df


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Generate synthetic snakebite envenomation 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'snakebite_{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'snakebite_{args.scenario}.csv')
        df.to_csv(out, index=False)
        print(f"  → Saved to {out}")