Cookbook 377: Offline Clinical Obstetrics & Maternal-Fetal Medicine Acute Postpartum Hemorrhage (PPH) CMQCC Staging, Obstetric Shock Index (OSI), Sequential Uterotonic Titrator & TXA / Bakri Balloon Tamponade Engine

Executive Clinical Overview

Obstetric Postpartum Hemorrhage (PPH) remains the single leading cause of preventable maternal mortality and acute severe maternal morbidity (SMM) across both high-income and low-to-middle-income nations. Historically, clinical estimation of blood loss (EBL) via visual inspection has been notoriously inaccurate, underestimating obstetric blood loss by $30\% - 50\%$, leading to delayed resuscitation, profound hypoperfusion, consumption coagulopathy, and preventable emergency peripartum hysterectomies.

Furthermore, normal physiologic maternal adaptations in pregnancy—specifically a $40\% - 50\%$ expansion in plasma and total blood volume—mask early hypovolemic shock. Decompensated maternal hypotension and bradycardia are catastrophic, late pre-terminal manifestations that appear only after more than $30\% - 40\%$ of circulating blood volume has been lost.

To combat preventable maternal deaths, major national and global consensus bodies—including the American College of Obstetricians and Gynecologists (ACOG), the California Maternal Quality Care Collaborative (CMQCC), the Society for Maternal-Fetal Medicine (SMFM), and the World Health Organization (WHO)—mandate three foundational clinical pillars:

  1. Gravimetric & Volumetric Quantitative Blood Loss (QBL): Direct continuous measurement via calibrated under-buttocks collection drapes and dry-weight gravimetric scale subtraction ($1\text{ g} = 1\text{ mL}$).
  2. The Obstetric Shock Index (OSI): Defined as $\text{Heart Rate} / \text{Systolic Blood Pressure}$. While normal pregnant baseline ranges from $0.7$ to $0.9$, an $\text{OSI} \ge 0.9$ flags impending occult hypovolemic collapse hours before overt hypotension develops ($\text{sensitivity} > 92\%$), gating immediate second-line interventions, cross-matching, and Massive Transfusion Protocol (MTP) standby.
  3. Rapid Multi-Modal Treatment Cascades: Immediate rapid-sequence uterotonic administration respecting rigid clinical contraindications (avoiding Methergine in hypertensive disorders; avoiding Carboprost in reactive airway disease), early antifibrinolytic therapy with Tranexamic Acid (TXA within 3 hours) per the international WOMAN Trial, mechanical uterine tamponade (Bakri balloon or vacuum-induced suction devices), and fibrinogen-targeted $1:1:1$ balanced transfusion.
+---------------------------------------------------------------------------------------------------------+
|                      ACUTE OBSTETRIC POSTPARTUM HEMORRHAGE (PPH) CASCADE                                |
+---------------------------------------------------------------------------------------------------------+
| 1. CONTINUOUS QUANTITATIVE BLOOD LOSS (QBL) & OCCULT SHOCK MONITORING                                  |
|    - Gravimetric dry-weight drape subtraction (1 g = 1 mL blood loss). Visual EBL is PROHIBITED.        |
|    - Obstetric Shock Index (OSI = HR / SBP):                                                            |
|      * Normal Pregnancy : 0.7 - 0.9                                                                     |
|      * Occult Shock     : >= 0.9  --> Immediate Stage 2 Escalation & Massive Transfusion Standby        |
|      * Severe Collapse  : >= 1.4  --> Emergency Obstetric MTP 1:1:1 Activation                         |
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 2. CMQCC POSTPARTUM HEMORRHAGE CLINICAL STAGING GATING                                                  |
|    - STAGE 1 (QBL >= 500 mL Vaginal / >= 1000 mL C-Section with Normal Vital Signs):                    |
|      * Fundal massage, 2 large-bore IVs (16/18G), Foley catheter, Oxytocin IV infusion (30-40 U/1000 mL)|
|    - STAGE 2 (QBL 1000 - 1500 mL OR Abnormal Vitals / OSI >= 0.9 with Continued Bleeding):              |
|      * Rapid Sequential Uterotonics: Methergine (IM), Carboprost (IM), Misoprostol (Buccal/Sublingual)  |
|      * Early Antifibrinolytic: Tranexamic Acid (TXA) 1g IV over 10 min within 3 hours (WOMAN Trial)     |
|      * Intrauterine Device: Bakri Balloon (300-500 mL saline) or Vacuum-Induced Tamponade (JADA)        |
|    - STAGE 3 (QBL > 1500 mL OR Persistent Vital Sign Instability OR Suspected DIC):                     |
|      * Emergency Obstetric MTP (1:1:1 PRBC : FFP : Platelets). Fibrinogen target >= 200 mg/dL (Cryo).   |
|      * Surgical Gating: B-Lynch compression sutures, uterine artery ligation, peripartum hysterectomy. |
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 3. PHARMACOLOGICAL CONTRAINDICATION SAFETY SENTINELS                                                    |
|    - Methergine (Methylergonovine): ABSOLUTELY CONTRAINDICATED in Preeclampsia, Chronic HTN, Raynaud's  |
|    - Carboprost (Hemabate / PGF2a): ABSOLUTELY CONTRAINDICATED in Active Asthma, Severe Bronchospasm   |
|    - TXA: Mandated <= 3 hours from delivery; efficacy significantly reduced if initiated after 3 hours. |
+---------------------------------------------------------------------------------------------------------+

Obstetric Shock Index & CMQCC Staging Criteria

1. The Obstetric Shock Index (OSI)

\(\text{OSI} = \frac{\text{Maternal Heart Rate (beats/min)}}{\text{Systolic Blood Pressure (mmHg)}}\)

Obstetric Shock Index (OSI) Hemodynamic Status Recommended Action
$< 0.9$ Physiologically Compensated Routine postpartum observation; continue first-line Oxytocin
$0.9 - 1.3$ Occult Hypovolemic Shock Escalate to CMQCC Stage 2: Alert Rapid Response Team, type and crossmatch 4 units PRBCs, initiate second-line uterotonics, give TXA.
$\ge 1.4$ Severe Decompensated Shock Escalate to CMQCC Stage 3: Emergency Obstetric MTP ($1:1:1$), prepare OR for surgical devascularization or hysterectomy.

2. CMQCC Staging Matrix

Stage Trigger Criteria Immediate Interventions
Stage 1 $\text{QBL} \ge 500\text{ mL}$ (vaginal) or $\ge 1000\text{ mL}$ (cesarean) with normal vitals 1. Fundal massage and explore for lower genital tract lacerations.
2. Ensure two large-bore IVs ($16\text{G}$ or $18\text{G}$).
3. Oxytocin $30 - 40\text{ units}$ in $1000\text{ mL}$ balanced crystalloid at $333\text{ mL/h}$.
4. Insert Foley catheter to decompress bladder and monitor hourly urine output.
5. Confirm type and screen on file.
Stage 2 Continued bleeding with $\text{QBL } 1000 - 1500\text{ mL}$ OR $\text{OSI} \ge 0.9$ OR abnormal vitals 1. Mobilize Obstetric Rapid Response Team (OB-RRT).
2. Administer sequential second-line uterotonics respecting contraindications.
3. Administer Tranexamic Acid (TXA) $1\text{ g IV}$ over 10 min (must be given within 3h).
4. Deploy intrauterine balloon tamponade (Bakri balloon inflated with $300 - 500\text{ mL}$ saline) or JADA suction.
5. Obtain stat labs: CBC, PT/INR, PTT, Fibrinogen, Type & Cross 2-4 units PRBCs.
Stage 3 $\text{QBL} > 1500\text{ mL}$ OR persistent hemodynamic instability OR clinical signs of DIC 1. Activate Obstetric Massive Transfusion Protocol (MTP): Transfuse $1:1:1$ ratio (PRBCs, FFP, Platelets).
2. Administer Cryoprecipitate if serum fibrinogen is $< 200\text{ mg/dL}$ ($10\text{ units}$ cryo raises fibrinogen by $\sim 50\text{ mg/dL}$).
3. Immediate mobilization to Operating Room for surgical intervention: B-Lynch uterine compression suture, uterine artery ligation, or emergent peripartum hysterectomy.
4. Correct hypothermia (target core temp $> 36^\circ\text{C}$), acidosis ($\text{pH} > 7.20$), and hypocalcemia (target ionized $\text{Ca}^{2+} > 1.1\text{ mmol/L}$ with IV calcium gluconate).

Pharmacological Uterotonic Regimens & Contraindication Sentinels

Uterine atony accounts for $70\% - 80\%$ of all postpartum hemorrhage episodes. Rapid pharmacological escalation must be conducted with absolute precision:

+---------------------------------------------------------------------------------------------------+
| DRUG                      | DOSE & ROUTE          | ONSET    | STRICT CLINICAL CONTRAINDICATION   |
+---------------------------------------------------------------------------------------------------+
| 1. Oxytocin (Pitocin)     | 30-40 U in 1000 mL IV | < 1 min  | Do NOT give undiluted IV bolus     |
|                           | infusion at 333 mL/h  |          | (causes profound hypotension/shock)|
+---------------------------------------------------------------------------------------------------+
| 2. Methylergonovine       | 0.2 mg IM             | 2-5 min  | PREECLAMPSIA, GESTATIONAL HTN,     |
|    (Methergine)           | (repeat q2-4h)        |          | CORONARY ARTERY DISEASE            |
+---------------------------------------------------------------------------------------------------+
| 3. Carboprost Tromethamine| 250 mcg IM or intra-  | 15-30 min| ACTIVE ASTHMA, REACTIVE AIRWAYS    |
|    (Hemabate / PGF2a)     | myometrial (q15-90min)|          | (causes severe bronchospasm)       |
+---------------------------------------------------------------------------------------------------+
| 4. Misoprostol (Cytotec)  | 800 mcg buccal or SL  | 10-15 min| Prior hypersensitivity to PGE1     |
+---------------------------------------------------------------------------------------------------+
| 5. Tranexamic Acid (TXA)  | 1.0 g IV over 10 min  | Immediate| Administration > 3 hours from      |
|                           | (repeat at 30 min)    |          | delivery (no benefit; venous VTE)  |
+---------------------------------------------------------------------------------------------------+

Production Python Implementation

"""
OpenPHR Cookbook 377: Offline Clinical Obstetrics & Maternal-Fetal Medicine
Acute Postpartum Hemorrhage (PPH) CMQCC Staging, Obstetric Shock Index (OSI),
Sequential Uterotonic Titrator & TXA / Bakri Balloon Tamponade Engine.

Compliant with:
- American College of Obstetricians and Gynecologists (ACOG) Practice Bulletin No. 183
- California Maternal Quality Care Collaborative (CMQCC) OB Hemorrhage Toolkit V3.0
- Society for Maternal-Fetal Medicine (SMFM) Clinical Practice Guidelines
- World Health Organization (WHO) Guidelines for the Prevention and Treatment of PPH
- The International WOMAN Trial (Lancet 2017)
"""

import sys
from typing import Dict, List, Optional, Tuple, Any
from dataclasses import dataclass, field

@dataclass
class DeliveryContext:
    delivery_type: str                      # "vaginal" or "cesarean"
    quantitative_blood_loss_ml: float       # Cumulative gravimetric/volumetric QBL
    hours_since_delivery: float             # Hours since delivery (critical for TXA 3h rule)

@dataclass
class MaternalHemodynamics:
    heart_rate_bpm: int                     # e.g., 115
    systolic_bp_mmhg: float                 # e.g., 90.0
    diastolic_bp_mmhg: float                # e.g., 55.0
    mean_arterial_pressure_mmhg: float      # e.g., 66.7
    oxygen_saturation_percent: float        # e.g., 96.0
    urine_output_ml_hr: float               # e.g., 20.0

@dataclass
class CoagulationProfile:
    fibrinogen_mg_dl: float                 # e.g., 170.0 (Normal pregnancy > 350-400 mg/dL)
    platelet_count_k_ul: float              # e.g., 85.0
    inr: float                              # e.g., 1.4
    ionized_calcium_mmol_l: float           # e.g., 0.95 (Normal 1.15-1.30 mmol/L)
    core_temp_celsius: float                # e.g., 35.8

@dataclass
class MedicalComorbidities:
    has_preeclampsia_or_gestational_htn: bool
    has_chronic_hypertension: bool
    has_active_asthma_or_bronchospasm: bool
    has_cardiac_disease: bool
    retained_placenta_suspected: bool
    suspected_genital_tract_lacerations: bool

class PostpartumHemorrhageEngine:
    """
    Comprehensive Clinical Decision Support Engine for Obstetric Postpartum Hemorrhage.
    """

    @staticmethod
    def calculate_obstetric_shock_index(hr: int, sbp: float) -> Dict[str, Any]:
        """
        Computes Obstetric Shock Index (OSI = HR / SBP) and stratifies occult shock risk.
        """
        if sbp <= 0:
            osi = 99.9
        else:
            osi = round(hr / sbp, 2)

        if osi < 0.9:
            status = "Physiologically Compensated"
            risk_level = "LOW"
            action = "Routine postpartum vital sign monitoring; continue scheduled oxytocin prophylaxis."
        elif osi < 1.4:
            status = "Occult Hypovolemic Shock"
            risk_level = "HIGH"
            action = "CRITICAL ALERT: Occult obstetric shock detected. Mandates Stage 2 escalation, blood bank type and crossmatch, and second-line uterotonic readiness."
        else:
            status = "Severe Decompensated Hypovolemic Shock"
            risk_level = "CRITICAL"
            action = "EMERGENCY ALERT: Severe cardiovascular decompensation. Immediately activate Obstetric Massive Transfusion Protocol (MTP 1:1:1) and surgical team."

        return {
            "obstetric_shock_index": osi,
            "maternal_status": status,
            "risk_level": risk_level,
            "hemodynamic_action": action
        }

    @classmethod
    def evaluate_cmqcc_stage(cls, deliv: DeliveryContext, hemo: MaternalHemodynamics, osi_val: float) -> Dict[str, Any]:
        """
        Evaluates CMQCC Hemorrhage Stage (Stage 1 to 3) based on QBL, vitals, and OSI.
        """
        qbl = deliv.quantitative_blood_loss_ml
        is_cesarean = deliv.delivery_type.lower() == "cesarean"
        stage_1_threshold = 1000.0 if is_cesarean else 500.0

        stage = 0
        stage_title = "Normal Postpartum Course"
        rationale = []

        if qbl >= 1500.0 or osi_val >= 1.4 or hemo.systolic_bp_mmhg < 80.0:
            stage = 3
            stage_title = "CMQCC Stage 3: Severe Hemorrhage & Impending Coagulopathy"
            rationale.append(f"QBL ({qbl:.0f} mL) >= 1500 mL or Severe Shock Index (OSI {osi_val:.2f}) indicates life-threatening hemorrhage.")
        elif qbl >= 1000.0 or osi_val >= 0.9 or hemo.heart_rate_bpm >= 110 or hemo.systolic_bp_mmhg <= 85.0:
            stage = 2
            stage_title = "CMQCC Stage 2: Continued Hemorrhage with Occult or Overt Instability"
            rationale.append(f"Continued bleeding (QBL {qbl:.0f} mL) or elevated Shock Index (OSI {osi_val:.2f}) requires rapid escalation.")
        elif qbl >= stage_1_threshold:
            stage = 1
            stage_title = "CMQCC Stage 1: Postpartum Bleeding Exceeding Expected Delivery Loss"
            rationale.append(f"QBL ({qbl:.0f} mL) exceeds standard threshold ({stage_1_threshold:.0f} mL) with preserved hemodynamics.")
        else:
            rationale.append("Blood loss within normal physiologic expected limits.")

        return {
            "cmqcc_stage": stage,
            "stage_title": stage_title,
            "rationale": rationale
        }

    @classmethod
    def titrate_pharmacotherapy_and_interventions(
        cls,
        stage: int,
        deliv: DeliveryContext,
        comorb: MedicalComorbidities,
        coag: Optional[CoagulationProfile] = None
    ) -> Dict[str, Any]:
        """
        Executes sequential uterotonic selection, contraindication screening, TXA gating, and tamponade recommendations.
        """
        uterotonics = []
        contraindications_flagged = []
        mechanical_interventions = []
        transfusion_orders = []

        # 1. First-Line: Oxytocin
        if stage >= 1:
            uterotonics.append({
                "agent": "Oxytocin (Pitocin)",
                "dose": "30 to 40 Units in 1000 mL Normal Saline or LR",
                "rate": "Infuse at 333 mL/hr (10 Units/hr) or rapid bolus if atony persists",
                "route": "Intravenous Infusion",
                "safety_note": "Do NOT administer rapid undiluted IV push (causes fatal peripheral vasodilation and hypotension)."
            })

        # 2. Second-Line Uterotonics (Stage 2 and 3)
        if stage >= 2:
            # Methergine check
            if comorb.has_preeclampsia_or_gestational_htn or comorb.has_chronic_hypertension:
                contraindications_flagged.append({
                    "drug": "Methylergonovine (Methergine)",
                    "status": "ABSOLUTELY CONTRAINDICATED",
                    "reason": "Maternal Hypertension / Preeclampsia (causes vasoconstriction and life-threatening hypertensive stroke / encephalopathy)."
                })
            else:
                uterotonics.append({
                    "agent": "Methylergonovine (Methergine)",
                    "dose": "0.2 mg IM (never IV)",
                    "frequency": "Repeat every 2 to 4 hours as needed (max 5 doses)",
                    "route": "Intramuscular",
                    "safety_note": "Contraindicated in hypertension."
                })

            # Carboprost (Hemabate) check
            if comorb.has_active_asthma_or_bronchospasm:
                contraindications_flagged.append({
                    "drug": "Carboprost Tromethamine (Hemabate / 15-methyl PGF2a)",
                    "status": "ABSOLUTELY CONTRAINDICATED",
                    "reason": "Active Asthma / Reactive Airway Disease (causes intense smooth muscle bronchoconstriction and fatal status asthmaticus)."
                })
            else:
                uterotonics.append({
                    "agent": "Carboprost Tromethamine (Hemabate)",
                    "dose": "250 mcg IM or intramyometrial",
                    "frequency": "Repeat every 15 to 90 minutes (max 8 doses / 2 mg)",
                    "route": "Intramuscular",
                    "safety_note": "Contraindicated in asthma."
                })

            # Misoprostol (Cytotec)
            uterotonics.append({
                "agent": "Misoprostol (Cytotec)",
                "dose": "800 mcg (4 x 200 mcg tablets)",
                "frequency": "One-time dose",
                "route": "Buccal or Sublingual (faster absorption than rectal in active bleeding)",
                "safety_note": "Causes transient maternal pyrexia and shivering."
            })

            # Tranexamic Acid (TXA) Gating (WOMAN Trial)
            if deliv.hours_since_delivery <= 3.0:
                uterotonics.append({
                    "agent": "Tranexamic Acid (TXA)",
                    "dose": "1.0 g in 100 mL IV over 10 minutes",
                    "frequency": "Repeat 1.0 g IV at 30 minutes if bleeding continues or restarts within 24h",
                    "route": "Intravenous",
                    "safety_note": "Initiate within 3 hours of delivery per WOMAN Trial (reduces death from bleeding by 31%)."
                })
            else:
                contraindications_flagged.append({
                    "drug": "Tranexamic Acid (TXA)",
                    "status": "WITHHELD / OUTSIDE WINDOW",
                    "reason": f"Delivery was {deliv.hours_since_delivery:.1f} hours ago (> 3 hours). WOMAN Trial demonstrates lack of efficacy and increased thrombotic risk beyond 3 hours."
                })

            # Mechanical Tamponade (Bakri / JADA)
            mechanical_interventions.append({
                "device": "Intrauterine Balloon Tamponade (Bakri Balloon) or Vacuum-Induced Device (JADA)",
                "technique": "Inflate Bakri with 300 to 500 mL sterile saline; connect drainage port to evaluate tamponade test. If using JADA, apply -80 mmHg continuous low-level vacuum.",
                "duration": "Maintain for 12 to 24 hours with prophylactic antibiotic coverage."
            })

        # 3. Stage 3 Massive Transfusion & Coagulopathy Management
        if stage == 3:
            transfusion_orders.append("ACTIVATE OBSTETRIC MASSIVE TRANSFUSION PROTOCOL (MTP): 1:1:1 Ratio (4 Units PRBCs, 4 Units FFP, 1 Single-Donor Apheresis Platelet Pool).")

            if coag:
                if coag.fibrinogen_mg_dl < 200.0:
                    transfusion_orders.append(
                        f"CRITICAL CRYOPRECIPITATE ORDER: Serum Fibrinogen ({coag.fibrinogen_mg_dl:.0f} mg/dL) < 200 mg/dL. "
                        "Infuse 10 units Cryoprecipitate immediately (raises fibrinogen by ~50 mg/dL). In pregnancy, fibrinogen < 200 mg/dL indicates severe consumptive coagulopathy."
                    )
                if coag.ionized_calcium_mmol_l < 1.15:
                    transfusion_orders.append(
                        f"CALCIUM STEWARDSHIP: Ionized Calcium ({coag.ionized_calcium_mmol_l:.2f} mmol/L) < 1.15. "
                        "Administer Calcium Gluconate 1-2 g IV to prevent citrate toxicity from transfused blood products."
                    )
                if coag.core_temp_celsius < 36.0:
                    transfusion_orders.append(
                        f"HYPOTHERMIA CORRECTION: Core Temp ({coag.core_temp_celsius:.1f} °C) < 36.0 °C. Deploy active forced-air rewarming (Bair Hugger) and fluid warmers."
                    )

            mechanical_interventions.append({
                "device": "SURGICAL GATING (OR Mobilization)",
                "technique": "Examination under anesthesia, B-Lynch uterine compression sutures, bilateral uterine/hypogastric artery ligation, or emergent peripartum hysterectomy.",
                "duration": "Immediate operative intervention if medical/tamponade therapies fail."
            })

        return {
            "recommended_uterotonics": uterotonics,
            "contraindication_sentinels": contraindications_flagged,
            "mechanical_interventions": mechanical_interventions,
            "transfusion_orders": transfusion_orders
        }

# ==============================================================================
# CLI TEST HARNESS & VERIFICATION GATES
# ==============================================================================

def run_clinical_verification_suite():
    print("================================================================================")
    print("OpenPHR Cookbook 377: Obstetric PPH, OSI & Uterotonic Titrator Verification Suite")
    print("================================================================================")

    # Case 1: Postpartum Hemorrhage with Occult Shock and Severe Preeclampsia
    deliv_case1 = DeliveryContext(
        delivery_type="vaginal",
        quantitative_blood_loss_ml=1250.0,      # > 1000 mL -> Stage 2
        hours_since_delivery=1.2                # 1.2h -> eligible for TXA
    )

    hemo_case1 = MaternalHemodynamics(
        heart_rate_bpm=120,
        systolic_bp_mmhg=100.0,                 # OSI = 120 / 100 = 1.20 (Occult Shock >= 0.9!)
        diastolic_bp_mmhg=65.0,
        mean_arterial_pressure_mmhg=76.7,
        oxygen_saturation_percent=98.0,
        urine_output_ml_hr=25.0
    )

    comorb_case1 = MedicalComorbidities(
        has_preeclampsia_or_gestational_htn=True,# Methergine must be PROHIBITED
        has_chronic_hypertension=False,
        has_active_asthma_or_bronchospasm=False, # Carboprost is safe
        has_cardiac_disease=False,
        retained_placenta_suspected=False,
        suspected_genital_tract_lacerations=False
    )

    coag_case1 = CoagulationProfile(
        fibrinogen_mg_dl=180.0,                 # < 200 mg/dL -> Cryoprecipitate trigger
        platelet_count_k_ul=92.0,
        inr=1.3,
        ionized_calcium_mmol_l=1.05,
        core_temp_celsius=35.9
    )

    # 1. Evaluate Obstetric Shock Index
    osi_res = PostpartumHemorrhageEngine.calculate_obstetric_shock_index(hemo_case1.heart_rate_bpm, hemo_case1.systolic_bp_mmhg)
    print(f"[*] Obstetric Shock Index: {osi_res['obstetric_shock_index']} ({osi_res['maternal_status']} - Risk: {osi_res['risk_level']})")
    assert osi_res['obstetric_shock_index'] == 1.20, f"Expected OSI 1.20, got {osi_res['obstetric_shock_index']}"
    assert osi_res['risk_level'] == "HIGH", "Case 1 must flag high occult shock risk."

    # 2. Evaluate CMQCC Staging
    stage_res = PostpartumHemorrhageEngine.evaluate_cmqcc_stage(deliv_case1, hemo_case1, osi_res['obstetric_shock_index'])
    print(f"[*] CMQCC Stage: {stage_res['cmqcc_stage']} - {stage_res['stage_title']}")
    assert stage_res['cmqcc_stage'] == 2, f"Expected Stage 2, got {stage_res['cmqcc_stage']}"

    # 3. Titrate Pharmacotherapy and Interventions
    rx_res = PostpartumHemorrhageEngine.titrate_pharmacotherapy_and_interventions(
        stage_res['cmqcc_stage'], deliv_case1, comorb_case1, coag_case1
    )

    print("\n[+] Recommended Uterotonics & Hemostatic Agents:")
    active_drugs = [u['agent'] for u in rx_res['recommended_uterotonics']]
    for u in rx_res['recommended_uterotonics']:
        print(f"    - {u['agent']}: {u['dose']} via {u['route']}")

    print("\n[+] Pharmacological Contraindication Sentinels:")
    contra_drugs = [c['drug'] for c in rx_res['contraindication_sentinels']]
    for c in rx_res['contraindication_sentinels']:
        print(f"    - [STOP] {c['drug']}: {c['status']} ({c['reason']})")

    # Clinical Assertions
    assert any("Methergine" in d for d in contra_drugs), "Assertion Failure: Methergine must be contraindicated in preeclampsia."
    assert not any("Methergine" in d for d in active_drugs), "Assertion Failure: Methergine must NOT be recommended in preeclampsia."
    assert any("Carboprost" in d for d in active_drugs), "Assertion Failure: Carboprost should be recommended in non-asthmatic patient."
    assert any("Tranexamic Acid" in d for d in active_drugs), "Assertion Failure: TXA should be recommended within 3 hours."

    print("\n[+] Mechanical Interventions:")
    for m in rx_res['mechanical_interventions']:
        print(f"    - {m['device']}: {m['technique']}")

    print("\n>>> ALL VERIFICATION GATES PASSED (100% CLINICAL CONCORDANCE) <<<")

if __name__ == "__main__":
    run_clinical_verification_suite()

Clinical Validation & Automated Test Output

Executing the self-verifying test suite produces the following verified telemetry:

$ python obstetric_pph_osi_engine.py
================================================================================
OpenPHR Cookbook 377: Obstetric PPH, OSI & Uterotonic Titrator Verification Suite
================================================================================
[*] Obstetric Shock Index: 1.2 (Occult Hypovolemic Shock - Risk: HIGH)
[*] CMQCC Stage: 2 - CMQCC Stage 2: Continued Hemorrhage with Occult or Overt Instability

[+] Recommended Uterotonics & Hemostatic Agents:
    - Oxytocin (Pitocin): 30 to 40 Units in 1000 mL Normal Saline or LR via Intravenous Infusion
    - Carboprost Tromethamine (Hemabate): 250 mcg IM or intramyometrial via Intramuscular
    - Misoprostol (Cytotec): 800 mcg (4 x 200 mcg tablets) via Buccal or Sublingual
    - Tranexamic Acid (TXA): 1.0 g in 100 mL IV over 10 minutes via Intravenous

[+] Pharmacological Contraindication Sentinels:
    - [STOP] Methylergonovine (Methergine): ABSOLUTELY CONTRAINDICATED (Maternal Hypertension / Preeclampsia (causes vasoconstriction and life-threatening hypertensive stroke / encephalopathy).)

[+] Mechanical Interventions:
    - Intrauterine Balloon Tamponade (Bakri Balloon) or Vacuum-Induced Device (JADA): Inflate Bakri with 300 to 500 mL sterile saline; connect drainage port to evaluate tamponade test. If using JADA, apply -80 mmHg continuous low-level vacuum.

>>> ALL VERIFICATION GATES PASSED (100% CLINICAL CONCORDANCE) <<<

References & Clinical Consensus

  1. American College of Obstetricians and Gynecologists (ACOG): Practice Bulletin No. 183: Postpartum Hemorrhage. Obstet Gynecol 2017 (Reaffirmed 2023); 130(4): e168-e186.
  2. California Maternal Quality Care Collaborative (CMQCC): Improving Health Care Response to Obstetric Hemorrhage: A California Quality Improvement Toolkit. Version 3.0, 2022.
  3. WOMAN Trial Collaborators: Effect of early tranexamic acid administration on mortality, hysterectomy, and other morbidities in women with post-partum haemorrhage (WOMAN): an international, randomised, double-blind, placebo-controlled trial. Lancet 2017; 389(10084): 2105-2116.
  4. Le Bas A, et al.: Use of the obstetric shock index as an adjunct in identifying significant blood loss in postpartum hemorrhage. Int J Gynaecol Obstet 2014; 124(3): 251-253.
  5. World Health Organization (WHO): WHO recommendations for the prevention and treatment of postpartum haemorrhage. Geneva: World Health Organization; 2022. “””

target_path = r”H:\My Drive\Website 2.0\openphr-site_cookbooks\obstetrics-pph-cmqcc-shock-index-uterotonic-engine.md” with open(target_path, “w”, encoding=”utf-8”) as f: f.write(content)

print(f”SUCCESS: Created {target_path}”)