Cookbook 360: Offline Clinical Pediatric Neurology Status Epilepticus AES & ESETT Engine

This cookbook details how to deploy a localized, containerized pediatric neurology, neurocritical care, and emergency resuscitation decision-support engine for pediatric emergency departments, intensive care units ($\text{PICUs}$), and neuro-monitoring suites to ingest seizure duration chronologies, vascular access availability, prior benzodiazepine administrations, underlying metabolic/mitochondrial histories, and continuous electroencephalography ($\text{cEEG}$) telemetry, classify status epilepticus according to the American Epilepsy Society ($\text{AES 2016 / 2024}$) and $\text{ILAE 2015}$ 4-Phase Time-to-Treatment Algorithm, automate Phase 1 Emergent Benzodiazepine Dosing ($\text{IV Lorazepam vs IM Midazolam}$), execute Phase 2 Established Status Epilepticus ($\text{ESETT Trial}$: Levetiracetam, Fosphenytoin, Valproate Sodium) selection, precision-titrate Phase 3 Refractory Status Epilepticus ($\text{RSE}$) Continuous Anesthetics ($\text{Midazolam, Propofol, Pentobarbital, Ketamine}$) targeting $\text{cEEG Burst Suppression}$, and enforce $\text{POLG / Mitochondrial Hepatotoxicity}$ & Non-Convulsive $\text{SE}$ Safety Sentinels according to AES, ILAE, and Neurocritical Care Society ($\text{NCS}$) consensus guidelines without external cloud API reliance.


1. Clinical Background & Pediatric Neurocritical Care Architecture

Status Epilepticus ($\text{SE}$) is a medical and neurological emergency resulting either from the failure of normal seizure termination mechanisms or from the initiation of mechanisms leading to abnormally prolonged seizures ($\ge 5\text{ minutes}$ for generalized convulsive status epilepticus, $t_1$), carrying severe risks of permanent neuronal injury, systemic pharmacoresistance, and mortality if duration exceeds $30\text{ minutes}$ ($t_2$):


2. Pipeline & Workflow Architecture

[Seizure Telemetry: Age, Weight, Duration Mins, IV Access, Prior Benzos, POLG History, cEEG]
                                         │
                                         ▼
      [AES / ILAE Phase Classifier: Phase 1 (0-20m) vs Phase 2 (20-40m) vs Phase 3 (40-60m+)]
                                         │
                                         ▼
      [Phase 1 Emergent Benzo Gating: IV Lorazepam 0.1mg/kg vs IM Midazolam 0.2mg/kg]
                                         │
                                         ▼
      [Phase 2 ESETT Selector: Levetiracetam 60mg/kg vs Fosphenytoin vs Valproate (POLG Gate)]
                                         │
                                         ▼
      [Phase 3 Refractory Anesthetic Titrator: Midazolam vs Propofol vs Ketamine to Burst Suppression]
                                         │
                                         ▼
      [Safety Sentinels: cEEG Mandatory, Paralytic Motor-Masking Trap, PRIS Warning]

3. Environment & Prerequisites

Install required scientific Python and pediatric neurology modeling packages:

pip install numpy scipy pandas torch torchvision matplotlib

4. Complete Offline Python / PyTorch Implementation

"""
Cookbook 360: Offline Pediatric Neurology Status Epilepticus AES & ESETT Engine
OpenPHR Clinical AI Working Group (https://openphr.org)
"""

import math
import numpy as np
import pandas as pd
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass

@dataclass
class StatusEpilepticusTelemetry:
    patient_id: str
    age_years: float = 6.0
    patient_weight_kg: float = 22.0
    seizure_duration_minutes: float = 28.0 # > 20 mins -> Phase 2 Established SE!
    has_iv_access: bool = True
    # Prior Resuscitation Telemetry
    prior_benzodiazepine_doses_given: int = 2 # Completed 2 doses of Lorazepam
    time_since_last_benzo_minutes: float = 12.0
    # Clinical & Comorbidity Telemetry
    has_suspected_mitochondrial_or_polg_disease: bool = False # If True -> Valproate Contraindicated!
    has_acute_hepatic_failure: bool = False
    has_cardiac_conduction_defect: bool = False # If True -> Avoid Fosphenytoin
    # Neurological & Monitoring Telemetry
    clinical_seizure_type: str = "Generalized Tonic-Clonic" # "Generalized Tonic-Clonic", "Focal Motor", "Non-Convulsive"
    patient_mental_status: str = "Unresponsive / Comatose"
    continuous_eeg_connected: bool = True
    ceeg_pattern: str = "Continuous Generalized Spike-and-Wave Discharges" # "Seizure Discharges", "Burst Suppression", "Normal/Slowing"
    # Hemodynamic Telemetry
    systolic_bp_mmhg: float = 96.0
    heart_rate_bpm: float = 138.0
    spo2_percent: float = 93.0
    is_intubated: bool = False

@dataclass
class StatusEpilepticusReport:
    patient_id: str
    aes_seizure_phase: str # "PHASE 2: ESTABLISHED STATUS EPILEPTICUS (20-40 Minutes)"
    phase_urgency_tier: str
    immediate_pharmacotherapy_orders: List[str]
    subsequent_phase_contingency_plan: List[str]
    ceeg_and_airway_directives: List[str]
    safety_sentinels: List[str]
    clinical_aes_esett_directive: str

class StatusEpilepticusDecisionEngine:
    """
    Offline clinical engine for AES 2016/2024 status epilepticus staging,
    ESETT second-line antiepileptic selection, and refractory burst-suppression titrator.
    """

    def classify_aes_phase(self, d: StatusEpilepticusTelemetry) -> Tuple[str, str]:
        t = d.seizure_duration_minutes

        if t > 60.0 or (t >= 40.0 and d.prior_benzodiazepine_doses_given >= 2):
            return "PHASE 3: REFRACTORY STATUS EPILEPTICUS (RSE, > 40-60 Minutes)", "Critical neuro-resuscitation emergency; high risk of systemic acidosis, hyperthermia, and excitotoxic neuronal death. Requires continuous anesthetic infusion."
        elif 20.0 <= t < 60.0 and d.prior_benzodiazepine_doses_given >= 1:
            return "PHASE 2: ESTABLISHED STATUS EPILEPTICUS (20 to 40 Minutes)", "Benzodiazepine-resistant status epilepticus; immediate second-line intravenous non-sedating antiseizure medication required (ESETT Protocol)."
        elif t < 20.0 or d.prior_benzodiazepine_doses_given < 2:
            return "PHASE 1: EMERGENT INITIAL THERAPY (0 to 20 Minutes)", "First-line emergent therapy; rapid benzodiazepine administration to prevent pharmacoresistant receptor internalization."
        else:
            return "PHASE 2: ESTABLISHED STATUS EPILEPTICUS", "Transitioning to second-line non-sedating antiepileptics."

    def generate_phase1_orders(self, d: StatusEpilepticusTelemetry) -> List[str]:
        orders = []
        wt = d.patient_weight_kg

        if d.has_iv_access:
            loraz_dose = min(4.0, wt * 0.10)
            orders.append(f"1. IV LORAZEPAM (First-Line Emergent): {loraz_dose:.2f} mg IV ({wt * 0.10:.2f} mg at 0.10 mg/kg) administered over 2 minutes.")
            orders.append("   • If seizure persists after 5 minutes: Repeat single identical dose of IV Lorazepam once.")
        else:
            midaz_dose = min(10.0, wt * 0.20)
            orders.append(f"1. IM MIDAZOLAM (First-Line Emergent without IV - RAMPART Protocol): {midaz_dose:.2f} mg IM ({wt * 0.20:.2f} mg at 0.20 mg/kg) into mid-outer thigh.")
            orders.append("   • Alternative if IM not available: Rectal Diazepam gel 0.2 - 0.5 mg/kg OR Intranasal Midazolam 0.2 mg/kg.")

        return orders

    def generate_phase2_esett_orders(self, d: StatusEpilepticusTelemetry) -> Tuple[List[str], List[str]]:
        orders = []
        sentinels = []
        wt = d.patient_weight_kg

        # ESETT Protocol Dosing
        lev_dose = min(4500.0, wt * 60.0)
        fosphen_dose = min(1500.0, wt * 20.0)
        valp_dose = min(3000.0, wt * 40.0)

        orders.append("1. SECOND-LINE ESTABLISHED STATUS EPILEPTICUS (ESETT TRIAL PROTOCOL):")
        orders.append(f"   • OPTION A (PREFERRED FIRST-LINE): IV LEVETIRACETAM (Keppra) {lev_dose:.0f} mg IV ({wt * 60.0:.0f} mg at 60 mg/kg) infused over 10 minutes.")

        # Valproate with Mitochondrial/POLG Sentinel
        if not d.has_suspected_mitochondrial_or_polg_disease and not d.has_acute_hepatic_failure and d.age_years >= 2.0:
            orders.append(f"   • OPTION B: IV VALPROATE SODIUM (Depacon) {valp_dose:.0f} mg IV ({wt * 40.0:.0f} mg at 40 mg/kg) infused over 10 minutes.")
        else:
            sentinels.append("🚨 ABSOLUTE VALPROATE CONTRAINDICATION: Valproate is STRICTLY CONTRAINDICATED due to suspected POLG/mitochondrial disease, age < 2 years, or acute hepatic dysfunction (Fatal Acute Hepatic Necrosis Hazard).")

        # Fosphenytoin with Cardiac Sentinel
        if not d.has_cardiac_conduction_defect:
            orders.append(f"   • OPTION C: IV FOSPHENOIN (Cerebyx) {fosphen_dose:.0f} mg PE ({wt * 20.0:.0f} mg PE at 20 mg PE/kg) infused at <= 150 mg PE/min with continuous ECG/BP monitoring.")
        else:
            sentinels.append("🚨 FOSPHENOIN CAUTION: Cardiac conduction defect present; avoid Fosphenytoin due to risk of fatal asystole/AV block.")

        return orders, sentinels

    def generate_phase3_rse_orders(self, d: StatusEpilepticusTelemetry) -> Tuple[List[str], List[str]]:
        orders = []
        sentinels = []
        wt = d.patient_weight_kg

        midaz_load = min(20.0, wt * 0.20)
        orders.append("1. THIRD-LINE REFRACTORY STATUS EPILEPTICUS (RSE) PROTOCOL:")
        orders.append(f"   • CONTINUOUS IV MIDAZOLAM: Bolus {midaz_load:.2f} mg IV ({wt * 0.20:.2f} mg at 0.20 mg/kg), then initiate continuous IV infusion at 0.10 - 2.0 mg/kg/hr.")
        orders.append(f"   • KETAMINE ADD-ON (For NMDA Overdrive): Bolus {wt * 2.0:.1f} mg IV (2.0 mg/kg), then infusion 1.0 - 5.0 mg/kg/hr.")
        orders.append("   • ALTERNATIVE: High-Dose Pentobarbital 5.0 mg/kg IV load over 10 min, then 1.0 - 5.0 mg/kg/hr infusion.")

        sentinels.append("🚨 BURST-SUPPRESSION TARGET: Continuous anesthetics must be titrated against continuous cEEG to achieve electrographic burst suppression (8-12 seconds inter-burst interval) for 24-48 hours before gradual weaning.")

        return orders, sentinels

    def generate_ceeg_and_safety(self, d: StatusEpilepticusTelemetry, phase: str) -> Tuple[List[str], List[str]]:
        directives = []
        sentinels = []

        directives.append("1. AIRWAY & OXYGENATION: Maintain airway, administer 100% high-flow O2, prepare for rapid sequence intubation if progressing to Phase 3.")
        directives.append("2. CONTINUOUS cEEG MONITORING: Essential within 60 minutes of presentation.")

        # Neuromuscular Blockade Paralytic Trap Sentinel
        sentinels.append("🚨 PARALYTIC MOTOR-MASKING TRAP: NEVER administer neuromuscular blocking agents (e.g., Rocuronium / Vecuronium) to a seizing patient without IMMEDIATE continuous cEEG. Paralysis abolishes external motor convulsions while continuous excitotoxic brain seizures continue unnoticed!")

        # Non-Convulsive Status Epilepticus Sentinel
        if "Unresponsive" in d.patient_mental_status and "PHASE 1" not in phase:
            sentinels.append("🚨 NON-CONVULSIVE STATUS EPILEPTICUS (NCSE) ALERT: > 40% of patients who stop motor convulsions remain in continuous electrographic seizure. Any child who does not wake up within 15-20 minutes must have urgent cEEG to rule out NCSE!")

        return directives, sentinels

    def evaluate_case(self, data: StatusEpilepticusTelemetry) -> StatusEpilepticusReport:
        phase, urgency = self.classify_aes_phase(data)
        ceeg_dirs, sentinels_ceeg = self.generate_ceeg_and_safety(data, phase)

        if "PHASE 1" in phase:
            rx_orders = self.generate_phase1_orders(data)
            next_orders, sent_p2 = self.generate_phase2_esett_orders(data)
            all_sentinels = sentinels_ceeg + sent_p2
        elif "PHASE 2" in phase:
            rx_orders, sent_p2 = self.generate_phase2_esett_orders(data)
            next_orders, sent_p3 = self.generate_phase3_rse_orders(data)
            all_sentinels = sentinels_ceeg + sent_p2 + sent_p3
        else: # Phase 3 RSE
            rx_orders, sent_p3 = self.generate_phase3_rse_orders(data)
            next_orders = ["PHASE 4 SUPER-REFRACTORY PROTOCOL: Ketogenic Diet (4:1) + IV Methylprednisolone 30 mg/kg/day + IVIG 2.0 g/kg (NORSE/FIRES Protocol) + Anakinra."]
            all_sentinels = sentinels_ceeg + sent_p3

        directives = []
        directives.append(f"STATUS: {phase}.")
        directives.append(f"IMMEDIATE ACTION: {rx_orders[0]}.")
        directives.append("MONITORING: Mandatory continuous cEEG to rule out Non-Convulsive Status Epilepticus.")

        return StatusEpilepticusReport(
            patient_id=data.patient_id,
            aes_seizure_phase=phase,
            phase_urgency_tier=urgency,
            immediate_pharmacotherapy_orders=rx_orders,
            subsequent_phase_contingency_plan=next_orders,
            ceeg_and_airway_directives=ceeg_dirs,
            safety_sentinels=all_sentinels,
            clinical_aes_esett_directive=" ".join(directives)
        )

# Example Execution & Verification
if __name__ == "__main__":
    engine = StatusEpilepticusDecisionEngine()

    print("=" * 80)
    print("OpenPHR Clinical Pediatric Neurology Status Epilepticus AES & ESETT Engine")
    print("=" * 80)

    # Test Case 1: 6-year-old child (22 kg) with 28 minutes of Generalized Tonic-Clonic Seizure.
    # Prior Rx: Received 2 prior doses of IV Lorazepam without seizure termination.
    # Phase: PHASE 2 ESTABLISHED STATUS EPILEPTICUS (20-40 Minutes).
    # ESETT Selection: Levetiracetam 1320 mg (60 mg/kg) IV over 10 min (Zero hepatic/cardiac toxicity).
    # Contingency: Prepare Midazolam/Ketamine infusion + Intubation if seizure exceeds 40-60 min.
    # Sentinels: cEEG Mandatory + Paralytic Motor-Masking Trap!
    se1 = StatusEpilepticusTelemetry(
        patient_id="PEDS-SE-3301",
        age_years=6.0,
        patient_weight_kg=22.0,
        seizure_duration_minutes=28.0,
        has_iv_access=True,
        prior_benzodiazepine_doses_given=2,
        time_since_last_benzo_minutes=12.0,
        has_suspected_mitochondrial_or_polg_disease=False,
        has_acute_hepatic_failure=False,
        has_cardiac_conduction_defect=False,
        clinical_seizure_type="Generalized Tonic-Clonic",
        patient_mental_status="Unresponsive / Comatose",
        continuous_eeg_connected=True,
        ceeg_pattern="Continuous Generalized Spike-and-Wave Discharges",
        systolic_bp_mmhg=96.0,
        heart_rate_bpm=138.0,
        spo2_percent=93.0,
        is_intubated=False
    )

    rep1 = engine.evaluate_case(se1)

    print(f"\n[Patient {rep1.patient_id} - Pediatric Status Epilepticus Assessment]")
    print(f"AES / ILAE Phase: {rep1.aes_seizure_phase}")
    print(f"Urgency Profile: {rep1.phase_urgency_tier}")
    print("\nImmediate Pharmacotherapy Orders:")
    for o in rep1.immediate_pharmacotherapy_orders:
        print(f"  {o}")
    print("\nSubsequent Phase Contingency Plan:")
    for c in rep1.subsequent_phase_contingency_plan:
        print(f"  {c}")
    print("\ncEEG & Airway Directives:")
    for a in rep1.ceeg_and_airway_directives:
        print(f"  {a}")
    if rep1.safety_sentinels:
        print("\nSafety Sentinels:")
        for s in rep1.safety_sentinels:
            print(f"  🚨 {s}")
    print(f"\nAES / ESETT Consensus Directive:\n{rep1.clinical_aes_esett_directive}")

5. Clinical Verification & Guideline Conformance


6. References