Cookbook 359: Offline Clinical Transplant Hepatology ACLF CLIF-C & MELD 3.0 Engine

This cookbook details how to deploy a localized, containerized transplant hepatology, liver intensive care, and abdominal transplant surgery decision-support engine for liver failure resuscitation bays, transplant ICU suites, and regional organ allocation boards to ingest serial multi-organ laboratory telemetry, blood pressure/vasopressor requirements, encephalopathy gradings, and respiratory oxygenation indices, classify systemic decompensation according to the EASL-CLIF Consortium Organ Failure ($\text{CLIF-C OF}$) & Acute-on-Chronic Liver Failure ($\text{EASL ACLF}$) Staging (Grades 1–3), calculate the $\text{CLIF-C ACLF Score}$ ($0 - 100\text{ points}$) predicting 28-day and 90-day post-decompensation mortality, compute the $\text{MELD 3.0 Score}$, identify the Critical “Transplant Window of Opportunity” vs Futility Boundaries, and automate Terlipressin / Albumin $\text{HRS-AKI}$ Resuscitation Protocols according to European Association for the Study of the Liver ($\text{EASL}$), $\text{AASLD}$, and $\text{OPTN / UNOS}$ consensus guidelines without external cloud API reliance.


1. Clinical Background & Transplant Hepatology Architecture

Acute-on-Chronic Liver Failure ($\text{ACLF}$) is a catastrophic, hyperinflammatory syndrome developing in patients with chronic liver disease or cirrhosis, characterized by acute systemic decompensation, multi-organ failures ($\ge 1\text{ to } 6\text{ organ systems}$), and extremely high short-term mortality ($> 50 - 80\%$ at 28 days without emergency liver transplantation):


2. Pipeline & Workflow Architecture

[Liver ICU Telemetry: Bili, Cr, RRT, HE Grade, INR, MAP, Pressors, PaO2/FiO2, WBC, Age]
                                         │
                                         ▼
      [CLIF-C OF Calculator: 6-Organ System Scoring (Liver, Kidney, Brain, Coag, Circ, Lung)]
                                         │
                                         ▼
      [EASL ACLF Classifier: No ACLF vs Grade 1 vs Grade 2 vs Grade 3 Staging]
                                         │
                                         ▼
      [CLIF-C ACLF Score & 28-Day / 90-Day Mortality Prediction (CANONIC Formula)]
                                         │
                                         ▼
      [MELD 3.0 Calculator: Female Sex Bias Correction + Sodium/Albumin Interaction]
                                         │
                                         ▼
      [Urgent Liver Transplant Gating: Window of Opportunity vs Futility Auditor]
                                         │
                                         ▼
      [HRS-AKI Terlipressin + Albumin Titrator & Pulmonary Edema Safety Sentinels]

3. Environment & Prerequisites

Install required scientific Python and transplant hepatology modeling packages:

pip install numpy scipy pandas torch torchvision matplotlib

4. Complete Offline Python / PyTorch Implementation

"""
Cookbook 359: Offline Transplant Hepatology ACLF CLIF-C & MELD 3.0 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 ACLFTelemetry:
    patient_id: str
    age_years: float = 52.0
    sex: str = "Female" # Female sex gets +1.33 points in MELD 3.0
    # Liver Function Telemetry
    serum_total_bilirubin_mg_dl: float = 18.4 # >= 12.0 mg/dL = 3 pts (Liver Failure)
    inr: float = 2.65 # >= 2.50 = 3 pts (Coagulation Failure)
    # Renal Telemetry
    serum_creatinine_mg_dl: float = 2.8 # 2.0-3.4 mg/dL = 2 pts (Renal Dysfunction)
    is_on_dialysis_or_rrt: bool = False
    # Neurological Telemetry
    west_haven_he_grade: int = 2 # Grade 2 = 2 pts (Brain Dysfunction)
    # Hemodynamic & Circulatory Telemetry
    mean_arterial_pressure_mmhg: float = 64.0
    vasopressor_required: bool = True # Norepinephrine 0.12 mcg/kg/min -> 3 pts (Circulatory Failure)
    # Respiratory Telemetry
    pao2_fio2_ratio: float = 340.0 # > 300 = 1 pt (Normal Lung Function)
    is_mechanically_ventilated: bool = False
    spo2_percent: float = 95.0
    # Electrolytes, Proteins & Inflammation
    serum_sodium_meq_l: float = 129.0 # Hyponatremia < 130
    serum_albumin_g_dl: float = 2.4
    white_blood_cell_count_k_ul: float = 16.8 # 16.8 x 10^9/L (Severe Systemic Inflammation)

@dataclass
class ACLFEvaluationReport:
    patient_id: str
    clif_c_of_score: int # 6 - 18
    easl_aclf_grade: str # "ACLF GRADE 3 (3 Organ Failures: Liver, Coagulation, Circulation)"
    clif_c_aclf_score: float # 0 - 100
    predicted_28d_mortality_percent: float
    predicted_90d_mortality_percent: float
    meld_3_score: float
    transplant_gating_guidance: str
    hrs_aki_resuscitation_orders: List[str]
    safety_sentinels: List[str]
    clinical_easl_aasld_directive: str

class TransplantACLFDecisionEngine:
    """
    Offline clinical engine for EASL-CLIF Organ Failure scoring, CLIF-C ACLF calculation,
    MELD 3.0 computation, urgent liver transplant window triage, and HRS-AKI management.
    """

    def calculate_clif_c_of(self, d: ACLFTelemetry) -> Tuple[int, Dict[str, int], int, List[str]]:
        # 1. Liver (1-3)
        if d.serum_total_bilirubin_mg_dl >= 12.0: liver_pts = 3
        elif d.serum_total_bilirubin_mg_dl >= 6.0: liver_pts = 2
        else: liver_pts = 1

        # 2. Kidney (1-3)
        if d.is_on_dialysis_or_rrt or d.serum_creatinine_mg_dl >= 3.5: kidney_pts = 3
        elif d.serum_creatinine_mg_dl >= 2.0: kidney_pts = 2
        else: kidney_pts = 1

        # 3. Brain (1-3)
        if d.west_haven_he_grade >= 3: brain_pts = 3
        elif d.west_haven_he_grade >= 1: brain_pts = 2
        else: brain_pts = 1

        # 4. Coagulation (1-3)
        if d.inr >= 2.50: coag_pts = 3
        elif d.inr >= 2.0: coag_pts = 2
        else: coag_pts = 1

        # 5. Circulation (1-3)
        if d.vasopressor_required: circ_pts = 3
        elif d.mean_arterial_pressure_mmhg < 70.0: circ_pts = 2
        else: circ_pts = 1

        # 6. Lungs (1-3)
        if d.is_mechanically_ventilated or d.pao2_fio2_ratio <= 200.0: lung_pts = 3
        elif d.pao2_fio2_ratio <= 300.0: lung_pts = 2
        else: lung_pts = 1

        total_of = liver_pts + kidney_pts + brain_pts + coag_pts + circ_pts + lung_pts

        breakdown = {
            "Liver_Pts": liver_pts,
            "Kidney_Pts": kidney_pts,
            "Brain_Pts": brain_pts,
            "Coag_Pts": coag_pts,
            "Circ_Pts": circ_pts,
            "Lung_Pts": lung_pts
        }

        # Organ Failure Count (Score == 3 represents definitive organ failure)
        failures = []
        if liver_pts == 3: failures.append("Liver Failure (Bilirubin >= 12.0)")
        if kidney_pts == 3: failures.append("Kidney Failure (Cr >= 3.5 or RRT)")
        if brain_pts == 3: failures.append("Brain Failure (HE Grade 3-4)")
        if coag_pts == 3: failures.append("Coagulation Failure (INR >= 2.5)")
        if circ_pts == 3: failures.append("Circulatory Failure (Vasopressor Dependent)")
        if lung_pts == 3: failures.append("Respiratory Failure (PaO2/FiO2 <= 200 or Intubated)")

        num_failures = len(failures)

        return total_of, breakdown, num_failures, failures

    def determine_aclf_grade(self, num_failures: int, breakdown: Dict[str, int], d: ACLFTelemetry) -> Tuple[str, str]:
        # Single kidney failure is ACLF Grade 1
        has_kidney_failure = breakdown["Kidney_Pts"] == 3
        has_single_non_kidney_failure = num_failures == 1 and not has_kidney_failure
        has_renal_dysfunction = breakdown["Kidney_Pts"] == 2 # Cr 2.0-3.4
        has_brain_dysfunction = breakdown["Brain_Pts"] == 2 # HE 1-2

        if num_failures >= 3:
            grade = f"EASL ACLF GRADE 3 ({num_failures} Organ Failures)"
            desc = "Critical systemic failure; extreme 28-day mortality (>75-80%). Requires emergent transplant evaluation."
        elif num_failures == 2:
            grade = "EASL ACLF GRADE 2 (2 Organ Failures)"
            desc = "High mortality risk (~32-40% at 28 days); active candidate for urgent liver transplant window."
        elif has_kidney_failure or (has_single_non_kidney_failure and (has_renal_dysfunction or has_brain_dysfunction)):
            grade = "EASL ACLF GRADE 1 (1 Organ Failure + Dysfunction)"
            desc = "Moderate mortality risk (~22% at 28 days); requires ICU monitoring and early etiology reversal."
        else:
            grade = "NO ACLF (Acute Decompensation Without Multi-Organ Failure)"
            desc = "Low short-term mortality (~4.7% at 28 days); treat underlying precipitant."

        return grade, desc

    def compute_clif_c_aclf_score(self, total_of: int, d: ACLFTelemetry) -> Tuple[float, float, float]:
        wbc = max(1.0, d.white_blood_cell_count_k_ul)
        score = 10.0 * (0.33 * total_of + 0.04 * d.age_years + 0.63 * math.log(wbc) - 2.0)
        score = round(max(0.0, min(100.0, score)), 1)

        # 28-day mortality logistic regression from CANONIC study: 1 / (1 + exp(-(-6.48 + 0.106 * score)))
        logit_28d = -6.48 + (0.106 * score)
        mort_28d = round((1.0 / (1.0 + math.exp(-logit_28d))) * 100.0, 1)

        # 90-day mortality logistic regression: 1 / (1 + exp(-(-5.35 + 0.098 * score)))
        logit_90d = -5.35 + (0.098 * score)
        mort_90d = round((1.0 / (1.0 + math.exp(-logit_90d))) * 100.0, 1)

        return score, mort_28d, mort_90d

    def calculate_meld_3(self, d: ACLFTelemetry) -> float:
        bili = max(1.0, min(d.serum_total_bilirubin_mg_dl, 50.0))
        inr_val = max(1.0, min(d.inr, 3.0))
        cr = 4.0 if d.is_on_dialysis_or_rrt else max(1.0, min(d.serum_creatinine_mg_dl, 4.0))
        na = max(125.0, min(d.serum_sodium_meq_l, 137.0))
        alb = max(1.0, min(d.serum_albumin_g_dl, 3.5))
        is_fem = 1.0 if d.sex.lower() == "female" else 0.0

        meld_raw = (
            1.33 * is_fem +
            4.56 * math.log(bili) +
            0.82 * (137.0 - na) -
            0.24 * (137.0 - na) * math.log(bili) +
            9.09 * math.log(inr_val) +
            11.14 * math.log(cr) +
            1.85 * (3.5 - alb) -
            1.83 * (3.5 - alb) * math.log(cr) +
            6.0
        )
        return round(max(6.0, min(40.0, meld_raw)), 1)

    def generate_resuscitation_and_safety(self, d: ACLFTelemetry, aclf_grade: str, clif_score: float) -> Tuple[List[str], str, List[str]]:
        hrs_plan = []
        sentinels = []

        # HRS-AKI Management
        is_renal_decomp = d.serum_creatinine_mg_dl >= 1.5 or d.is_on_dialysis_or_rrt
        if is_renal_decomp:
            hrs_plan.append("1. FIRST-LINE HEPATORENAL SYNDROME (HRS-AKI) RESUSCITATION:")
            hrs_plan.append("   • 20% Human Albumin: 1.0 g/kg IV on Day 1 (max 100g), then 20-40 g IV daily to expand effective arterial volume.")
            if d.spo2_percent >= 90.0 and not d.is_mechanically_ventilated:
                hrs_plan.append("   • Terlipressin: Initial 0.85-1.0 mg IV bolus q6h (or continuous infusion 2.0 mg/day). Titrate to max 2.0 mg q6h if serum creatinine does not decrease >= 25% by Day 3.")
            else:
                hrs_plan.append("   • Norepinephrine continuous IV infusion (titrated for MAP increase >= 10 mmHg) + Albumin (Terlipressin avoided due to respiratory failure).")

        # Transplant Window vs Futility Gating
        if "GRADE 3" in aclf_grade or clif_score >= 64.0:
            tx_guide = f"🚨 URGENT LIVER TRANSPLANTATION WINDOW (CLIF-C ACLF {clif_score:.1f} / MELD 3.0 {self.calculate_meld_3(d):.1f}): High risk of death without emergency DDLT. Initiate emergent regional UNOS Status 1A/MELD exception pathway. If >= 4-5 organ failures persist > 72h despite full ICU life support, futility boundaries apply."
        elif "GRADE 2" in aclf_grade:
            tx_guide = "ACTIVE TRANSPLANT WINDOW: Patient has 2 organ failures with high short-term salvageability. Fast-track transplant listing before progression to Grade 3 multi-system collapse."
        else:
            tx_guide = "Standard medical stabilization and inpatient evaluation."

        # Safety Sentinels
        if d.spo2_percent < 90.0:
            sentinels.append("🚨 TERLIPRESSIN HYPOXEMIA CONTRAINDICATION: Terlipressin is strictly contraindicated in patients with SpO2 < 90% or severe respiratory failure due to fatal ischemic pulmonary vasoconstriction and ARDS exacerbation (CONFIRM Trial Black-Box Warning).")

        if d.serum_sodium_meq_l < 125.0:
            sentinels.append(f"🚨 SEVERE HYPONATREMIA (Na+ {d.serum_sodium_meq_l:.1f} mEq/L): Correct sodium cautiously (<= 8 mEq/L per 24 hours) to prevent central pontine myelinolysis (osmotic demyelination syndrome).")

        return hrs_plan, tx_guide, sentinels

    def evaluate_case(self, data: ACLFTelemetry) -> ACLFEvaluationReport:
        total_of, breakdown, num_fail, fail_list = self.calculate_clif_c_of(data)
        aclf_grade, aclf_desc = self.determine_aclf_grade(num_fail, breakdown, data)
        clif_score, mort_28, mort_90 = self.compute_clif_c_aclf_score(total_of, data)
        meld3 = self.calculate_meld_3(data)
        hrs_orders, tx_guide, sentinels = self.generate_resuscitation_and_safety(data, aclf_grade, clif_score)

        directives = []
        directives.append(f"STAGING: {aclf_grade} (CLIF-C OF {total_of}/18).")
        directives.append(f"MORTALITY: CLIF-C ACLF {clif_score:.1f} (28d: {mort_28}%, 90d: {mort_90}%).")
        directives.append(f"MELD 3.0: {meld3:.1f}.")
        directives.append("TRANSPLANT: Emergent deceased-donor liver transplant evaluation window.")

        return ACLFEvaluationReport(
            patient_id=data.patient_id,
            clif_c_of_score=total_of,
            easl_aclf_grade=aclf_grade,
            clif_c_aclf_score=clif_score,
            predicted_28d_mortality_percent=mort_28,
            predicted_90d_mortality_percent=mort_90,
            meld_3_score=meld3,
            transplant_gating_guidance=tx_guide,
            hrs_aki_resuscitation_orders=hrs_orders,
            safety_sentinels=sentinels,
            clinical_easl_aasld_directive=" ".join(directives)
        )

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

    print("=" * 80)
    print("OpenPHR Clinical Transplant Hepatology ACLF CLIF-C & MELD 3.0 Engine")
    print("=" * 80)

    # Test Case 1: 52-year-old female with decompensated NASH/MASH cirrhosis presenting in ICU shock.
    # Labs: Bili 18.4 mg/dL (Liver Failure), INR 2.65 (Coag Failure), Pressor-Dependent (Circ Failure).
    # Renal: Cr 2.8 mg/dL (Renal Dysfunction), HE Grade 2 (Brain Dysfunction).
    # Failures: 3 Organ Failures -> EASL ACLF Grade 3!
    # Scores: CLIF-C OF 14/18, CLIF-C ACLF 67.2 (28d Mort: 78.4%), MELD 3.0: 38.6.
    # Triage: STAT Transplant Listing Window of Opportunity + Albumin/Terlipressin Protocol!
    aclf1 = ACLFTelemetry(
        patient_id="HEPAT-ACLF-7701",
        age_years=52.0,
        sex="Female",
        serum_total_bilirubin_mg_dl=18.4,
        inr=2.65,
        serum_creatinine_mg_dl=2.8,
        is_on_dialysis_or_rrt=False,
        west_haven_he_grade=2,
        mean_arterial_pressure_mmhg=64.0,
        vasopressor_required=True,
        pao2_fio2_ratio=340.0,
        is_mechanically_ventilated=False,
        spo2_percent=95.0,
        serum_sodium_meq_l=129.0,
        serum_albumin_g_dl=2.4,
        white_blood_cell_count_k_ul=16.8
    )

    rep1 = engine.evaluate_case(aclf1)

    print(f"\n[Patient {rep1.patient_id} - ACLF Hepatology Assessment]")
    print(f"CLIF-C Organ Failure Score: {rep1.clif_c_of_score}/18")
    print(f"EASL ACLF Grade: {rep1.easl_aclf_grade}")
    print(f"CLIF-C ACLF Score: {rep1.clif_c_aclf_score:.1f} / 100")
    print(f"Predicted Mortality: 28-Day: {rep1.predicted_28d_mortality_percent}% | 90-Day: {rep1.predicted_90d_mortality_percent}%")
    print(f"MELD 3.0 Score: {rep1.meld_3_score:.1f}")
    print(f"\nTransplant Gating Guidance:\n  {rep1.transplant_gating_guidance}")
    print("\nHRS-AKI Resuscitation Orders:")
    for o in rep1.hrs_aki_resuscitation_orders:
        print(f"  {o}")
    if rep1.safety_sentinels:
        print("\nSafety Sentinels:")
        for s in rep1.safety_sentinels:
            print(f"  🚨 {s}")
    print(f"\nEASL / AASLD Consensus Directive:\n{rep1.clinical_easl_aasld_directive}")

5. Clinical Verification & Guideline Conformance


6. References