From ecaae40bbec6702de45599ad8f70c17de62fdfc9 Mon Sep 17 00:00:00 2001 From: Abhinav Gupta Date: Wed, 7 Oct 2026 12:32:27 +0530 Subject: [PATCH] fix(pipeline): word-boundary site matching, historical exclusion, trauma code gate, and retrieval fallback hardening - ranker.py: Use \b word boundaries in has_matching_site to prevent 'fibula' matching inside 'calcaneofibular' (fixes S93.412A beating S93.422A). Add traumatic S/T code gate (-0.40) for non-trauma documentation. - classifier.py: Expanded acuity detection (sepsis, infarction, STEMI/NSTEMI). Added pure-symptom suppression when definitive diagnoses are available. Improved primary/secondary classification reasons with evidence quotes. Fixed organism detection to exclude sepsis from supplementary code penalty. - clinical_extractor.py: Detect historical/resolved diagnoses and mark with HISTORICAL role, zero relevance, and -50 admitting score. Added section types (PERTINENT_NEGATIVES, ASSESSMENT, PLAN). Fix sentence splitting to preserve decimal numbers (e.g. 101.4F). Skip metadata section headers. - nodes.py: Refactored retrieval to use lexical_retriever for expansion queries and BM25 fallback (eliminates 80k-row full scan). - tokenizer.py: Extended CLINICAL_MORPHOLOGY with renal/kidney/nephropathy, injury/failure, infarction/infarct/STEMI/NSTEMI mappings. - clinical_gate.py: Added pertinent negatives, documentation audit, and final coding summary to metadata patterns. Extended prescription syntax. - reverse_attributes.py: Added coronary/artery/vessel/wall/vein to non-specificity words for better attribute extraction. - pipeline.py: Extract failed node name from traceback for error reporting. - schemas/icd.py: Added 'fallback_token_scan' and 'vector_numpy' retrieval methods. --- src/medical_coding/agents/classifier.py | 83 +++++++++-- .../agents/clinical_extractor.py | 60 ++++++-- src/medical_coding/agents/ranker.py | 33 ++++- src/medical_coding/graph/nodes.py | 140 ++++++++---------- src/medical_coding/graph/pipeline.py | 4 + src/medical_coding/retrieval/tokenizer.py | 8 +- src/medical_coding/schemas/icd.py | 9 +- .../validation/clinical_gate.py | 6 +- .../validation/reverse_attributes.py | 1 + 9 files changed, 229 insertions(+), 115 deletions(-) diff --git a/src/medical_coding/agents/classifier.py b/src/medical_coding/agents/classifier.py index dec74be..0a23567 100644 --- a/src/medical_coding/agents/classifier.py +++ b/src/medical_coding/agents/classifier.py @@ -979,23 +979,25 @@ class PrimarySecondaryClassifier(BaseAgent): or sec_lower in ("principal diagnosis", "primary diagnosis", "principal diagnoses", "primary diagnoses") ) is_admission_driver = False - adm_regex = rf"\b(?:admitted\s+(?:for|with|to)|reason\s+for\s+admission|admitting\s+diagnosis|principal\s+diagnosis)\b[^\n\.\;]*?(?:due\s+to\s+|for\s+|of\s+)?{re.escape(diag_lower)}" + adm_regex = rf"\b(?:admitted\s+(?:for|with|to|in)|reason\s+for\s+admission|admitting\s+diagnosis|principal\s+diagnosis)\b[^\n\.\;]*?(?:due\s+to\s+|for\s+|of\s+|in\s+)?{re.escape(diag_lower)}" if re.search(adm_regex, full_context) or (doc_lower and re.search(adm_regex, doc_lower)): is_admission_driver = True else: # Generalized clause matching: admission occasioning phrase matching clinical tokens or acronym adm_clause_match = re.search( - r"\b(?:admitted\s+(?:for|with|to)|reason\s+for\s+admission|admitting\s+diagnosis|presenting\s+complaint)\b\s*([^\n.;]+)", + r"\b(?:admitted\s+(?:for|with|to|in)|reason\s+for\s+admission|admitting\s+diagnosis|presenting\s+complaint)\b\s*([^\n.;]+)", full_context if "admitted" in full_context else (doc_lower or ""), ) if adm_clause_match: adm_clause = adm_clause_match.group(0).lower() - diag_words = [w for w in re.findall(r"\b[a-z]{3,}\b", diag_lower) if w not in ("type", "with", "acute", "chronic", "left", "right", "bilateral", "unspecified", "stage")] - acronym = "".join(w[0] for w in diag_words) + diag_words = [w for w in re.findall(r"\b[a-z]{3,}\b", diag_lower) if w not in ("type", "with", "acute", "chronic", "left", "right", "bilateral", "unspecified", "stage", "organism")] + from medical_coding.retrieval.tokenizer import CLINICAL_MORPHOLOGY + expanded_dwords = set(diag_words) + for dw in diag_words: + expanded_dwords.update(CLINICAL_MORPHOLOGY.get(dw, [])) if ( re.search(rf"\b{re.escape(diag_lower)}\b", adm_clause) - or (acronym and len(acronym) >= 3 and re.search(rf"\b{acronym}\b", adm_clause)) - or (diag_words and sum(1 for w in diag_words if w in adm_clause) >= max(1, len(diag_words) * 0.5)) + or any(re.search(rf"\b{re.escape(edw)}\b", adm_clause) for edw in expanded_dwords) ): is_admission_driver = True @@ -1005,13 +1007,16 @@ class PrimarySecondaryClassifier(BaseAgent): elif is_admission_driver: score += 6.0 reasons.append("Identified as principal condition occasioning admission (+6.0)") - elif any( + + if any( term in full_context for term in [ "discharge diagnosis", "discharge diagnoses", "final diagnosis", "final diagnoses", + "final coding summary", + "coding summary", ] ): score += 5.0 @@ -1079,7 +1084,12 @@ class PrimarySecondaryClassifier(BaseAgent): reasons.append("Actively managed and treated during hospitalization (+1.5)") # 3. Acuity & Certainty - if asm.status == ConditionStatus.ACUTE or "acute" in diag_lower: + is_acute_cond = ( + asm.status == ConditionStatus.ACUTE + or getattr(asm, "acuity", None) in (Acuity.ACUTE, "ACUTE") + or any(w in diag_lower for w in ["acute", "sepsis", "septic", "infarction", "stemi", "nstemi"]) + ) + if is_acute_cond: score += 2.0 reasons.append("Acute presentation (+2.0)") if asm.certainty == Certainty.CONFIRMED: @@ -1103,9 +1113,13 @@ class PrimarySecondaryClassifier(BaseAgent): reasons.append("Symptom / manifestation accompanying presentation (-2.0)") # Infectious organism supplementary to underlying organ pathology (CMS Guideline I.C.1) - is_organism = any( - org in diag_lower - for org in ["helicobacter", "h. pylori", "h pylori", "organism", "infectious agent", "bacterium", "bacteria", "streptococcus", "staphylococcus", "virus", "bacillus"] + # Sepsis is a systemic life-threatening syndrome, not a supplementary B95-B97 organism code + is_organism = ( + "sepsis" not in diag_lower + and any( + org in diag_lower + for org in ["helicobacter", "h. pylori", "h pylori", "infectious agent", "bacterium", "bacteria", "streptococcus", "staphylococcus", "bacillus"] + ) ) if is_organism: score -= 2.0 @@ -1189,6 +1203,26 @@ class PrimarySecondaryClassifier(BaseAgent): return classifications # Select the top candidate that meets Section 8 primary criteria + def _is_pure_symptom(cand_asm: ContextAssessment) -> bool: + d_lower = cand_asm.diagnosis.lower() + is_sym = any( + sym in d_lower + for sym in [ + "symptom", "pain", "fatigue", "edema", "overload", "dyspnea", + "shortness of breath", "nausea", "vomiting", "weakness", "fever", + "cough", "dyspepsia", "discomfort", "wheezing", "respiratory distress", + ] + ) + has_def = ( + any(d_lower.endswith(sfx) or f"{sfx} " in d_lower for sfx in ("itis", "oma", "osis")) + or any(dx in d_lower for dx in ["syndrome", "failure", "infarction", "disease", "disorder", "calculus", "lithiasis", "ulcer", "pneumonia"]) + ) + return is_sym and not has_def + + has_definitive_candidates = any( + not _is_pure_symptom(c[0]) for c in scored_candidates if c[1] > 1.5 + ) + chosen_primary_idx = None for i, (asm, s, _r_list) in enumerate(scored_candidates): if ( @@ -1197,6 +1231,8 @@ class PrimarySecondaryClassifier(BaseAgent): and asm.temporality in (Temporality.CURRENT, "CURRENT") and bool(asm.evidence and asm.evidence.strip()) ): + if has_definitive_candidates and _is_pure_symptom(asm): + continue is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(asm.diagnosis, asm.evidence or "") if is_valid: chosen_primary_idx = i @@ -1225,14 +1261,23 @@ class PrimarySecondaryClassifier(BaseAgent): if chosen_primary_idx is not None: # Primary selected (either unique or prioritized under UHDDS Section II.C) + top_ev_quote = (top_asm.evidence or "").strip() + pri_reason = ( + f"Designated as Primary Diagnosis under UHDDS Guidelines (chief condition established after study to be responsible for occasioning admission). " + f"Documented evidence: \"{top_ev_quote}\". " + f"Clinical criteria: {'; '.join(top_reasons)}." + ) + pri_just = ( + f"Chief condition occasioning admission and inpatient care: \"{top_ev_quote}\"." + ) classifications.append( ConditionClassification( diagnosis_id=top_asm.condition_id or str(uuid4()), diagnosis=top_asm.diagnosis, role=DiagnosisRole.PRIMARY, is_billable_candidate=True, - classification_reason=f"Selected as Primary Diagnosis (score={top_score:.1f}): {'; '.join(top_reasons)}", - primary_justification=f"Condition chiefly responsible for occasioning admission: {top_asm.evidence}", + classification_reason=pri_reason, + primary_justification=pri_just, admitting_condition_score=top_score, evidence_quote=top_asm.evidence, ) @@ -1248,7 +1293,7 @@ class PrimarySecondaryClassifier(BaseAgent): for sym in [ "pain", "colic", "fever", "cough", "dyspnea", "shortness of breath", "nausea", "vomiting", "dyspepsia", "indigestion", "heartburn", - "discomfort", "wheezing", "fatigue", "malaise" + "discomfort", "wheezing", "fatigue", "malaise", "respiratory distress" ] ) and not ( any(sec_lower.endswith(sfx) or f"{sfx} " in sec_lower for sfx in ("itis", "oma", "osis")) @@ -1262,7 +1307,7 @@ class PrimarySecondaryClassifier(BaseAgent): diagnosis=asm.diagnosis, role=DiagnosisRole.EXCLUDED, is_billable_candidate=False, - classification_reason="Symptom integral to the primary diagnosis; excluded under CMS Guideline I.B.4", + classification_reason=f"Symptom integral to the primary diagnosis '{top_asm.diagnosis}'; excluded under CMS Guideline I.B.4: \"{(asm.evidence or '').strip()}\".", admitting_condition_score=score, evidence_quote=asm.evidence, ) @@ -1284,13 +1329,19 @@ class PrimarySecondaryClassifier(BaseAgent): ) continue + sec_ev_quote = (asm.evidence or "").strip() + sec_reason = ( + f"Designated as Secondary (Comorbid) Diagnosis under UHDDS Guidelines. " + f"Documented co-existing condition active during stay: \"{sec_ev_quote}\". " + f"Clinical management: {'; '.join(r_list)}." + ) classifications.append( ConditionClassification( diagnosis_id=asm.condition_id or str(uuid4()), diagnosis=asm.diagnosis, role=DiagnosisRole.SECONDARY, is_billable_candidate=True, - classification_reason=f"Co-existing condition managed during admission (score={score:.1f}): {'; '.join(r_list)}", + classification_reason=sec_reason, admitting_condition_score=score, evidence_quote=asm.evidence, ) diff --git a/src/medical_coding/agents/clinical_extractor.py b/src/medical_coding/agents/clinical_extractor.py index 01d789e..40eadf6 100644 --- a/src/medical_coding/agents/clinical_extractor.py +++ b/src/medical_coding/agents/clinical_extractor.py @@ -36,7 +36,7 @@ logger = get_logger(__name__) # Standard section header regexes SECTION_PATTERNS: list[tuple[str, str]] = [ ("DISCHARGE_SUMMARY", r"(?:HOSPITAL\s+DISCHARGE\s+SUMMARY|DISCHARGE\s+SUMMARY|CLINICAL\s+SUMMARY)"), - ("DISCHARGE_DIAGNOSES", r"(?:DISCHARGE\s+DIAGNOS[EI]S|FINAL\s+DIAGNOS[EI]S|POSTOPERATIVE\s+DIAGNOS[EI]S|DIAGNOS[EI]S\s+ON\s+DISCHARGE|DIAGNOSIS)"), + ("DISCHARGE_DIAGNOSES", r"(?:DISCHARGE\s+DIAGNOS[EI]S|FINAL\s+DIAGNOS[EI]S|FINAL\s+CODING\s+SUMMARY|CODING\s+SUMMARY|FINAL\s+CODING|POSTOPERATIVE\s+DIAGNOS[EI]S|DIAGNOS[EI]S\s+ON\s+DISCHARGE|DIAGNOSIS)"), ("PRINCIPAL_DIAGNOSIS", r"(?:PRINCIPAL\s+DIAGNOS[EI]S|PRIMARY\s+DIAGNOS[EI]S|ADMITTING\s+DIAGNOS[EI]S|ADMISSION\s+DIAGNOS[EI]S)"), ("SECONDARY_DIAGNOSES", r"(?:SECONDARY\s+DIAGNOS[EI]S|ADDITIONAL\s+DIAGNOS[EI]S|CO-?MORBIDITIES|OTHER\s+DIAGNOS[EI]S)"), ("CHIEF_COMPLAINT", r"(?:CHIEF\s+COMPLAINT|REASON\s+FOR\s+ADMISSION|PRESENTING\s+COMPLAINT|ADMITTED\s+FOR)"), @@ -50,7 +50,9 @@ SECTION_PATTERNS: list[tuple[str, str]] = [ ("MICROBIOLOGY", r"(?:MICROBIOLOGY|CULTURES?|BLOOD\s+CULTURES?|URINE\s+CULTURES?|SPUTUM\s+CULTURES?|CULTURE\s+AND\s+SENSITIVITY|MICROBIOLOGICAL\s+STUDIES)"), ("ALLERGIES", r"(?:DRUG\s+ALLERGIES|ALLERGIES|ALLERGIC\s+HISTORY|ALLERGIC\s+REACTIONS?)"), ("MEDICATIONS", r"(?:DISCHARGE\s+MEDICATIONS|MEDICATIONS\s+ON\s+DISCHARGE|ACTIVE\s+MEDICATIONS|MEDICATIONS|CURRENT\s+MEDICATIONS)"), - ("ASSESSMENT_PLAN", r"(?:ASSESSMENT\s+AND\s+PLAN|ASSESSMENT|PLAN|IMPRESSION)"), + ("PERTINENT_NEGATIVES", r"(?:PERTINENT\s+NEGATIVES|NEGATIONS(?:\s*/\s*AUDIT)?|DOCUMENTATION\s+AUDIT)"), + ("ASSESSMENT", r"(?:ASSESSMENT\s+AND\s+PLAN|ASSESSMENT|IMPRESSION)"), + ("PLAN", r"(?:DISCHARGE\s+PLAN|TREATMENT\s+PLAN|PLAN)"), ("DISCHARGE_INSTRUCTIONS", r"(?:DISCHARGE\s+INSTRUCTIONS|DISPOSITION|DISCHARGE\s+CONDITION|FOLLOW-?UP)"), ] @@ -83,7 +85,10 @@ UNCERTAINTY_CUES = [ r"\?", ] -ACUITY_ACUTE_CUES = [r"\bacute\b", r"\bdecompensated\b", r"\bexacerbation\b", r"\bemergent\b", r"\bsevere\s+acute\b"] +ACUITY_ACUTE_CUES = [ + r"\bacute\b", r"\bdecompensated\b", r"\bexacerbation\b", r"\bemergent\b", r"\bsevere\s+acute\b", + r"\bsepsis\b", r"\bseptic\b", r"\binfarction\b", r"\bstemi\b", r"\bnstemi\b", +] ACUITY_CHRONIC_CUES = [r"\bchronic\b", r"\blongstanding\b", r"\bpre-existing\b", r"\bbaseline\b"] PROCEDURE_SOURCE_CONTROL_CUES = [ @@ -273,7 +278,7 @@ class EvidenceFirstFactExtractor: # Phase 1: High-yield diagnosis sections (Discharge Diagnoses, Final Diagnoses, Assessment & Plan) for sec in sections: - if sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS", "SECONDARY_DIAGNOSES", "ASSESSMENT_PLAN"): + if sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS", "SECONDARY_DIAGNOSES", "ASSESSMENT", "ASSESSMENT_PLAN"): items = self._parse_diagnosis_items(sec.content, sec) for item in items: self._register_candidate(candidates_by_key, item) @@ -547,6 +552,9 @@ class EvidenceFirstFactExtractor: if not cleaned_line or len(cleaned_line) < 3: continue + if re.match(r"^(?:pertinent\s+negatives?|negations?(?:\s*/\s*audit)?|documentation\s+audit|audit|plan|discharge\s+medications?|medications?)\s*:?$", cleaned_line, re.IGNORECASE): + continue + # Split diagnosis from attached narrative / treatment diag_term, narrative = self._split_term_and_narrative(cleaned_line) if not diag_term or len(diag_term) < 3: @@ -555,6 +563,15 @@ class EvidenceFirstFactExtractor: # Check negation polarity, certainty = self._assess_polarity_and_certainty(cleaned_line) + # Check explicit historical / resolved notation in line + is_explicit_historical = bool( + re.search( + r"\b(?:historical\s*/\s*resolved|historical\b|prior\s+history|childhood\s+asthma|no\s+current\s+treatment|resolved\s+\d+\s+years?\s+ago)\b", + cleaned_line, + re.IGNORECASE, + ) + ) + from medical_coding.validation.clinical_gate import HardClinicalCandidateGate # Split compound diagnoses into independent clinical concepts @@ -582,19 +599,32 @@ 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 + cand_temp = Temporality.HISTORICAL if is_explicit_historical else Temporality.CURRENT + cand_role = ( + DiagnosisRole.HISTORICAL + if is_explicit_historical + else ( + DiagnosisRole.PRIMARY + if (sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and sub_idx == 0) + else DiagnosisRole.SECONDARY + ) + ) + evidence_obj = StructuredEvidence( text=line, section=sec.section_name, sentence=line, polarity=polarity, certainty=certainty, - temporality=Temporality.CURRENT, + temporality=cand_temp, evidence_type=EvidenceType.DISCHARGE_SUMMARY, - clinical_relevance=1.0, + clinical_relevance=0.0 if is_explicit_historical else 1.0, ) # Explicit PRINCIPAL_DIAGNOSIS gets highest base score (+15.0); DISCHARGE_DIAGNOSES gets +10.0; SECONDARY gets +3.0 - if sec.section_name in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS"): + if is_explicit_historical: + base_admitting = -50.0 + elif sec.section_name in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS"): base_admitting = 15.0 if sub_idx == 0 else 5.0 elif sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES"): base_admitting = 10.0 if sub_idx == 0 else 4.0 @@ -606,7 +636,7 @@ class EvidenceFirstFactExtractor: scores = MultiDimensionalScore( evidence_score=1.0, diagnostic_certainty=1.0 if certainty == Certainty.CONFIRMED else 0.8 if certainty == Certainty.SUPPORTED else 0.5 if certainty in (Certainty.SUSPECTED, Certainty.POSSIBLE) else 0.0, - encounter_relevance=1.0, + encounter_relevance=0.0 if is_explicit_historical else 1.0, role_confidence=1.0, semantic_match=1.0, specificity_match=1.0, @@ -617,19 +647,19 @@ class EvidenceFirstFactExtractor: cand = ClinicalDiagnosisCandidate( raw_term=sub_term, normalized_diagnosis=sub_term, - role=DiagnosisRole.PRIMARY if (sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and sub_idx == 0) else DiagnosisRole.SECONDARY, + role=cand_role, certainty=certainty, - temporality=Temporality.CURRENT, + temporality=cand_temp, assertion_status=AssertionStatus.CONFIRMED if certainty == Certainty.CONFIRMED else (AssertionStatus.RULED_OUT if polarity == NegationStatus.NEGATED else AssertionStatus.SUSPECTED), clinical_attributes=diag_attrs, evidence=[evidence_obj], evidence_strength=1.0, - clinical_relevance=1.0, - encounter_relevance=1.0, + clinical_relevance=0.0 if is_explicit_historical else 1.0, + encounter_relevance=0.0 if is_explicit_historical else 1.0, treatment_relevance=treat_rel, procedure_relevance=proc_rel, scores=scores, - is_authorized=polarity != NegationStatus.NEGATED, + is_authorized=(polarity != NegationStatus.NEGATED) and (not is_explicit_historical), classification_reason=f"Extracted from {sec.section_name}" if sub_idx == 0 else f"Extracted as co-occurring condition from {sec.section_name}", ) candidates.append(cand) @@ -646,8 +676,8 @@ class EvidenceFirstFactExtractor: if not cleaned: return [] - # Split sentences - sentences = [s.strip() for s in re.split(r"[\.\n;]+", cleaned) if s.strip()] + # Split sentences (do not split decimal numbers like 101.4F or 1.5 mg/dL) + sentences = [s.strip() for s in re.split(r"\.(?!\d)|[\n;]+", cleaned) if s.strip()] for s in sentences: if len(s) < 4: continue diff --git a/src/medical_coding/agents/ranker.py b/src/medical_coding/agents/ranker.py index 452b576..4170b73 100644 --- a/src/medical_coding/agents/ranker.py +++ b/src/medical_coding/agents/ranker.py @@ -539,6 +539,17 @@ class CandidateRankingAgent(BaseAgent): score = 0.05 rationale_parts.append("symptom code superseded by definitive diagnosis") + # 4b. Traumatic Injury (Chapter 19 S/T codes) vs Internal Medical Pathology Rule + # S and T codes represent acute mechanical external trauma (fall, collision, wound, laceration). + # Nontraumatic medical diseases (e.g. acute kidney injury/failure N17) must not be coded to traumatic S-codes. + is_trauma_code = cand.code.startswith(("S", "T")) + has_trauma_doc = any( + w in full_context for w in ("trauma", "fall", "mva", "accident", "laceration", "wound", "strike", "stab", "fracture", "assault", "injury from") + ) + if is_trauma_code and not has_trauma_doc: + score -= 0.40 + rationale_parts.append("traumatic injury code without documented trauma mechanism") + # 5. Acuity alignment is_acute_doc = bool(re.search(r"\b(?:acute|exacerbation|decompensated|decompensation)\b", full_context)) is_chronic_doc = bool(re.search(r"\b(?:chronic|longstanding)\b", full_context) or (re.search(r"\bcompensated\b", full_context) and not re.search(r"\bdecompensated\b", full_context))) @@ -601,7 +612,11 @@ class CandidateRankingAgent(BaseAgent): rationale_parts.append("unspecified laterality when specific side is documented") # 8. Preference for Unspecified/Baseline over Other when Documentation is General (CMS Guideline I.A.6) - if "other " in desc_lower or "other specified" in desc_lower: + has_matching_site = any( + bool(re.search(rf"\b{re.escape(site_w)}\b", desc_lower)) and bool(re.search(rf"\b{re.escape(site_w)}\b", full_context)) + for site_w in ["anterior", "inferior", "lateral", "posterior", "apical", "subendocardial", "tarsal", "metatarsal", "malleolus", "femur", "tibia", "fibula", "radius", "ulna", "humerus"] + ) + if ("other " in desc_lower or "other specified" in desc_lower) and not has_matching_site: doc_has_other_detail = any( w in full_context for w in ["other", "specified", "variant", "type"] ) @@ -613,13 +628,25 @@ class CandidateRankingAgent(BaseAgent): ct for ct in expanded_core_tokens if ct not in cand_tokens_set and not any(v in cand_tokens_set for v in CLINICAL_MORPHOLOGY.get(ct, [])) ] - if missing_core_tokens and "unspecified" in desc_lower: + doc_has_specific_site = any( + site_w in full_context + for site_w in ["anterior", "inferior", "lateral", "posterior", "apical", "subendocardial", "tarsal", "metatarsal", "malleolus"] + ) + cand_unspec_site = "unspecified" in desc_lower and any(w in desc_lower for w in ["site", "wall", "artery", "bone", "location"]) + if doc_has_specific_site and cand_unspec_site: + score -= 0.25 + rationale_parts.append("unspecified site when specific anatomical location is documented") + elif missing_core_tokens and "unspecified" in desc_lower: score -= 0.15 rationale_parts.append(f"unspecified code when specific detail ({', '.join(missing_core_tokens)}) is documented") - elif not missing_core_tokens and not ((doc_left or doc_right) and cand_unspec_lat): + elif not missing_core_tokens and not ((doc_left or doc_right) and cand_unspec_lat) and not (doc_has_specific_site and cand_unspec_site): score += 0.10 rationale_parts.append("canonical base/unspecified code for general documentation") + if has_matching_site: + score += 0.25 + rationale_parts.append("documented anatomical site match") + scored_candidates.append( (cand, round(score, 4), ", ".join(rationale_parts) or "evidence overlap") ) diff --git a/src/medical_coding/graph/nodes.py b/src/medical_coding/graph/nodes.py index e737dd6..159a8a1 100644 --- a/src/medical_coding/graph/nodes.py +++ b/src/medical_coding/graph/nodes.py @@ -557,85 +557,86 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]: candidate_pool: dict[str, list[ICDCandidate]] = {} def _retrieve_for_condition(cond: ClassifiedDiagnosis) -> tuple[str, Any, Any, list[ICDCandidate]]: - query = cond.raw_term + raw_query = cond.raw_term ev_quote = ( getattr(cond.context.evidence, "quote", "") if hasattr(cond, "context") and hasattr(cond.context, "evidence") and cond.context.evidence else "" ) - # 1. Derive structured ClinicalConcept (Sections 5 & 6) + # 1. Clean query for core clinical entity (strip trailing medications, status, or parentheticals) + clean_query = re.sub(r"\s*\([^)]*\)", "", raw_query).strip() + clean_query = re.split(r"\s*[-–—]\s*|\s*;\s*|\s*:\s*", clean_query)[0].strip() + if not clean_query: + clean_query = raw_query + + # 2. Derive structured ClinicalConcept (Sections 5 & 6) concept = ClinicalConceptReasoner.reason_concept( cond, evidence_text=ev_quote, document_text=raw_doc_text, ) - # 2. Build deterministic MatchSpec (Sections 7 & 8) + # 3. Build deterministic MatchSpec (Sections 7 & 8) match_spec = MatchSpecBuilder.build_match_spec(concept) hits: list[ICDCandidate] = [] existing_codes: set[str] = set() - # 3. Multi-Stage Bounded Retrieval Cascade (Master Prompt Sections 18, 19, 21, 22) - # LEVEL 1: Exact query hybrid retrieval - queries_to_run = [query] + # STAGE 1: Primary Hybrid Retrieval (Single fast dense+sparse search) + primary_hits = retriever.retrieve(clean_query, top_k=25) + for h in primary_hits: + if h.code not in existing_codes: + hits.append(h) + existing_codes.add(h.code) - # LEVEL 2: Universal Concept & Token Morphology Expansion (Master Directive Sections 17 & 23) + # STAGE 2: Microsecond BM25 Inverted-Index Expansions (Bypasses redundant neural vector calls) from medical_coding.retrieval.tokenizer import ( CLINICAL_ABBREVIATIONS, + CLINICAL_MORPHOLOGY, get_expanded_query_tokens, ) + lexical_terms: list[str] = [] + 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 = query.lower() - expanded_terms: list[str] = [] - - # A. Normalized canonical concept name - if concept.canonical_name and concept.canonical_name.lower() != query_lower: - expanded_terms.append(concept.canonical_name) - - # B. Generic abbreviation expansion + query_lower = clean_query.lower() for ab, full in CLINICAL_ABBREVIATIONS.items(): if re.search(rf"\b{re.escape(ab)}\b", query_lower): - expanded_terms.append(re.sub(rf"\b{re.escape(ab)}\b", full, query_lower)) + lexical_terms.append(re.sub(rf"\b{re.escape(ab)}\b", full, query_lower)) - # C. Concept attribute combination query if concept.metastatic_status and concept.body_site: - expanded_terms.append(f"secondary malignant neoplasm of {concept.body_site}") - expanded_terms.append(f"secondary neoplasm of {concept.body_site}") + lexical_terms.append(f"secondary malignant neoplasm of {concept.body_site}") elif concept.histology and concept.body_site: - expanded_terms.append(f"{concept.histology} of {concept.body_site}") - expanded_terms.append(f"malignant neoplasm of {concept.body_site}") + lexical_terms.append(f"{concept.histology} of {concept.body_site}") if concept.acuity and concept.canonical_name: - expanded_terms.append(f"{concept.acuity} {concept.canonical_name}") + lexical_terms.append(f"{concept.acuity} {concept.canonical_name}") - # D. Generic morphological query tokens - exp_tokens = get_expanded_query_tokens(query) + exp_tokens = get_expanded_query_tokens(clean_query) if exp_tokens and len(exp_tokens) > 1: - morph_query = " ".join(exp_tokens[:6]) - if morph_query not in expanded_terms: - expanded_terms.append(morph_query) + morph_q = " ".join(exp_tokens[:6]) + if morph_q not in lexical_terms: + lexical_terms.append(morph_q) - for exp in expanded_terms: - if exp not in queries_to_run: - queries_to_run.append(exp) + for lt in lexical_terms[:4]: + try: + lex_hits = retriever.lexical_retriever.retrieve(lt, top_k=15) + for h in lex_hits: + if h.code not in existing_codes: + hits.append(h) + existing_codes.add(h.code) + except Exception: + pass - # Run hybrid retrieval for each query term in cascade - for q in queries_to_run[:4]: - q_hits = retriever.retrieve(q, top_k=15) - for h in q_hits: - if h.code not in existing_codes: - hits.append(h) - existing_codes.add(h.code) - - # LEVEL 3: Clinical Family Prefix Retrieval (Master Prompt Section 20) + # STAGE 3: Clinical Family Prefix Retrieval (Master Prompt Section 20) if match_spec.allowed_code_families: family_recs = catalog.get_by_family_prefixes(match_spec.allowed_code_families) if family_recs: - query_tokens = set(re.findall(r"\b[a-z0-9]+\b", query.lower())) + query_tokens = set(re.findall(r"\b[a-z0-9]+\b", clean_query.lower())) expanded_q_tokens = set(query_tokens) - from medical_coding.retrieval.tokenizer import CLINICAL_MORPHOLOGY for qt in query_tokens: expanded_q_tokens.update(CLINICAL_MORPHOLOGY.get(qt, [])) scored_recs: list[tuple[float, Any]] = [] @@ -661,46 +662,31 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]: hits.append(cand) existing_codes.add(rec.code) - # LEVEL 5: Broad Local Database Fallback (if hits < 5) + # STAGE 4: Ultra-fast BM25 Inverted-Index Fallback (Only if hits < 5; eliminates full 80k-row scan!) if len(hits) < 5: content_words = [ - w for w in re.findall(r"\b[a-z0-9]{4,}\b", query.lower()) + w for w in re.findall(r"\b[a-z0-9]{4,}\b", clean_query.lower()) if w not in ("with", "without", "acute", "chronic", "status", "post", "from", "type") ] if content_words: - fallback_recs = [ - r for r in catalog.get_all_records() - if any(cw in r.description.lower() for cw in content_words) - ] - for r in fallback_recs[:15]: - if r.code not in existing_codes: - cand = ICDCandidate( - code=r.code, - description=r.description, - is_valid_billable=r.is_valid_billable, - coding_system=getattr(r, "coding_system", "ICD-10-CM"), - retrieval_score=0.45, - retrieval_method="fallback_token_scan", - ) - hits.append(cand) - existing_codes.add(r.code) + try: + fb_hits = retriever.lexical_retriever.retrieve(" ".join(content_words), top_k=15) + for h in fb_hits: + if h.code not in existing_codes: + hits.append(h) + existing_codes.add(h.code) + except Exception: + pass elif concept.body_site: - fallback_recs = [ - r for r in catalog.get_all_records() - if concept.body_site in r.description.lower() - ] - for r in fallback_recs[:10]: - if r.code not in existing_codes: - cand = ICDCandidate( - code=r.code, - description=r.description, - is_valid_billable=r.is_valid_billable, - coding_system=getattr(r, "coding_system", "ICD-10-CM"), - retrieval_score=0.45, - retrieval_method="hybrid", - ) - hits.append(cand) - existing_codes.add(r.code) + try: + fb_hits = retriever.lexical_retriever.retrieve(concept.body_site, top_k=10) + for h in fb_hits: + if h.code not in existing_codes: + hits.append(h) + existing_codes.add(h.code) + except Exception: + pass + # 4. Post-Retrieval Compatibility Reasoning (Section 10) scored_hits: list[tuple[float, ICDCandidate]] = [] @@ -728,10 +714,10 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]: # Handle ICD-O for neoplasms is_neoplasm = ( concept.disease_family in ("breast_malignancy", "lymphoma", "pleural_metastasis", "kaposi_sarcoma", "liver_sarcoma", "neuroendocrine_tumor") - or any(w in query.lower() for w in ["cancer", "carcinoma", "neoplasm", "lymphoma", "tumor", "sarcoma"]) + or any(w in raw_query.lower() for w in ["cancer", "carcinoma", "neoplasm", "lymphoma", "tumor", "sarcoma"]) ) if is_neoplasm: - icdo_hits = retriever.retrieve(query, top_k=5, system="ICD-O") + icdo_hits = retriever.retrieve(raw_query, top_k=5, system="ICD-O") for o_hit in icdo_hits: if o_hit.code not in existing_codes: final_hits.append(o_hit) diff --git a/src/medical_coding/graph/pipeline.py b/src/medical_coding/graph/pipeline.py index dfe94b7..1ece0ec 100644 --- a/src/medical_coding/graph/pipeline.py +++ b/src/medical_coding/graph/pipeline.py @@ -1,6 +1,7 @@ """Asynchronous document and batch execution pipeline orchestrating LangGraph workflows.""" import asyncio +import re import time import traceback from collections.abc import Callable @@ -231,6 +232,9 @@ async def process_clinical_document( except Exception as exc: total_elapsed_ms = (time.perf_counter() - start_time) * 1000.0 tb_str = traceback.format_exc() + task_match = re.search(r"During task with name '([^']+)'", tb_str) + if task_match: + current_node_name = task_match.group(1) logger.exception("Pipeline failed at node %s: %s", current_node_name, exc) if repo: diff --git a/src/medical_coding/retrieval/tokenizer.py b/src/medical_coding/retrieval/tokenizer.py index 36f7616..2ffe707 100644 --- a/src/medical_coding/retrieval/tokenizer.py +++ b/src/medical_coding/retrieval/tokenizer.py @@ -251,8 +251,12 @@ CLINICAL_MORPHOLOGY: dict[str, list[str]] = { "calculi": ["calculus", "stone", "stones", "cholelithiasis", "gallstone", "gallstones"], "stone": ["calculus", "calculi", "stones", "cholelithiasis", "gallstone", "gallstones"], "stones": ["calculus", "calculi", "stone", "cholelithiasis", "gallstone", "gallstones"], - "renal": ["kidney", "renal"], - "kidney": ["renal", "kidney"], + "renal": ["kidney", "renal", "nephropathy"], + "kidney": ["renal", "kidney", "nephropathy"], + "injury": ["failure", "injury"], + "failure": ["injury", "failure", "insufficiency"], + "infarction": ["infarct", "infarctions", "stemi", "nstemi", "ami", "attack"], + "attack": ["infarction", "mi"], "gastric": ["stomach", "gastric"], "stomach": ["gastric", "stomach"], "cardiac": ["heart", "cardiac"], diff --git a/src/medical_coding/schemas/icd.py b/src/medical_coding/schemas/icd.py index 4be14a1..fa11cd3 100644 --- a/src/medical_coding/schemas/icd.py +++ b/src/medical_coding/schemas/icd.py @@ -170,7 +170,14 @@ class ICDCandidate(BaseModel): le=1.0, description="Normalized similarity/relevance score from retrieval engine.", ) - retrieval_method: Literal["bm25", "faiss", "hybrid", "family_filtered_lexical"] = Field( + retrieval_method: Literal[ + "bm25", + "faiss", + "hybrid", + "family_filtered_lexical", + "fallback_token_scan", + "vector_numpy", + ] = Field( description="Algorithm that produced or consolidated this candidate.", ) is_valid_billable: bool = Field( diff --git a/src/medical_coding/validation/clinical_gate.py b/src/medical_coding/validation/clinical_gate.py index f907033..192b86b 100644 --- a/src/medical_coding/validation/clinical_gate.py +++ b/src/medical_coding/validation/clinical_gate.py @@ -49,7 +49,7 @@ DOSAGE_FORM_PATTERNS = [ PRESCRIPTION_SYNTAX_PATTERNS = [ r"\b(?:\d+\s*(?:mg|mcg|gm|g|ml|iu|units?|tablets?|capsules?|pills?|puffs?|drops?))\b", r"\b(?:po|iv|im|sc|prn|daily|od|bd|bid|tds|tid|qid|sos|hs|at\s+bedtime|before\s+meals?|after\s+meals?|subcutaneously|orally|topically)\b", - r"^\s*(?:take|apply|instill|inhale|inject|infuse|give)\b", + r"^\s*(?:take|apply|instill|inhale|inject|infuse|give|initiated|started\s+on)\b", ] # 4. Section headers, document metadata, allergy statements, and non-diagnostic observations @@ -63,6 +63,10 @@ METADATA_PATTERNS = [ r"^\s*chief\s+complaint\b", r"^\s*discharge\s+medications?\b", r"^\s*investigations?\b", + r"^\s*pertinent\s+negatives?\b", + r"^\s*negations?(?:\s*/\s*audit)?\b", + r"^\s*documentation\s+audit\b", + r"^\s*final\s+coding\s+summary\b", r"^\s*general\s+condition\b", r"^\s*physical\s+examination\b", # Allergy statements and negative metadata (Section 3) diff --git a/src/medical_coding/validation/reverse_attributes.py b/src/medical_coding/validation/reverse_attributes.py index fdcd4f3..edbb8f9 100644 --- a/src/medical_coding/validation/reverse_attributes.py +++ b/src/medical_coding/validation/reverse_attributes.py @@ -26,6 +26,7 @@ NON_SPECIFICITY_WORDS: set[str] = { "closed", "bone", "bones", "female", "acute", "chronic", "subacute", "spontaneous", "disruption", "injury", "sites", "secondary", "neoplasm", "neoplasms", "tumor", "tumour", "intrahepatic", "bile", "duct", + "coronary", "artery", "arteries", "vessel", "vessels", "wall", "vein", "veins", } # Clinical attribute qualifiers mapped to documentary confirmation tokens/synonyms