From 16f5559035be8f8d1be5b8c03a08f0f9ef43ffd6 Mon Sep 17 00:00:00 2001 From: Abhinav Gupta Date: Fri, 16 Oct 2026 12:31:02 +0530 Subject: [PATCH] feat: update author to Abhinav Gupta, add concept matcher, track Database folder, and configure gitea --- .gitignore | 6 +- Database/.gitkeep | 0 README.md | 26 +- pyproject.toml | 2 +- src/medical_coding/agents/classifier.py | 47 +- .../agents/clinical_extractor.py | 128 +++- src/medical_coding/agents/ranker.py | 86 ++- src/medical_coding/graph/nodes.py | 449 ++++++------ src/medical_coding/reasoning/__init__.py | 11 + src/medical_coding/reasoning/compatibility.py | 63 +- .../reasoning/concept_matcher.py | 285 ++++++++ .../reasoning/concept_reasoner.py | 74 +- src/medical_coding/retrieval/hybrid.py | 78 ++- src/medical_coding/utils/clinical_lexicon.py | 15 +- src/medical_coding/utils/text.py | 20 +- .../validation/clinical_gate.py | 4 + .../validation/deterministic.py | 132 ++-- .../validation/reverse_attributes.py | 150 +++- ...est_normalization_and_primary_selection.py | 646 ++++++++++++++++++ 19 files changed, 1847 insertions(+), 375 deletions(-) create mode 100644 Database/.gitkeep create mode 100644 src/medical_coding/reasoning/concept_matcher.py diff --git a/.gitignore b/.gitignore index 9e18919..b5c9fed 100644 --- a/.gitignore +++ b/.gitignore @@ -101,8 +101,10 @@ models/embeddings/* !models/gguf/.gitkeep # Large External Datasets & User Uploads -/Database/ -/database/ +Database/* +!Database/.gitkeep +database/* +!database/.gitkeep *.xls *.xlsx data/icd10/*.txt diff --git a/Database/.gitkeep b/Database/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/README.md b/README.md index 8d29dcd..34d001e 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,10 @@ ### 🏥 Production System Overview **Autonomous Clinical Medical Coding Architecture** 🛡️ **Strict UHDDS & HIPAA Validation Engine** -📦 **Repository**: [Agentic ICD Code Matcher](https://github.com/AbhinavEliac/Agentic_ICD_Code_Matcher) +👤 **Author**: **Abhinav Gupta** — AI Developer, AI India Innovations +📧 **Email**: [abhinavg.aiindia@gmail.com](mailto:abhinavg.aiindia@gmail.com) +📦 **Gitea Repository**: [Agentic-ICD-Code-Matcher](https://gitea.aiindia.ai/Abhinav_Gupta/Agentic-ICD-Code-Matcher.git) +🌐 **GitHub Mirror**: [Agentic_ICD_Code_Matcher](https://github.com/AbhinavEliac/Agentic_ICD_Code_Matcher) @@ -47,6 +50,7 @@ - [10. Verification, Testing & Diagnostic Case Studies](#10-verification-testing--diagnostic-case-studies) - [11. Security & Data Privacy (HIPAA Compliance)](#11-security--data-privacy-hipaa-compliance) - [12. License](#12-license) +- [13. Author & Contact](#13-author--contact) --- @@ -408,6 +412,14 @@ Agentic_ICD_Code_Matcher/ ## 6. Installation & Environment Setup +### 📥 Clone Repository + +```bash +# Clone from Gitea +git clone https://gitea.aiindia.ai/Abhinav_Gupta/Agentic-ICD-Code-Matcher.git +cd Agentic-ICD-Code-Matcher +``` + ### 🚀 Automated Quick-Start Installers (Windows & Linux) The repository provides cross-platform installer scripts that automate the entire setup: @@ -690,6 +702,18 @@ Distributed under the **MIT License**. See `LICENSE` for details. --- +## 13. Author & Contact + +**Abhinav Gupta** +*AI Developer, AI India Innovations* +- 📧 **Email**: [abhinavg.aiindia@gmail.com](mailto:abhinavg.aiindia@gmail.com) +- 🏢 **Organization**: AI India Innovations +- 🐙 **GitHub**: [@AbhinavEliac](https://github.com/AbhinavEliac) +- 📦 **Gitea Repository**: [Agentic-ICD-Code-Matcher](https://gitea.aiindia.ai/Abhinav_Gupta/Agentic-ICD-Code-Matcher.git) +- 🔄 **GitHub Mirror**: [Agentic_ICD_Code_Matcher](https://github.com/AbhinavEliac/Agentic_ICD_Code_Matcher) + +--- +
**Autonomous Clinical ICD-10-CM Medical Coding Engine** diff --git a/pyproject.toml b/pyproject.toml index 18c376c..c860df6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ description = "Production-oriented local medical ICD-10-CM coding system using o readme = "README.md" requires-python = ">=3.13" license = { text = "Proprietary" } -authors = [{ name = "Principal Software Architect" }] +authors = [{ name = "Abhinav Gupta", email = "abhinavg.aiindia@gmail.com" }] [tool.setuptools.packages.find] where = ["src"] diff --git a/src/medical_coding/agents/classifier.py b/src/medical_coding/agents/classifier.py index 71db832..b4bb4e6 100644 --- a/src/medical_coding/agents/classifier.py +++ b/src/medical_coding/agents/classifier.py @@ -1360,8 +1360,8 @@ class PrimarySecondaryClassifier(BaseAgent): if is_chronic_cond and not is_explicit_primary and not is_admission_driver: has_acute_crisis = any(ac in full_context for ac in ["crisis", "emergency", "urgency", "malignant hypertension", "acute exacerbation", "decompensated", "ketoacidosis", "dka"]) if not has_acute_crisis: - score -= 1.5 - reasons.append("Chronic background condition without acute exacerbation (-1.5)") + score -= 6.0 + reasons.append("Chronic background condition without acute exacerbation (-6.0)") scored_candidates.append((asm, score, reasons)) @@ -1450,8 +1450,21 @@ class PrimarySecondaryClassifier(BaseAgent): ) return is_sym and not has_def + def _is_chronic_baseline(cand_asm: ContextAssessment) -> bool: + d_l = cand_asm.diagnosis.lower() + return bool( + re.search( + r"\b(?:type\s*(?:2|ii)?\s*diabetes|diabetes\s+mellitus|essential\s+hypertension|hyperlipidemia|dyslipidemia|hypothyroidism|osteoporosis|gerd|bph)\b", + d_l, + ) + and not re.search( + r"\b(?:ketoacidosis|dka|hyperosmolar|crisis|emergency|urgency|acute|gangrene|severe|decompensated)\b", + d_l, + ) + ) + has_definitive_candidates = any( - not _is_pure_symptom(c[0]) for c in scored_candidates if c[1] > 1.5 + not _is_pure_symptom(c[0]) and not _is_chronic_baseline(c[0]) for c in scored_candidates if c[1] > 1.5 ) chosen_primary_idx = None @@ -1528,7 +1541,13 @@ class PrimarySecondaryClassifier(BaseAgent): is_integral = HardClinicalCandidateGate.is_symptom_integral_to_primary( asm.diagnosis, top_asm.diagnosis, asm.evidence or "" ) - if is_integral: + has_dedicated_management = ( + getattr(asm, "treated_or_managed", False) + or getattr(asm, "monitored", False) + or getattr(asm, "affected_clinical_management", False) + or any(w in (asm.evidence or "").lower() for w in ("treated", "managed", "laxative", "fluid", "bolus", "iv ", "support", "transfusion", "monitored")) + ) + if is_integral and not has_dedicated_management: classifications.append( ConditionClassification( diagnosis_id=asm.condition_id or str(uuid4()), @@ -1661,7 +1680,7 @@ class PrimarySecondaryClassifier(BaseAgent): ) # UHDDS Guardrail: Verify if LLM marked an etiological 'Primary' condition (e.g. Primary hypertension) - # as the PRIMARY role when another acute occasioning condition is present + # or a chronic baseline comorbidity (e.g. Type 2 diabetes) as the PRIMARY role when an acute occasioning condition is present primaries = [c for c in classifications if c.role == DiagnosisRole.PRIMARY] if len(primaries) == 1: p = primaries[0] @@ -1672,13 +1691,25 @@ class PrimarySecondaryClassifier(BaseAgent): r"spontaneous\s+pneumothorax|amyloidosis|insomnia|cough\s+headache|polycythemia|thrombocythemia)\b", p_name, )) - if is_etio: + is_chronic_comorbid = bool( + re.search( + r"\b(?:type\s*(?:2|ii)?\s*diabetes|diabetes\s+mellitus|essential\s+hypertension|hyperlipidemia|dyslipidemia|hypothyroidism|osteoporosis|gerd|bph)\b", + p_name, + ) + and not re.search( + r"\b(?:ketoacidosis|dka|hyperosmolar|crisis|emergency|urgency|acute|gangrene|severe|decompensated)\b", + p_name, + ) + ) + if is_etio or is_chronic_comorbid: acute_other = next((c for c in classifications if c != p and c.role == DiagnosisRole.SECONDARY and ( - any(w in c.diagnosis.lower() for w in ["acute", "infarction", "fracture", "appendicitis", "cholecystitis", "sepsis", "stroke", "pneumonia"]) + any(w in c.diagnosis.lower() for w in ["acute", "infarction", "fracture", "appendicitis", "cholecystitis", "sepsis", "stroke", "pneumonia", "fever", "hypotension", "infection"]) + or any(w in (c.evidence_quote or "").lower() for w in ["admitted", "presented", "chief complaint", "reason for admission", "fever", "hypotension"]) )), None) if acute_other: p.role = DiagnosisRole.SECONDARY - p.classification_reason = f"Etiological 'Primary' in condition name denotes idiopathic etiology; reclassified as Secondary comorbidity under UHDDS guidelines. {p.classification_reason}" + reason_label = "Etiological 'Primary' in condition name denotes idiopathic etiology" if is_etio else "Chronic baseline comorbidity" + p.classification_reason = f"{reason_label}; reclassified as Secondary comorbidity under UHDDS guidelines. {p.classification_reason}" acute_other.role = DiagnosisRole.PRIMARY acute_other.primary_justification = f"Acute condition occasioning inpatient admission: {acute_other.evidence_quote}" diff --git a/src/medical_coding/agents/clinical_extractor.py b/src/medical_coding/agents/clinical_extractor.py index 884a437..c8d4721 100644 --- a/src/medical_coding/agents/clinical_extractor.py +++ b/src/medical_coding/agents/clinical_extractor.py @@ -308,12 +308,45 @@ class EvidenceFirstFactExtractor: if not key or len(key) < 2: return + # Check if item itself is contradicted by clinical stability / absence in its evidence quote + ev_snippet = (item.primary_evidence_quote or "").lower() + if "shock" in key or "shock" in raw_t.lower(): + if re.search(r"\b(?:no\s+shock|normotensive\s+without\s+shock|hemodynamically\s+stable|ruled\s+out\s+shock|shock\s+ruled\s+out|no\s+evidence\s+of\s+shock|stable\s+without\s+shock|not\s+in\s+shock|stable\s+hemodynamics|normotensive)\b", ev_snippet): + item.certainty = Certainty.RULED_OUT + item.role = DiagnosisRole.RULED_OUT + item.assertion_status = AssertionStatus.RULED_OUT + item.is_authorized = False + item.classification_reason = "Contradictory clinical evidence: shock documented as absent/ruled out or patient hemodynamically stable" + if key not in candidates_by_key: candidates_by_key[key] = item else: existing = candidates_by_key[key] existing.evidence.extend(item.evidence) - if item.role == DiagnosisRole.PRIMARY: + + # Contradiction / Ruled-out propagation: subsequent negative or ruled-out findings supersede initial impressions + if ( + item.certainty == Certainty.RULED_OUT + or item.role == DiagnosisRole.RULED_OUT + or any(ev.polarity == NegationStatus.NEGATED for ev in item.evidence) + ): + existing.certainty = Certainty.RULED_OUT + existing.role = DiagnosisRole.RULED_OUT + existing.assertion_status = AssertionStatus.RULED_OUT + existing.is_authorized = False + existing.classification_reason = f"Ruled out / negated by clinical evidence: {item.primary_evidence_quote}" + + # Check shock contradiction in merged evidence + if "shock" in key or "shock" in existing.raw_term.lower(): + all_ev_text = " ".join(ev.text for ev in existing.evidence).lower() + if re.search(r"\b(?:no\s+shock|normotensive\s+without\s+shock|hemodynamically\s+stable|ruled\s+out\s+shock|shock\s+ruled\s+out|no\s+evidence\s+of\s+shock|stable\s+without\s+shock|not\s+in\s+shock|stable\s+hemodynamics|normotensive)\b", all_ev_text): + existing.certainty = Certainty.RULED_OUT + existing.role = DiagnosisRole.RULED_OUT + existing.assertion_status = AssertionStatus.RULED_OUT + existing.is_authorized = False + existing.classification_reason = "Contradictory clinical evidence: shock documented as absent/ruled out or patient hemodynamically stable" + + if existing.certainty != Certainty.RULED_OUT and item.role == DiagnosisRole.PRIMARY: existing.role = DiagnosisRole.PRIMARY if item.primary_justification: existing.primary_justification = item.primary_justification @@ -333,7 +366,7 @@ class EvidenceFirstFactExtractor: existing.encounter_relevance = 0.0 existing.scores.encounter_relevance = 0.0 existing.scores.admitting_score = -50.0 - elif item.temporality == Temporality.CURRENT: + elif item.temporality == Temporality.CURRENT and existing.certainty != Certainty.RULED_OUT: existing.temporality = Temporality.CURRENT if existing.role == DiagnosisRole.HISTORICAL: existing.role = DiagnosisRole.SECONDARY @@ -825,6 +858,17 @@ class EvidenceFirstFactExtractor: proc_rel = 1.0 if any(re.search(pat, cleaned_line, re.IGNORECASE) for pat in PROCEDURE_SOURCE_CONTROL_CUES) else 0.0 treat_rel = 1.0 if any(w in cleaned_line.lower() for w in ["treated", "iv", "antibiotic", "diuresis", "insulin", "surgery", "stent", "infusion"]) else 0.0 + is_chronic_baseline = bool( + re.search( + r"\b(?:type\s*(?:2|ii)?\s*diabetes|diabetes\s+mellitus|essential\s+hypertension|hyperlipidemia|dyslipidemia|hypothyroidism|osteoporosis|gerd|benign\s+prostatic\s+hyperplasia|bph)\b", + sub_term.lower(), + ) + and not re.search( + r"\b(?:ketoacidosis|dka|hyperosmolar|crisis|emergency|urgency|acute|gangrene|severe|decompensated|failure)\b", + sub_term.lower(), + ) + ) + cand_temp = Temporality.HISTORICAL if is_explicit_historical else Temporality.CURRENT cand_role = ( DiagnosisRole.HISTORICAL @@ -832,8 +876,11 @@ class EvidenceFirstFactExtractor: else ( DiagnosisRole.PRIMARY if ( - (is_explicit_primary_line and sub_idx == 0) - or (sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and line_idx == 0 and sub_idx == 0) + not is_chronic_baseline + and ( + (is_explicit_primary_line and sub_idx == 0) + or (sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and line_idx == 0 and sub_idx == 0) + ) ) else DiagnosisRole.SECONDARY ) @@ -853,6 +900,8 @@ class EvidenceFirstFactExtractor: # Explicit PRINCIPAL_DIAGNOSIS gets highest base score (+15.0); DISCHARGE_DIAGNOSES gets +10.0; SECONDARY gets +3.0 if is_explicit_historical: base_admitting = -50.0 + elif is_chronic_baseline: + base_admitting = 4.0 elif is_explicit_primary_line and sub_idx == 0: base_admitting = 15.0 elif sec.section_name in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS"): @@ -2276,8 +2325,8 @@ class EvidenceFirstFactExtractor: # Independent organ conditions where "with" introduces a distinct co-occurring disease independent_with_pattern = ( - r",?\s*\bwith\s+(?:an?\s+)?(?:acute\s+|chronic\s+|severe\s+)?(?:right\s+|left\s+|bilateral\s+)?(?:parenchymal\s+)?(?:obstructive\s+)?" - r"(renal\s+calculus|kidney\s+stone|ureteral\s+stone|ureteric\s+stone|nephrolithiasis|renal\s+abscess|bacteremia|septic\s+shock|sepsis|cholecystitis|pancreatitis|pneumonia|abscess|(?:bilobar\s+|multiple\s+|solitary\s+)?(?:liver|pleural|pulmonary|bone|brain|distant)?\s*metastases?)\b" + r",?\s*\bwith\s+(?:an?\s+)?(?:acute\s+|chronic\s+|severe\s+|generalized\s+)?(?:right\s+|left\s+|bilateral\s+)?(?:parenchymal\s+)?(?:obstructive\s+)?" + r"(renal\s+calculus|kidney\s+stone|ureteral\s+stone|ureteric\s+stone|nephrolithiasis|renal\s+abscess|bacteremia|septic\s+shock|sepsis|cholecystitis|pancreatitis|pneumonia|abscess|(?:bilobar\s+|multiple\s+|solitary\s+)?(?:liver|pleural|pulmonary|bone|brain|distant)?\s*metastases?|hypotension|hypovolemia|dehydration|thrombocytopenia|petechiae|petechia|body\s+aches?|myalgia|arthralgia|constipation|vomiting|diarrhea|acute\s+kidney\s+injury|aki|acidosis|electrolyte\s+imbalance)\b" ) refined_chunks: list[str] = [] @@ -2358,11 +2407,26 @@ class EvidenceFirstFactExtractor: refined_chunks.append(chunk) # 2. Split chunks on " and " when connecting distinct clinical entities + ANATOMICAL_OR_MODIFIER_WORDS = { + "renal", "ureteral", "hepatic", "biliary", "aortic", "coronary", "gastric", "duodenal", + "splenic", "calcaneofibular", "deltoid", "left", "right", "bilateral", "upper", "lower", + "inner", "outer", "medial", "lateral", "anterior", "posterior", "acute", "chronic", + "subacute", "mild", "moderate", "severe", "head", "neck", "tarsal", "metatarsal", + "bone", "osseous", "signs", "symptoms", "rest", "fluids", "without", "with", + } final_items: list[str] = [] for item in refined_chunks: item_clean = re.sub(r"^(?:and|or)\s+", "", item.strip(), flags=re.IGNORECASE).strip() and_parts = [p.strip().strip(",; ") for p in re.split(r",?\s*\band\b\s*", item_clean, flags=re.IGNORECASE) if p.strip().strip(",; ")] - if len(and_parts) > 1 and all(len(p) >= 3 for p in and_parts): + can_split = ( + len(and_parts) > 1 + and all(len(p) >= 3 for p in and_parts) + and not any( + set(re.findall(r"[a-z]+", p.lower())).issubset(ANATOMICAL_OR_MODIFIER_WORDS) + for p in and_parts + ) + ) + if can_split: for p in and_parts: final_items.append(p) else: @@ -2462,8 +2526,15 @@ class EvidenceFirstFactExtractor: def _canonicalize_term(self, term: str) -> str: clean = re.sub(r"^\d+[\.\)\-]\s*", "", term).strip() - # Strip parenthetical annotations if attached (e.g. "(BP 210/110)", "(K 7.2 - 8.9)", "(CLD)", "(PVT)") - clean = re.sub(r"\([^)]*\)", "", clean).strip() + # Handle parentheticals: preserve clinical qualifiers e.g. (calculous), (stage 3b); strip purely administrative artifacts + from medical_coding.utils.text import _is_administrative_parenthetical + def _clean_paren(m: re.Match[str]) -> str: + inside = m.group(1).strip() + if _is_administrative_parenthetical(inside): + return " " + return f" ({inside}) " + + clean = re.sub(r"[\(\[\{]([^\)\]\}]+)[\)\]\}]", _clean_paren, clean) clean = re.sub(r",?\s*with\s+(?:significantly\s+)?elevated\s+creatinine.*$", "", clean, flags=re.IGNORECASE).strip() clean = re.sub(r"\s+", " ", clean).strip(".,;: ") @@ -2472,7 +2543,7 @@ class EvidenceFirstFactExtractor: return "Malignant neoplasm of ampulla of Vater" if re.search(r"\b(?:adenocarcinoma\s+nos|invasive\s+adenocarcinoma|infiltrating\s+adenocarcinoma|adenocarcinoma\s+composed\s+of\s+solid\s+glands|moderately\s+differentiated\s+adenocarcinoma)\b", clean, re.IGNORECASE): - return "ADENOMAS NAD ADENCARCINOMAS-Adenocarcinoma NOS" + return "Adenocarcinoma NOS" # 2. Oncology metastatic manifestations if re.search( @@ -2564,10 +2635,10 @@ class EvidenceFirstFactExtractor: return "Portal vein thrombosis" if re.search(r"\b(?:smv\s+and\s+portal\s+vein\s+thrombosis|smv\s+thrombosis|superior\s+mesenteric\s+vein\s+thrombosis)\b", clean, re.IGNORECASE): - return "Chronic embolism and thrombosis of inferior vena cava" + return "Superior mesenteric vein thrombosis" if re.search(r"\b(?:portal\s+hypertensive\s+gastropathy|phg)\b", clean, re.IGNORECASE): - return "Angiodysplasia of stomach and duodenum with bleeding" + return "Portal hypertensive gastropathy" if re.search(r"\b(?:colitis|noninfective\s+colitis|mild\s+colitis)\b", clean, re.IGNORECASE): return "Noninfective gastroenteritis and colitis, unspecified" @@ -2585,9 +2656,6 @@ class EvidenceFirstFactExtractor: if re.search(r"\b(?:type\s+2\s+diabetes|t2dm|diabetes\s+mellitus\s+type\s+2|type\s+ii\s+diabetes)\b", clean, re.IGNORECASE): return "Type 2 diabetes mellitus" - if re.search(r"\b(?:portal\s+hypertensive\s+gastropathy|phg|gastropathy\s+portal)\b", clean, re.IGNORECASE): - return "Angiodysplasia of stomach and duodenum with bleeding" - if re.search(r"\bportal\s+hypertension\b", clean, re.IGNORECASE): return "Portal hypertension" @@ -2849,6 +2917,29 @@ class EvidenceFirstFactExtractor: cand.role = DiagnosisRole.EXCLUDED cand.is_authorized = False + def _is_chronic_baseline_cand(c: ClinicalDiagnosisCandidate) -> bool: + c_term = c.normalized_diagnosis.lower() + return bool( + re.search( + r"\b(?:type\s*(?:2|ii)?\s*diabetes|diabetes\s+mellitus|essential\s+hypertension|hyperlipidemia|dyslipidemia|hypothyroidism|osteoporosis|gerd|benign\s+prostatic\s+hyperplasia|bph)\b", + c_term, + ) + and not re.search( + r"\b(?:ketoacidosis|dka|hyperosmolar|crisis|emergency|urgency|acute|gangrene|severe|decompensated|failure)\b", + c_term, + ) + ) + + has_acute_driver = any( + (c.scores.admitting_score >= 4.0 or any(w in c.normalized_diagnosis.lower() for w in ("acute", "fever", "hypotension", "sepsis", "shock", "infarction", "fracture", "appendicitis", "cholecystitis", "pneumonia"))) + and not _is_chronic_baseline_cand(c) + for c in valid_active + ) + if has_acute_driver: + for c in valid_active: + if _is_chronic_baseline_cand(c): + c.scores.admitting_score = min(c.scores.admitting_score, 3.5) + # 2. Sort active candidates by admitting score descending valid_active.sort(key=lambda c: c.scores.admitting_score, reverse=True) @@ -2928,7 +3019,12 @@ class EvidenceFirstFactExtractor: is_integral = HardClinicalCandidateGate.is_symptom_integral_to_primary( sec_cand.normalized_diagnosis, top.normalized_diagnosis, sec_cand.primary_evidence_quote ) - if is_integral: + has_dedicated_management = ( + sec_cand.treatment_relevance > 0 + or sec_cand.procedure_relevance > 0 + or any(w in sec_cand.primary_evidence_quote.lower() for w in ("treated", "managed", "laxative", "fluid", "bolus", "iv ", "support", "transfusion", "monitored")) + ) + if is_integral and not has_dedicated_management: from medical_coding.schemas.enums import ClinicalEntityType sec_cand.role = DiagnosisRole.SYMPTOM sec_cand.entity_type = ClinicalEntityType.SYMPTOM diff --git a/src/medical_coding/agents/ranker.py b/src/medical_coding/agents/ranker.py index d8f18ee..7b97fbc 100644 --- a/src/medical_coding/agents/ranker.py +++ b/src/medical_coding/agents/ranker.py @@ -529,10 +529,29 @@ class CandidateRankingAgent(BaseAgent): # 3. Direct diagnosis term overlap (differentiates diagnosis from incidental narrative mentions) norm_desc = (getattr(condition, "normalized_description", None) or getattr(condition, "diagnosis", "") or "").lower().strip() - if desc_lower == term_clean or (norm_desc and desc_lower == norm_desc): + from medical_coding.reasoning.concept_matcher import ( + normalize_for_concept_matching, + strip_nonessential_modifiers, + ) + desc_stripped = strip_nonessential_modifiers(desc_lower) + term_stripped = strip_nonessential_modifiers(term_clean) + norm_stripped = strip_nonessential_modifiers(norm_desc) if norm_desc else "" + + cand_norm = normalize_for_concept_matching(desc_lower) + term_norm = normalize_for_concept_matching(term_clean) + norm_norm = normalize_for_concept_matching(norm_desc) if norm_desc else "" + + if ( + desc_lower == term_clean + or (norm_desc and desc_lower == norm_desc) + or desc_stripped == term_stripped + or (norm_stripped and desc_stripped == norm_stripped) + or cand_norm == term_norm + or (norm_norm and cand_norm == norm_norm) + ): score += 0.60 rationale_parts.append("exact clinical description match") - elif any(syn in term_clean or (norm_desc and syn in norm_desc) for syn in [cand.code.lower(), desc_lower]): + elif any(syn in term_clean or (norm_desc and syn in norm_desc) for syn in [cand.code.lower(), desc_lower, desc_stripped]): score += 0.40 rationale_parts.append("strong synonym match") @@ -615,11 +634,20 @@ class CandidateRankingAgent(BaseAgent): code_description=cand.description, evidence_text=evidence_clean, diagnosis_term=term_clean, + code=cand.code, ) if not is_attr_valid: - # Proportional soft specificity penalty instead of binary disqualification (Master Prompt Section 4 & 25) - score -= min(0.35, 0.15 * len(unsupp_attrs)) - rationale_parts.append(f"unsupported attributes: {', '.join(unsupp_attrs)}") + has_hard_fail = any( + any(k in u.lower() for k in ("demographic", "perinatal", "neonatal", "pregnancy", "obstetric", "polarity", "contradictory", "mismatch", "pathogen")) + for u in unsupp_attrs + ) + if has_hard_fail: + score = -10.0 + rationale_parts.append(f"disqualified by clinical contradiction: {', '.join(unsupp_attrs)}") + else: + # Proportional soft specificity penalty instead of binary disqualification (Master Prompt Section 4 & 25) + score -= min(0.35, 0.15 * len(unsupp_attrs)) + rationale_parts.append(f"unsupported attributes: {', '.join(unsupp_attrs)}") # 7. Laterality alignment (Master Prompt Section 5, 24: reward documented laterality, penalize unspecified laterality) doc_left = bool(re.search(r"\b(?:left|lt)\b", full_context)) @@ -725,32 +753,42 @@ class CandidateRankingAgent(BaseAgent): # and has core_match_fraction > 0.0 matching_status = "MATCHED" if top_score < self.min_confidence: - fallback_cand = None + valid_candidates = [] for cand, s, rat in scored_candidates: if not cand.is_valid_billable: continue is_valid, _ = ReverseAttributeChecker.validate_code_attributes( - cand.description, evidence_clean, term_clean + cand.description, evidence_clean, term_clean, code=cand.code ) - if is_valid and s >= 0.35: - fallback_cand = cand - top_score = s - top_rationale = f"specificity realigned: {rat}" - break + if is_valid: + valid_candidates.append(cand) - if fallback_cand: - top_cand = fallback_cand + if valid_candidates: + from medical_coding.reasoning.concept_matcher import select_best_concept_match + best_cand, best_s, best_rat = select_best_concept_match( + candidates=valid_candidates, + concept_name=raw_term, + evidence_text=evidence_clean, + min_score_threshold=0.30, + ) + if best_cand: + top_cand = best_cand + top_score = max(0.40, best_s) + top_rationale = f"specificity realigned (best concept match): {best_rat}" elif candidates and evidence_quote: - # Per requirement: for [no_local_code] diagnoses with evidence, display the nearest relatable code - nearest_cand = scored_candidates[0][0] - for cand, s, rat in scored_candidates: - if cand.is_valid_billable: - nearest_cand = cand - break - top_cand = nearest_cand - top_score = max(0.40, top_score) - top_rationale = f"nearest relatable candidate assigned for documented condition ({top_rationale})" - matching_status = "NEAREST_MATCH" + from medical_coding.reasoning.concept_matcher import select_best_concept_match + billable_pool = [c for c in candidates if c.is_valid_billable] or candidates + best_cand, best_s, best_rat = select_best_concept_match( + candidates=billable_pool, + concept_name=raw_term, + evidence_text=evidence_clean, + min_score_threshold=0.20, + ) + if best_cand: + top_cand = best_cand + top_score = max(0.40, best_s) + top_rationale = f"nearest relatable candidate for documented condition: {best_rat}" + matching_status = "NEAREST_MATCH" else: abstain_reason = ( "UNSUPPORTED_SPECIFICITY" diff --git a/src/medical_coding/graph/nodes.py b/src/medical_coding/graph/nodes.py index 2cfc909..835a0bf 100644 --- a/src/medical_coding/graph/nodes.py +++ b/src/medical_coding/graph/nodes.py @@ -603,7 +603,7 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]: hits.append(h) existing_codes.add(h.code) - if search_query != clean_query and (not primary_hits or primary_hits[0].retrieval_score < 0.70): + if search_query != clean_query: fallback_primary = retriever.retrieve(clean_query, top_k=15, system="ICD-10-CM") for h in fallback_primary: if h.code not in existing_codes: @@ -611,39 +611,52 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]: existing_codes.add(h.code) # STAGE 2: Microsecond BM25 Inverted-Index Expansions (Bypasses redundant neural vector calls) + from medical_coding.reasoning.concept_matcher import compute_concept_match_score from medical_coding.retrieval.tokenizer import ( CLINICAL_ABBREVIATIONS, CLINICAL_MORPHOLOGY, get_expanded_query_tokens, ) + + has_exact_match = False + for h in hits: + _, _, is_ex = compute_concept_match_score( + candidate_code=h.code, + candidate_description=h.description, + concept_name=concept.canonical_name or clean_query, + evidence_text=ev_quote, + ) + if is_ex: + has_exact_match = True + break + lexical_terms: list[str] = [] - has_exact_match = bool(hits and hits[0].retrieval_score >= 0.90) if not has_exact_match: if concept.canonical_name and concept.canonical_name.lower() != clean_query.lower(): lexical_terms.append(concept.canonical_name) if raw_query.lower() != clean_query.lower(): lexical_terms.append(raw_query) - query_lower = clean_query.lower() - for ab, full in CLINICAL_ABBREVIATIONS.items(): - if re.search(rf"\b{re.escape(ab)}\b", query_lower): - lexical_terms.append(re.sub(rf"\b{re.escape(ab)}\b", full, query_lower)) + query_lower = clean_query.lower() + for ab, full in CLINICAL_ABBREVIATIONS.items(): + if re.search(rf"\b{re.escape(ab)}\b", query_lower): + lexical_terms.append(re.sub(rf"\b{re.escape(ab)}\b", full, query_lower)) - if concept.metastatic_status and concept.body_site: - lexical_terms.append(f"secondary malignant neoplasm of {concept.body_site}") - elif concept.histology and concept.body_site: - lexical_terms.append(f"{concept.histology} of {concept.body_site}") + if concept.metastatic_status and concept.body_site: + lexical_terms.append(f"secondary malignant neoplasm of {concept.body_site}") + elif concept.histology and concept.body_site: + lexical_terms.append(f"{concept.histology} of {concept.body_site}") - if concept.acuity and concept.canonical_name: - lexical_terms.append(f"{concept.acuity} {concept.canonical_name}") + if concept.acuity and concept.canonical_name: + lexical_terms.append(f"{concept.acuity} {concept.canonical_name}") - exp_tokens = get_expanded_query_tokens(clean_query) - if exp_tokens and len(exp_tokens) > 1: - morph_q = " ".join(exp_tokens[:6]) - if morph_q not in lexical_terms: - lexical_terms.append(morph_q) + exp_tokens = get_expanded_query_tokens(clean_query) + if exp_tokens and len(exp_tokens) > 1: + morph_q = " ".join(exp_tokens[:6]) + if morph_q not in lexical_terms: + lexical_terms.append(morph_q) - for lt in lexical_terms[:4]: + for lt in lexical_terms[:6]: try: lex_hits = retriever.lexical_retriever.retrieve(lt, top_k=15) for h in lex_hits: @@ -739,7 +752,10 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]: cand.retrieval_score = round(max(cand.retrieval_score, c_score), 4) final_hits.append(cand) if not final_hits: - final_hits = hits[:10] + if not concept.contradictory_attributes and concept.assertion_status != "RULED_OUT": + final_hits = hits[:10] + else: + final_hits = [] # Handle ICD-O for neoplasms: only primary neoplasms require histology morphology coding is_primary_neoplasm = ( @@ -863,6 +879,8 @@ def rank_candidates_node(state: PipelineGraphState) -> dict[str, Any]: and bool(clean_evidence_quote.strip()) and cond.role in (DiagnosisRole.PRIMARY, DiagnosisRole.SECONDARY) and getattr(cond, "is_billable_candidate", True) + and getattr(cond.context, "certainty", None) != Certainty.RULED_OUT + and getattr(cond.context, "negation", None) != NegationStatus.NEGATED ): logger.info("Condition '%s' with positive evidence lacked code; re-checking with multi-round BM25 and vector search...", cond.raw_term) _, retry_retriever = get_or_initialize_retrieval_system() @@ -1057,7 +1075,15 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: else Acuity.CHRONIC if "chronic" in item.description.lower() else Acuity.UNSPECIFIED, - certainty=Certainty.CONFIRMED, + certainty=( + Certainty.RULED_OUT + if any(k in item.raw_term.lower() for k in ("ruled out", "negated")) + or ( + ("shock" in item.raw_term.lower() or "shock" in item.description.lower()) + and re.search(r"\b(?:no\s+shock|hemodynamically\s+stable|normotensive\s+without\s+shock|ruled\s+out\s+shock|shock\s+ruled\s+out|no\s+evidence\s+of\s+shock|stable\s+without\s+shock|normotensive)\b", item.evidence.quote.lower()) + ) + else (getattr(item, "certainty", Certainty.CONFIRMED) or Certainty.CONFIRMED) + ), evidence_quote=item.evidence.quote, evidence=[ { @@ -1078,6 +1104,19 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: icdo=icdo_val, cpt=cpt_val, ) + if resp.certainty == Certainty.RULED_OUT: + if not any(a.raw_term and a.raw_term.lower() == item.raw_term.lower() for a in abstentions): + abstentions.append( + AbstentionRecord( + diagnosis_id=getattr(item, "diagnosis_id", "unknown"), + raw_term=item.raw_term, + reason=AbstentionReason.EXCLUDED_BY_NEGATION, + detail=f"Condition '{item.raw_term}' is ruled out or contradicted by clinical evidence; excluded from final report.", + stage=PipelineStage.FINAL_OUTPUT, + ) + ) + continue + if item.role == DiagnosisRole.PRIMARY: primary_response = resp elif item.role == DiagnosisRole.SECONDARY: @@ -1085,6 +1124,18 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: catalog, retriever = get_or_initialize_retrieval_system() + def _is_abstained_or_rejected(diag_id: str, diag_term: str) -> bool: + term_l = (diag_term or "").lower().strip() + for a in abstentions: + if a.diagnosis_id and a.diagnosis_id == diag_id: + return True + if a.raw_term and a.raw_term.lower().strip() == term_l: + return True + for r in state.get("ranked_selections", []): + if r.diagnosis_id == diag_id and r.decision in ("ABSTAINED", "REJECTED"): + return True + return False + # SEPARATION OF CLINICAL DIAGNOSIS AND ICD CODE MAPPING (Sections 4 & 11) # If primary diagnosis was clinically confirmed and established, but ICD mapping abstained or failed: if primary_response is None: @@ -1098,77 +1149,84 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: if clin_primary: term = getattr(clin_primary, "normalized_diagnosis", None) or getattr(clin_primary, "raw_term", "") - c_ev = ( - getattr(clin_primary, "evidence_quote", None) - or getattr(clin_primary, "primary_evidence_quote", None) - or ( - clin_primary.context.evidence.quote - if hasattr(clin_primary, "context") and hasattr(clin_primary.context, "evidence") and clin_primary.context.evidence - else "" - ) - or "" - ) - retrieved = retriever.retrieve(term, top_k=5) if term else [] - nearest_cand = None - for cand in retrieved: - if catalog.is_valid_code(cand.code) and catalog.is_billable_code(cand.code): - cand_desc_lower = cand.description.lower() - term_lower = term.lower() - from medical_coding.retrieval.tokenizer import expand_medical_abbreviations, CLINICAL_MORPHOLOGY - t_exp = expand_medical_abbreviations(term_lower) - c_exp = expand_medical_abbreviations(cand_desc_lower) - ignore_w = {"primary", "secondary", "acute", "chronic", "type", "with", "unspecified", "disease", "syndrome", "disorder", "essential"} - term_words = [w for w in re.findall(r"\b[a-z]{3,}\b", t_exp) if w not in ignore_w] - desc_words = set(w for w in re.findall(r"\b[a-z]{3,}\b", c_exp) if w not in ignore_w) - has_core_overlap = any( - tw in desc_words or any(syn in desc_words for syn in CLINICAL_MORPHOLOGY.get(tw, [])) - for tw in term_words - ) if term_words else False - score_val = getattr(cand, "retrieval_score", 0.0) - if has_core_overlap and score_val >= 0.45: - nearest_cand = cand - break - - if nearest_cand and c_ev: - is_icdo = bool(getattr(nearest_cand, "coding_system", None) == "ICD-O" or nearest_cand.code.startswith("M")) - is_cpt = bool(getattr(nearest_cand, "coding_system", None) == "CPT" or (nearest_cand.code.isdigit() and len(nearest_cand.code) in (4, 5))) - icd10_val = nearest_cand.code if not is_icdo and not is_cpt else None - icdo_val = nearest_cand.code if is_icdo else None - cpt_val = nearest_cand.code if is_cpt else None - - primary_response = CodedDiagnosisResponse( - raw_term=term, - normalized_diagnosis=term, - description=nearest_cand.description, - database_code=nearest_cand.code, - database_description=nearest_cand.description, - matching_status="NEAREST_MATCH", - source_section=getattr(clin_primary, "source_section", "") or "CLINICAL_DOCUMENTATION", - role=DiagnosisRole.PRIMARY, - acuity=Acuity.ACUTE if "acute" in term.lower() else (Acuity.CHRONIC if "chronic" in term.lower() else Acuity.UNSPECIFIED), - certainty=Certainty.CONFIRMED, - evidence_quote=c_ev or term, - evidence=[{ - "quote": c_ev or term, - "section": getattr(clin_primary, "source_section", "") or "CLINICAL_DOCUMENTATION", - "evidence_type": "CLINICAL_EVIDENCE", - }], - confidence_score=max(0.40, getattr(nearest_cand, "retrieval_score", 0.50)), - is_terminal_billable=True, - icd10cm=icd10_val, - icdo=icdo_val, - cpt=cpt_val, - ) - elif not any(a.reason == AbstentionReason.NO_MATCHING_ICD_CANDIDATE and a.raw_term and a.raw_term.lower() == term.lower() for a in abstentions): - abstentions.append( - AbstentionRecord( - diagnosis_id=getattr(clin_primary, "diagnosis_id", "primary"), - raw_term=term, - reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE, - detail=f"Clinical primary diagnosis '{term}' lacked verified local code match; strictly abstained under coding rules.", - stage=PipelineStage.VALIDATION, + clin_primary_id = getattr(clin_primary, "diagnosis_id", "") + if _is_abstained_or_rejected(clin_primary_id, term): + logger.info("Primary diagnosis '%s' was explicitly abstained/rejected in validation; honoring decision.", term) + if secondary_responses: + primary_response = secondary_responses.pop(0) + primary_response.role = DiagnosisRole.PRIMARY + else: + c_ev = ( + getattr(clin_primary, "evidence_quote", None) + or getattr(clin_primary, "primary_evidence_quote", None) + or ( + clin_primary.context.evidence.quote + if hasattr(clin_primary, "context") and hasattr(clin_primary.context, "evidence") and clin_primary.context.evidence + else "" ) + or "" ) + from medical_coding.reasoning.concept_matcher import select_best_concept_match + from medical_coding.validation.reverse_attributes import ReverseAttributeChecker + retrieved = retriever.retrieve(term, top_k=15) if term else [] + nearest_cand, best_concept_s, best_rat = select_best_concept_match( + candidates=retrieved, + concept_name=term, + evidence_text=c_ev, + catalog=catalog, + min_score_threshold=0.35, + ) + + if nearest_cand and c_ev: + anat_ok, _ = ReverseAttributeChecker.validate_anatomical_site(nearest_cand.description, c_ev, term) + lat_ok, _ = ReverseAttributeChecker.validate_laterality(nearest_cand.description, c_ev, term) + attr_ok, _ = ReverseAttributeChecker.validate_code_attributes(nearest_cand.description, c_ev, term, code=nearest_cand.code) + if not (anat_ok and lat_ok and attr_ok): + nearest_cand = None + + if nearest_cand and c_ev: + is_icdo = bool(getattr(nearest_cand, "coding_system", None) == "ICD-O" or nearest_cand.code.startswith("M")) + is_cpt = bool(getattr(nearest_cand, "coding_system", None) == "CPT" or (nearest_cand.code.isdigit() and len(nearest_cand.code) in (4, 5))) + icd10_val = nearest_cand.code if not is_icdo and not is_cpt else None + icdo_val = nearest_cand.code if is_icdo else None + cpt_val = nearest_cand.code if is_cpt else None + + primary_response = CodedDiagnosisResponse( + raw_term=term, + normalized_diagnosis=term, + description=nearest_cand.description, + database_code=nearest_cand.code, + database_description=nearest_cand.description, + matching_status="NEAREST_MATCH", + source_section=getattr(clin_primary, "source_section", "") or "CLINICAL_DOCUMENTATION", + role=DiagnosisRole.PRIMARY, + acuity=Acuity.ACUTE if "acute" in term.lower() else (Acuity.CHRONIC if "chronic" in term.lower() else Acuity.UNSPECIFIED), + certainty=getattr(clin_primary, "certainty", Certainty.CONFIRMED) or Certainty.CONFIRMED, + evidence_quote=c_ev or term, + evidence=[{ + "quote": c_ev or term, + "section": getattr(clin_primary, "source_section", "") or "CLINICAL_DOCUMENTATION", + "evidence_type": "CLINICAL_EVIDENCE", + }], + confidence_score=max(0.40, getattr(nearest_cand, "retrieval_score", 0.50)), + is_terminal_billable=True, + icd10cm=icd10_val, + icdo=icdo_val, + cpt=cpt_val, + ) + elif not any(a.reason == AbstentionReason.NO_MATCHING_ICD_CANDIDATE and a.raw_term and a.raw_term.lower() == term.lower() for a in abstentions): + abstentions.append( + AbstentionRecord( + diagnosis_id=getattr(clin_primary, "diagnosis_id", "primary"), + raw_term=term, + reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE, + detail=f"Clinical primary diagnosis '{term}' lacked verified local code match; strictly abstained under coding rules.", + stage=PipelineStage.VALIDATION, + ) + ) + if secondary_responses: + primary_response = secondary_responses.pop(0) + primary_response.role = DiagnosisRole.PRIMARY # SEPARATION OF CLINICAL DIAGNOSIS AND ICD CODE MAPPING FOR SECONDARIES seen_sec_terms = set() @@ -1200,8 +1258,16 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: for c in candidates_to_check: c_role = getattr(c, "role", None) c_billable = getattr(c, "is_billable_candidate", True) + c_certainty = getattr(c, "certainty", None) + if hasattr(c, "context") and getattr(c.context, "certainty", None): + c_certainty = c.context.certainty + if getattr(c, "is_authorized", True) is False: continue + if c_certainty == Certainty.RULED_OUT: + continue + if c_role in (DiagnosisRole.RULED_OUT, DiagnosisRole.EXCLUDED, "RULED_OUT", "EXCLUDED"): + continue if (c_role in (DiagnosisRole.SECONDARY, "SECONDARY")) and c_billable: c_term = ( getattr(c, "normalized_diagnosis", None) @@ -1245,6 +1311,12 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: if not is_valid_cand: continue + if _is_abstained_or_rejected(getattr(c, "diagnosis_id", ""), c_term): + continue + + if "shock" in c_norm and bool(re.search(r"\b(?:no\s+shock|normotensive\s+without\s+shock|hemodynamically\s+stable|ruled\s+out\s+shock|shock\s+ruled\s+out|no\s+evidence\s+of\s+shock|stable\s+without\s+shock|not\s+in\s+shock|stable\s+hemodynamics|bp\s+normalized|normotensive)\b", f"{c_quote} {raw_doc_text}".lower())): + continue + # Per requirement: for [no_local_code] type diagnosis, nearest relatable code should get displayed, because they also have evidence from medical_coding.validation.reverse_attributes import ReverseAttributeChecker @@ -1269,24 +1341,26 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: code_description=cand.description, evidence_text=c_quote, diagnosis_term=c_term, + code=cand.code, ) if not attr_ok: return False return True - nearest_cand = None + from medical_coding.reasoning.concept_matcher import select_best_concept_match cand_pool_item = state.get("candidate_pool", {}).get(getattr(c, "diagnosis_id", ""), []) - if cand_pool_item: - for cand in cand_pool_item: - if _is_clinically_relatable(cand): - nearest_cand = cand - break - if not nearest_cand and c_term: - retrieved = retriever.retrieve(c_term, top_k=5) - for cand in retrieved: - if _is_clinically_relatable(cand): - nearest_cand = cand - break + relatable_pool = [cand for cand in cand_pool_item if _is_clinically_relatable(cand)] + if not relatable_pool and c_term: + retrieved = retriever.retrieve(c_term, top_k=15) + relatable_pool = [cand for cand in retrieved if _is_clinically_relatable(cand)] + + nearest_cand, best_score, best_rat = select_best_concept_match( + candidates=relatable_pool, + concept_name=c_term, + evidence_text=c_quote, + catalog=catalog, + min_score_threshold=0.35, + ) if nearest_cand and c_quote: is_icdo = bool(getattr(nearest_cand, "coding_system", None) == "ICD-O" or nearest_cand.code.startswith("M")) @@ -1305,7 +1379,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: source_section=getattr(c, "source_section", "") or "CLINICAL_DOCUMENTATION", role=DiagnosisRole.SECONDARY, acuity=Acuity.ACUTE if "acute" in c_norm else (Acuity.CHRONIC if "chronic" in c_norm else Acuity.UNSPECIFIED), - certainty=Certainty.CONFIRMED, + certainty=getattr(c, "certainty", Certainty.CONFIRMED) or Certainty.CONFIRMED, evidence_quote=c_quote or c_term, evidence=[{ "quote": c_quote or c_term, @@ -1348,12 +1422,31 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: coded_secondaries.append(s) elif s.evidence_quote: s_name = s.normalized_diagnosis or s.raw_term or s.description or "" + if _is_abstained_or_rejected(getattr(s, "diagnosis_id", ""), s_name): + if s_name and not any(a.raw_term and a.raw_term.lower() == s_name.lower() for a in abstentions): + abstentions.append( + AbstentionRecord( + diagnosis_id=getattr(s, "diagnosis_id", "secondary-abstained"), + raw_term=s_name, + reason=AbstentionReason.UNSUPPORTED_SPECIFICITY, + detail=f"Condition '{s_name}' was abstained during validation; strictly honoring abstention.", + stage=PipelineStage.VALIDATION, + ) + ) + continue retrieved = retriever.retrieve_with_retry(s_name, evidence=s.evidence_quote, top_k=5, min_score=0.20) if s_name else [] - if retrieved: - top_r = retrieved[0] - s.icd10cm = top_r.code - s.database_code = top_r.code - s.database_description = top_r.description + valid_top = None + for cand in retrieved: + anat_ok, _ = ReverseAttributeChecker.validate_anatomical_site(cand.description, s.evidence_quote, s_name) + lat_ok, _ = ReverseAttributeChecker.validate_laterality(cand.description, s.evidence_quote, s_name) + attr_ok, _ = ReverseAttributeChecker.validate_code_attributes(cand.description, s.evidence_quote, s_name, code=cand.code) + if anat_ok and lat_ok and attr_ok: + valid_top = cand + break + if valid_top: + s.icd10cm = valid_top.code + s.database_code = valid_top.code + s.database_description = valid_top.description s.matching_status = "NEAREST_MATCH" coded_secondaries.append(s) else: @@ -1386,15 +1479,24 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: p_code = primary_response.code or getattr(primary_response, "database_code", None) if not p_code or p_code == "None" or primary_response.matching_status == "NO_DATABASE_MATCH": p_name = primary_response.normalized_diagnosis or primary_response.raw_term or primary_response.description or "" - if primary_response.evidence_quote and p_name: + if _is_abstained_or_rejected(getattr(primary_response, "diagnosis_id", ""), p_name): + p_code = None + elif primary_response.evidence_quote and p_name: retrieved = retriever.retrieve_with_retry(p_name, evidence=primary_response.evidence_quote, top_k=5, min_score=0.20) - if retrieved: - top_r = retrieved[0] - primary_response.icd10cm = top_r.code - primary_response.database_code = top_r.code - primary_response.database_description = top_r.description + valid_p = None + for cand in retrieved: + anat_ok, _ = ReverseAttributeChecker.validate_anatomical_site(cand.description, primary_response.evidence_quote, p_name) + lat_ok, _ = ReverseAttributeChecker.validate_laterality(cand.description, primary_response.evidence_quote, p_name) + attr_ok, _ = ReverseAttributeChecker.validate_code_attributes(cand.description, primary_response.evidence_quote, p_name, code=cand.code) + if anat_ok and lat_ok and attr_ok: + valid_p = cand + break + if valid_p: + primary_response.icd10cm = valid_p.code + primary_response.database_code = valid_p.code + primary_response.database_description = valid_p.description primary_response.matching_status = "NEAREST_MATCH" - p_code = top_r.code + p_code = valid_p.code if not p_code or p_code == "None" or primary_response.matching_status == "NO_DATABASE_MATCH": if p_name and not any(a.raw_term and a.raw_term.lower() == p_name.lower() for a in abstentions): abstentions.append( @@ -1412,124 +1514,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: else: primary_response = None - # Multi-round checking for abstentions with positive evidence - from medical_coding.utils.text import normalize_diagnosis_name - rechecked_abstentions: list[AbstentionRecord] = [] - for abst in abstentions: - a_term = abst.raw_term or "" - a_detail = abst.detail or "" - is_negated_or_ruled_out = ( - abst.reason in ( - AbstentionReason.EXCLUDED_BY_NEGATION, - AbstentionReason.EXCLUDED_BY_TEMPORALITY, - AbstentionReason.CONTRADICTORY_DOCUMENTATION, - ) - or "ruled out" in a_detail.lower() - or "ruled-out" in a_detail.lower() - or "negat" in a_detail.lower() - or "past medical history alone without" in a_detail.lower() - ) - if is_negated_or_ruled_out or not a_term: - rechecked_abstentions.append(abst) - continue - - ev_quote = "" - matching_cond = next(( - c for c in classified - if (getattr(c, "diagnosis", None) or getattr(c, "raw_term", "")).lower() == a_term.lower() - ), None) - if matching_cond: - ev_quote = getattr(matching_cond, "evidence_quote", "") or ( - matching_cond.context.evidence.quote - if hasattr(matching_cond, "context") and hasattr(matching_cond.context, "evidence") and matching_cond.context.evidence - else "" - ) - if not ev_quote and diag_state: - matching_diag = next(( - d for d in diag_state.all_candidates - if d.raw_term.lower() == a_term.lower() or (d.normalized_diagnosis and d.normalized_diagnosis.lower() == a_term.lower()) - ), None) - if matching_diag: - ev_quote = matching_diag.primary_evidence_quote or "" - if not ev_quote: - raw_doc = state.get("raw_text", "") - if a_term.lower() in raw_doc.lower(): - ev_quote = a_term - - if not ev_quote: - rechecked_abstentions.append(abst) - continue - - is_valid_cand, _ = HardClinicalCandidateGate.evaluate_candidate(a_term, ev_quote) - if not is_valid_cand: - rechecked_abstentions.append(abst) - continue - - norm_a = normalize_diagnosis_name(a_term) - retry_hits = retriever.retrieve_with_retry( - norm_a or a_term, - evidence=ev_quote, - top_k=5, - min_score=0.20, - ) - - valid_hit = None - for h in retry_hits: - if catalog.is_valid_code(h.code) and catalog.is_billable_code(h.code): - valid_hit = h - break - if not valid_hit and retry_hits: - valid_hit = retry_hits[0] - - if valid_hit: - hit_code = valid_hit.code - is_dup = ( - (primary_response and primary_response.code == hit_code) - or any(s.code == hit_code for s in secondary_responses) - ) - if not is_dup: - is_icdo = bool(getattr(valid_hit, "coding_system", None) == "ICD-O" or valid_hit.code.startswith("M")) - is_cpt = bool(getattr(valid_hit, "coding_system", None) == "CPT" or (valid_hit.code.isdigit() and len(valid_hit.code) in (4, 5))) - icd10_val = valid_hit.code if not is_icdo and not is_cpt else None - icdo_val = valid_hit.code if is_icdo else None - cpt_val = valid_hit.code if is_cpt else None - - promoted = CodedDiagnosisResponse( - raw_term=a_term, - normalized_diagnosis=norm_a or a_term, - description=valid_hit.description, - database_code=valid_hit.code, - database_description=valid_hit.description, - matching_status="MATCHED" if valid_hit.retrieval_score >= 0.40 else "NEAREST_MATCH", - source_section=getattr(matching_cond, "source_section", "") or "CLINICAL_DOCUMENTATION", - role=DiagnosisRole.SECONDARY if primary_response else DiagnosisRole.PRIMARY, - acuity=Acuity.ACUTE if "acute" in norm_a.lower() else (Acuity.CHRONIC if "chronic" in norm_a.lower() else Acuity.UNSPECIFIED), - certainty=Certainty.CONFIRMED, - evidence_quote=ev_quote, - evidence=[{ - "quote": ev_quote, - "section": getattr(matching_cond, "source_section", "") or "CLINICAL_DOCUMENTATION", - "evidence_type": "CLINICAL_EVIDENCE", - }], - confidence_score=max(0.40, valid_hit.retrieval_score), - is_terminal_billable=True, - icd10cm=icd10_val, - icdo=icdo_val, - cpt=cpt_val, - ) - if not primary_response: - primary_response = promoted - else: - secondary_responses.append(promoted) - logger.info( - "Re-check success: Promoted abstained condition '%s' with positive evidence to %s (code '%s')", - a_term, promoted.role.value, valid_hit.code - ) - continue - - rechecked_abstentions.append(abst) - - abstentions = rechecked_abstentions + # Audit & Output Consistency: Retain all abstentions without resurrecting rejected/abstained candidates into accepted codes # Deduplicate and clean repetitive evidences on primary response from medical_coding.utils.text import ( diff --git a/src/medical_coding/reasoning/__init__.py b/src/medical_coding/reasoning/__init__.py index 94af8ac..ca62a5b 100644 --- a/src/medical_coding/reasoning/__init__.py +++ b/src/medical_coding/reasoning/__init__.py @@ -1,6 +1,12 @@ """Structured Clinical Reasoning and Retrieval Constraints Package.""" from medical_coding.reasoning.compatibility import CompatibilityReasoner +from medical_coding.reasoning.concept_matcher import ( + compute_concept_match_score, + normalize_for_concept_matching, + select_best_concept_match, + strip_nonessential_modifiers, +) from medical_coding.reasoning.concept_reasoner import ClinicalConceptReasoner from medical_coding.reasoning.match_spec import MatchSpecBuilder @@ -8,4 +14,9 @@ __all__ = [ "ClinicalConceptReasoner", "MatchSpecBuilder", "CompatibilityReasoner", + "compute_concept_match_score", + "normalize_for_concept_matching", + "select_best_concept_match", + "strip_nonessential_modifiers", ] + diff --git a/src/medical_coding/reasoning/compatibility.py b/src/medical_coding/reasoning/compatibility.py index d5d1f24..fd8c20b 100644 --- a/src/medical_coding/reasoning/compatibility.py +++ b/src/medical_coding/reasoning/compatibility.py @@ -35,6 +35,14 @@ class CompatibilityReasoner: supported_attrs: list[str] = [] unsupported_attrs: list[str] = [] + # 0. Concept-Level Assertion & Contradiction Evaluation (Hard Contradictions) + if getattr(concept, "assertion_status", None) == "RULED_OUT": + contradictions.append(f"Clinical concept '{concept.canonical_name}' is ruled out/excluded in documentation") + for ca in getattr(concept, "contradictory_attributes", []): + contradictions.append(f"Concept contradiction: {ca}") + for ce in getattr(concept, "contradiction_evidence", []): + contradictions.append(f"Contradicting evidence: {ce}") + # 1. Family / Prefix Compatibility (Master Prompt Section 20 & 21: SOFT Prior) matches_family = True if match_spec and match_spec.allowed_code_families: @@ -74,42 +82,69 @@ class CompatibilityReasoner: code_description=candidate_description, evidence_text=combined_ev, diagnosis_term=concept.canonical_name, + code=candidate_code, ) if not is_attr_valid: unsupported_attrs.extend(unsupp) + for u in unsupp: + if "contradiction" in u.lower() or "conflict" in u.lower(): + contradictions.append(u) # Identify supported attributes in code description for a in concept.supported_attributes: if a in desc_lower: supported_attrs.append(a) - # 5. Composite Dimensional Compatibility Score (Master Prompt Section 24, 25) - # Unknown is NOT contradiction; missing info is NOT negative info. - base_score = 0.60 + # 5. Composite Concept Match & Dimensional Compatibility Score + from medical_coding.reasoning.concept_matcher import compute_concept_match_score + + concept_score, match_rat, is_exact = compute_concept_match_score( + candidate_code=candidate_code, + candidate_description=candidate_description, + concept_name=concept.canonical_name or concept.normalized_concept or "", + evidence_text=combined_ev, + ) + + if is_exact and not contradictions and not unsupported_attrs: + final_score = 1.0 + is_compatible = True + reason = f"Candidate '{candidate_code}' is an exact clinical concept match for '{concept.canonical_name}' ({match_rat})." + return CompatibilityResult( + compatible=is_compatible, + score=final_score, + candidate_code=candidate_code, + candidate_description=candidate_description, + supported_attributes=supported_attrs, + unsupported_attributes=unsupported_attrs, + contradictions=contradictions, + reason=reason, + ) + + base_score = concept_score if matches_family: - base_score += 0.25 + base_score = min(1.0, base_score + 0.08) else: - # Soft penalty for being outside family prefix if specified, but NOT a hard rejection - base_score -= 0.15 + base_score = max(0.0, base_score - 0.15) if supported_attrs: - base_score += 0.10 + base_score = min(1.0, base_score + 0.05) # Specificity penalty for unevidenced qualifiers (e.g. bleeding when none documented) spec_penalty = min(0.35, 0.10 * len(unsupported_attrs)) base_score -= spec_penalty - # Severe penalty for explicit contradictions + # Zero tolerance for explicit contradictions (Master Specification Section 5 & 10) if contradictions: - base_score -= 0.80 - - final_score = max(0.0, min(1.0, round(base_score, 4))) - is_compatible = (len(contradictions) == 0) and (final_score >= 0.35) + final_score = 0.0 + is_compatible = False + else: + final_score = max(0.0, min(1.0, round(base_score, 4))) + is_compatible = final_score >= 0.35 if is_compatible: - reason = f"Candidate '{candidate_code}' is clinically compatible with concept '{concept.canonical_name}' (score={final_score})." + reason = f"Candidate '{candidate_code}' is clinically compatible with concept '{concept.canonical_name}' (score={final_score}, {match_rat})." else: - reason_parts: list[str] = [] + reason_parts: list[str] = [match_rat] if contradictions: reason_parts.append(f"Contradictions: {'; '.join(contradictions)}") if unsupported_attrs: diff --git a/src/medical_coding/reasoning/concept_matcher.py b/src/medical_coding/reasoning/concept_matcher.py new file mode 100644 index 0000000..511d064 --- /dev/null +++ b/src/medical_coding/reasoning/concept_matcher.py @@ -0,0 +1,285 @@ +"""Clinical concept matcher and scorer. + +Enforces: +1. Exact concept matching over first "good enough" match. +2. Handling of ICD-10-CM nonessential modifiers (parenthetical terms like '(primary)', '(congestive)'). +3. Deep evaluation of core clinical entities, anatomical site, laterality, acuity, and complications. +4. Bounded scoring prioritizing the best concept match across all available candidates. +""" + +import re +from typing import Any + +from medical_coding.schemas.icd import ICDCandidate +from medical_coding.utils.clinical_lexicon import CLINICAL_ABBREVIATIONS, CLINICAL_MORPHOLOGY +from medical_coding.validation.reverse_attributes import ReverseAttributeChecker + +# Common clinical qualifiers that describe severity, status, or administrative attributes +PERIPHERAL_QUALIFIERS = { + "mild", "moderate", "severe", "routine", "unspecified", "uncontrolled", "controlled", + "status", "post", "s/p", "primary", "secondary", "admitted", "discharge", "history", + "compensated", "decompensated", "recurrent", "underlying", "known", "case", "of", + "with", "without", "and", "or", "in", "for", "to", "from", "due", +} + + +def strip_nonessential_modifiers(text: str) -> str: + """Strip ICD-10-CM nonessential modifiers (parenthetical text in descriptions). + + Under official ICD-10-CM conventions, terms in parentheses are nonessential modifiers + that do not affect the code assignment (e.g., 'Essential (primary) hypertension', + 'Acute systolic (congestive) heart failure'). + """ + if not text: + return "" + # Strip parentheses and their contents + stripped = re.sub(r"\([^)]*\)", " ", text) + stripped = re.sub(r"\[[^\]]*\]", " ", stripped) + return re.sub(r"\s+", " ", stripped).strip() + + +def normalize_for_concept_matching(text: str) -> str: + """Normalize a clinical phrase or ICD description for exact/semantic concept comparison.""" + if not text: + return "" + + cleaned = text.strip().lower() + # Strip nonessential modifiers + cleaned = strip_nonessential_modifiers(cleaned) + # Strip list markers, dates, codes + cleaned = re.sub(r"^\d+[\.\)\-]\s*", "", cleaned) + # Remove punctuation + cleaned = re.sub(r"[^\w\s]", " ", cleaned) + + # Expand abbreviations + tokens = cleaned.split() + expanded_tokens: list[str] = [] + for t in tokens: + if t in CLINICAL_ABBREVIATIONS: + expanded_tokens.extend(CLINICAL_ABBREVIATIONS[t].split()) + else: + expanded_tokens.append(t) + + return " ".join(expanded_tokens).strip() + + +def get_core_concept_tokens(text: str) -> list[str]: + """Extract significant core clinical entity tokens (ignoring peripheral qualifiers).""" + norm = normalize_for_concept_matching(text) + tokens = [t for t in norm.split() if len(t) > 2] + core = [t for t in tokens if t not in PERIPHERAL_QUALIFIERS] + return core or tokens + + +def compute_concept_match_score( + candidate_code: str, + candidate_description: str, + concept_name: str, + evidence_text: str = "", + attributes: dict[str, Any] | None = None, +) -> tuple[float, str, bool]: + """Compute exact and dimensional concept match score between a candidate and clinical concept. + + Returns: + (score, rationale, is_exact_match) + """ + if not candidate_description or not concept_name: + return 0.0, "Missing candidate description or concept name", False + + cand_desc_clean = candidate_description.strip() + concept_clean = concept_name.strip() + evidence_clean = (evidence_text or "").lower() + full_context = f"{concept_clean.lower()} {evidence_clean}" + + # 1. Normalized string comparisons + cand_norm = normalize_for_concept_matching(cand_desc_clean) + concept_norm = normalize_for_concept_matching(concept_clean) + cand_raw_lower = re.sub(r"[^\w\s]", "", cand_desc_clean.lower()).strip() + concept_raw_lower = re.sub(r"[^\w\s]", "", concept_clean.lower()).strip() + + # Exact string match (ignoring nonessential parentheticals & punctuation) + if cand_norm == concept_norm or cand_raw_lower == concept_raw_lower: + return 1.0, "exact clinical description match", True + + # 2. Token sets + cand_tokens = cand_norm.split() + concept_tokens = concept_norm.split() + cand_token_set = set(cand_tokens) + concept_token_set = set(concept_tokens) + + # Core diagnostic entity tokens + core_concept_tokens = get_core_concept_tokens(concept_clean) + core_matches = 0 + for ct in core_concept_tokens: + variants = [ct] + CLINICAL_MORPHOLOGY.get(ct, []) + if any(v in cand_token_set for v in variants): + core_matches += 1 + + core_fraction = (core_matches / len(core_concept_tokens)) if core_concept_tokens else 0.0 + + # If core entity does not match at all (e.g. kidney vs skin), candidate is incompatible + if core_fraction == 0.0 and len(core_concept_tokens) >= 1: + return 0.05, "core clinical entity mismatch", False + + # 3. Base score derived from core fraction and token overlap + shared_tokens = cand_token_set & concept_token_set + jaccard = len(shared_tokens) / len(cand_token_set | concept_token_set) if (cand_token_set | concept_token_set) else 0.0 + + base_score = 0.50 + (0.35 * core_fraction) + (0.15 * jaccard) + rationale_parts: list[str] = [f"core entity match ({core_matches}/{len(core_concept_tokens)})"] + + # If all concept tokens appear in candidate + if concept_token_set.issubset(cand_token_set): + base_score += 0.10 + rationale_parts.append("full concept token coverage") + + # 4. Acuity alignment + is_acute_doc = bool(re.search(r"\b(?:acute|exacerbation|decompensated)\b", full_context)) + is_chronic_doc = bool(re.search(r"\b(?:chronic|longstanding|compensated)\b", full_context)) + cand_is_acute = "acute" in cand_norm and "chronic" not in cand_norm + cand_is_chronic = "chronic" in cand_norm and "acute" not in cand_norm + cand_is_acute_on_chronic = "acute on chronic" in cand_desc_clean.lower() or ("acute" in cand_norm and "chronic" in cand_norm) + + if cand_is_acute_on_chronic: + if is_acute_doc and is_chronic_doc: + base_score += 0.10 + rationale_parts.append("acute on chronic match") + elif not is_acute_doc or not is_chronic_doc: + base_score -= 0.20 + elif cand_is_acute: + if is_acute_doc and not is_chronic_doc: + base_score += 0.10 + rationale_parts.append("acute acuity match") + elif is_chronic_doc and not is_acute_doc: + base_score -= 0.20 + rationale_parts.append("unsupported acute acuity") + elif cand_is_chronic: + if is_chronic_doc and not is_acute_doc: + base_score += 0.10 + rationale_parts.append("chronic acuity match") + elif is_acute_doc and not is_chronic_doc: + base_score -= 0.20 + rationale_parts.append("unsupported chronic acuity") + + # 5. Laterality alignment + doc_left = bool(re.search(r"\b(?:left|lt)\b", full_context)) + doc_right = bool(re.search(r"\b(?:right|rt)\b", full_context)) + cand_left = "left" in cand_norm and "right" not in cand_norm + cand_right = "right" in cand_norm and "left" not in cand_norm + cand_unspec_lat = "unspecified" in cand_norm and any( + w in cand_norm for w in ("side", "breast", "kidney", "ureter", "flank", "foot", "ankle", "knee", "extremity") + ) + + if (doc_left and cand_left) or (doc_right and cand_right): + base_score += 0.15 + rationale_parts.append("laterality match") + elif (doc_left and cand_right) or (doc_right and cand_left): + return 0.0, "contradictory laterality", False + elif (doc_left or doc_right) and cand_unspec_lat: + base_score -= 0.15 + rationale_parts.append("unspecified laterality when specific side documented") + + # 6. Reverse attributes check + is_attr_valid, unsupp = ReverseAttributeChecker.validate_code_attributes( + code_description=candidate_description, + evidence_text=evidence_clean, + diagnosis_term=concept_clean, + code=candidate_code, + ) + if not is_attr_valid: + has_hard_fail = any( + any(k in u.lower() for k in ("demographic", "perinatal", "neonatal", "pregnancy", "obstetric", "polarity", "contradictory", "mismatch", "pathogen")) + for u in unsupp + ) + if has_hard_fail: + base_score = 0.0 + rationale_parts.append(f"disqualified by clinical contradiction: {', '.join(unsupp)}") + else: + base_score -= min(0.40, 0.15 * len(unsupp)) + rationale_parts.append(f"unsupported attributes: {', '.join(unsupp)}") + + # 7. Bleeding / manifestation status + has_no_bleed = "no active bleeding" in full_context or "without bleeding" in full_context or "no bleeding" in full_context + has_bleed = "active bleeding" in full_context or "with bleeding" in full_context or "with hemorrhage" in full_context + if has_no_bleed and "without bleeding" in cand_norm: + base_score += 0.15 + rationale_parts.append("without bleeding documentation match") + elif has_no_bleed and "with bleeding" in cand_norm: + base_score -= 0.35 + rationale_parts.append("unsupported bleeding in candidate") + elif has_bleed and "with bleeding" in cand_norm: + base_score += 0.15 + rationale_parts.append("with bleeding documentation match") + + # 8. Unspecified vs specific alignment + is_unspec_cand = candidate_code.endswith((".9", ".90", ".99")) or "unspecified" in cand_norm + has_specific_detail = any( + w in full_context + for w in ["systolic", "diastolic", "anterior", "inferior", "lateral", "retroperitoneal", "ureteric", "ureter", "antral"] + ) + if is_unspec_cand and has_specific_detail: + base_score -= 0.10 + elif is_unspec_cand and not has_specific_detail: + base_score += 0.08 + rationale_parts.append("canonical unspecified code for general condition") + + final_score = max(0.0, min(1.0, round(base_score, 4))) + is_exact = final_score >= 0.95 and core_fraction >= 0.90 + return final_score, ", ".join(rationale_parts), is_exact + + +def select_best_concept_match( + candidates: list[ICDCandidate], + concept_name: str, + evidence_text: str = "", + catalog: Any = None, + attributes: dict[str, Any] | None = None, + min_score_threshold: float = 0.35, +) -> tuple[ICDCandidate | None, float, str]: + """Evaluate ALL candidates in the pool and select the single BEST concept match. + + NEVER stops at the first candidate that passes a threshold. + Ranks every candidate and selects the highest scoring match. + """ + if not candidates or not concept_name: + return None, 0.0, "No candidates or empty concept name" + + scored_list: list[tuple[ICDCandidate, float, str, bool]] = [] + + for cand in candidates: + # Filter non-billable headers if billable required + if catalog is not None: + if not catalog.is_valid_code(cand.code): + continue + + score, rat, is_exact = compute_concept_match_score( + candidate_code=cand.code, + candidate_description=cand.description, + concept_name=concept_name, + evidence_text=evidence_text, + attributes=attributes, + ) + + # Non-billable penalty + if not cand.is_valid_billable: + score *= 0.3 + rat = f"non-billable header ({rat})" + + # Incorporate original retrieval score gently (up to 15% weight) + cand_retrieval_s = getattr(cand, "retrieval_score", 0.5) or 0.5 + composite_score = round((0.85 * score) + (0.15 * cand_retrieval_s), 4) + + scored_list.append((cand, composite_score, rat, is_exact)) + + if not scored_list: + return None, 0.0, "No valid candidates in candidate pool" + + # Sort descending by composite concept score + scored_list.sort(key=lambda x: x[1], reverse=True) + + best_cand, best_score, best_rat, best_is_exact = scored_list[0] + + if best_score < min_score_threshold: + return None, best_score, f"Top candidate '{best_cand.code}' below threshold ({best_score:.2f} < {min_score_threshold:.2f}): {best_rat}" + + return best_cand, best_score, best_rat diff --git a/src/medical_coding/reasoning/concept_reasoner.py b/src/medical_coding/reasoning/concept_reasoner.py index 7e4f25a..6ae5f52 100644 --- a/src/medical_coding/reasoning/concept_reasoner.py +++ b/src/medical_coding/reasoning/concept_reasoner.py @@ -264,12 +264,73 @@ class ClinicalConceptReasoner: if not any(q in local_context for q in quadrants): unknown_attributes.append("quadrant") - # 6. Assertion & Temporality + # 6. Assertion, Temporality & Clinical Contradiction Analysis assertion = "CONFIRMED" - if "ruled out" in quote.lower() or "no evidence" in quote.lower(): + contradictory_attributes: list[str] = [] + contradiction_evidence: list[str] = [] + + # Check candidate's pre-existing certainty, role, or negation metadata + cand_certainty = str(getattr(candidate, "certainty", "")).upper() + cand_role = str(getattr(candidate, "role", "")).upper() + cand_negation = str(getattr(candidate, "negation", "")).upper() + is_auth = getattr(candidate, "is_authorized", True) + + if ( + "RULED_OUT" in cand_certainty + or "RULED_OUT" in cand_role + or "EXCLUDED" in cand_role + or "NEGATED" in cand_negation + or is_auth is False + ): assertion = "RULED_OUT" - elif "?" in raw_term or "suspected" in quote.lower() or "possible" in quote.lower(): - assertion = "SUSPECTED" + contradictory_attributes.append("negated_or_ruled_out_in_extraction") + + # Linguistic assertion check on quote and local context + explicit_ruled_out_pat = r"\b(?:ruled\s+out|no\s+evidence\s+of|negative\s+for|denies|denied|no\s+active|free\s+of|unsupported)\b" + if re.search(explicit_ruled_out_pat, quote.lower()): + assertion = "RULED_OUT" + contradictory_attributes.append("explicitly_ruled_out") + contradiction_evidence.append(quote) + elif "?" in raw_term or re.search(r"\b(?:suspected|possible|probable|differential|rule\s+out)\b", quote.lower()): + if assertion != "RULED_OUT": + assertion = "SUSPECTED" + + # Check physiological and hemodynamic polarity contradictions across document and local context + combined_text_for_contra = f"{local_context} {document_text}".lower() + + # 1. Shock vs Hemodynamic Stability / Normotension + if "shock" in term_lower or matched_family in ("septic_shock", "shock"): + shock_stability_pats = [ + r"\b(?:no\s+shock|normotensive\s+without\s+shock|hemodynamically\s+stable|ruled\s+out\s+shock|shock\s+ruled\s+out|no\s+evidence\s+of\s+shock|stable\s+without\s+shock|not\s+in\s+shock|stable\s+hemodynamics|bp\s+normalized|normotensive)\b", + ] + for pat in shock_stability_pats: + m = re.search(pat, combined_text_for_contra) + if m: + assertion = "RULED_OUT" + contradictory_attributes.append("hemodynamic_stability_contradiction") + contradiction_evidence.append(m.group(0)) + break + + # 2. Acute Hypotension vs Hypertensive Emergency / Crisis + if ("hypotension" in term_lower or "hypotensive" in term_lower) and ( + matched_family == "hypertension" or "emergency" in term_lower or "crisis" in term_lower + ): + assertion = "RULED_OUT" + contradictory_attributes.append("hypotension_hypertension_polarity_conflict") + + # 3. Hypoglycemia vs Hyperglycemia / DKA + if "hypoglycemia" in term_lower and any(w in combined_text_for_contra for w in ["hyperglycemia", "dka", "ketoacidosis"]): + if not any(w in local_context for w in ["hypoglycemia", "low blood sugar"]): + assertion = "RULED_OUT" + contradictory_attributes.append("glycemic_polarity_conflict") + + # 4. Neonatal Condition in Adult Patient + if matched_family in ("neonatal_diabetes", "perinatal_condition") or "neonatal" in term_lower: + has_adult = bool(re.search(r"\b(?:adult|\d+\s*(?:years?[\s\-]old|yo|y/o|year)|type\s+2|t2dm|geriatric|elderly)\b", combined_text_for_contra)) + has_neonate = bool(re.search(r"\b(?:neonate|newborn|infant|day\s+of\s+life)\b", combined_text_for_contra)) + if has_adult and not has_neonate: + assertion = "RULED_OUT" + contradictory_attributes.append("neonatal_adult_demographic_contradiction") temporality = "CURRENT" if getattr(candidate, "temporality", None) in ("HISTORICAL", "RESOLVED"): @@ -313,8 +374,9 @@ class ClinicalConceptReasoner: source_sections=[getattr(candidate, "source_section", "DISCHARGE_DIAGNOSES") or "DISCHARGE_DIAGNOSES"], supported_attributes=supported_attributes, unknown_attributes=unknown_attributes, - contradictory_attributes=[], - contradiction_evidence=[], + contradictory_attributes=contradictory_attributes, + contradiction_evidence=contradiction_evidence, confidence=float(getattr(candidate, "confidence_score", 1.0) or 1.0), clinical_confidence=float(getattr(candidate, "confidence_score", 1.0) or 1.0), ) + diff --git a/src/medical_coding/retrieval/hybrid.py b/src/medical_coding/retrieval/hybrid.py index 8c2951b..24579a7 100644 --- a/src/medical_coding/retrieval/hybrid.py +++ b/src/medical_coding/retrieval/hybrid.py @@ -245,18 +245,34 @@ class HybridICDRetriever(BaseICDRetriever): k = top_k if top_k is not None else self.default_top_k threshold = min_score if min_score is not None else self.min_score_threshold - # Round 1: Standard retrieval with original query - round1_hits = self.retrieve(query, top_k=k, min_score=threshold, system=system) - if round1_hits and round1_hits[0].retrieval_score >= threshold: - return round1_hits - + from medical_coding.reasoning.concept_matcher import ( + compute_concept_match_score, + normalize_for_concept_matching, + ) from medical_coding.utils.text import extract_search_query_variations - variations = extract_search_query_variations(query, evidence=evidence) + # Round 1: Standard retrieval with original query + round1_hits = self.retrieve(query, top_k=k, min_score=threshold, system=system) merged_candidates: dict[str, ICDCandidate] = {c.code: c for c in round1_hits} - # Round 2: Query variations with slightly relaxed threshold - if max_rounds >= 2 and variations: + # Check if Round 1 already contains an exact match + has_exact = False + for c in round1_hits: + _, _, is_exact = compute_concept_match_score( + candidate_code=c.code, + candidate_description=c.description, + concept_name=query, + evidence_text=evidence, + ) + if is_exact: + has_exact = True + break + + # If no exact match in Round 1, expand across normalized query variations + variations = extract_search_query_variations(query, evidence=evidence) + + # Round 2: Query variations (core clinical entities, synonyms, expanded acronyms) + if (not has_exact or len(merged_candidates) < k) and max_rounds >= 2 and variations: relaxed_threshold_r2 = max(0.20, threshold - 0.10) for var in variations: if var.lower().strip() == query.lower().strip(): @@ -265,22 +281,38 @@ class HybridICDRetriever(BaseICDRetriever): for h in var_hits: if h.code not in merged_candidates or h.retrieval_score > merged_candidates[h.code].retrieval_score: merged_candidates[h.code] = h + _, _, is_exact = compute_concept_match_score( + candidate_code=h.code, + candidate_description=h.description, + concept_name=query, + evidence_text=evidence, + ) + if is_exact: + has_exact = True - if merged_candidates: - ranked = sorted(merged_candidates.values(), key=lambda c: c.retrieval_score, reverse=True) - if ranked[0].retrieval_score >= threshold: - return ranked[:k] - - # Round 3: Evidence-anchored search and relaxed threshold - if max_rounds >= 3: + # Round 3: Evidence-anchored search if still below top_k or no exact match + if (not has_exact or len(merged_candidates) < 5) and max_rounds >= 3 and evidence: relaxed_threshold_r3 = max(0.15, threshold - 0.15) - # Try evidence text directly if available - if evidence: - ev_hits = self.retrieve(evidence[:120], top_k=k, min_score=relaxed_threshold_r3, system=system) - for h in ev_hits: - if h.code not in merged_candidates or h.retrieval_score > merged_candidates[h.code].retrieval_score: - merged_candidates[h.code] = h + ev_hits = self.retrieve(evidence[:120], top_k=k, min_score=relaxed_threshold_r3, system=system) + for h in ev_hits: + if h.code not in merged_candidates or h.retrieval_score > merged_candidates[h.code].retrieval_score: + merged_candidates[h.code] = h - ranked = sorted(merged_candidates.values(), key=lambda c: c.retrieval_score, reverse=True) - return ranked[:k] if ranked else [] + # Rescore all candidates based on clinical concept match to prevent returning first good-enough candidate + scored_candidates: list[tuple[float, ICDCandidate]] = [] + for cand in merged_candidates.values(): + c_score, _, is_ex = compute_concept_match_score( + candidate_code=cand.code, + candidate_description=cand.description, + concept_name=query, + evidence_text=evidence, + ) + composite_score = round(max(cand.retrieval_score, (0.80 * c_score) + (0.20 * cand.retrieval_score)), 4) + if is_ex: + composite_score = max(composite_score, 0.98) + cand.retrieval_score = composite_score + scored_candidates.append((composite_score, cand)) + + scored_candidates.sort(key=lambda x: x[0], reverse=True) + return [c for _, c in scored_candidates[:k]] diff --git a/src/medical_coding/utils/clinical_lexicon.py b/src/medical_coding/utils/clinical_lexicon.py index 5a7994d..9877f4e 100644 --- a/src/medical_coding/utils/clinical_lexicon.py +++ b/src/medical_coding/utils/clinical_lexicon.py @@ -305,11 +305,18 @@ CLINICAL_MORPHOLOGY: dict[str, list[str]] = { "urinary": ["urogenital"], "urogenital": ["urinary", "genital"], "urosepsis": ["urinary", "sepsis"], - "hbv": ["hepatitis", "viral"], - "hepatitis": ["hbv", "hcv", "viral"], + "hbv": ["hepatitis b"], + "hepatitis": ["hepatic inflammation", "hbv", "hcv"], "sarcoma": ["kaposi", "sarcomas", "malignant", "neoplasm", "cancer"], - "viral": ["virus", "hepatitis", "hiv"], - "virus": ["viral", "hepatitis", "hiv"], + "viral": ["virus", "viral infection"], + "virus": ["viral", "viral infection"], + "hypotension": ["hypotensive", "low blood pressure"], + "fever": ["pyrexia", "febrile"], + "myalgia": ["body ache", "body aches", "muscle pain", "myalgias"], + "petechiae": ["petechia", "purpura", "ecchymosis", "ecchymoses"], + "constipation": ["constipated", "obstipation"], + "dehydration": ["volume depletion", "hypovolemia"], + "mucositis": ["stomatitis", "oral mucositis"], "cancer": ["malignant", "neoplasm", "carcinoma"], "carcinoma": ["cancer", "malignant", "neoplasm"], "malignant": ["cancer", "carcinoma", "neoplasm", "metastasis", "metastatic", "metastases", "malignancy"], diff --git a/src/medical_coding/utils/text.py b/src/medical_coding/utils/text.py index 0d5105b..41db643 100644 --- a/src/medical_coding/utils/text.py +++ b/src/medical_coding/utils/text.py @@ -161,6 +161,14 @@ def normalize_diagnosis_name(text: str) -> str: # Step 3: Strip trailing medication attachments cleaned = MEDICATION_ATTACHMENT_PATTERN.sub("", cleaned).strip() + # Step 3b: Strip narrative explanations attached via delimiters (e.g. "Acute systolic heart failure - Patient admitted...") + for delim in [" - ", " – ", " — ", " : "]: + if delim in cleaned: + cand_head = cleaned.split(delim, 1)[0].strip() + if len(cand_head) >= 3 and not cand_head.lower().startswith(("date", "mrn", "patient", "name", "dr")): + cleaned = cand_head + break + # Step 4: Handle parentheticals (preserve clinical qualifiers, strip purely administrative artifacts) def _clean_paren(m: re.Match[str]) -> str: inside = m.group(1).strip() @@ -175,12 +183,22 @@ def normalize_diagnosis_name(text: str) -> str: cleaned = expand_medical_abbreviations(cleaned) # Step 6: Normalize whitespace and trailing punctuation - cleaned = re.sub(r"[,\-–—:;]+$", "", cleaned).strip() + cleaned = re.sub(r"[\.,\-–—:;]+$", "", cleaned).strip() cleaned = normalize_whitespace(cleaned) return cleaned +def strip_nonessential_modifiers(text: str) -> str: + """Strip ICD-10-CM parenthetical nonessential modifiers for exact concept matching.""" + if not text: + return "" + stripped = re.sub(r"\([^)]*\)", " ", text) + stripped = re.sub(r"\[[^\]]*\]", " ", stripped) + return re.sub(r"\s+", " ", stripped).strip() + + + def extract_search_query_variations(raw_term: str, evidence: str = "") -> list[str]: """Generate prioritized query variations for robust multi-round BM25 and vector search. diff --git a/src/medical_coding/validation/clinical_gate.py b/src/medical_coding/validation/clinical_gate.py index 280bc03..158ea6b 100644 --- a/src/medical_coding/validation/clinical_gate.py +++ b/src/medical_coding/validation/clinical_gate.py @@ -173,11 +173,14 @@ PATHOLOGY_KEYWORDS = { "sclerosis", "fibrosis", "adhesions", "dns", "mastoiditis", "flu", "influenza", "viral", "virus", "illness", "coryza", "rhonchi", "bronchospasm", "stricture", "varices", "variceal", "varix", "thrombus", "embolus", + "petechiae", "petechia", "purpura", "ecchymosis", "myalgia", "arthralgia", } # Clinical symptoms, signs, and patient complaints SYMPTOM_KEYWORDS = { "pain", "colic", "discomfort", "ache", "aching", "soreness", "tenderness", + "body ache", "body aches", "myalgia", "arthralgia", + "petechiae", "petechia", "purpura", "ecchymosis", "fever", "pyrexia", "chill", "chills", "rigor", "rigors", "sweating", "diaphoresis", "cough", "coughing", "hemoptysis", "dyspnea", "breathlessness", "tachypnea", "wheeze", "wheezing", "stridor", "rhonchi", "rales", "crackles", @@ -487,6 +490,7 @@ class HardClinicalCandidateGate: "psychos", "malformat", "anomal", "dysplas", "deviat", "hypertroph", "hyperplas", "atroph", "thicken", "narrow", "calcif", "flu", "influenz", "viral", "virus", "illness", "coryza", "rhonch", "bronchospas", "strictur", "varic", + "petechi", "purpur", "ecchymo", "myalg", "arthralg", ) has_clinical_root = any(r in term_lower for r in CLINICAL_ROOTS) diff --git a/src/medical_coding/validation/deterministic.py b/src/medical_coding/validation/deterministic.py index 3677956..7d30cf5 100644 --- a/src/medical_coding/validation/deterministic.py +++ b/src/medical_coding/validation/deterministic.py @@ -105,13 +105,18 @@ class DeterministicValidator: ) # 3. Clinical Meaning & Anatomical Consistency Checks - ev_text = ( - getattr(condition.context.evidence, "quote", "") - if hasattr(condition, "context") and hasattr(condition.context, "evidence") and condition.context.evidence - else "" - ) + ev_pieces: list[str] = [] + if hasattr(condition, "context") and hasattr(condition.context, "evidence") and condition.context.evidence: + ev_pieces.append(condition.context.evidence.quote) + if hasattr(condition, "context") and hasattr(condition.context, "clinical_justification") and condition.context.clinical_justification: + ev_pieces.append(condition.context.clinical_justification) + if getattr(condition, "classification_reason", None): + ev_pieces.append(condition.classification_reason) + if getattr(condition, "evidence_quote", None): + ev_pieces.append(condition.evidence_quote) if selection.supporting_evidence: - ev_text = f"{ev_text} {' '.join(selection.supporting_evidence)}" + ev_pieces.extend(selection.supporting_evidence) + ev_text = " | ".join(p.strip() for p in ev_pieces if p and p.strip()) def _evaluate_candidate_clinical_meaning(cand: ICDCandidate) -> tuple[bool, str | None, bool, str | None, bool, list[str]]: anat_ok, anat_err = ReverseAttributeChecker.validate_anatomical_site( @@ -128,6 +133,7 @@ class DeterministicValidator: code_description=cand.description, evidence_text=ev_text, diagnosis_term=condition.raw_term, + code=cand.code, ) return anat_ok, anat_err, lat_ok, lat_err, attr_ok, attr_errs @@ -137,28 +143,30 @@ class DeterministicValidator: if not is_clinically_valid: better_candidate = None if selection.candidate_pool: + valid_alts: list[ICDCandidate] = [] for alt_cand in selection.candidate_pool: if not self.catalog.is_valid_code(alt_cand.code) or not self.catalog.is_billable_code(alt_cand.code): continue a_ok, _, l_ok, _, at_ok, _ = _evaluate_candidate_clinical_meaning(alt_cand) if a_ok and l_ok and at_ok: - better_candidate = alt_cand - break + valid_alts.append(alt_cand) + + if valid_alts: + from medical_coding.reasoning.concept_matcher import select_best_concept_match + better_candidate, _, _ = select_best_concept_match( + candidates=valid_alts, + concept_name=condition.raw_term, + evidence_text=ev_text, + catalog=self.catalog, + ) if better_candidate: candidate = better_candidate code = better_candidate.code anat_ok, anat_err, lat_ok, lat_err, attr_ok, attr_errs = _evaluate_candidate_clinical_meaning(candidate) - elif getattr(selection, "matching_status", "") == "NEAREST_MATCH": - # User requirement: for [no_local_code] type diagnosis, nearest relatable code should get displayed, because they also have evidence - checks.append( - ValidationCheck( - rule_name="NearestRelatableMatch", - passed=True, - details=f"Nearest relatable code '{code}' ({candidate.description}) accepted for documented clinical condition.", - ) - ) - else: + is_clinically_valid = anat_ok and lat_ok and attr_ok + + if not is_clinically_valid: failure_reasons = [] if not anat_ok and anat_err: failure_reasons.append(anat_err) @@ -298,7 +306,24 @@ class DeterministicValidator: selection_map = {s.diagnosis_id: s for s in selections} for cond in conditions: - if not cond.is_billable_candidate or cond.role == DiagnosisRole.EXCLUDED: + cond_certainty = getattr(cond.context, "certainty", None) if hasattr(cond, "context") else None + cond_negation = getattr(cond.context, "negation", None) if hasattr(cond, "context") else None + is_excluded = not cond.is_billable_candidate or cond.role == DiagnosisRole.EXCLUDED + is_ruled_out = ( + cond_certainty == Certainty.RULED_OUT + or cond_negation == NegationStatus.NEGATED + or any(k in cond.raw_term.lower() for k in ("ruled out", "negated")) + ) + # Polarity contradiction check: Shock with documented stability + cond_ev = f"{cond.raw_term} {getattr(cond, 'classification_reason', '')}".lower() + if hasattr(cond, "context") and hasattr(cond.context, "evidence") and cond.context.evidence: + cond_ev = f"{cond_ev} {cond.context.evidence.quote.lower()}" + is_shock_contra = ( + "shock" in cond.raw_term.lower() + and bool(re.search(r"\b(?:no\s+shock|normotensive\s+without\s+shock|hemodynamically\s+stable|ruled\s+out\s+shock|shock\s+ruled\s+out|no\s+evidence\s+of\s+shock|stable\s+without\s+shock|not\s+in\s+shock|stable\s+hemodynamics|bp\s+normalized|normotensive)\b", cond_ev)) + ) + + if is_excluded or is_ruled_out or is_shock_contra: abstention_list.append( AbstentionRecord( diagnosis_id=cond.diagnosis_id, @@ -306,7 +331,7 @@ class DeterministicValidator: reason=AbstentionReason.EXCLUDED_BY_TEMPORALITY if "historical" in cond.classification_reason.lower() else AbstentionReason.EXCLUDED_BY_NEGATION, - detail=cond.classification_reason, + detail=cond.classification_reason or f"Condition '{cond.raw_term}' is excluded, ruled out, or contradicted by evidence.", stage=PipelineStage.CLASSIFICATION, ) ) @@ -415,7 +440,7 @@ class PrimarySecondaryClassificationValidator: cond = cond_in.model_copy() ctx = ctx_map.get(cond.diagnosis_id) or ctx_map.get(cond.diagnosis.lower()) - # Rule: Ruled-out or negated conditions CANNOT be PRIMARY or SECONDARY + # Rule: Ruled-out, negated, or contradicted conditions CANNOT be PRIMARY or SECONDARY is_ruled_out_or_negated = False if ctx: if ctx.certainty == Certainty.RULED_OUT or ctx.negation == NegationStatus.NEGATED: @@ -426,14 +451,20 @@ class PrimarySecondaryClassificationValidator: ): is_ruled_out_or_negated = True - if is_ruled_out_or_negated and cond.role != DiagnosisRole.EXCLUDED: + # Rule: Physiological contradiction (e.g. provisional impression contradicted by objective stability) + is_contradicted = False + ev_check = f"{cond.diagnosis} {getattr(cond, 'evidence_quote', '')} {cond.classification_reason}".lower() + if "shock" in cond.diagnosis.lower() and bool(re.search(r"\b(?:no\s+shock|normotensive\s+without\s+shock|hemodynamically\s+stable|ruled\s+out\s+shock|shock\s+ruled\s+out|no\s+evidence\s+of\s+shock|stable\s+without\s+shock|not\s+in\s+shock|stable\s+hemodynamics|bp\s+normalized|normotensive)\b", ev_check)): + is_contradicted = True + + if (is_ruled_out_or_negated or is_contradicted) and cond.role != DiagnosisRole.EXCLUDED: audit_notes.append( f"Deterministic override: Condition '{cond.diagnosis}' was marked {cond.role.value} " - "but is ruled out/negated. Forcing to EXCLUDED." + "but is ruled out/contradicted by clinical evidence. Forcing to EXCLUDED." ) cond.role = DiagnosisRole.EXCLUDED cond.is_billable_candidate = False - cond.classification_reason = f"Ruled out / negated condition excluded from coding: {cond.classification_reason}" + cond.classification_reason = f"Ruled out / contradicted condition excluded from coding: {cond.classification_reason}" abstentions.append( AbstentionRecord( diagnosis_id=cond.diagnosis_id, @@ -847,14 +878,39 @@ class CandidateRankingDeterministicValidator: decision="ABSTAINED", ) - # Reverse Attribute Check (Master Prompt: CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY) - is_attr_valid, unsupp_attrs = ReverseAttributeChecker.validate_code_attributes( - code_description=matching_candidate.description, - evidence_text=clean_evidence, - diagnosis_term=clean_diagnosis, - ) - if not is_attr_valid: - # Look for a candidate in candidate pool that is billable and valid under reverse attribute check + # 6. Reverse Attribute & Clinical Semantic Consistency Check (CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY) + def _evaluate_candidate_semantics(cand: ICDCandidate) -> tuple[bool, list[str]]: + errs: list[str] = [] + anat_ok, anat_err = ReverseAttributeChecker.validate_anatomical_site( + code_description=cand.description, + evidence_text=clean_evidence, + diagnosis_term=clean_diagnosis, + ) + if not anat_ok and anat_err: + errs.append(anat_err) + + lat_ok, lat_err = ReverseAttributeChecker.validate_laterality( + code_description=cand.description, + evidence_text=clean_evidence, + diagnosis_term=clean_diagnosis, + ) + if not lat_ok and lat_err: + errs.append(lat_err) + + attr_ok, attr_errs = ReverseAttributeChecker.validate_code_attributes( + code_description=cand.description, + evidence_text=clean_evidence, + diagnosis_term=clean_diagnosis, + code=cand.code, + ) + if not attr_ok and attr_errs: + errs.extend(attr_errs) + + return (len(errs) == 0), errs + + is_cand_valid, unsupp_attrs = _evaluate_candidate_semantics(matching_candidate) + if not is_cand_valid: + # Look for a candidate in candidate pool that is billable and valid under full semantic validation better_candidate = None best_cand_score = -999.0 diag_clean_lower = clean_diagnosis.lower() @@ -864,11 +920,7 @@ class CandidateRankingDeterministicValidator: for alt_cand in sorted_candidates: if not alt_cand.is_valid_billable: continue - alt_valid, _ = ReverseAttributeChecker.validate_code_attributes( - code_description=alt_cand.description, - evidence_text=clean_evidence, - diagnosis_term=clean_diagnosis, - ) + alt_valid, _ = _evaluate_candidate_semantics(alt_cand) if alt_valid: alt_desc_lower = alt_cand.description.lower() if any(t in alt_desc_lower for t in diag_tokens): @@ -891,7 +943,7 @@ class CandidateRankingDeterministicValidator: selection.selected_description = better_candidate.description selection.selected_candidate = better_candidate selection.ranking_reason = ( - f"Specificity realigned: Documentation does not support {', '.join(unsupp_attrs)}; " + f"Clinical semantic realigned: Original candidate violated {'; '.join(unsupp_attrs)}; " f"selected supported code {better_candidate.code} ({better_candidate.description})." ) else: @@ -902,8 +954,8 @@ class CandidateRankingDeterministicValidator: selected_description=None, selected_candidate=None, ranking_reason=( - f"Unsupported specificity: Candidate '{matching_candidate.code}' requires {', '.join(unsupp_attrs)}, " - "which is not documented in clinical evidence." + f"Failed clinical semantic validation: Candidate '{matching_candidate.code}' violates " + f"{'; '.join(unsupp_attrs)}, which is not documented in clinical evidence." ), supporting_evidence=[clean_evidence], confidence=0.0, diff --git a/src/medical_coding/validation/reverse_attributes.py b/src/medical_coding/validation/reverse_attributes.py index 4a39a16..bbbeb74 100644 --- a/src/medical_coding/validation/reverse_attributes.py +++ b/src/medical_coding/validation/reverse_attributes.py @@ -30,7 +30,7 @@ NON_SPECIFICITY_WORDS: set[str] = { "essential", "uncomplicated", "native", "atherosclerotic", "atherosclerosis", "arteriosclerotic", "gallbladder", "collapse", "failure", "pneumonia", - "septicemia", "shock", "bacteremia", "systemic", + "systemic", } # Clinical attribute qualifiers mapped to documentary confirmation tokens/synonyms @@ -281,6 +281,11 @@ class ReverseAttributeChecker: "lymph_node": [r"\blymph\s*nodes?\b", r"\blymphadenopathy\b", r"\bretroperitoneal\b", r"\bintra-abdominal\b", r"\bintrapelvic\b", r"\bmesenteric\b", r"\baxillary\b", r"\bmediastinal\b", r"\binguinal\b"], "brain": [r"\bbrain\b", r"\bcerebral\b", r"\bcerebellum\b"], "adrenal": [r"\badrenal\b"], + "oral": [r"\boral\b", r"\bmouth\b", r"\bbuccal\b", r"\blips?\b", r"\btongue\b", r"\bgingiv\w*", r"\bgums?\b", r"\bpalate\b", r"\bstomatitis\b"], + "nasal": [r"\bnasal\b", r"\bnose\b", r"\bnares\b", r"\bseptum\b", r"\bsinus(?:es)?\b", r"\bsinusitis\b", r"\bturbinate\w*"], + "pharynx": [r"\bpharyn\w*", r"\bthroat\b", r"\btonsil\w*", r"\badenoid\w*"], + "ear": [r"\bear\b", r"\botic\b", r"\baural\b", r"\btympanic\b"], + "eye": [r"\beye\b", r"\beyes\b", r"\bocular\b", r"\bophthalm\w*", r"\bcornea\w*", r"\bretina\w*", r"\bconjunctiv\w*"], } # Determine documented organs in diagnosis term (primary) and combined text @@ -319,6 +324,14 @@ class ReverseAttributeChecker: f"but documented condition is {', '.join(sorted(doc_organs))}", ) + # Enforce CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY: + # If code specifies an organ/site, evidence must substantiate at least one organ/site in that code + if code_organs and not code_organs.intersection(doc_organs): + return ( + False, + f"unsupported anatomical site: code specifies '{', '.join(sorted(code_organs))}' but evidence does not document this site", + ) + # Breast quadrants check: If code specifies a specific quadrant, evidence must support it quadrant_specs = { "upper-outer quadrant": [r"upper[- ]outer\s+quadrant", r"\buoq\b", r"upper\s+and\s+outer"], @@ -342,6 +355,7 @@ class ReverseAttributeChecker: code_description: str, evidence_text: str, diagnosis_term: str = "", + code: str = "", ) -> tuple[bool, list[str]]: """Validate that all positive attributes in the code description are evidenced. @@ -349,14 +363,143 @@ class ReverseAttributeChecker: code_description: Exact description from the database. evidence_text: Verbatim clinical documentation / evidence quote. diagnosis_term: Extracted normalized clinical diagnosis term. + code: Optional ICD-10-CM / CPT code string. Returns: Tuple of (is_valid: bool, unsupported_attributes: list[str]). """ combined_evidence = f"{diagnosis_term} {evidence_text}".lower() - implied_attributes = cls.extract_code_attributes(code_description) + clean_code = (code or "").strip().upper() + desc_lower = code_description.lower() unsupported: list[str] = [] + # 1. Demographic & Perinatal Guardrail (ICD-10-CM Chapter 16: P00-P96) + # Chapter 16 codes are strictly for perinatal conditions (birth through day 28 of life). + is_perinatal_code = clean_code.startswith("P") or bool( + re.search(r"\b(?:neonatal|perinatal|newborn|fetus|fetal)\b", desc_lower) + ) + if is_perinatal_code: + has_adult_context = bool( + re.search( + r"\b(?:adult|\d+\s*(?:years?[\s\-]old|yo|y/o|year)|type\s+2|t2dm|geriatric|elderly|gentleman|lady|man|woman)\b", + combined_evidence, + ) + ) + has_neonate_evidence = bool( + re.search( + r"\b(?:neonate|neonatal|newborn|day\s+of\s+life|dol\s*\d+|birth\s+weight|premature\s+infant|gestational\s+age)\b", + combined_evidence, + ) + ) + if has_adult_context and not has_neonate_evidence: + unsupported.append("demographic mismatch: perinatal/neonatal code (Chapter 16) for adult patient") + elif not has_neonate_evidence and re.search(r"\b(?:neonatal|newborn)\b", desc_lower): + unsupported.append("unsupported neonatal/newborn status") + + # 2. Obstetric & Pregnancy Guardrail (ICD-10-CM Chapter 15: O00-O9A, Z33-Z34) + is_pregnancy_code = ( + clean_code.startswith("O") + or clean_code.startswith("Z33") + or clean_code.startswith("Z34") + or bool(re.search(r"\b(?:incidental\s+pregnancy|in\s+pregnancy|during\s+pregnancy|childbirth|puerperium|antepartum|postpartum|gestational)\b", desc_lower)) + ) + if is_pregnancy_code: + has_pregnancy_evidence = bool( + re.search( + r"\b(?:pregnant|pregnancy|gravid|gravida|gestation|intrauterine\s+pregnancy|trimester|postpartum|puerperal|delivery|labor)\b", + combined_evidence, + ) + ) + if not has_pregnancy_evidence: + unsupported.append("unsupported pregnancy/obstetric status in non-pregnant documentation") + + # 3. Clinical Polarity & Hemodynamic Contradiction Guardrail + # Hypotension vs Hypertension / Hypertensive Emergency + has_hypotension = ( + has_positive_mention("hypotension", combined_evidence) + or has_positive_mention("hypotensive", combined_evidence) + or has_positive_mention("low blood pressure", combined_evidence) + or bool(re.search(r"\bbp\s*(?:of\s*)?(?:6\d|7\d|8\d)/\d+", combined_evidence)) + ) + is_hypertension_code = ( + clean_code.startswith("I16") + or clean_code == "I10" + or bool(re.search(r"\b(?:hypertensive\s+emergency|hypertensive\s+crisis|urgency|essential\s+hypertension)\b", desc_lower)) + ) + if is_hypertension_code: + has_hypertension_doc = ( + has_positive_mention("hypertension", combined_evidence) + or has_positive_mention("hypertensive", combined_evidence) + or has_positive_mention("htn", combined_evidence) + or has_positive_mention("high blood pressure", combined_evidence) + ) + if clean_code.startswith("I16") or "emergency" in desc_lower or "crisis" in desc_lower: + has_crisis_doc = bool(re.search(r"\b(?:hypertensive\s+(?:emergency|crisis|urgency)|malignant\s+hypertension)\b", combined_evidence)) + if not has_crisis_doc: + unsupported.append("unsupported hypertensive emergency/crisis (requires documented crisis)") + if has_hypotension and not has_hypertension_doc: + unsupported.append("clinical polarity conflict: hypertension code assigned when evidence documents hypotension") + + # Shock confirmation vs documented contradiction / stability + is_shock_code = ( + clean_code.startswith("R57") + or bool(re.search(r"\bshock\b", desc_lower) and not re.search(r"\b(?:without|no)\s+shock\b", desc_lower)) + ) + if is_shock_code: + has_shock_doc = has_positive_mention("shock", combined_evidence) + has_shock_contradiction = bool( + re.search( + r"\b(?:no\s+shock|normotensive\s+without\s+shock|hemodynamically\s+stable|ruled\s+out\s+shock|shock\s+ruled\s+out|no\s+evidence\s+of\s+shock|stable\s+without\s+shock|not\s+in\s+shock|stable\s+hemodynamics|bp\s+normalized|normotensive)\b", + combined_evidence, + ) + ) + if not has_shock_doc: + unsupported.append("unsupported shock: shock code assigned without affirmative diagnosis of shock in evidence") + elif has_shock_contradiction: + unsupported.append("contradictory clinical evidence: shock documented as absent/ruled out or patient hemodynamically stable") + + # Glycemic Polarity: Hypoglycemia vs Hyperglycemia + if "hypoglycemia" in desc_lower and (has_positive_mention("hyperglycemia", combined_evidence) or has_positive_mention("dka", combined_evidence)): + if not has_positive_mention("hypoglycemia", combined_evidence): + unsupported.append("clinical polarity conflict: hypoglycemia code assigned when evidence documents hyperglycemia") + + # 4. Specific Pathogen & Organism Hallucination Guardrail + # A code for a specific pathogen (e.g. Hepatitis B/C) MUST require evidence of that pathogen + is_hepatitis_code = ( + clean_code.startswith("B15") + or clean_code.startswith("B16") + or clean_code.startswith("B17") + or clean_code.startswith("B18") + or clean_code.startswith("B19") + or bool(re.search(r"\b(?:viral\s+hepatitis|hepatitis\s+[abcde])\b", desc_lower)) + ) + if is_hepatitis_code: + has_hepatitis_doc = ( + has_positive_mention("hepatitis", combined_evidence) + or has_positive_mention("hbv", combined_evidence) + or has_positive_mention("hcv", combined_evidence) + or has_positive_mention("hav", combined_evidence) + ) + if not has_hepatitis_doc: + unsupported.append("unsupported pathogen specificity: viral hepatitis code assigned without documented hepatitis diagnosis") + + # 5. Core Anatomical Entity vs General Constitutional Symptom Guardrail + # e.g., R39.14 (Feeling of incomplete bladder emptying) derived from "feverish feeling" + is_urinary_code = clean_code.startswith("R39") or clean_code.startswith("N30") or clean_code.startswith("N39") or bool( + re.search(r"\b(?:bladder|urinary|emptying|micturition|voiding|urine|dysuria)\b", desc_lower) + ) + is_constitutional_term = bool( + re.search(r"^\s*(?:fever|feverish|feverish\s+feeling|chills?|rigors?|malaise|fatigue|weakness|body\s+aches?)\s*$", diagnosis_term.lower().strip()) + ) + if is_urinary_code and is_constitutional_term: + has_urinary_doc = bool( + re.search(r"\b(?:bladder|urinary|urine|dysuria|frequency|urgency|micturition|voiding|emptying|retention)\b", combined_evidence) + ) + if not has_urinary_doc: + unsupported.append("core anatomical entity mismatch: urinary/bladder code assigned for constitutional symptom") + + implied_attributes = cls.extract_code_attributes(code_description) + for attr, is_positive in implied_attributes.items(): if not is_positive: continue @@ -387,7 +530,6 @@ class ReverseAttributeChecker: unsupported.append(anat_error) # Diabetes Type 1 vs Type 2 distinction - desc_lower = code_description.lower() if re.search(r"\btype\s+1\b", desc_lower) and not re.search( r"\b(?:type\s+1|t1dm|type\s+i\b)", combined_evidence ): @@ -488,6 +630,7 @@ class ReverseAttributeChecker: code_description: str, evidence_text: str, diagnosis_term: str = "", + code: str = "", ) -> float: """Calculate penalty (0.0 to 0.95) for unsupported attributes. @@ -498,6 +641,7 @@ class ReverseAttributeChecker: code_description=code_description, evidence_text=evidence_text, diagnosis_term=diagnosis_term, + code=code, ) if not is_valid: return 0.90 diff --git a/tests/test_normalization_and_primary_selection.py b/tests/test_normalization_and_primary_selection.py index 67664ab..aa95ba8 100644 --- a/tests/test_normalization_and_primary_selection.py +++ b/tests/test_normalization_and_primary_selection.py @@ -15,6 +15,7 @@ from medical_coding.schemas.enums import ( DiagnosisRole, Laterality, NegationStatus, + PipelineStage, Temporality, ) from medical_coding.schemas.response import CodedDiagnosisResponse, CodingResult @@ -343,3 +344,648 @@ def test_no_arbitrary_secondary_promotion_in_finalize_output(): assert len(result.secondary_diagnoses) == 1 assert result.secondary_diagnoses[0].database_code == "I10" assert result.secondary_diagnoses[0].role == DiagnosisRole.SECONDARY + + +# ============================================================================== +# 5. Exact Concept Match & Nonessential Modifier Tests +# ============================================================================== + + +def test_exact_concept_match_over_first_good_enough_candidate(): + """Verify that the ranking and matching system chooses the BEST exact concept match + rather than stopping at the first candidate that meets a threshold.""" + from medical_coding.reasoning.concept_matcher import ( + compute_concept_match_score, + select_best_concept_match, + ) + from medical_coding.schemas.icd import ICDCandidate + + # Candidate pool ordered with a generic 'good enough' match first + candidates = [ + ICDCandidate( + code="I50.9", + description="Heart failure, unspecified", + retrieval_score=0.85, + is_valid_billable=True, + coding_system="ICD-10-CM", + ), + ICDCandidate( + code="I50.20", + description="Unspecified systolic (congestive) heart failure", + retrieval_score=0.75, + is_valid_billable=True, + coding_system="ICD-10-CM", + ), + ICDCandidate( + code="I50.21", + description="Acute systolic (congestive) heart failure", + retrieval_score=0.60, # Lower retrieval score, but EXACT concept match + is_valid_billable=True, + coding_system="ICD-10-CM", + ), + ] + + best_cand, best_score, best_rat = select_best_concept_match( + candidates=candidates, + concept_name="Acute systolic heart failure", + evidence_text="Echo demonstrated EF 20% with acute decompensated heart failure.", + ) + + assert best_cand is not None + assert best_cand.code == "I50.21", f"Expected exact concept match I50.21, but got {best_cand.code}" + assert "exact" in best_rat.lower() or best_score >= 0.90 + + +def test_strip_nonessential_modifiers_matches_canonical_concepts(): + """Verify ICD-10-CM nonessential modifiers in parentheses match documented concepts.""" + from medical_coding.reasoning.concept_matcher import ( + compute_concept_match_score, + normalize_for_concept_matching, + strip_nonessential_modifiers, + ) + + # I10 has nonessential modifier '(primary)' + desc_i10 = "Essential (primary) hypertension" + assert strip_nonessential_modifiers(desc_i10) == "Essential hypertension" + score_i10, _, is_ex_i10 = compute_concept_match_score( + candidate_code="I10", + candidate_description=desc_i10, + concept_name="Essential hypertension", + ) + assert is_ex_i10 is True + assert score_i10 >= 0.95 + + # I50.21 has nonessential modifier '(congestive)' + desc_i5021 = "Acute systolic (congestive) heart failure" + assert strip_nonessential_modifiers(desc_i5021) == "Acute systolic heart failure" + score_hf, _, is_ex_hf = compute_concept_match_score( + candidate_code="I50.21", + candidate_description=desc_i5021, + concept_name="Acute systolic heart failure", + ) + assert is_ex_hf is True + assert score_hf >= 0.95 + + +def test_concept_recall_preserves_compound_anatomical_phrases(): + """Verify compound phrases where 'and' joins anatomical adjectives do not fragment concepts.""" + from medical_coding.agents.clinical_extractor import EvidenceFirstFactExtractor + + extractor = EvidenceFirstFactExtractor() + doc = """ + DISCHARGE SUMMARY + DISCHARGE DIAGNOSES: + 1. Acute cholecystitis (calculous) + 2. Hydronephrosis with renal and ureteral calculous obstruction + """ + state = extractor.extract_clinical_state(doc, doc_id="test-recall-doc") + terms = [c.raw_term.lower() for c in state.all_candidates] + + # Verify parenthetical clinical qualifier is preserved + assert any("calculous" in t for t in terms), f"Expected calculous in terms: {terms}" + + # Verify 'renal and ureteral' was not split into a bare dangling 'renal' fragment + assert not any(t.strip() == "renal" for t in terms), f"Bare 'renal' fragment found: {terms}" + assert any("calculous obstruction" in t or "hydronephrosis" in t for t in terms) + + +# ============================================================================== +# 5. Semantic Mismatch, Polarity, UHDDS Priority & Audit Consistency Tests +# ============================================================================== + + +def test_neonatal_diabetes_blocked_for_adult(): + """Verify Chapter 16 perinatal code P70.2 is blocked for adult patient.""" + from medical_coding.reasoning.concept_matcher import compute_concept_match_score + from medical_coding.validation.reverse_attributes import ReverseAttributeChecker + + # P70.2 is strictly neonatal (age < 28 days) + is_valid, unsupp = ReverseAttributeChecker.validate_code_attributes( + code_description="Neonatal diabetes mellitus", + evidence_text="45-year-old male with long-standing Type 2 diabetes mellitus admitted with acute fever.", + diagnosis_term="Type 2 diabetes mellitus", + code="P70.2", + ) + assert is_valid is False + assert any("perinatal" in u.lower() or "neonatal" in u.lower() for u in unsupp) + + score, rat, _ = compute_concept_match_score( + candidate_code="P70.2", + candidate_description="Neonatal diabetes mellitus", + concept_name="Type 2 diabetes mellitus", + evidence_text="45-year-old male with long-standing Type 2 diabetes mellitus admitted with acute fever.", + ) + assert score == 0.0 + assert "disqualified" in rat.lower() + + +def test_hypertensive_emergency_blocked_for_hypotensive_patient(): + """Verify hypertensive emergency I16.1 is blocked when patient is hypotensive.""" + from medical_coding.reasoning.concept_matcher import compute_concept_match_score + from medical_coding.validation.reverse_attributes import ReverseAttributeChecker + + is_valid, unsupp = ReverseAttributeChecker.validate_code_attributes( + code_description="Hypertensive emergency", + evidence_text="Patient presented hypotensive with BP 75/45 requiring IV fluid boluses and vasopressors.", + diagnosis_term="Hypotension", + code="I16.1", + ) + assert is_valid is False + assert any("hypertension" in u.lower() or "polarity" in u.lower() or "emergency" in u.lower() for u in unsupp) + + score, rat, _ = compute_concept_match_score( + candidate_code="I16.1", + candidate_description="Hypertensive emergency", + concept_name="Hypotension", + evidence_text="Patient presented hypotensive with BP 75/45 requiring IV fluid boluses and vasopressors.", + ) + assert score == 0.0 + assert "disqualified" in rat.lower() + + +def test_hepatitis_b_blocked_for_viral_fever(): + """Verify specific pathogen code B19.10 is blocked when evidence only documents generic viral fever.""" + from medical_coding.reasoning.concept_matcher import compute_concept_match_score + from medical_coding.validation.reverse_attributes import ReverseAttributeChecker + + is_valid, unsupp = ReverseAttributeChecker.validate_code_attributes( + code_description="Unspecified viral hepatitis B without hepatic coma", + evidence_text="Patient admitted for acute viral fever with myalgia and chills. LFTs normal.", + diagnosis_term="Viral fever", + code="B19.10", + ) + assert is_valid is False + assert any("pathogen" in u.lower() or "hepatitis" in u.lower() for u in unsupp) + + score, rat, _ = compute_concept_match_score( + candidate_code="B19.10", + candidate_description="Unspecified viral hepatitis B without hepatic coma", + concept_name="Viral fever", + evidence_text="Patient admitted for acute viral fever with myalgia and chills.", + ) + assert score == 0.0 + assert "disqualified" in rat.lower() + + +def test_bladder_emptying_blocked_for_feverish_feeling(): + """Verify urinary bladder code R39.14 is blocked when derived from constitutional 'feverish feeling'.""" + from medical_coding.reasoning.concept_matcher import compute_concept_match_score + from medical_coding.validation.reverse_attributes import ReverseAttributeChecker + + is_valid, unsupp = ReverseAttributeChecker.validate_code_attributes( + code_description="Feeling of incomplete bladder emptying", + evidence_text="Patient complained of feverish feeling and generalized weakness.", + diagnosis_term="feverish feeling", + code="R39.14", + ) + assert is_valid is False + assert any("bladder" in u.lower() or "mismatch" in u.lower() for u in unsupp) + + score, rat, _ = compute_concept_match_score( + candidate_code="R39.14", + candidate_description="Feeling of incomplete bladder emptying", + concept_name="feverish feeling", + evidence_text="Patient complained of feverish feeling and generalized weakness.", + ) + assert score == 0.0 + assert "disqualified" in rat.lower() + + +def test_shock_code_blocked_when_contradicted_by_evidence(): + """Verify R57.9 is blocked when evidence explicitly documents absence of shock.""" + from medical_coding.reasoning.concept_matcher import compute_concept_match_score + from medical_coding.validation.reverse_attributes import ReverseAttributeChecker + + is_valid, unsupp = ReverseAttributeChecker.validate_code_attributes( + code_description="Shock, unspecified", + evidence_text="Patient was normotensive without shock; hemodynamically stable on discharge.", + diagnosis_term="Shock", + code="R57.9", + ) + assert is_valid is False + assert any("shock" in u.lower() and "absent" in u.lower() for u in unsupp) + + score, rat, _ = compute_concept_match_score( + candidate_code="R57.9", + candidate_description="Shock, unspecified", + concept_name="Shock", + evidence_text="Patient was normotensive without shock; hemodynamically stable on discharge.", + ) + assert score == 0.0 + assert "disqualified" in rat.lower() + + +def test_primary_diagnosis_selection_fever_hypotension_over_chronic_diabetes(): + """Verify UHDDS principle: acute admission driver (fever with hypotension) outranks chronic comorbidity (T2DM).""" + classifier = PrimarySecondaryClassifier(llm=DummyLLM()) + doc = """ + DISCHARGE SUMMARY + DIAGNOSES: + 1. Type 2 Diabetes Mellitus + 2. Acute Viral Fever with Hypotension + HPI: Patient admitted with high-grade fever, chills, and acute hypotension (BP 75/40). + PMH: Known Type 2 diabetes on metformin at baseline. + """ + conditions = [ + ExtractedClinicalCondition( + condition_id="c1", + original_mention="Type 2 Diabetes Mellitus", + normalized_description="Type 2 Diabetes Mellitus", + evidence_text="Type 2 Diabetes Mellitus | Known Type 2 diabetes on metformin at baseline.", + status=ConditionStatus.CHRONIC, + section="DISCHARGE_DIAGNOSES", + ), + ExtractedClinicalCondition( + condition_id="c2", + original_mention="Acute Viral Fever with Hypotension", + normalized_description="Acute Viral Fever with Hypotension", + evidence_text="Patient admitted with high-grade fever, chills, and acute hypotension (BP 75/40).", + status=ConditionStatus.ACUTE, + section="CHIEF_COMPLAINT", + ), + ] + + res = classifier.classify_diagnoses(conditions, clinical_text=doc) + assert res is not None + primaries = [c for c in res if c.role == DiagnosisRole.PRIMARY] + assert len(primaries) == 1 + # Acute admission driver must be PRIMARY under UHDDS + assert "fever" in primaries[0].diagnosis.lower() or "hypotension" in primaries[0].diagnosis.lower() + + secondaries = [c for c in res if c.role == DiagnosisRole.SECONDARY] + assert any("diabetes" in s.diagnosis.lower() for s in secondaries) + + +def test_concept_recall_captures_symptoms_and_findings(): + """Verify body ache, petechiae, and constipation are captured during full document extraction.""" + from medical_coding.agents.clinical_extractor import EvidenceFirstFactExtractor + + extractor = EvidenceFirstFactExtractor() + doc = """ + HOSPITAL DISCHARGE SUMMARY + CHIEF COMPLAINT: High fever and generalized body ache for 3 days. + PHYSICAL EXAMINATION: Petechiae noted on lower extremities. + HOSPITAL COURSE: Patient developed constipation managed with laxatives. + DISCHARGE DIAGNOSES: + 1. Acute viral illness with thrombocytopenia + """ + state = extractor.extract_clinical_state(doc, doc_id="test-findings-recall") + all_terms = [c.raw_term.lower() for c in state.all_candidates] + + assert any("body ache" in t for t in all_terms), f"Expected 'body ache' in {all_terms}" + assert any("petechiae" in t for t in all_terms), f"Expected 'petechiae' in {all_terms}" + assert any("constipation" in t for t in all_terms), f"Expected 'constipation' in {all_terms}" + + +def test_output_audit_consistency_abstained_candidate_never_output(): + """Verify an abstained candidate is strictly preserved in abstentions and never resurrected in final report.""" + from medical_coding.schemas.validation import AbstentionRecord + from medical_coding.schemas.candidate import RankedSelection + + state = { + "document_id": "test-audit-consistency", + "validated_diagnoses": [], + "abstentions": [ + AbstentionRecord( + diagnosis_id="diag-dm", + raw_term="Type 2 diabetes mellitus", + reason=AbstentionReason.UNSUPPORTED_SPECIFICITY, + detail="P70.2 failed clinical semantic validation: demographic mismatch", + stage=PipelineStage.VALIDATION, + ) + ], + "audit_trail": [], + "classified_diagnoses": [ + ExtractedClinicalCondition( + condition_id="diag-dm", + original_mention="Type 2 diabetes mellitus", + normalized_description="Type 2 diabetes mellitus", + evidence_text="45-year-old adult with Type 2 diabetes", + section="DISCHARGE_DIAGNOSES", + role=DiagnosisRole.PRIMARY, + ) + ], + "ranked_selections": [ + RankedSelection( + diagnosis_id="diag-dm", + decision="ABSTAINED", + ranking_reason="Demographic mismatch", + confidence=0.0, + ) + ], + } + + result = finalize_output_node(state) + report_dict = result.get("final_report", {}) + report_abstentions = report_dict.get("abstentions", []) + + # The abstained candidate MUST be present in the report's abstentions + assert any(a.get("raw_term") == "Type 2 diabetes mellitus" for a in report_abstentions) + + # The abstained candidate must NOT be in primary_diagnosis or secondary_diagnoses as an accepted code + primary_dx = report_dict.get("primary_diagnosis") + if primary_dx: + assert primary_dx.get("database_code") != "P70.2", "P70.2 must not be output as primary code!" + assert primary_dx.get("raw_term") != "Type 2 diabetes mellitus", "Abstained diabetes must not be output as accepted primary!" + + +def test_nasal_mucositis_blocked_for_oral_mucositis(): + """Verify that candidate code J34.81 (Nasal mucositis) is disqualified for oral mucositis / general mucositis.""" + from medical_coding.reasoning.concept_matcher import compute_concept_match_score + from medical_coding.validation.reverse_attributes import ReverseAttributeChecker + + # Oral mucositis -> J34.81 (nasal) must fail reverse attribute check + is_valid, unsupp = ReverseAttributeChecker.validate_code_attributes( + code_description="Nasal mucositis (ulcerative)", + evidence_text="Patient developed severe oral mucositis and stomatitis.", + diagnosis_term="Oral mucositis", + code="J34.81", + ) + assert is_valid is False + assert any("mismatch" in u.lower() or "nasal" in u.lower() or "site" in u.lower() for u in unsupp) + + # Concept score must be disqualified + score, rat, _ = compute_concept_match_score( + candidate_code="J34.81", + candidate_description="Nasal mucositis (ulcerative)", + concept_name="Oral mucositis", + evidence_text="Patient developed severe oral mucositis and stomatitis.", + ) + assert score == 0.0 + + # Oral mucositis -> K12.30 (Oral mucositis) must succeed + is_valid_oral, _ = ReverseAttributeChecker.validate_code_attributes( + code_description="Oral mucositis (ulcerative), unspecified", + evidence_text="Patient developed oral mucositis.", + diagnosis_term="Oral mucositis", + code="K12.30", + ) + assert is_valid_oral is True + + +def test_compound_with_splitting_hypotension_and_dehydration(): + """Verify compound phrase 'Acute viral fever with hypotension and dehydration' decomposes into independent concepts.""" + from medical_coding.agents.clinical_extractor import EvidenceFirstFactExtractor + + extractor = EvidenceFirstFactExtractor() + doc = """ + DISCHARGE SUMMARY + DIAGNOSES: + 1. Acute viral fever with hypotension and dehydration + HPI: Admitted with high fever, BP 75/45, and marked dehydration. + """ + state = extractor.extract_clinical_state(doc, doc_id="test-compound-with") + extracted_terms = [c.raw_term.lower() for c in state.all_candidates] + + assert any("viral fever" in t or "viral" in t for t in extracted_terms) + assert any("hypotension" in t for t in extracted_terms) + assert any("dehydration" in t for t in extracted_terms) + + +def test_contradictory_shock_resolved_to_ruled_out(): + """Verify that when a heading mentions shock but examination/course shows stability, shock is ruled out and NOT confirmed.""" + from medical_coding.agents.clinical_extractor import EvidenceFirstFactExtractor + + extractor = EvidenceFirstFactExtractor() + doc = """ + DISCHARGE SUMMARY + IMPRESSION: Shock + EXAMINATION: Patient is alert, warm, normotensive without shock (BP 120/80). Hemodynamically stable. + HOSPITAL COURSE: Fluid challenge was completed; no evidence of septic shock. + FINAL DIAGNOSIS: Acute viral fever with dehydration. + """ + state = extractor.extract_clinical_state(doc, doc_id="test-shock-contradiction") + + # Shock must NOT be in primary_diagnosis or secondary_diagnoses as active/confirmed + if state.primary_diagnosis: + assert "shock" not in state.primary_diagnosis.raw_term.lower() + for sec in state.secondary_diagnoses: + assert "shock" not in sec.raw_term.lower() + + # Shock should be in ruled_out_conditions + assert any("shock" in r.raw_term.lower() for r in state.ruled_out_conditions) + + +def test_ten_concept_catalogue_recall_matrix(): + """Verify strict concept-and-code matching reaches 90-100% across the 10 catalogue-addressable concepts.""" + from medical_coding.reasoning.concept_matcher import compute_concept_match_score + + # Benchmark: 10 catalogue-addressable clinical concepts and their defensible ICD-10-CM codes + benchmark_cases = [ + # (Concept, Document Evidence, Expected Code, Expected Code Desc, False Positive Code to Reject) + ( + "Hypotension", + "Patient was hypotensive with BP 75/45 requiring IV fluid boluses.", + "I95.9", + "Hypotension, unspecified", + "I16.1", # Hypertensive emergency + ), + ( + "Acute viral fever", + "Patient admitted for acute viral fever with generalized weakness.", + "B34.9", + "Viral infection, unspecified", + "B19.10", # Viral hepatitis B + ), + ( + "Type 2 diabetes mellitus", + "52-year-old adult patient with baseline Type 2 diabetes on metformin.", + "E11.9", + "Type 2 diabetes mellitus without complications", + "P70.2", # Neonatal diabetes + ), + ( + "Essential hypertension", + "Past history of essential hypertension controlled on amlodipine.", + "I10", + "Essential (primary) hypertension", + "I16.1", # Hypertensive emergency + ), + ( + "Oral mucositis", + "Examination revealed oral mucositis and stomatitis of the buccal mucosa.", + "K12.30", + "Oral mucositis (ulcerative), unspecified", + "J34.81", # Nasal mucositis + ), + ( + "Myalgia", + "Patient complained of severe generalized body aches and myalgia.", + "M79.10", + "Myalgia, unspecified site", + "R39.14", # Incomplete bladder emptying + ), + ( + "Petechiae", + "Physical examination noted petechiae on lower extremities.", + "R23.3", + "Spontaneous ecchymoses", + "Z33.1", # Incidental pregnancy + ), + ( + "Constipation", + "Patient developed constipation during hospital stay managed with laxatives.", + "K59.00", + "Constipation, unspecified", + "R57.9", # Unspecified shock + ), + ( + "Dehydration", + "Patient presented with volume depletion and dehydration.", + "E86.0", + "Dehydration", + "I16.1", + ), + ( + "Fever", + "Patient presented with high-grade fever of 103 F.", + "R50.9", + "Fever, unspecified", + "R39.14", # Bladder emptying + ), + ] + + correct_matches = 0 + total_targets = len(benchmark_cases) + + for concept, ev, expected_code, expected_desc, rejected_code in benchmark_cases: + # 1. Expected code must score high (best concept match) + score_exp, rat_exp, _ = compute_concept_match_score( + candidate_code=expected_code, + candidate_description=expected_desc, + concept_name=concept, + evidence_text=ev, + ) + assert score_exp >= 0.80, f"Expected code {expected_code} scored too low ({score_exp}): {rat_exp}" + + # 2. Rejected false positive must score 0.0 (disqualified by clinical gates) + score_rej, rat_rej, _ = compute_concept_match_score( + candidate_code=rejected_code, + candidate_description="False positive candidate description", + concept_name=concept, + evidence_text=ev, + ) + assert score_rej == 0.0 or score_rej < score_exp, f"Rejected code {rejected_code} not disqualified: {rat_rej}" + + if score_exp > score_rej and score_exp >= 0.80: + correct_matches += 1 + + strict_recall = (correct_matches / total_targets) * 100.0 + print(f"\nBenchmark Strict Concept-and-Code Recall: {strict_recall:.1f}% ({correct_matches}/{total_targets})") + assert strict_recall >= 90.0, f"Strict recall {strict_recall}% must be >= 90%!" + + +# ============================================================================== +# 5. Clinical Semantic Validation & Contradiction Handling Regression Tests +# ============================================================================== + + +def test_concept_reasoner_detects_shock_contradiction(): + """Verify ClinicalConceptReasoner populates contradictory_attributes and sets RULED_OUT + when provisional shock is contradicted by hemodynamic stability or normotension.""" + from medical_coding.reasoning.concept_reasoner import ClinicalConceptReasoner + from medical_coding.schemas.clinical import ExtractedClinicalCondition, EvidenceLocation + + candidate = ExtractedClinicalCondition( + condition_id="c-shock-1", + raw_term="Shock", + normalized_diagnosis="Shock", + evidence_quote="IMPRESSION: Shock", + evidence_location=EvidenceLocation(section="IMPRESSION"), + certainty=Certainty.CONFIRMED, + ) + doc_text = ( + "IMPRESSION: Shock.\n" + "PHYSICAL EXAMINATION: Patient is warm, alert, normotensive without shock (BP 125/82).\n" + "HOSPITAL COURSE: Hemodynamically stable throughout." + ) + + concept = ClinicalConceptReasoner.reason_concept( + candidate=candidate, + evidence_text="IMPRESSION: Shock", + document_text=doc_text, + ) + + assert concept.assertion_status == "RULED_OUT" + assert "hemodynamic_stability_contradiction" in concept.contradictory_attributes + assert len(concept.contradiction_evidence) > 0 + + +def test_compatibility_reasoner_rejects_contradicted_concept(): + """Verify CompatibilityReasoner returns compatible=False and score=0.0 when concept has contradictions.""" + from medical_coding.reasoning.concept_reasoner import ClinicalConceptReasoner + from medical_coding.reasoning.compatibility import CompatibilityReasoner + from medical_coding.schemas.clinical import ExtractedClinicalCondition, EvidenceLocation + + candidate = ExtractedClinicalCondition( + condition_id="c-shock-2", + raw_term="Septic shock", + normalized_diagnosis="Septic shock", + evidence_quote="Impression: Septic shock", + evidence_location=EvidenceLocation(section="IMPRESSION"), + certainty=Certainty.CONFIRMED, + ) + doc_text = "Impression: Septic shock. Examination shows patient is normotensive without shock and hemodynamically stable." + + concept = ClinicalConceptReasoner.reason_concept( + candidate=candidate, + evidence_text="Impression: Septic shock", + document_text=doc_text, + ) + + result = CompatibilityReasoner.evaluate_candidate( + candidate_code="R57.2", + candidate_description="Septic shock", + concept=concept, + ) + + assert result.compatible is False + assert result.score == 0.0 + assert len(result.contradictions) > 0 + + +def test_semantic_validation_rejects_and_realigns_mismatches(): + """Verify CandidateRankingDeterministicValidator rejects anatomical and physiological mismatches + and realigns to supported candidates from the candidate pool.""" + from medical_coding.validation.deterministic import CandidateRankingDeterministicValidator + from medical_coding.schemas.icd import ICDCandidate, RankedSelection + + validator = CandidateRankingDeterministicValidator() + + # Case 1: Oral mucositis with candidate pool containing J34.81 (nasal) and K12.30 (oral) + cand_nasal = ICDCandidate( + code="J34.81", + description="Nasal mucositis (ulcerative)", + retrieval_score=0.95, + is_valid_billable=True, + ) + cand_oral = ICDCandidate( + code="K12.30", + description="Oral mucositis (ulcerative), unspecified", + retrieval_score=0.88, + is_valid_billable=True, + ) + + initial_sel = RankedSelection( + diagnosis_id="diag-mucositis", + raw_term="Oral mucositis", + selected_code="J34.81", + selected_description=cand_nasal.description, + selected_candidate=cand_nasal, + candidate_pool=[cand_nasal, cand_oral], + ) + + validated_sel = validator.validate_ranking_selection( + selection=initial_sel, + candidates=[cand_nasal, cand_oral], + evidence_text="Patient has severe oral mucositis and stomatitis of buccal mucosa.", + diagnosis_term="Oral mucositis", + ) + + # Must be realigned to K12.30 (oral), NOT J34.81 (nasal) + assert validated_sel.selected_code == "K12.30" + assert "oral" in validated_sel.selected_description.lower() + + + +