File size: 12,850 Bytes
91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 91b591f ad9e267 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | """
Utility functions for clinical calculations and data parsing.
- Creatinine Clearance (CrCl) via Cockcroft-Gault
- MIC trend analysis and creep detection
- Prescription card formatter
- JSON parsing and data normalization helpers
"""
import json
import math
import re
from typing import Any, Dict, List, Literal, Optional, Tuple
# --- CrCl calculator ---
def calculate_crcl(
age_years: float,
weight_kg: float,
serum_creatinine_mg_dl: float,
sex: Literal["male", "female"],
use_ibw: bool = False,
height_cm: Optional[float] = None,
) -> float:
"""
Cockcroft-Gault equation.
CrCl = [(140 - age) × weight × (0.85 if female)] / (72 × SCr)
When use_ibw=True and height is given, uses Ideal Body Weight.
For obese patients (actual > 1.3 × IBW), switches to Adjusted Body Weight.
Returns CrCl in mL/min.
"""
if serum_creatinine_mg_dl <= 0:
raise ValueError("Serum creatinine must be positive")
if age_years <= 0 or weight_kg <= 0:
raise ValueError("Age and weight must be positive")
weight = weight_kg
if use_ibw and height_cm:
ibw = calculate_ibw(height_cm, sex)
weight = calculate_adjusted_bw(ibw, weight_kg) if weight_kg > ibw * 1.3 else ibw
crcl = ((140 - age_years) * weight) / (72 * serum_creatinine_mg_dl)
if sex == "female":
crcl *= 0.85
return round(crcl, 1)
def calculate_ibw(height_cm: float, sex: Literal["male", "female"]) -> float:
"""
Devine formula for Ideal Body Weight.
Male: 50 kg + 2.3 kg per inch over 5 feet
Female: 45.5 kg + 2.3 kg per inch over 5 feet
"""
height_over_60_inches = max(0, height_cm / 2.54 - 60)
base = 50 if sex == "male" else 45.5
return round(base + 2.3 * height_over_60_inches, 1)
def calculate_adjusted_bw(ibw: float, actual_weight: float) -> float:
"""
Adjusted Body Weight for obese patients.
AdjBW = IBW + 0.4 × (Actual - IBW)
"""
return round(ibw + 0.4 * (actual_weight - ibw), 1)
def get_renal_dose_category(crcl: float) -> str:
"""Map CrCl value to a dosing category string."""
if crcl >= 90:
return "normal"
elif crcl >= 60:
return "mild_impairment"
elif crcl >= 30:
return "moderate_impairment"
elif crcl >= 15:
return "severe_impairment"
else:
return "esrd"
# --- MIC trend analysis ---
def calculate_mic_trend(
mic_values: List[Dict[str, Any]],
susceptible_breakpoint: Optional[float] = None,
resistant_breakpoint: Optional[float] = None,
) -> Dict[str, Any]:
"""
Analyze a list of MIC readings over time.
Requires at least 2 readings. Uses linear regression slope for trend
direction when >= 3 points are available; falls back to ratio comparison
for exactly 2 points.
"""
if len(mic_values) < 2:
return {
"trend": "insufficient_data",
"risk_level": "UNKNOWN",
"alert": "Need at least 2 MIC values for trend analysis",
}
mics = [float(v["mic_value"]) for v in mic_values]
baseline_mic = mics[0]
current_mic = mics[-1]
fold_change = (current_mic / baseline_mic) if baseline_mic > 0 else float("inf")
if len(mics) >= 3:
n = len(mics)
x_mean = (n - 1) / 2
y_mean = sum(mics) / n
numerator = sum((i - x_mean) * (mics[i] - y_mean) for i in range(n))
denominator = sum((i - x_mean) ** 2 for i in range(n))
slope = numerator / denominator if denominator != 0 else 0
trend = "increasing" if slope > 0.5 else "decreasing" if slope < -0.5 else "stable"
else:
trend = "increasing" if current_mic > baseline_mic * 1.5 else "decreasing" if current_mic < baseline_mic * 0.67 else "stable"
# Fold change per time step (geometric rate of change)
velocity = fold_change ** (1 / (len(mics) - 1)) if len(mics) > 1 else 1.0
risk_level, alert = _assess_mic_risk(
current_mic, baseline_mic, fold_change, trend,
susceptible_breakpoint, resistant_breakpoint,
)
return {
"baseline_mic": baseline_mic,
"current_mic": current_mic,
"ratio": round(fold_change, 2),
"trend": trend,
"velocity": round(velocity, 3),
"risk_level": risk_level,
"alert": alert,
"n_readings": len(mics),
}
def _assess_mic_risk(
current_mic: float,
baseline_mic: float,
fold_change: float,
trend: str,
s_breakpoint: Optional[float],
r_breakpoint: Optional[float],
) -> Tuple[str, str]:
"""
Assign a risk level (LOW/MODERATE/HIGH/CRITICAL) based on breakpoints and fold change.
Prefers breakpoint-based assessment when breakpoints are available.
Falls back to fold-change thresholds otherwise.
"""
if s_breakpoint is not None and r_breakpoint is not None:
margin = s_breakpoint / current_mic if current_mic > 0 else float("inf")
if current_mic > r_breakpoint:
return "CRITICAL", f"MIC ({current_mic}) exceeds resistant breakpoint ({r_breakpoint}). Organism is RESISTANT."
if current_mic > s_breakpoint:
return "HIGH", f"MIC ({current_mic}) exceeds susceptible breakpoint ({s_breakpoint}). Consider alternative therapy."
if margin < 2:
if trend == "increasing":
return "HIGH", f"MIC approaching breakpoint (margin: {margin:.1f}x) with increasing trend. High risk of resistance emergence."
return "MODERATE", f"MIC close to breakpoint (margin: {margin:.1f}x). Monitor closely."
if margin < 4:
if trend == "increasing":
return "MODERATE", f"MIC rising with {margin:.1f}x margin to breakpoint. Consider enhanced monitoring."
return "LOW", "MIC stable with adequate margin to breakpoint."
return "LOW", "MIC well below breakpoint with good safety margin."
# No breakpoints — use fold change thresholds from EUCAST MIC creep criteria
if fold_change >= 8:
return "CRITICAL", f"MIC increased {fold_change:.1f}-fold from baseline. Urgent review needed."
if fold_change >= 4:
return "HIGH", f"MIC increased {fold_change:.1f}-fold from baseline. High risk of treatment failure."
if fold_change >= 2:
if trend == "increasing":
return "MODERATE", f"MIC increased {fold_change:.1f}-fold with rising trend. Enhanced monitoring recommended."
return "LOW", f"MIC increased {fold_change:.1f}-fold but trend is {trend}."
if trend == "increasing":
return "MODERATE", "MIC showing upward trend. Continue monitoring."
return "LOW", "MIC stable or decreasing. Current therapy appropriate."
def detect_mic_creep(
organism: str,
antibiotic: str,
mic_history: List[Dict[str, Any]],
breakpoints: Dict[str, float],
) -> Dict[str, Any]:
"""
Detect MIC creep for a specific organism-antibiotic pair.
Augments calculate_mic_trend with a time-to-resistance estimate
when the MIC is rising and a susceptible breakpoint is available.
"""
result = calculate_mic_trend(
mic_history,
susceptible_breakpoint=breakpoints.get("susceptible"),
resistant_breakpoint=breakpoints.get("resistant"),
)
result["organism"] = organism
result["antibiotic"] = antibiotic
result["breakpoint_susceptible"] = breakpoints.get("susceptible")
result["breakpoint_resistant"] = breakpoints.get("resistant")
# Estimate how many more time-points until MIC reaches the susceptible breakpoint
if result["trend"] == "increasing" and result["velocity"] > 1.0:
current = result["current_mic"]
s_bp = breakpoints.get("susceptible")
if s_bp and current < s_bp:
doublings_needed = math.log2(s_bp / current) if current > 0 else 0
log_velocity = math.log(result["velocity"]) / math.log(2)
if log_velocity > 0:
result["estimated_readings_to_resistance"] = round(doublings_needed / log_velocity, 1)
return result
# --- Prescription formatter ---
def format_prescription_card(recommendation: Dict[str, Any]) -> str:
"""Format a recommendation dict as a plain-text prescription card."""
lines = []
lines.append("=" * 50)
lines.append("ANTIBIOTIC PRESCRIPTION")
lines.append("=" * 50)
primary = recommendation.get("primary_recommendation", recommendation)
lines.append(f"\nDRUG: {primary.get('antibiotic', 'N/A')}")
lines.append(f"DOSE: {primary.get('dose', 'N/A')}")
lines.append(f"ROUTE: {primary.get('route', 'N/A')}")
lines.append(f"FREQUENCY: {primary.get('frequency', 'N/A')}")
lines.append(f"DURATION: {primary.get('duration', 'N/A')}")
if primary.get("aware_category"):
lines.append(f"WHO AWaRe: {primary.get('aware_category')}")
adjustments = recommendation.get("dose_adjustments", {})
if adjustments.get("renal") and adjustments["renal"] != "None needed":
lines.append(f"\nRENAL ADJUSTMENT: {adjustments['renal']}")
if adjustments.get("hepatic") and adjustments["hepatic"] != "None needed":
lines.append(f"HEPATIC ADJUSTMENT: {adjustments['hepatic']}")
alerts = recommendation.get("safety_alerts", [])
if alerts:
lines.append("\n" + "-" * 50)
lines.append("SAFETY ALERTS:")
for alert in alerts:
level = alert.get("level", "INFO")
marker = {"CRITICAL": "[!!!]", "WARNING": "[!!]", "INFO": "[i]"}.get(level, "[?]")
lines.append(f" {marker} {alert.get('message', '')}")
monitoring = recommendation.get("monitoring_parameters", [])
if monitoring:
lines.append("\n" + "-" * 50)
lines.append("MONITORING:")
for param in monitoring:
lines.append(f" - {param}")
if recommendation.get("rationale"):
lines.append("\n" + "-" * 50)
lines.append("RATIONALE:")
lines.append(f" {recommendation['rationale']}")
lines.append("\n" + "=" * 50)
return "\n".join(lines)
# --- JSON parsing ---
def safe_json_parse(text: str) -> Optional[Dict[str, Any]]:
"""
Extract and parse the first JSON object from a string.
Handles model output that may wrap JSON in markdown code fences.
Returns None if no valid JSON is found.
"""
if not text:
return None
try:
return json.loads(text)
except json.JSONDecodeError:
pass
for pattern in [r"```json\s*\n?(.*?)\n?```", r"```\s*\n?(.*?)\n?```", r"\{[\s\S]*\}"]:
match = re.search(pattern, text, re.DOTALL)
if match:
try:
json_str = match.group(1) if match.lastindex else match.group(0)
return json.loads(json_str)
except (json.JSONDecodeError, IndexError):
continue
return None
def validate_agent_output(output: Dict[str, Any], required_fields: List[str]) -> Tuple[bool, List[str]]:
"""Return (is_valid, missing_fields) for an agent output dict."""
missing = [f for f in required_fields if f not in output]
return len(missing) == 0, missing
# --- Name normalization ---
def normalize_antibiotic_name(name: str) -> str:
"""Map common abbreviations and brand names to standard antibiotic names."""
mappings = {
"amox": "amoxicillin",
"amox/clav": "amoxicillin-clavulanate",
"augmentin": "amoxicillin-clavulanate",
"pip/tazo": "piperacillin-tazobactam",
"zosyn": "piperacillin-tazobactam",
"tmp/smx": "trimethoprim-sulfamethoxazole",
"bactrim": "trimethoprim-sulfamethoxazole",
"cipro": "ciprofloxacin",
"levo": "levofloxacin",
"moxi": "moxifloxacin",
"vanc": "vancomycin",
"vanco": "vancomycin",
"mero": "meropenem",
"imi": "imipenem",
"gent": "gentamicin",
"tobra": "tobramycin",
"ceftriax": "ceftriaxone",
"rocephin": "ceftriaxone",
"cefepime": "cefepime",
"maxipime": "cefepime",
}
return mappings.get(name.lower().strip(), name.lower().strip())
def normalize_organism_name(name: str) -> str:
"""Map common abbreviations to full organism names."""
abbreviations = {
"e. coli": "Escherichia coli",
"e.coli": "Escherichia coli",
"k. pneumoniae": "Klebsiella pneumoniae",
"k.pneumoniae": "Klebsiella pneumoniae",
"p. aeruginosa": "Pseudomonas aeruginosa",
"p.aeruginosa": "Pseudomonas aeruginosa",
"s. aureus": "Staphylococcus aureus",
"s.aureus": "Staphylococcus aureus",
"mrsa": "Staphylococcus aureus (MRSA)",
"mssa": "Staphylococcus aureus (MSSA)",
"enterococcus": "Enterococcus species",
"vre": "Enterococcus (VRE)",
}
return abbreviations.get(name.strip().lower(), name.strip())
|