Offline Clinical Neurocritical Care Acute Ischemic Stroke Endovascular Thrombectomy (EVT) DAWN & DEFUSE 3 Perfusion Mismatch Engine (ASPECTS Score, Core-Penumbra Ratio, NIHSS & TICI Revascularization Titrator)

An enterprise-ready, offline-first Python clinical decision support engine for the emergency assessment, neuro-imaging triage, and post-revascularization intensive care management of acute ischemic stroke (AIS) with large vessel occlusion (LVO). Conforms to the American Heart Association / American Stroke Association (AHA/ASA 2019/2023) Guidelines, the DAWN Trial (N Engl J Med 2018; 378:11-21), DEFUSE 3 Trial (N Engl J Med 2018; 378:708-718), and large-core randomized trials (SELECT2, ANGEL-ASPECT). Automates Alberta Stroke Programme Early CT Score (ASPECTS) evaluation, IV thrombolysis eligibility and dosing, automated core-penumbra perfusion mismatch qualification, post-thrombectomy modified TICI hemodynamics, and malignant cerebral edema / decompressive hemicraniectomy screening.


Clinical Architecture & Multi-Window EVT Resuscitation Pipeline

Endovascular thrombectomy is the standard of care for acute ischemic stroke caused by large vessel occlusion. Optimal patient selection hinges on time from last known normal (LKN), clinical severity (NIHSS), non-contrast CT core estimation (ASPECTS), and advanced CT/MR perfusion imaging:

[ Acute Ischemic Stroke Suspected: Last Known Normal (LKN) Established ]
                               |
            [ Emergent Non-Contrast Head CT + CTA/MRA ]
                               |
             +-----------------+-----------------+
             |                                   |
  [ Intracranial Hemorrhage ]          [ No Hemorrhage: AIS Confirmed ]
             |                                   |
  [ Stroke Preclusion / ICH Care ]    [ ASPECTS Score Evaluated (0-10) ]
                                                 |
                       +-------------------------+-------------------------+
                       |                                                   |
           [ Time <= 4.5 Hours from LKN ]                           [ Time > 4.5 Hours ]
                       |                                                   |
        [ IV Thrombolysis Screen (TNK/rtPA) ]                              |
        (BP < 185/110, INR <= 1.7, Plt >= 100k)                            |
                       |                                                   |
                       +-------------------------+-------------------------+
                                                 |
                                  [ CTA/MRA Vessel Assessment ]
                                  (ICA Terminus, M1, M2, Basilar)
                                                 |
        +----------------------------------------+----------------------------------------+
        |                                                                                 |
 [ Early Window: 0 - 6.0 Hours ]                                          [ Extended Window: 6.0 - 24.0 Hours ]
        |                                                                                 |
  +-----+-----+                                                            +--------------+--------------+
  |           |                                                            |                             |
[ASPECTS>=6] [ASPECTS 3-5]                                        [ 6.0 - 16.0 Hours ]          [ 16.0 - 24.0 Hours ]
  |           |                                                            |                             |
[Class 1A]   [Class 2a: SELECT2]                                 [ DEFUSE 3 & DAWN Sieve ]         [ DAWN Sieve Only ]
  |           |                                                  - Core < 70 mL                 - Clinical-Core
  +-----+-----+                                                  - Mismatch Ratio >= 1.8          Mismatch
        |                                                        - Penumbra >= 15 mL            (Groups A, B, C)
        +----------------------------------------+---------------------------------+                     |
                                                 |                                                       |
                                    [ Endovascular Thrombectomy ] <--------------------------------------+
                                                 |
                                    [ Digital Subtraction Angio ]
                                    [ mTICI Reperfusion Grade ]
                                                 |
                         +-----------------------+-----------------------+
                         |                                               |
             [ Successful Reperfusion ]                      [ Suboptimal / Failed ]
                 (mTICI 2b / 2c / 3)                             (mTICI 0 / 1 / 2a)
                         |                                               |
              [ Strict BP Lowering ]                          [ Permissive Hypertension ]
              (Target SBP 120-140 mmHg)                       (Target SBP 140-180 mmHg)
                         |                                               |
                         +-----------------------+-----------------------+
                                                 |
                             [ Serial Neuro-ICU Surveillance ]
                           (Malignant Edema, Midline Shift >= 5mm,
                            Emergent Hemicraniectomy < 48 Hours)

Landmark Clinical Evidence & Triage Frameworks

Landmark Paradigm Target Window Key Inclusion Criteria Clinical Endpoint / Trial Benchmark
HERMES Meta-analysis (2016) 0 - 6 hours LVO (ICA, M1), ASPECTS >= 6, NIHSS >= 6, pre-stroke mRS 0-1 NNT = 2.6 for functional independence (mRS 0-2 at 90 days)
DAWN Trial (NEJM 2018) 6 - 24 hours Clinical-imaging mismatch: Group A (Age >= 80, NIHSS >= 10, Core < 21 mL); Group B (Age < 80, NIHSS >= 10, Core < 31 mL); Group C (Age < 80, NIHSS >= 20, Core 31 to < 51 mL) 49% vs 13% 90-day functional independence (rate ratio 3.77; 95% CI, 2.30-6.19)
DEFUSE 3 Trial (NEJM 2018) 6 - 16 hours ICA or M1 occlusion, NIHSS >= 6, pre-stroke mRS 0-2, Ischemic core < 70 mL, Mismatch ratio >= 1.8, Absolute penumbra >= 15 mL 45% vs 17% functional independence at 90 days (P < 0.001); lower mortality
SELECT2 / ANGEL-ASPECT (2023) 0 - 24 hours Large ischemic core: ASPECTS 3-5 or core volume >= 50 mL Functional recovery superior with EVT vs medical care alone; modest symptomatic ICH rate
ATTENTION / BAOCHE (2022) 0 - 24 hours Basilar artery occlusion (BAO), NIHSS >= 6-10 Proven efficacy in posterior circulation ischemic stroke

Complete Enterprise Python CDS Implementation

"""
Clinical Decision Support Engine for Acute Ischemic Stroke Endovascular Thrombectomy (EVT)
Implements AHA/ASA 2019/2023 Guidelines, DAWN Trial, and DEFUSE 3 Trial Criteria.
"""

from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Tuple, Dict
import math
import unittest


class OcclusionSite(str, Enum):
    ICA_TERMINUS = "Internal Carotid Artery Terminus (T-occlusion)"
    ICA_CERVICAL = "Internal Carotid Artery (Cervical / Tandem)"
    MCA_M1 = "Middle Cerebral Artery (M1 segment)"
    MCA_M2_DOMINANT = "Middle Cerebral Artery (M2 segment - Dominant division)"
    MCA_M2_NONDOMINANT = "Middle Cerebral Artery (M2 segment - Non-dominant)"
    BASILAR_ARTERY = "Basilar Artery (Vertebrobasilar LVO)"
    ANTERIOR_CEREBRAL = "Anterior Cerebral Artery (ACA A1/A2)"
    POSTERIOR_CEREBRAL = "Posterior Cerebral Artery (PCA P1/P2)"
    OTHER_DISTAL = "Distal Medium Vessel Occlusion (MeVO)"
    NO_LVO = "No Large Vessel Occlusion Identified"


class ASPECTSLocation(str, Enum):
    CAUDATE = "Caudate Head"
    LENTIFORM = "Lentiform Nucleus"
    INTERNAL_CAPSULE = "Internal Capsule (Posterior Limb)"
    INSULAR_RIBBON = "Insular Ribbon / Cortex"
    M1_ANTERIOR_INFERIOR = "M1: Anterior MCA Cortex (Ganglionic level)"
    M2_LATERAL_INSULAR = "M2: Lateral Temporal MCA Cortex (Ganglionic level)"
    M3_POSTERIOR_TEMPORAL = "M3: Posterior Temporal MCA Cortex (Ganglionic level)"
    M4_ANTERIOR_SUPRAGANGLIONIC = "M4: Anterior MCA Cortex (Supraganglionic level)"
    M5_LATERAL_SUPRAGANGLIONIC = "M5: Lateral MCA Cortex (Supraganglionic level)"
    M6_POSTERIOR_SUPRAGANGLIONIC = "M6: Posterior MCA Cortex (Supraganglionic level)"


class TICIGrade(str, Enum):
    GRADE_0 = "mTICI 0: No Perfusion / No antegrade flow"
    GRADE_1 = "mTICI 1: Minimal flow past occlusion with negligible tissue filling"
    GRADE_2A = "mTICI 2a: Partial filling (< 50% of target vascular territory)"
    GRADE_2B = "mTICI 2b: Partial filling (>= 50% of target vascular territory - Successful Reperfusion)"
    GRADE_2C = "mTICI 2c: Near complete perfusion with minimal slow distal branch flow"
    GRADE_3 = "mTICI 3: Complete tissue reperfusion with normal arterial transit"


class ThrombolysisAgent(str, Enum):
    TENECTEPLASE = "Tenecteplase (TNK-tPA)"
    ALTEPLASE = "Alteplase (rt-PA)"
    NONE = "None / Ineligible"


@dataclass
class ThrombolysisScreening:
    eligible: bool
    agent: ThrombolysisAgent
    recommended_dose: str
    contraindications: List[str] = field(default_factory=list)
    precautions: List[str] = field(default_factory=list)
    bp_management_required: bool = False
    target_bp: str = "SBP < 185 mmHg and DBP < 110 mmHg prior to initiation"


@dataclass
class DAWNEvaluation:
    met: bool
    group: Optional[str]
    max_allowable_core_ml: float
    actual_core_ml: float
    details: str


@dataclass
class DEFUSE3Evaluation:
    met: bool
    actual_core_ml: float
    hypoperfusion_vol_ml: float
    mismatch_vol_ml: float
    mismatch_ratio: float
    details: str


@dataclass
class EVTTriageDecision:
    evt_indicated: bool
    level_of_evidence: str
    trial_paradigm: str
    target_vessel: OcclusionSite
    aspects_score: int
    core_volume_ml: float
    penumbra_volume_ml: float
    mismatch_ratio: float
    contraindications: List[str]
    urgent_recommendations: List[str]


@dataclass
class PostEVTHemodynamics:
    tici_grade: TICIGrade
    successful_reperfusion: bool
    target_sbp_range: str
    target_dbp_ceiling: str
    permissive_hypertension_allowed: bool
    rationale: str
    recommended_antihypertensives: List[str]
    monitoring_frequency: str


class AcuteStrokeEVTEngine:
    """
    Enterprise-grade, offline-native clinical decision support engine for
    Acute Ischemic Stroke (AIS) Endovascular Thrombectomy (EVT), ASPECTS scoring,
    DAWN/DEFUSE 3 extended-window triage, and post-revascularization hemodynamic titration.
    """

    @staticmethod
    def calculate_aspects(infarcted_regions: List[ASPECTSLocation]) -> Tuple[int, List[str]]:
        """
        Calculates Alberta Stroke Programme Early CT Score (ASPECTS) from a baseline of 10.
        Subtracts 1 point for each distinct region showing early ischemic changes on NCCT.
        """
        unique_regions = set(infarcted_regions)
        deductions = len(unique_regions)
        score = max(0, 10 - deductions)
        deducted_names = [r.value for r in unique_regions]
        return score, deducted_names

    @classmethod
    def screen_intravenous_thrombolysis(
        cls,
        time_since_lkn_hours: float,
        weight_kg: float,
        current_sbp: int,
        current_dbp: int,
        inr: float = 1.0,
        platelets_per_uL: int = 250_000,
        blood_glucose_mg_dl: float = 120.0,
        head_ct_hemorrhage: bool = False,
        active_internal_bleeding: bool = False,
        known_aneurysm_or_avm: bool = False,
        recent_major_surgery_days: int = 45,
        recent_stroke_months: int = 12,
        on_doac_last_48h: bool = False,
        prefer_tenecteplase: bool = True
    ) -> ThrombolysisScreening:
        """
        Evaluates IV Thrombolysis (IVT) eligibility within the 0 to 4.5-hour time window.
        AHA/ASA 2019/2023 Guidelines.
        """
        contraindications = []
        precautions = []

        if head_ct_hemorrhage:
            contraindications.append("Acute intracranial hemorrhage confirmed on non-contrast head CT.")
        if time_since_lkn_hours > 4.5:
            contraindications.append(f"Time from Last Known Normal ({time_since_lkn_hours:.1f}h) exceeds the 4.5-hour IVT window.")
        if active_internal_bleeding:
            contraindications.append("Active internal bleeding or acute bleeding diathesis.")
        if known_aneurysm_or_avm:
            contraindications.append("Known intracranial neoplasm, arteriovenous malformation, or aneurysm.")
        if inr > 1.7:
            contraindications.append(f"Coagulopathy: INR {inr:.2f} > 1.7 threshold.")
        if platelets_per_uL < 100_000:
            contraindications.append(f"Thrombocytopenia: Platelet count {platelets_per_uL:,}/uL < 100,000/uL.")
        if on_doac_last_48h:
            contraindications.append("Direct oral anticoagulant (DOAC) ingestion within past 48 hours without specific reversal.")
        if recent_major_surgery_days < 14:
            contraindications.append(f"Major surgical procedure within last 14 days ({recent_major_surgery_days} days ago).")
        if recent_stroke_months < 3:
            contraindications.append(f"Severe head trauma or ischemic stroke within past 3 months ({recent_stroke_months} months).")
        if blood_glucose_mg_dl < 50.0:
            contraindications.append(f"Severe hypoglycemia ({blood_glucose_mg_dl:.1f} mg/dL) must be corrected before re-evaluating deficit.")

        bp_requires_intervention = False
        if current_sbp > 185 or current_dbp > 110:
            bp_requires_intervention = True
            precautions.append(f"Blood pressure ({current_sbp}/{current_dbp} mmHg) exceeds IVT safety threshold (> 185/110 mmHg). Requires urgent reduction.")

        is_eligible = len(contraindications) == 0

        if not is_eligible:
            return ThrombolysisScreening(
                eligible=False,
                agent=ThrombolysisAgent.NONE,
                recommended_dose="No IV thrombolysis indicated.",
                contraindications=contraindications,
                precautions=precautions,
                bp_management_required=bp_requires_intervention
            )

        if prefer_tenecteplase:
            # TNK: 0.25 mg/kg IV single bolus over 5 seconds; max 25 mg
            calc_dose = min(25.0, weight_kg * 0.25)
            dose_str = f"Tenecteplase 0.25 mg/kg IV single bolus over 5 seconds: {calc_dose:.1f} mg (Maximum 25 mg)."
            agent = ThrombolysisAgent.TENECTEPLASE
        else:
            # Alteplase: 0.9 mg/kg IV (max 90 mg); 10% bolus over 1 min, 90% infused over 60 min
            total_dose = min(90.0, weight_kg * 0.9)
            bolus_dose = total_dose * 0.10
            infusion_dose = total_dose * 0.90
            dose_str = (
                f"Alteplase 0.9 mg/kg (Total: {total_dose:.1f} mg, Max 90 mg): "
                f"{bolus_dose:.1f} mg IV bolus over 1 min, followed by {infusion_dose:.1f} mg IV infusion over 60 min."
            )
            agent = ThrombolysisAgent.ALTEPLASE

        return ThrombolysisScreening(
            eligible=True,
            agent=agent,
            recommended_dose=dose_str,
            contraindications=[],
            precautions=precautions,
            bp_management_required=bp_requires_intervention
        )

    @classmethod
    def evaluate_dawn_trial_criteria(
        cls,
        age: int,
        nihss: int,
        core_volume_ml: float
    ) -> DAWNEvaluation:
        """
        Evaluates DAWN Trial (6 to 24 hours from LKN) Clinical-Imaging Mismatch Criteria.
        - Group A: Age >= 80, NIHSS >= 10, Core < 21 mL
        - Group B: Age < 80, NIHSS >= 10, Core < 31 mL
        - Group C: Age < 80, NIHSS >= 20, Core 31 to < 51 mL
        """
        if nihss < 10:
            return DAWNEvaluation(
                met=False,
                group=None,
                max_allowable_core_ml=0.0,
                actual_core_ml=core_volume_ml,
                details=f"DAWN requires NIHSS >= 10 (Current NIHSS: {nihss})."
            )

        if age >= 80:
            if core_volume_ml < 21.0:
                return DAWNEvaluation(
                    met=True,
                    group="DAWN Group A (Age >= 80, NIHSS >= 10, Core < 21 mL)",
                    max_allowable_core_ml=21.0,
                    actual_core_ml=core_volume_ml,
                    details=f"Eligible under DAWN Group A: Age {age} >= 80, NIHSS {nihss} >= 10, Core {core_volume_ml:.1f} mL < 21 mL."
                )
            else:
                return DAWNEvaluation(
                    met=False,
                    group="DAWN Group A Exceeded",
                    max_allowable_core_ml=21.0,
                    actual_core_ml=core_volume_ml,
                    details=f"Infarct core volume {core_volume_ml:.1f} mL exceeds DAWN Group A ceiling (< 21 mL for age >= 80)."
                )
        else:
            # Age < 80
            if nihss >= 20 and 31.0 <= core_volume_ml < 51.0:
                return DAWNEvaluation(
                    met=True,
                    group="DAWN Group C (Age < 80, NIHSS >= 20, Core 31 - < 51 mL)",
                    max_allowable_core_ml=51.0,
                    actual_core_ml=core_volume_ml,
                    details=f"Eligible under DAWN Group C: Age {age} < 80, NIHSS {nihss} >= 20, Core {core_volume_ml:.1f} mL in [31, 51) mL."
                )
            elif core_volume_ml < 31.0:
                return DAWNEvaluation(
                    met=True,
                    group="DAWN Group B (Age < 80, NIHSS >= 10, Core < 31 mL)",
                    max_allowable_core_ml=31.0,
                    actual_core_ml=core_volume_ml,
                    details=f"Eligible under DAWN Group B: Age {age} < 80, NIHSS {nihss} >= 10, Core {core_volume_ml:.1f} mL < 31 mL."
                )
            else:
                return DAWNEvaluation(
                    met=False,
                    group=None,
                    max_allowable_core_ml=31.0 if nihss < 20 else 51.0,
                    actual_core_ml=core_volume_ml,
                    details=f"Core volume {core_volume_ml:.1f} mL exceeds DAWN mismatch threshold for Age {age} and NIHSS {nihss}."
                )

    @classmethod
    def evaluate_defuse3_trial_criteria(
        cls,
        nihss: int,
        premorbid_mrs: int,
        core_volume_ml: float,
        hypoperfusion_vol_ml: float,
        occlusion: OcclusionSite
    ) -> DEFUSE3Evaluation:
        """
        Evaluates DEFUSE 3 Trial (6 to 16 hours from LKN) Perfusion Mismatch Criteria.
        - ICA or MCA-M1 occlusion
        - NIHSS >= 6, pre-stroke mRS <= 2
        - Infarct core volume (rCBF < 30%) < 70 mL
        - Mismatch ratio (hypoperfusion Tmax > 6s / core) >= 1.8
        - Absolute mismatch volume (hypoperfusion - core) >= 15 mL
        """
        if occlusion not in [OcclusionSite.ICA_TERMINUS, OcclusionSite.ICA_CERVICAL, OcclusionSite.MCA_M1]:
            return DEFUSE3Evaluation(
                met=False,
                actual_core_ml=core_volume_ml,
                hypoperfusion_vol_ml=hypoperfusion_vol_ml,
                mismatch_vol_ml=max(0.0, hypoperfusion_vol_ml - core_volume_ml),
                mismatch_ratio=0.0,
                details=f"Occlusion at {occlusion.value} does not meet DEFUSE 3 anatomical criteria (ICA or MCA-M1)."
            )

        if nihss < 6:
            return DEFUSE3Evaluation(
                met=False,
                actual_core_ml=core_volume_ml,
                hypoperfusion_vol_ml=hypoperfusion_vol_ml,
                mismatch_vol_ml=max(0.0, hypoperfusion_vol_ml - core_volume_ml),
                mismatch_ratio=0.0,
                details=f"DEFUSE 3 requires baseline NIHSS >= 6 (Current NIHSS: {nihss})."
            )

        if premorbid_mrs > 2:
            return DEFUSE3Evaluation(
                met=False,
                actual_core_ml=core_volume_ml,
                hypoperfusion_vol_ml=hypoperfusion_vol_ml,
                mismatch_vol_ml=max(0.0, hypoperfusion_vol_ml - core_volume_ml),
                mismatch_ratio=0.0,
                details=f"Pre-stroke modified Rankin Scale (mRS) {premorbid_mrs} > 2 violates functional independence inclusion."
            )

        if core_volume_ml >= 70.0:
            return DEFUSE3Evaluation(
                met=False,
                actual_core_ml=core_volume_ml,
                hypoperfusion_vol_ml=hypoperfusion_vol_ml,
                mismatch_vol_ml=max(0.0, hypoperfusion_vol_ml - core_volume_ml),
                mismatch_ratio=hypoperfusion_vol_ml / core_volume_ml if core_volume_ml > 0 else 0.0,
                details=f"Ischemic core volume {core_volume_ml:.1f} mL exceeds the 70 mL ceiling."
            )

        penumbra_ml = max(0.0, hypoperfusion_vol_ml - core_volume_ml)
        ratio = (hypoperfusion_vol_ml / core_volume_ml) if core_volume_ml > 0 else (999.0 if hypoperfusion_vol_ml > 0 else 1.0)

        if penumbra_ml < 15.0:
            return DEFUSE3Evaluation(
                met=False,
                actual_core_ml=core_volume_ml,
                hypoperfusion_vol_ml=hypoperfusion_vol_ml,
                mismatch_vol_ml=penumbra_ml,
                mismatch_ratio=ratio,
                details=f"Absolute mismatch volume {penumbra_ml:.1f} mL is below the required 15 mL penumbra threshold."
            )

        if ratio < 1.8:
            return DEFUSE3Evaluation(
                met=False,
                actual_core_ml=core_volume_ml,
                hypoperfusion_vol_ml=hypoperfusion_vol_ml,
                mismatch_vol_ml=penumbra_ml,
                mismatch_ratio=ratio,
                details=f"Mismatch ratio {ratio:.2f} is below the 1.8 threshold (Tmax > 6s vol / Core vol)."
            )

        return DEFUSE3Evaluation(
            met=True,
            actual_core_ml=core_volume_ml,
            hypoperfusion_vol_ml=hypoperfusion_vol_ml,
            mismatch_vol_ml=penumbra_ml,
            mismatch_ratio=ratio,
            details=f"DEFUSE 3 criteria fulfilled: Core {core_volume_ml:.1f} mL (<70 mL), Penumbra {penumbra_ml:.1f} mL (>=15 mL), Ratio {ratio:.2f} (>=1.8)."
        )

    @classmethod
    def evaluate_evt_candidacy(
        cls,
        time_since_lkn_hours: float,
        age: int,
        nihss: int,
        premorbid_mrs: int,
        occlusion: OcclusionSite,
        aspects_score: int,
        core_volume_ml: float = 0.0,
        hypoperfusion_vol_ml: float = 0.0,
        intracranial_hemorrhage: bool = False
    ) -> EVTTriageDecision:
        """
        Comprehensive multi-window EVT triage combining Early Window (0-6h) AHA/ASA Level 1A
        and Extended Window (6-24h) DAWN/DEFUSE 3 criteria, including SELECT2/ANGEL-ASPECT considerations.
        """
        contraindications = []
        recommendations = []

        if intracranial_hemorrhage:
            contraindications.append("Acute intracranial hemorrhage present on non-contrast CT.")
            return EVTTriageDecision(
                evt_indicated=False,
                level_of_evidence="Contraindicated",
                trial_paradigm="Hemorrhage Preclusion",
                target_vessel=occlusion,
                aspects_score=aspects_score,
                core_volume_ml=core_volume_ml,
                penumbra_volume_ml=0.0,
                mismatch_ratio=0.0,
                contraindications=contraindications,
                urgent_recommendations=["Immediate neurosurgical / neurocritical consultation for hemorrhage management."]
            )

        if occlusion == OcclusionSite.NO_LVO:
            contraindications.append("No large vessel occlusion (LVO) detected on CTA/MRA.")
            return EVTTriageDecision(
                evt_indicated=False,
                level_of_evidence="Class III: No Benefit",
                trial_paradigm="No Target Vessel",
                target_vessel=occlusion,
                aspects_score=aspects_score,
                core_volume_ml=core_volume_ml,
                penumbra_volume_ml=0.0,
                mismatch_ratio=0.0,
                contraindications=contraindications,
                urgent_recommendations=["Optimize medical management, secondary stroke prevention, telemetry monitoring."]
            )

        penumbra_ml = max(0.0, hypoperfusion_vol_ml - core_volume_ml)
        ratio = (hypoperfusion_vol_ml / core_volume_ml) if core_volume_ml > 0 else (999.0 if hypoperfusion_vol_ml > 0 else 0.0)

        # -------------------------------------------------------------
        # 1. EARLY WINDOW (0.0 to 6.0 HOURS)
        # -------------------------------------------------------------
        if time_since_lkn_hours <= 6.0:
            is_lvo_standard = occlusion in [OcclusionSite.ICA_TERMINUS, OcclusionSite.ICA_CERVICAL, OcclusionSite.MCA_M1]
            is_m2_or_basilar = occlusion in [OcclusionSite.MCA_M2_DOMINANT, OcclusionSite.BASILAR_ARTERY]

            if is_lvo_standard:
                if aspects_score >= 6 and premorbid_mrs <= 1 and nihss >= 6:
                    recommendations.append("EMERGENCY ENDOVASCULAR THROMBECTOMY ACTIVATION: AHA/ASA Class I, Level A indication.")
                    recommendations.append("Immediate transport to Angio Suite; do not delay EVT to assess response to IV thrombolysis.")
                    recommendations.append("Target door-to-groin puncture < 60 minutes (or < 90 minutes for transfer).")
                    return EVTTriageDecision(
                        evt_indicated=True,
                        level_of_evidence="Class I, Level A (AHA/ASA 2019/2023 Early Window)",
                        trial_paradigm="HERMES Meta-analysis / Standard 6h Window",
                        target_vessel=occlusion,
                        aspects_score=aspects_score,
                        core_volume_ml=core_volume_ml,
                        penumbra_volume_ml=penumbra_ml,
                        mismatch_ratio=ratio,
                        contraindications=[],
                        urgent_recommendations=recommendations
                    )
                elif aspects_score in [3, 4, 5]:
                    # Large core trial evidence (SELECT2, ANGEL-ASPECT, RESCUE-JAPAN TENSION)
                    recommendations.append("Large Ischemic Core EVT Candidate (ASPECTS 3-5): Supported by SELECT2 / ANGEL-ASPECT trials (Class IIa).")
                    recommendations.append("Counsel family on functional improvement vs increased risk of symptomatic ICH.")
                    return EVTTriageDecision(
                        evt_indicated=True,
                        level_of_evidence="Class IIa, Level B-R (SELECT2 / ANGEL-ASPECT Large Core Criteria)",
                        trial_paradigm="Large Core Infarction Window (ASPECTS 3-5)",
                        target_vessel=occlusion,
                        aspects_score=aspects_score,
                        core_volume_ml=core_volume_ml,
                        penumbra_volume_ml=penumbra_ml,
                        mismatch_ratio=ratio,
                        contraindications=[],
                        urgent_recommendations=recommendations
                    )
                else:
                    contraindications.append(f"Severely extensive completed infarction (ASPECTS {aspects_score} < 3). High malignant reperfusion hemorrhage risk.")
                    return EVTTriageDecision(
                        evt_indicated=False,
                        level_of_evidence="Class III: Potential Harm (ASPECTS < 3)",
                        trial_paradigm="Established Malignant Infarction",
                        target_vessel=occlusion,
                        aspects_score=aspects_score,
                        core_volume_ml=core_volume_ml,
                        penumbra_volume_ml=penumbra_ml,
                        mismatch_ratio=ratio,
                        contraindications=contraindications,
                        urgent_recommendations=["Admit to Neuro-ICU; initiate hyperosmolar therapy and emergent hemicraniectomy protocol surveillance."]
                    )
            elif is_m2_or_basilar:
                recommendations.append(f"EVT Reasonable for {occlusion.value}: AHA/ASA Class IIb (M2) or Class IIa (Basilar Artery BAOCHE/ATTENTION).")
                return EVTTriageDecision(
                    evt_indicated=True,
                    level_of_evidence="Class IIa/IIb, Level B-R (ATTENTION / BAOCHE / Non-M1 Consensus)",
                    trial_paradigm="Non-M1 / Vertebrobasilar Thrombectomy",
                    target_vessel=occlusion,
                    aspects_score=aspects_score,
                    core_volume_ml=core_volume_ml,
                    penumbra_volume_ml=penumbra_ml,
                    mismatch_ratio=ratio,
                    contraindications=[],
                    urgent_recommendations=recommendations
                )

        # -------------------------------------------------------------
        # 2. EXTENDED WINDOW (6.0 to 16.0 HOURS)
        # -------------------------------------------------------------
        if 6.0 < time_since_lkn_hours <= 16.0:
            dawn_eval = cls.evaluate_dawn_trial_criteria(age=age, nihss=nihss, core_volume_ml=core_volume_ml)
            defuse3_eval = cls.evaluate_defuse3_trial_criteria(
                nihss=nihss,
                premorbid_mrs=premorbid_mrs,
                core_volume_ml=core_volume_ml,
                hypoperfusion_vol_ml=hypoperfusion_vol_ml,
                occlusion=occlusion
            )

            if dawn_eval.met or defuse3_eval.met:
                rationale_list = []
                if dawn_eval.met:
                    rationale_list.append(dawn_eval.details)
                if defuse3_eval.met:
                    rationale_list.append(defuse3_eval.details)

                recommendations.append("EXTENDED WINDOW EVT CANDIDATE (6-16h): Meets Level 1A criteria.")
                recommendations.extend(rationale_list)
                recommendations.append("Proceed to rapid groin puncture; preserve penumbral tissue.")

                trial_name = "DAWN & DEFUSE 3 Combined" if (dawn_eval.met and defuse3_eval.met) else ("DAWN Protocol" if dawn_eval.met else "DEFUSE 3 Protocol")

                return EVTTriageDecision(
                    evt_indicated=True,
                    level_of_evidence="Class I, Level A (AHA/ASA Extended Window Guideline)",
                    trial_paradigm=trial_name,
                    target_vessel=occlusion,
                    aspects_score=aspects_score,
                    core_volume_ml=core_volume_ml,
                    penumbra_volume_ml=penumbra_ml,
                    mismatch_ratio=ratio,
                    contraindications=[],
                    urgent_recommendations=recommendations
                )
            else:
                contraindications.append(f"Does not satisfy DAWN criteria ({dawn_eval.details}) nor DEFUSE 3 criteria ({defuse3_eval.details}).")
                return EVTTriageDecision(
                    evt_indicated=False,
                    level_of_evidence="Class III: Lack of Mismatch",
                    trial_paradigm="Perfusion Mismatch Exhausted (6-16h)",
                    target_vessel=occlusion,
                    aspects_score=aspects_score,
                    core_volume_ml=core_volume_ml,
                    penumbra_volume_ml=penumbra_ml,
                    mismatch_ratio=ratio,
                    contraindications=contraindications,
                    urgent_recommendations=["Intensive neurocritical medical management, perfusion support, and ICP monitoring."]
                )

        # -------------------------------------------------------------
        # 3. LATE EXTENDED WINDOW (16.0 to 24.0 HOURS)
        # -------------------------------------------------------------
        if 16.0 < time_since_lkn_hours <= 24.0:
            dawn_eval = cls.evaluate_dawn_trial_criteria(age=age, nihss=nihss, core_volume_ml=core_volume_ml)
            if dawn_eval.met and occlusion in [OcclusionSite.ICA_TERMINUS, OcclusionSite.ICA_CERVICAL, OcclusionSite.MCA_M1]:
                recommendations.append("LATE EXTENDED WINDOW EVT CANDIDATE (16-24h): Meets DAWN Class I, Level A criteria.")
                recommendations.append(dawn_eval.details)
                recommendations.append("Urgent neuro-intervention transfer.")
                return EVTTriageDecision(
                    evt_indicated=True,
                    level_of_evidence="Class I, Level A (DAWN Extended 24-Hour Window)",
                    trial_paradigm="DAWN Clinical-Core Mismatch",
                    target_vessel=occlusion,
                    aspects_score=aspects_score,
                    core_volume_ml=core_volume_ml,
                    penumbra_volume_ml=penumbra_ml,
                    mismatch_ratio=ratio,
                    contraindications=[],
                    urgent_recommendations=recommendations
                )
            else:
                contraindications.append(f"Patient beyond 16h window fails DAWN eligibility: {dawn_eval.details}")
                return EVTTriageDecision(
                    evt_indicated=False,
                    level_of_evidence="Class III: Beyond Validated Trial Criteria",
                    trial_paradigm="Late Window Non-Mismatch",
                    target_vessel=occlusion,
                    aspects_score=aspects_score,
                    core_volume_ml=core_volume_ml,
                    penumbra_volume_ml=penumbra_ml,
                    mismatch_ratio=ratio,
                    contraindications=contraindications,
                    urgent_recommendations=["Supportive neuro-ICU care; monitor for swelling and midline shift."]
                )

        # Beyond 24 hours
        contraindications.append(f"Time from LKN ({time_since_lkn_hours:.1f}h) exceeds the 24.0-hour window.")
        return EVTTriageDecision(
            evt_indicated=False,
            level_of_evidence="Class III: Unproven Benefit / Harm",
            trial_paradigm="Beyond 24-Hour Window",
            target_vessel=occlusion,
            aspects_score=aspects_score,
            core_volume_ml=core_volume_ml,
            penumbra_volume_ml=penumbra_ml,
            mismatch_ratio=ratio,
            contraindications=contraindications,
            urgent_recommendations=["Secondary prevention, antiplatelet therapy, vascular imaging workup, and rehabilitation."]
        )

    @classmethod
    def titrate_post_revascularization_hemodynamics(
        cls,
        tici_grade: TICIGrade,
        current_sbp: int,
        current_dbp: int,
        received_iv_thrombolysis: bool = False
    ) -> PostEVTHemodynamics:
        """
        Determines post-procedural hemodynamic targets based on modified TICI reperfusion score.
        - Successful reperfusion (mTICI 2b, 2c, 3): Strict blood pressure control (SBP < 140 or < 160 mmHg)
          to prevent reperfusion injury, hyperperfusion syndrome, and catastrophic hemorrhagic transformation.
        - Incomplete / Failed reperfusion (mTICI 0, 1, 2a): Permissive hypertension (SBP < 180/105 mmHg)
          to drive leptomeningeal collateral flow through the hypoperfused penumbra.
        """
        successful = tici_grade in [TICIGrade.GRADE_2B, TICIGrade.GRADE_2C, TICIGrade.GRADE_3]

        if successful:
            target_sbp = "120 - 140 mmHg (Strict Normotension)"
            target_dbp = "< 90 mmHg"
            permissive = False
            rationale = (
                f"{tici_grade.value} achieved. Full vascular bed restored. Strict blood pressure control "
                "is vital to mitigate reperfusion injury, capillary breakthrough, and hemorrhagic transformation (PH2)."
            )
            antihypertensives = [
                "Nicardipine IV continuous infusion: start at 5 mg/hr, titrate by 2.5 mg/hr q5-15 min (max 15 mg/hr).",
                "Clevidipine IV emulsion: start at 1-2 mg/hr, double dose q90s until target reached (max 32 mg/hr).",
                "Labetalol IV bolus: 10-20 mg IV over 1-2 min; repeat or double q10 min (max 300 mg)."
            ]
        else:
            target_sbp = "140 - 180 mmHg (Permissive Collateral Drive)"
            target_dbp = "< 105 mmHg"
            permissive = True
            rationale = (
                f"{tici_grade.value} indicates sub-optimal or absent recanalization. Leptomeningeal collateral "
                "perfusion must be sustained by permissive hypertension. Avoid aggressive blood pressure lowering unless SBP > 180 mmHg (or > 185/110 if IVT given)."
            )
            antihypertensives = [
                "Hold antihypertensives unless SBP > 180 mmHg or DBP > 105 mmHg.",
                "If SBP > 180 mmHg, gently titrate Nicardipine 2.5 - 5 mg/hr to maintain SBP in 150-170 mmHg band.",
                "Avoid precipitous BP drops (> 20% drop within 1 hour is strongly contraindicated)."
            ]

        monitoring = (
            "Blood pressure monitoring frequency: Every 15 minutes for 2 hours, "
            "then every 30 minutes for 6 hours, then every 1 hour for 16 hours (Total 24h Neuro-ICU protocol)."
        )

        return PostEVTHemodynamics(
            tici_grade=tici_grade,
            successful_reperfusion=successful,
            target_sbp_range=target_sbp,
            target_dbp_ceiling=target_dbp,
            permissive_hypertension_allowed=permissive,
            rationale=rationale,
            recommended_antihypertensives=antihypertensives,
            monitoring_frequency=monitoring
        )

    @classmethod
    def screen_malignant_edema_and_hemicraniectomy(
        cls,
        age: int,
        baseline_aspects: int,
        core_volume_ml: float,
        midline_shift_mm: float,
        nihss_current: int,
        gcs_motor_score: int,
        pupillary_asymmetry: bool = False
    ) -> Dict[str, str]:
        """
        Screens for malignant middle cerebral artery (MMCA) infarction syndrome and evaluates
        eligibility for early decompressive hemicraniectomy (DECIMAL, DESTINY, HAMLET criteria).
        """
        high_risk_edema = (
            baseline_aspects <= 5 or
            core_volume_ml >= 82.0 or
            midline_shift_mm >= 5.0 or
            nihss_current >= 20 or
            pupillary_asymmetry
        )

        hemicraniectomy_candidate = False
        urgency = "Standard ICU Monitoring"

        if age <= 60 and (core_volume_ml >= 82.0 or baseline_aspects <= 5 or midline_shift_mm >= 4.0):
            hemicraniectomy_candidate = True
            urgency = "URGENT SURGICAL WINDOW (< 48 HOURS)"
        elif 60 < age <= 80 and (midline_shift_mm >= 5.0 or pupillary_asymmetry):
            hemicraniectomy_candidate = True
            urgency = "CONSIDER DECOMPRESSIVE SURGERY (DESTINY II Criteria)"

        action = (
            "EMERGENT NEUROSURGERY CONSULTATION: Patient meets high-risk criteria for malignant MCA infarction. "
            "Decompressive hemicraniectomy within 48 hours significantly reduces mortality (NNT=2) and improves mRS <= 3."
            if hemicraniectomy_candidate else
            "Continue serial pupillometry, GCS tracking, and repeat NCCT at 24 hours post-EVT."
        )

        return {
            "high_risk_edema": "YES" if high_risk_edema else "NO",
            "hemicraniectomy_indicated": "YES" if hemicraniectomy_candidate else "NO",
            "urgency_tier": urgency,
            "midline_shift_status": f"{midline_shift_mm:.1f} mm shift" + (" (CRITICAL >= 5 mm)" if midline_shift_mm >= 5.0 else ""),
            "action_plan": action
        }


# =====================================================================
# EMBEDDED VERIFICATION UNIT TESTS
# =====================================================================

class TestAcuteStrokeEVTEngine(unittest.TestCase):
    def test_aspects_calculation(self):
        # 3 infarcted regions: Caudate, Lentiform, Insular ribbon -> ASPECTS 7
        infarcts = [
            ASPECTSLocation.CAUDATE,
            ASPECTSLocation.LENTIFORM,
            ASPECTSLocation.INSULAR_RIBBON
        ]
        score, deducted = AcuteStrokeEVTEngine.calculate_aspects(infarcts)
        self.assertEqual(score, 7)
        self.assertEqual(len(deducted), 3)

        # 0 regions -> ASPECTS 10
        score10, _ = AcuteStrokeEVTEngine.calculate_aspects([])
        self.assertEqual(score10, 10)

        # All 10 regions -> ASPECTS 0
        all_10 = list(ASPECTSLocation)
        score0, _ = AcuteStrokeEVTEngine.calculate_aspects(all_10)
        self.assertEqual(score0, 0)

    def test_thrombolysis_screening(self):
        # Eligible candidate within 3 hours, TNK preference
        res = AcuteStrokeEVTEngine.screen_intravenous_thrombolysis(
            time_since_lkn_hours=2.5,
            weight_kg=70.0,
            current_sbp=160,
            current_dbp=95,
            prefer_tenecteplase=True
        )
        self.assertTrue(res.eligible)
        self.assertEqual(res.agent, ThrombolysisAgent.TENECTEPLASE)
        self.assertIn("17.5 mg", res.recommended_dose)
        self.assertFalse(res.bp_management_required)

        # Contraindication: INR 2.1 and Head CT Hemorrhage
        res_contra = AcuteStrokeEVTEngine.screen_intravenous_thrombolysis(
            time_since_lkn_hours=1.0,
            weight_kg=80.0,
            current_sbp=170,
            current_dbp=90,
            inr=2.1,
            head_ct_hemorrhage=True
        )
        self.assertFalse(res_contra.eligible)
        self.assertEqual(len(res_contra.contraindications), 2)

    def test_dawn_trial_criteria(self):
        # Group A: Age 82, NIHSS 14, Core 15 mL -> Met
        eval_a = AcuteStrokeEVTEngine.evaluate_dawn_trial_criteria(age=82, nihss=14, core_volume_ml=15.0)
        self.assertTrue(eval_a.met)
        self.assertIn("Group A", eval_a.group)

        # Group A failed: Core 25 mL (> 21 mL ceiling)
        eval_a_fail = AcuteStrokeEVTEngine.evaluate_dawn_trial_criteria(age=82, nihss=14, core_volume_ml=25.0)
        self.assertFalse(eval_a_fail.met)

        # Group B: Age 65, NIHSS 12, Core 28 mL -> Met
        eval_b = AcuteStrokeEVTEngine.evaluate_dawn_trial_criteria(age=65, nihss=12, core_volume_ml=28.0)
        self.assertTrue(eval_b.met)
        self.assertIn("Group B", eval_b.group)

        # Group C: Age 58, NIHSS 22, Core 45 mL -> Met
        eval_c = AcuteStrokeEVTEngine.evaluate_dawn_trial_criteria(age=58, nihss=22, core_volume_ml=45.0)
        self.assertTrue(eval_c.met)
        self.assertIn("Group C", eval_c.group)

    def test_defuse3_trial_criteria(self):
        # Eligible DEFUSE 3: Core 25 mL, Hypoperfusion 90 mL (Mismatch: 65 mL, Ratio: 3.6), NIHSS 15, MCA-M1
        eval_def = AcuteStrokeEVTEngine.evaluate_defuse3_trial_criteria(
            nihss=15,
            premorbid_mrs=0,
            core_volume_ml=25.0,
            hypoperfusion_vol_ml=90.0,
            occlusion=OcclusionSite.MCA_M1
        )
        self.assertTrue(eval_def.met)
        self.assertAlmostEqual(eval_def.mismatch_vol_ml, 65.0)
        self.assertAlmostEqual(eval_def.mismatch_ratio, 3.6)

        # Ineligible DEFUSE 3: Core 75 mL (>= 70 mL ceiling)
        eval_fail_core = AcuteStrokeEVTEngine.evaluate_defuse3_trial_criteria(
            nihss=15,
            premorbid_mrs=0,
            core_volume_ml=75.0,
            hypoperfusion_vol_ml=110.0,
            occlusion=OcclusionSite.MCA_M1
        )
        self.assertFalse(eval_fail_core.met)

    def test_early_window_evt_triage(self):
        # 3.5 hours, NIHSS 18, ASPECTS 8, MCA-M1 -> Class I, Level A
        triage = AcuteStrokeEVTEngine.evaluate_evt_candidacy(
            time_since_lkn_hours=3.5,
            age=68,
            nihss=18,
            premorbid_mrs=0,
            occlusion=OcclusionSite.MCA_M1,
            aspects_score=8
        )
        self.assertTrue(triage.evt_indicated)
        self.assertIn("Class I, Level A", triage.level_of_evidence)

    def test_extended_window_evt_triage(self):
        # 12.0 hours, NIHSS 16, Age 72, MCA-M1, Core 20 mL, Hypoperfusion 80 mL -> Meets DEFUSE 3 & DAWN
        triage_ext = AcuteStrokeEVTEngine.evaluate_evt_candidacy(
            time_since_lkn_hours=12.0,
            age=72,
            nihss=16,
            premorbid_mrs=1,
            occlusion=OcclusionSite.MCA_M1,
            aspects_score=7,
            core_volume_ml=20.0,
            hypoperfusion_vol_ml=80.0
        )
        self.assertTrue(triage_ext.evt_indicated)
        self.assertIn("Class I, Level A", triage_ext.level_of_evidence)

    def test_hemodynamic_titration(self):
        # Successful reperfusion TICI 2b -> Strict control
        hemo_success = AcuteStrokeEVTEngine.titrate_post_revascularization_hemodynamics(
            tici_grade=TICIGrade.GRADE_2B,
            current_sbp=165,
            current_dbp=92
        )
        self.assertTrue(hemo_success.successful_reperfusion)
        self.assertFalse(hemo_success.permissive_hypertension_allowed)
        self.assertIn("Strict Normotension", hemo_success.target_sbp_range)

        # Failed reperfusion TICI 1 -> Permissive hypertension
        hemo_failed = AcuteStrokeEVTEngine.titrate_post_revascularization_hemodynamics(
            tici_grade=TICIGrade.GRADE_1,
            current_sbp=165,
            current_dbp=92
        )
        self.assertFalse(hemo_failed.successful_reperfusion)
        self.assertTrue(hemo_failed.permissive_hypertension_allowed)
        self.assertIn("Permissive Collateral Drive", hemo_failed.target_sbp_range)

    def test_malignant_edema_screening(self):
        screen = AcuteStrokeEVTEngine.screen_malignant_edema_and_hemicraniectomy(
            age=52,
            baseline_aspects=4,
            core_volume_ml=95.0,
            midline_shift_mm=6.2,
            nihss_current=22,
            gcs_motor_score=4,
            pupillary_asymmetry=True
        )
        self.assertEqual(screen["high_risk_edema"], "YES")
        self.assertEqual(screen["hemicraniectomy_indicated"], "YES")
        self.assertIn("URGENT SURGICAL WINDOW", screen["urgency_tier"])


if __name__ == "__main__":
    unittest.main()

Clinical Case Studies & CDS Verification Walkthrough

Case 1: Early Window (3.0 Hours) Right MCA-M1 Occlusion with High ASPECTS

Case 2: Wake-Up Stroke (13.5 Hours from LKN) Meeting DEFUSE 3 & DAWN

Case 3: Post-Thrombectomy Revascularization Titration (mTICI 2b vs mTICI 1)


Edge Deployment & Automated Verification Gate

To execute the offline test suite and verify deterministic clinical logic on local clinical servers or air-gapped container runtimes:

# Verify unit tests directly with standard library Python
python -m unittest _cookbooks/neurocritical-care-acute-ischemic-stroke-evt-dawn-defuse3-engine.md
Verified Offline Clinical Architecture

Clinical Execution Complete

Explore peer algorithms across acute neurology, critical care, and cardiology.

📖 All 418 Cookbooks Explore 737 Assets →
CRITICAL CARE / ICU
Septic Shock Sepsis-3 SOFA & Surviving Sepsis Bundle Engine

Automated 6-organ SOFA scoring, 30 mL/kg fluid resuscitation, and multi-tier vasopressor escalation.

NEUROLOGY / STROKE
Stroke EVT DAWN & DEFUSE 3 Perfusion Mismatch Engine

10-point ASPECTS score, CT perfusion core/penumbra ratio, and post-revascularization TICI hemodynamics.

CARDIOLOGY / RESUSCITATION
Post-Cardiac Arrest TTM2 & Neuroprognostication

Targeted Temperature Management (37.5°C ceiling), SSEP, and multi-modal neurological recovery staging.

OpenPHR AI Student Fellowship

Build Publication-Ready Clinical AI with Penn & MIT Mentors

Work on open-source medical foundation models, DICOM/FHIR architectures, and clinical CDS engines.

Apply for Fellowship →