Cookbook 319: Offline Clinical Pediatric Pulmonology BPD Jensen Staging & Echo Engine

This cookbook details how to deploy a localized, containerized pediatric pulmonology, neonatal intensive care ($\text{NICU}$), and pediatric cardiology decision-support engine for neonatal nurseries, infant pulmonary clinics, and pediatric critical care units to ingest respiratory support telemetry, delivered oxygen concentrations, and transthoracic echocardiography findings, stage Bronchopulmonary Dysplasia ($\text{BPD}$) at $36\text{ weeks}$ Postmenstrual Age ($\text{PMA}$) according to the 2021 Jensen / NICHD Consensus Criteria (Grades 1–3), quantify BPD-Associated Pulmonary Hypertension ($\text{BPD-PH}$) risk via Tricuspid Regurgitation Jet Velocity ($\text{TRJV}$) and septal flattening, and generate precision Dual Diuretic (HCTZ + Spironolactone), Inhaled Corticosteroid, and Sildenafil Pulmonary Vasodilator regimens according to ATS, AAP, and BPD Collaborative guidelines without external cloud API reliance.


1. Clinical Background & Jensen 2021 BPD Classification Architecture

Bronchopulmonary Dysplasia ($\text{BPD}$) is the most prevalent chronic respiratory disease of premature infants born at $<32\text{ weeks}$ gestation:


2. Pipeline & Workflow Architecture

[Infant Telemetry: Gestational Age, 36w PMA Support (Room Air, LFNC, CPAP, ETT), FiO2]
                                         │
                                         ▼
      [Jensen 2021 NICHD Staging Engine: No BPD vs Grade 1 vs Grade 2 vs Grade 3]
                                         │
                                         ▼
     [Echocardiographic BPD-PH Classifier: TRJV >= 2.8 m/s, Septal Bowing, ePASP]
                                         │
                                         ▼
     [Pharmacotherapy Gating: HCTZ + Spironolactone & Inhaled Budesonide Titration]
                                         │
                                         ▼
     [Sildenafil Vasodilator Protocol & Long-Term Tracheostomy/PFT Surveillance]

3. Environment & Prerequisites

Install required scientific Python and neonatal pulmonology modeling packages:

pip install numpy scipy pandas torch torchvision matplotlib

4. Complete Offline Python / PyTorch Implementation

"""
Cookbook 319: Offline Pediatric Pulmonology BPD Jensen Staging & Echo 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 InfantBPDTelemetry:
    patient_id: str
    gestational_age_weeks_at_birth: float # e.g. 26.2 weeks (< 32 weeks)
    current_postmenstrual_age_weeks: float # e.g. 36.0 weeks (Jensen staging milestone)
    birth_weight_grams: float # e.g. 780 g
    current_weight_kg: float # e.g. 2.15 kg
    # Respiratory Support Modality at 36 Weeks PMA
    respiratory_support_modality: str # "Room Air (No Support)", "Low-Flow Nasal Cannula (<= 2 L/min)", "Nasal CPAP / NIPPV / High-Flow (> 2 L/min)", "Invasive Mechanical Ventilation (ETT / Trach)"
    flow_rate_liters_per_min: float = 1.0 # For LFNC/HFNC
    fio2_fraction: float = 0.30 # e.g. 30% oxygen
    # Transthoracic Echocardiography (Echo) Parameters
    tricuspid_regurgitation_jet_velocity_ms: float = 3.2 # m/s (Normal < 2.5 m/s)
    estimated_right_atrial_pressure_mmhg: float = 5.0 # mmHg
    interventricular_septal_flattening_systole: bool = True # Flag for RV pressure overload >= 50% systemic
    right_ventricular_dilation_or_hypertrophy: bool = True
    pulmonary_vein_stenosis_ruled_out: bool = True # Critical before sildenafil!
    # Pulmonary & Systemic Status
    tachypnea_and_intercostal_retractions: bool = True
    chronic_lung_crackles_or_wheeze: bool = True
    serum_potassium_meq_l: float = 4.2

@dataclass
class BPDEvaluationReport:
    patient_id: str
    jensen_2021_bpd_stage: str # "No BPD", "Grade 1 BPD", "Grade 2 BPD", "Grade 3 BPD"
    bpd_associated_pulmonary_hypertension_status: str # "No PH", "Borderline PH", "Confirmed Moderate-to-Severe BPD-PH"
    estimated_pasp_mmhg: float
    diuretic_and_airway_pharmacotherapy_orders: List[str]
    pulmonary_vasodilator_orders: List[str]
    respiratory_and_monitoring_sentinels: List[str]
    clinical_ats_aap_directive: str

class PediatricBPDDecisionEngine:
    """
    Offline clinical engine for Jensen 2021 BPD severity staging,
    echocardiographic pulmonary hypertension risk stratification,
    and multimodal pharmacotherapy protocol generation.
    """

    def stage_jensen_bpd(self, d: InfantBPDTelemetry) -> str:
        mod = d.respiratory_support_modality.lower()

        if "invasive" in mod or "ett" in mod or "trach" in mod:
            return "Grade 3 BPD (Invasive Mechanical Ventilation at 36w PMA - Severe)"
        elif "cpap" in mod or "nippv" in mod or "high-flow" in mod or (d.flow_rate_liters_per_min > 2.0 and "nasal" in mod):
            return "Grade 2 BPD (Non-Invasive Positive Pressure / HFNC at 36w PMA - Moderate)"
        elif "low-flow" in mod or ("nasal" in mod and d.flow_rate_liters_per_min <= 2.0) or d.fio2_fraction > 0.21:
            return "Grade 1 BPD (Low-Flow Nasal Cannula <= 2 L/min at 36w PMA - Mild)"
        else:
            return "No BPD (Room Air with No Respiratory Support at 36w PMA)"

    def evaluate_pulmonary_hypertension(self, d: InfantBPDTelemetry) -> Tuple[str, float]:
        # Modified Bernoulli Equation: Delta P = 4 * v^2 -> PASP = 4*(TRJV^2) + RAP
        v = d.tricuspid_regurgitation_jet_velocity_ms
        if v > 0:
            epasp = round(4.0 * (v ** 2) + d.estimated_right_atrial_pressure_mmhg, 1)
        else:
            epasp = 0.0

        if v >= 2.8 or epasp >= 35.0 or d.interventricular_septal_flattening_systole:
            if v >= 3.4 or epasp >= 50.0:
                ph_status = "Confirmed Severe BPD-Associated Pulmonary Hypertension"
            else:
                ph_status = "Confirmed Moderate BPD-Associated Pulmonary Hypertension"
        elif v >= 2.5 or epasp >= 28.0:
            ph_status = "Borderline / Mild Pulmonary Hypertension Risk"
        else:
            ph_status = "No Echocardiographic Evidence of Pulmonary Hypertension"

        return ph_status, epasp

    def generate_pharmacotherapy_orders(self, d: InfantBPDTelemetry, bpd_stage: str, ph_status: str, epasp: float) -> Tuple[List[str], List[str]]:
        rx_orders = []
        vaso_orders = []

        w = d.current_weight_kg

        # 1. Inhaled Corticosteroid for Airway Reactivity (Grades 1-3)
        if "Grade" in bpd_stage:
            rx_orders.append("1. INHALED CORTICOSTEROID: Nebulized Budesonide 0.25 mg (0.5 mg if Grade 3) inhalation BID via in-line ventilator circuit or infant aerochamber mask.")

        # 2. Dual Diuretic Therapy for Chronic Pulmonary Edema
        if d.tachypnea_and_intercostal_retractions and "Grade" in bpd_stage:
            hctz_dose = round(1.0 * w, 2)
            spiro_dose = round(1.0 * w, 2)
            rx_orders.append(f"2. DUAL DIURETIC THERAPY (Weight = {w:.2f} kg):")
            rx_orders.append(f"   • Hydrochlorothiazide (HCTZ): {hctz_dose} mg PO BID (1.0 mg/kg/dose).")
            rx_orders.append(f"   • Spironolactone: {spiro_dose} mg PO BID (1.0 mg/kg/dose).")
            rx_orders.append("   • Electrolyte Monitoring: Serial BMP every 1-2 weeks to prevent hypokalemic alkalosis and hyponatremia.")

        # 3. Pulmonary Vasodilator Therapy for Confirmed BPD-PH
        if "Confirmed" in ph_status:
            sild_start = round(0.5 * w, 2)
            sild_target = round(1.5 * w, 2)
            vaso_orders.append(f"1. TARGETED PULMONARY VASODILATOR (Sildenafil PO):")
            vaso_orders.append(f"   • Initial Dose: Sildenafil {sild_start} mg PO TID (0.5 mg/kg/dose).")
            vaso_orders.append(f"   • Titration Target: Titrate weekly to target {sild_target} mg PO TID (1.5 mg/kg/dose) under pediatric cardiology supervision.")
            vaso_orders.append("   • Safety Check: Confirm absence of pulmonary vein stenosis or severe left heart dysfunction prior to initiation.")
        elif "Borderline" in ph_status:
            vaso_orders.append("1. CARDIOLOGY SURVEILLANCE: Repeat transthoracic echocardiogram in 4 weeks; optimize oxygenation (target SpO2 92-95%) to prevent hypoxic pulmonary vasoconstriction.")

        return rx_orders, vaso_orders

    def evaluate_case(self, data: InfantBPDTelemetry) -> BPDEvaluationReport:
        bpd_stage = self.stage_jensen_bpd(data)
        ph_status, epasp = self.evaluate_pulmonary_hypertension(data)
        rx_orders, vaso_orders = self.generate_pharmacotherapy_orders(data, bpd_stage, ph_status, epasp)

        sentinels = []
        if "Grade 3" in bpd_stage:
            sentinels.append("CRITICAL MORBIDITY ALERT (Grade 3 BPD): Highest risk tier for prolonged ventilator dependence and tracheostomy. Schedule multidisciplinary pediatric pulmonary, feeding, and physical therapy team consults.")
        if "Confirmed" in ph_status:
            sentinels.append(f"BPD-PH VASCULAR SENTINEL (TRJV {data.tricuspid_regurgitation_jet_velocity_ms} m/s | ePASP {epasp} mmHg): Maintain SpO2 target strictly between 92% - 96% to avoid reactive pulmonary hypertensive crises.")

        directives = []
        directives.append(f"JENSEN 2021 DIAGNOSIS: {bpd_stage}.")
        directives.append(f"CARDIOVASCULAR STATUS: {ph_status} (ePASP = {epasp} mmHg).")
        directives.append(f"MANAGEMENT: {'Inhaled Budesonide + Dual Diuretics (HCTZ/Spiro) + Sildenafil' if 'Confirmed' in ph_status else ('Inhaled Budesonide + Dual Diuretics' if 'Grade' in bpd_stage else 'Room Air Weaning / Routine Care')}.")

        return BPDEvaluationReport(
            patient_id=data.patient_id,
            jensen_2021_bpd_stage=bpd_stage,
            bpd_associated_pulmonary_hypertension_status=ph_status,
            estimated_pasp_mmhg=epasp,
            diuretic_and_airway_pharmacotherapy_orders=rx_orders,
            pulmonary_vasodilator_orders=vaso_orders,
            respiratory_and_monitoring_sentinels=sentinels,
            clinical_ats_aap_directive=" ".join(directives)
        )

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

    print("=" * 80)
    print("OpenPHR Clinical Pediatric Pulmonology BPD Jensen Staging & Echo Engine")
    print("=" * 80)

    # Test Case 1: Preterm infant born at 26.2 weeks, now at 36.0 weeks PMA (Weight 2.15 kg)
    # Support: Non-invasive CPAP + FiO2 30% -> Jensen Grade 2 BPD (Moderate)
    # Echo: TRJV = 3.2 m/s, ePASP = 46 mmHg + Interventricular septal systolic flattening -> Confirmed Moderate BPD-PH!
    # Management: Inhaled Budesonide + HCTZ (2.15 mg PO BID) + Spironolactone (2.15 mg PO BID) + Sildenafil (1.08 mg PO TID)!
    infant1 = InfantBPDTelemetry(
        patient_id="NICU-BPD-9104",
        gestational_age_weeks_at_birth=26.2,
        current_postmenstrual_age_weeks=36.0,
        birth_weight_grams=780.0,
        current_weight_kg=2.15,
        respiratory_support_modality="Nasal CPAP / NIPPV / High-Flow (> 2 L/min)",
        fio2_fraction=0.30,
        tricuspid_regurgitation_jet_velocity_ms=3.2,
        estimated_right_atrial_pressure_mmhg=5.0,
        interventricular_septal_flattening_systole=True,
        right_ventricular_dilation_or_hypertrophy=True,
        tachypnea_and_intercostal_retractions=True
    )

    rep1 = engine.evaluate_case(infant1)

    print(f"\n[Infant {rep1.patient_id} - BPD & Pulmonary Vascular Report]")
    print(f"Jensen 2021 Severity: {rep1.jensen_2021_bpd_stage}")
    print(f"Pulmonary Hypertension: {rep1.bpd_associated_pulmonary_hypertension_status} (ePASP = {rep1.estimated_pasp_mmhg} mmHg)")
    print("\nDiuretic & Airway Orders:")
    for d_ord in rep1.diuretic_and_airway_pharmacotherapy_orders:
        print(f"  {d_ord}")
    print("\nPulmonary Vasodilator Orders:")
    for v_ord in rep1.pulmonary_vasodilator_orders:
        print(f"  {v_ord}")
    print("\nCritical Clinical Sentinels:")
    for s in rep1.respiratory_and_monitoring_sentinels:
        print(f"  • {s}")
    print(f"\nATS / AAP Consensus Directive:\n{rep1.clinical_ats_aap_directive}")

    # Test Case 2: Infant on Room Air at 36w PMA -> No BPD!
    infant2 = InfantBPDTelemetry(
        patient_id="NICU-BPD-1042",
        gestational_age_weeks_at_birth=29.4,
        current_postmenstrual_age_weeks=36.0,
        birth_weight_grams=1150.0,
        current_weight_kg=2.45,
        respiratory_support_modality="Room Air (No Support)",
        fio2_fraction=0.21,
        tricuspid_regurgitation_jet_velocity_ms=1.8,
        tachypnea_and_intercostal_retractions=False
    )

    rep2 = engine.evaluate_case(infant2)
    print(f"\n[Infant {rep2.patient_id}] - Status: {rep2.jensen_2021_bpd_stage}")

5. Clinical Verification & Guideline Conformance


6. References