Cookbook 316: Offline Clinical Orthopedic Oncology Mirels Fracture & Enneking Sarcoma Engine

This cookbook details how to deploy a localized, containerized orthopedic surgery, musculoskeletal oncology, and radiation oncology decision-support engine for sarcoma tumor boards, orthopedic trauma centers, and cancer institutes to ingest radiographic bone measurements, pain characteristics, and histopathological tumor grades, calculate the Mirels Score for Impending Pathologic Fracture ($4 - 12\text{ points}$), classify primary bone sarcomas under the Enneking / Musculoskeletal Tumor Society ($\text{MSTS}$) Surgical Staging System (Stages IA–III), gate Prophylactic Intramedullary Nailing vs Palliative Radiotherapy, and plan Limb-Salvage En-Bloc Resection Margins according to NCCN, MSTS, and AAOS consensus guidelines without external cloud API reliance.


1. Clinical Background & Orthopedic Oncology Architecture

Metastatic bone disease and primary musculoskeletal sarcomas present critical mechanical and oncologic challenges:


2. Pipeline & Workflow Architecture

[Clinical Telemetry: Primary Cancer, Long Bone Site, Pain Character, Lytic %, Grade]
                                         │
                                         ▼
      [Mirels Score Derivation (4 - 12) & Pathologic Fracture Probability Engine]
                                         │
                                         ▼
     [Surgical Decision Gatekeeper: Score >= 9 -> Mandatory Prophylactic Nailing]
                                         │
                                         ▼
      [Enneking / MSTS Sarcoma Staging Engine: Stages IA - IIIB & Compartmentalization]
                                         │
                                         ▼
    [Multidisciplinary Treatment Protocol: Fixation vs Radiotherapy vs Limb-Salvage]

3. Environment & Prerequisites

Install required scientific Python and musculoskeletal oncology modeling packages:

pip install numpy scipy pandas torch torchvision matplotlib

4. Complete Offline Python / PyTorch Implementation

"""
Cookbook 316: Offline Orthopedic Oncology Mirels Fracture & Enneking Sarcoma 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 BoneLesionTelemetry:
    patient_id: str
    age_years: float
    primary_oncology_diagnosis: str # "Renal Cell Carcinoma", "Breast Adenocarcinoma", "Lung Carcinoma", "Multiple Myeloma", "Osteosarcoma", "Undifferentiated Pleomorphic Sarcoma"
    is_primary_sarcoma: bool = False # Flag for Enneking staging
    # Mirels 4-Variable Telemetry (For Metastatic Bone Disease)
    anatomical_location: str = "Peritrochanteric Region of Femur" # "Upper Extremity", "Lower Extremity Shaft", "Peritrochanteric Region of Femur"
    pain_character: str = "Functional Mechanical Pain" # "Mild / Non-Mechanical", "Moderate Pain", "Functional Mechanical Pain"
    radiographic_appearance: str = "Pure Lytic / Osteolytic" # "Blastic / Osteosclerotic", "Mixed Lytic-Blastic", "Pure Lytic / Osteolytic"
    cortical_involvement_extent: str = "> 2/3 of Cortical Diameter" # "< 1/3 of Cortical Diameter", "1/3 to 2/3 of Cortical Diameter", "> 2/3 of Cortical Diameter"
    # Primary Sarcoma Telemetry (Enneking Variables)
    histopathologic_grade: str = "High Grade (G2)" # "Low Grade (G1)" or "High Grade (G2)"
    anatomical_compartmentalization: str = "Extracompartmental (T2)" # "Intracompartmental (T1)" or "Extracompartmental (T2)"
    regional_or_distant_metastasis_present: bool = False # M0 vs M1

@dataclass
class OrthopedicOncologyReport:
    patient_id: str
    calculated_mirels_score: int # 4 - 12 points
    fracture_risk_percentage: str # "< 5%", "15%", "33% - 100%"
    surgical_stabilization_recommendation: str # "MANDATORY PROPHYLACTIC SURGICAL FIXATION", "Borderline / Protected Weight-Bearing", "Non-Operative / Radiotherapy & Medical"
    enneking_sarcoma_stage: Optional[str] # Stages IA - III
    surgical_orthopedic_orders: List[str]
    radiation_and_medical_orders: List[str]
    critical_safety_sentinels: List[str]
    clinical_nccn_msts_directive: str

class OrthopedicOncologyDecisionEngine:
    """
    Offline clinical engine for Mirels impending fracture scoring,
    prophylactic surgical gating, and Enneking sarcoma staging.
    """

    def compute_mirels_score(self, d: BoneLesionTelemetry) -> Tuple[int, Dict[str, int]]:
        breakdown = {}

        # 1. Site (1-3)
        loc = d.anatomical_location.lower()
        if "upper" in loc: s_site = 1
        elif "lower" in loc or "shaft" in loc: s_site = 2
        else: s_site = 3 # Peritrochanteric
        breakdown["Site_Score"] = s_site

        # 2. Pain (1-3)
        p = d.pain_character.lower()
        if "mild" in p or "non-mechanical" in p: s_pain = 1
        elif "moderate" in p: s_pain = 2
        else: s_pain = 3 # Functional mechanical
        breakdown["Pain_Score"] = s_pain

        # 3. Radiographic Lesion (1-3)
        rad = d.radiographic_appearance.lower()
        if "blastic" in rad or "sclerotic" in rad: s_rad = 1
        elif "mixed" in rad: s_rad = 2
        else: s_rad = 3 # Pure lytic
        breakdown["Radiograph_Score"] = s_rad

        # 4. Cortical Extent (1-3)
        cort = d.cortical_involvement_extent.lower()
        if "< 1/3" in cort or "less than 1/3" in cort: s_cort = 1
        elif "1/3 to 2/3" in cort or "1/3 - 2/3" in cort: s_cort = 2
        else: s_cort = 3 # > 2/3
        breakdown["Cortical_Score"] = s_cort

        total_mirels = sum(breakdown.values())
        return total_mirels, breakdown

    def stage_enneking_sarcoma(self, d: BoneLesionTelemetry) -> Optional[str]:
        if not d.is_primary_sarcoma:
            return None

        is_high = "g2" in d.histopathologic_grade.lower() or "high" in d.histopathologic_grade.lower()
        is_extra = "t2" in d.anatomical_compartmentalization.lower() or "extra" in d.anatomical_compartmentalization.lower()

        if d.regional_or_distant_metastasis_present:
            return "Stage III Sarcoma (Any G, Any T, M1 - Metastatic Disease)"
        elif is_high and is_extra:
            return "Stage IIB Sarcoma (High Grade G2, Extracompartmental T2, M0)"
        elif is_high and not is_extra:
            return "Stage IIA Sarcoma (High Grade G2, Intracompartmental T1, M0)"
        elif not is_high and is_extra:
            return "Stage IB Sarcoma (Low Grade G1, Extracompartmental T2, M0)"
        else:
            return "Stage IA Sarcoma (Low Grade G1, Intracompartmental T1, M0)"

    def determine_interventions(self, mirels: int, d: BoneLesionTelemetry, enneking: Optional[str]) -> Tuple[str, str, List[str], List[str]]:
        surg_orders = []
        rad_orders = []

        if mirels >= 9:
            fx_risk = "33% to 100% (High Fracture Probability)"
            surg_rec = "MANDATORY PROPHYLACTIC SURGICAL FIXATION (Prior to Radiation Therapy)"
            
            if "peritrochanteric" in d.anatomical_location.lower():
                surg_orders.append("1. PROPHYLACTIC CEPHALOMEDULLARY NAILING: Schedule urgent reconstruction cephalomedullary nailing (e.g. long femoral nail with femoral neck/head fixation screws) or modular cemented bipolar hemiarthroplasty/calcar replacement.")
            elif "lower" in d.anatomical_location.lower():
                surg_orders.append("1. PROPHYLACTIC INTRAMEDULLARY STABILIZATION: Long locked intramedullary femoral/tibial nailing spanning the entire length of the bone.")
            else:
                surg_orders.append("1. PROPHYLACTIC UPPER EXTREMITY FIXATION: Locked intramedullary humeral nailing or rigid compression plating augmented with polymethylmethacrylate (PMMA) bone cement.")

            surg_orders.append("2. PREOPERATIVE EMBOLIZATION: If hypervascular primary (Renal Cell Carcinoma or Thyroid Cancer), perform preoperative catheter arterial embolization within 24-48 hours of surgery to minimize intraoperative blood loss.")
            rad_orders.append("1. POSTOPERATIVE CONSOLIDATIVE RADIOTHERAPY: Deliver 30 Gy in 10 fractions (or 20 Gy in 5 fractions) beginning 2-3 weeks postoperatively following surgical wound healing.")

        elif mirels == 8:
            fx_risk = "15% (Borderline / Moderate Fracture Risk)"
            surg_rec = "BORDERLINE / PROTECTED WEIGHT-BEARING (Clinical Judgment with Orthopedic Oncology)"
            surg_orders.append("1. ORTHOPEDIC ONCOLOGY SURVEILLANCE: Strict non-weight-bearing / toe-touch weight-bearing with crutches or walker; biweekly serial radiographs.")
            rad_orders.append("1. PRIMARY FRACTIONATED RADIOTHERAPY: Deliver 30 Gy in 10 fractions with bisphosphonates (Zoledronic Acid 4 mg IV q4w) or Denosumab (120 mg SC q4w).")

        else:
            fx_risk = "< 5% (Low Fracture Probability)"
            surg_rec = "NON-OPERATIVE MANAGEMENT / RADIOTHERAPY & BONE-TARGETED AGENTS"
            surg_orders.append("1. CONSERVATIVE ORTHOPEDIC OBSERVATION: Full weight-bearing as tolerated; follow-up plain radiograph in 4-6 weeks.")
            rad_orders.append("1. PALLIATIVE EXTERNAL BEAM RADIOTHERAPY: Single-fraction 8 Gy (or 20-30 Gy fractionated) for local pain control and remineralization.")
            rad_orders.append("2. BONE-TARGETED AGENT: Zoledronic Acid 4 mg IV every 4 weeks or Denosumab 120 mg SC every 4 weeks.")

        if enneking:
            surg_orders.insert(0, f"PRIMARY SARCOMA DIRECTIVE ({enneking}): Multidisciplinary tumor board evaluation for neoadjuvant chemotherapy followed by wide en-bloc limb-salvage resection with clear 1-2 cm surgical margins.")

        return fx_risk, surg_rec, surg_orders, rad_orders

    def evaluate_case(self, data: BoneLesionTelemetry) -> OrthopedicOncologyReport:
        mirels, bdown = self.compute_mirels_score(data)
        enneking_stage = self.stage_enneking_sarcoma(data)
        fx_risk, surg_rec, surg_orders, rad_orders = self.determine_interventions(mirels, data, enneking_stage)

        safety = []
        if mirels >= 9:
            safety.append("FRACTURE WARNING: Lesion meets Mirels >= 9 criteria (Catastrophic displacement imminent upon weight-bearing). Strictly prohibit unassisted ambulation until orthopedic fixation is completed.")
        if "Renal" in data.primary_oncology_diagnosis or "Thyroid" in data.primary_oncology_diagnosis:
            safety.append(f"HYPERVASCULAR TUMOR SENTINEL ({data.primary_oncology_diagnosis}): Massive hemorrhage risk during fixation. Schedule interventional angiography for catheter embolization 24 hours pre-op.")

        directives = []
        directives.append(f"MIRELS ASSESSMENT: Score = {mirels}/12 ({fx_risk}).")
        directives.append(f"SURGICAL TRIAGE: {surg_rec}.")
        if enneking_stage:
            directives.append(f"ENNEKING SARCOMA STAGE: {enneking_stage}.")
        directives.append(f"MANAGEMENT: {'Prophylactic Intramedullary Nailing -> Post-Op Radiotherapy' if mirels >= 9 else 'Palliative Radiotherapy + Bone Agents'}.")

        return OrthopedicOncologyReport(
            patient_id=data.patient_id,
            calculated_mirels_score=mirels,
            fracture_risk_percentage=fx_risk,
            surgical_stabilization_recommendation=surg_rec,
            enneking_sarcoma_stage=enneking_stage,
            surgical_orthopedic_orders=surg_orders,
            radiation_and_medical_orders=rad_orders,
            critical_safety_sentinels=safety,
            clinical_nccn_msts_directive=" ".join(directives)
        )

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

    print("=" * 80)
    print("OpenPHR Clinical Orthopedic Oncology Mirels Fracture & Enneking Engine")
    print("=" * 80)

    # Test Case 1: 62-year-old female with metastatic Renal Cell Carcinoma to Left Proximal Femur
    # Location: Peritrochanteric region (score 3) | Pain: Functional mechanical pain with ambulation (score 3)
    # Radiograph: Pure osteolytic lesion (score 3) | Cortical extent: > 2/3 diameter (score 3)
    # Total Mirels = 12/12 -> Fracture probability 100%!
    # Management: Mandatory Prophylactic Cephalomedullary Nailing + Pre-op Angiographic Embolization!
    bone1 = BoneLesionTelemetry(
        patient_id="ORTHO-ONC-9104",
        age_years=62.0,
        primary_oncology_diagnosis="Renal Cell Carcinoma",
        anatomical_location="Peritrochanteric Region of Femur",
        pain_character="Functional Mechanical Pain",
        radiographic_appearance="Pure Lytic / Osteolytic",
        cortical_involvement_extent="> 2/3 of Cortical Diameter"
    )

    rep1 = engine.evaluate_case(bone1)

    print(f"\n[Patient {rep1.patient_id} - Orthopedic Oncology Assessment]")
    print(f"Mirels Score: {rep1.calculated_mirels_score} / 12 ({rep1.fracture_risk_percentage})")
    print(f"Surgical Recommendation: {rep1.surgical_stabilization_recommendation}")
    print("\nSurgical Orders:")
    for s in rep1.surgical_orthopedic_orders:
        print(f"  • {s}")
    print("\nRadiation & Medical Orders:")
    for r in rep1.radiation_and_medical_orders:
        print(f"  • {r}")
    print("\nSafety Sentinels:")
    for sent in rep1.critical_safety_sentinels:
        print(f"  {sent}")
    print(f"\nNCCN / MSTS Consensus Directive:\n{rep1.clinical_nccn_msts_directive}")

    # Test Case 2: 22-year-old male with Distal Femur High-Grade Osteosarcoma (Enneking Stage IIB)
    bone2 = BoneLesionTelemetry(
        patient_id="ORTHO-ONC-1042",
        age_years=22.0,
        primary_oncology_diagnosis="Osteosarcoma",
        is_primary_sarcoma=True,
        histopathologic_grade="High Grade (G2)",
        anatomical_compartmentalization="Extracompartmental (T2)",
        regional_or_distant_metastasis_present=False
    )

    rep2 = engine.evaluate_case(bone2)
    print(f"\n[Patient {rep2.patient_id}] - Primary Sarcoma: {rep2.enneking_sarcoma_stage}")

5. Clinical Verification & Guideline Conformance


6. References