Cookbook 329: Offline Clinical Pediatric Gastroenterology Biliary Atresia, Stool Color Card & Kasai Engine

This cookbook details how to deploy a localized, containerized pediatric gastroenterology, hepatology, and neonatal cholestasis decision-support engine for newborn nurseries, pediatric outpatient clinics, and children’s surgical centers to ingest total and fractionated serum bilirubin measurements, infant stool colorimetry readings, high-frequency hepatobiliary ultrasound telemetry, and hepatobiliary scintigraphy findings, evaluate NASPGHAN / ESPGHAN Neonatal Cholestasis Screening Thresholds ($\text{Direct/Conjugated Bilirubin} > 1.0\text{ mg/dL}$), classify infant stool pigmentation using Stool Color Card ($\text{SCC}$) Digital Colorimetry (Acholic Colors 1–3 vs Normal Colors 4–7), detect the High-Frequency Ultrasound Triangular Cord Sign ($\text{TC} > 3.4\text{ mm}$) and Gallbladder Ghost Triad, and enforce the Kasai Hepatoportoenterostomy ($\text{HPE}$) Golden Window ($\le 45 - 60\text{ days of life}$) to maximize native liver survival without external cloud API reliance.


1. Clinical Background & Neonatal Cholestasis Architecture

Biliary Atresia ($\text{BA}$) is a progressive, fibro-obliterative cholangiopathy of the intrahepatic and extrahepatic biliary tree affecting $1\text{ in } 10,000 - 18,000$ live births. It is the most common cause of neonatal cholestasis and the leading indication for pediatric liver transplantation:


2. Pipeline & Workflow Architecture

[Infant Telemetry: Age, Total/Direct Bilirubin, Stool Colorimetry, Ultrasound, GGT]
                                         │
                                         ▼
      [Cholestasis Screener: Direct Bilirubin > 1.0 mg/dL (NASPGHAN / ESPGHAN)]
                                         │
                                         ▼
   [Stool Color Card Vision Classifier: Acholic (Colors 1-3) vs Normal (Colors 4-7)]
                                         │
                                         ▼
   [US Diagnostic Engine: Triangular Cord > 3.4 mm + Gallbladder Ghost Triad]
                                         │
                                         ▼
   [Kasai Golden Window Urgency Calculator: <=45d (Optimal) to >90d (Cirrhosis/Transplant)]
                                         │
                                         ▼
   [Post-Kasai Regimen: TMP-SMX Prophylaxis + UDCA Choleretic + ADEK Vitamin Sentinel]

3. Environment & Prerequisites

Install required scientific Python and pediatric hepatology modeling packages:

pip install numpy scipy pandas torch torchvision matplotlib

4. Complete Offline Python / PyTorch Implementation

"""
Cookbook 329: Offline Pediatric Gastroenterology Biliary Atresia, Stool Card & Kasai 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 InfantCholestasisTelemetry:
    patient_id: str
    age_days: int = 38 # Infant age in days (Golden window <= 45d)
    gestational_age_weeks: float = 39.0 # Term infant
    # Bilirubin Fractionation Telemetry
    total_bilirubin_mg_dl: float = 8.6 # mg/dL
    direct_conjugated_bilirubin_mg_dl: float = 4.2 # mg/dL (> 1.0 = Pathologic Cholestasis)
    # Stool Colorimetry & Card Telemetry
    stool_color_card_reported_score: int = 2 # 1-3 = Acholic (White/Clay/Pale), 4-7 = Pigmented
    stool_rgb_color: Tuple[int, int, int] = (225, 222, 205) # Pale grayish-beige acholic stool
    # Ultrasound Telemetry
    ultrasound_triangular_cord_thickness_mm: float = 4.1 # mm (> 3.4 mm = Pathognomonic TC sign)
    ultrasound_gallbladder_length_mm: float = 11.0 # mm (< 15 mm = Diminutive/Ghost GB)
    ultrasound_gallbladder_mucosal_irregularity: bool = True
    ultrasound_hepatic_artery_diameter_mm: float = 1.8 # mm (> 1.5 mm = Hypertrophy)
    # Serum Hepatic Biochemistry Telemetry
    serum_ggt_iu_l: float = 680.0 # IU/L (Elevated GGT > 300 supports biliary etiology)
    serum_alt_iu_l: float = 145.0 # IU/L
    serum_ast_iu_l: float = 190.0 # IU/L
    # Scintigraphy / HIDA Telemetry
    hida_scan_performed: bool = True
    hida_phenobarbital_priming_completed: bool = True # 5 mg/kg/day x 5 days
    hida_24h_bowel_excretion_detected: bool = False # False = Complete biliary obstruction

@dataclass
class BiliaryAtresiaEvaluationReport:
    patient_id: str
    cholestasis_screening_result: str
    stool_color_card_interpretation: str
    ultrasound_triad_status: str
    kasai_golden_window_urgency: str
    diagnostic_workup_orders: List[str]
    post_kasai_management_protocol: List[str]
    safety_sentinels: List[str]
    clinical_naspghan_espghan_directive: str

class BiliaryAtresiaDecisionEngine:
    """
    Offline clinical engine for NASPGHAN neonatal cholestasis screening, Stool Color Card classification,
    high-frequency ultrasound triangular cord evaluation, and Kasai Portoenterostomy timing optimization.
    """

    def screen_neonatal_cholestasis(self, d: InfantCholestasisTelemetry) -> Tuple[bool, str]:
        # NASPGHAN/ESPGHAN threshold: Direct Bilirubin > 1.0 mg/dL defines cholestasis
        is_cholestatic = d.direct_conjugated_bilirubin_mg_dl > 1.0
        pct_direct = (d.direct_conjugated_bilirubin_mg_dl / max(d.total_bilirubin_mg_dl, 0.1)) * 100.0

        if is_cholestatic:
            desc = f"🚨 CONFIRMED NEONATAL CHOLESTASIS: Direct Bilirubin {d.direct_conjugated_bilirubin_mg_dl:.2f} mg/dL (> 1.0 mg/dL cutoff, {pct_direct:.1f}% of Total {d.total_bilirubin_mg_dl:.1f} mg/dL). Immediate structural & metabolic evaluation indicated."
        else:
            desc = f"Normal direct bilirubin ({d.direct_conjugated_bilirubin_mg_dl:.2f} mg/dL <= 1.0 mg/dL cutoff)."

        return is_cholestatic, desc

    def evaluate_stool_colorimetry(self, card_score: int, rgb: Tuple[int, int, int]) -> Tuple[str, str]:
        # Colors 1-3 are acholic/pathologic; 4-7 are pigmented/normal
        r, g, b = rgb
        # Acholic stools have high lightness and low green/brown saturation
        brightness = (r + g + b) / 3.0

        if card_score <= 3 or brightness > 200:
            tier = "ACHOLIC / HYPOCHOLIC STOOL (Pathologic - Card Colors 1-3)"
            desc = f"Stool color score {card_score} (RGB {rgb}) indicates lack of biliary excretion into intestinal tract. High suspicion for extrahepatic biliary obstruction / Biliary Atresia."
        else:
            tier = "PIGMENTED STOOL (Normal - Card Colors 4-7)"
            desc = f"Stool color score {card_score} indicates presence of intestinal stercobilin bile pigment."

        return tier, desc

    def evaluate_ultrasound_triad(self, d: InfantCholestasisTelemetry) -> Tuple[bool, str, List[str]]:
        features = []
        is_tc_positive = d.ultrasound_triangular_cord_thickness_mm >= 3.4
        is_gb_ghost = d.ultrasound_gallbladder_length_mm < 15.0 or d.ultrasound_gallbladder_mucosal_irregularity
        is_ha_hypertrophy = d.ultrasound_hepatic_artery_diameter_mm >= 1.5

        if is_tc_positive:
            features.append(f"• Triangular Cord Sign POSITIVE: Fibrous ductal thickness {d.ultrasound_triangular_cord_thickness_mm:.1f} mm (>= 3.4 mm pathognomonic threshold).")
        if is_gb_ghost:
            features.append(f"• Gallbladder Ghost Triad POSITIVE: Atretic gallbladder length {d.ultrasound_gallbladder_length_mm:.1f} mm (< 15 mm) with irregular mucosal wall.")
        if is_ha_hypertrophy:
            features.append(f"• Hepatic Artery Hypertrophy: Diameter {d.ultrasound_hepatic_artery_diameter_mm:.1f} mm (>= 1.5 mm).")

        ba_likely = is_tc_positive or (is_gb_ghost and is_ha_hypertrophy)
        summary = "HIGH ULTRASONIC LIKELIHOOD OF BILIARY ATRESIA (Positive TC sign / GB Ghost Triad)" if ba_likely else "Inconclusive / Negative Ultrasound for classic BA signs"

        return ba_likely, summary, features

    def calculate_kasai_urgency(self, age_days: int) -> Tuple[str, str]:
        if age_days <= 45:
            urgency = "OPTIMAL GOLDEN WINDOW (Age <= 45 Days)"
            prognosis = f"Infant is {age_days} days old. Immediate Kasai Hepatoportoenterostomy within this window delivers >70-85% 5-year native liver survival."
        elif age_days <= 60:
            urgency = "FAVORABLE WINDOW (Age 46 - 60 Days)"
            prognosis = f"Infant is {age_days} days old. Urgent Kasai indicated; expected 5-year native liver survival ~50-60%."
        elif age_days <= 90:
            urgency = "GUARDED WINDOW (Age 61 - 90 Days)"
            prognosis = f"Infant is {age_days} days old. Progressive portal fibrosis established; native liver survival drops to 25-35%. Expedite surgery without delay."
        else:
            urgency = "LATE DIAGNOSIS (Age > 90 Days)"
            prognosis = f"Infant is {age_days} days old. Established biliary cirrhosis; native liver survival <20%. Perform intraoperative cholangiogram/Kasai and initiate parallel pediatric liver transplant evaluation."

        return urgency, prognosis

    def generate_management_plans(self, d: InfantCholestasisTelemetry, urgency: str) -> Tuple[List[str], List[str], List[str]]:
        workup = []
        post_op = []
        sentinels = []

        # Diagnostic Workup Orders
        workup.append("1. STAT PEDIATRIC SURGICAL & GI CONSULTATION: Emergency evaluation for exploratory laparotomy and intraoperative cholangiogram (IOC).")
        workup.append("2. FRACTIONATED BILIRUBIN & COAGULATION PANEL: STAT PT/INR, PTT, Fibrinogen, AST, ALT, GGT, and Total/Direct Bilirubin.")
        if not d.hida_scan_performed:
            workup.append("3. HIDA SCINTIGRAPHY (Optional/Adjunctive): Initiate Phenobarbital priming 5 mg/kg/day PO x 5 days prior to Tc-99m mebrofenin scan if IOC delayed.")

        # Post-Kasai Protocol
        post_op.append("1. ASCENDING CHOLANGITIS PROPHYLAXIS: Trimethoprim-Sulfamethoxazole (TMP-SMX) 2-4 mg/kg/day PO daily for 6-12 months post-operatively.")
        post_op.append("2. CHOLERETIC THERAPY: Ursodeoxycholic Acid (UDCA) 15-20 mg/kg/day PO divided BID to promote bile flow.")
        post_op.append("3. FAT-SOLUBLE VITAMIN SUPPLEMENTATION: Daily water-soluble ADEKs formulation with supplemental Vitamin K (1-2 mg PO weekly) to prevent coagulopathy.")
        post_op.append("4. POST-OP CORTICOSTEROID PROTOCOL: Oral Prednisolone (2 mg/kg/day tapering over 4-6 weeks) to reduce ductal anastomotic inflammation.")

        # Safety Sentinels
        if d.age_days > 45:
            sentinels.append(f"KASAI TIMING DELAY SENTINEL: Patient is {d.age_days} days old. Every 10-day surgical delay significantly decreases native liver survival and accelerates biliary cirrhosis. Fast-track operating room scheduling!")

        sentinels.append("VITAMIN K DEFICIENCY BLEEDING (VKDB) SENTINEL: Severe cholestasis impairs fat-soluble Vitamin K absorption, risking fatal intracranial hemorrhage. Administer Parenteral Vitamin K1 1.0 - 2.0 mg IV/SC prior to any invasive procedures.")

        return workup, post_op, sentinels

    def evaluate_case(self, data: InfantCholestasisTelemetry) -> BiliaryAtresiaEvaluationReport:
        is_chol, chol_desc = self.screen_neonatal_cholestasis(data)
        stool_tier, stool_desc = self.evaluate_stool_colorimetry(data.stool_color_card_reported_score, data.stool_rgb_color)
        ba_us, us_desc, us_features = self.evaluate_ultrasound_triad(data)
        urgency_tier, urgency_desc = self.calculate_kasai_urgency(data.age_days)
        workup_plan, postop_plan, sentinels = self.generate_management_plans(data, urgency_tier)

        directives = []
        directives.append(f"CHOLESTASIS: {chol_desc}")
        directives.append(f"STOOL CARD: {stool_tier}.")
        directives.append(f"ULTRASOUND: {us_desc}.")
        directives.append(f"KASAI TIMING: {urgency_tier} -> {urgency_desc}")

        return BiliaryAtresiaEvaluationReport(
            patient_id=data.patient_id,
            cholestasis_screening_result=chol_desc,
            stool_color_card_interpretation=stool_desc,
            ultrasound_triad_status=us_desc + " | " + " ".join(us_features),
            kasai_golden_window_urgency=urgency_tier + " (" + urgency_desc + ")",
            diagnostic_workup_orders=workup_plan,
            post_kasai_management_protocol=postop_plan,
            safety_sentinels=sentinels,
            clinical_naspghan_espghan_directive=" ".join(directives)
        )

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

    print("=" * 80)
    print("OpenPHR Clinical Pediatric Gastroenterology Biliary Atresia & Kasai Engine")
    print("=" * 80)

    # Test Case 1: 38-day-old infant presenting with persistent jaundice and pale clay stool.
    # Total Bilirubin: 8.6 mg/dL, Direct Bilirubin: 4.2 mg/dL (> 1.0 mg/dL cholestasis).
    # Stool Card Score: 2 (Acholic). Ultrasound: TC Sign 4.1 mm (> 3.4 mm) + Gallbladder 11 mm.
    # Kasai Golden Window: 38 Days (Optimal <= 45d window, >70-85% native liver survival)!
    ba1 = InfantCholestasisTelemetry(
        patient_id="PEDS-GI-5501",
        age_days=38,
        total_bilirubin_mg_dl=8.6,
        direct_conjugated_bilirubin_mg_dl=4.2,
        stool_color_card_reported_score=2,
        stool_rgb_color=(225, 222, 205),
        ultrasound_triangular_cord_thickness_mm=4.1,
        ultrasound_gallbladder_length_mm=11.0,
        ultrasound_gallbladder_mucosal_irregularity=True,
        ultrasound_hepatic_artery_diameter_mm=1.8,
        serum_ggt_iu_l=680.0,
        hida_scan_performed=True,
        hida_phenobarbital_priming_completed=True,
        hida_24h_bowel_excretion_detected=False
    )

    rep1 = engine.evaluate_case(ba1)

    print(f"\n[Patient {rep1.patient_id} - Neonatal Cholestasis Assessment]")
    print(f"Cholestasis Status:\n  {rep1.cholestasis_screening_result}")
    print(f"\nStool Colorimetry:\n  {rep1.stool_color_card_interpretation}")
    print(f"\nUltrasound Findings:\n  {rep1.ultrasound_triad_status}")
    print(f"\nKasai Surgical Urgency:\n  {rep1.kasai_golden_window_urgency}")
    print("\nDiagnostic Workup Orders:")
    for w in rep1.diagnostic_workup_orders:
        print(f"  {w}")
    print("\nPost-Kasai Medical Regimen:")
    for p in rep1.post_kasai_management_protocol:
        print(f"  {p}")
    if rep1.safety_sentinels:
        print("\nSafety Sentinels:")
        for s in rep1.safety_sentinels:
            print(f"  🚨 {s}")
    print(f"\nNASPGHAN / ESPGHAN Consensus Directive:\n{rep1.clinical_naspghan_espghan_directive}")

5. Clinical Verification & Guideline Conformance


6. References