Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0528e65f4d | ||
|
|
c167c4369a | ||
|
|
d42370a07a | ||
|
|
e48a70eb2a |
+3
-1
@@ -26,6 +26,7 @@ gpt4all
|
||||
sentence-transformers
|
||||
transformers
|
||||
torch
|
||||
accelerate
|
||||
|
||||
# ============================================================
|
||||
# VECTOR SEARCH
|
||||
@@ -48,13 +49,14 @@ xlrd
|
||||
PyMuPDF
|
||||
pdfplumber
|
||||
rapidocr_onnxruntime
|
||||
|
||||
Pillow
|
||||
|
||||
# ============================================================
|
||||
# TEXT / NLP
|
||||
# ============================================================
|
||||
regex
|
||||
nltk
|
||||
beautifulsoup4
|
||||
|
||||
# ============================================================
|
||||
# API & UI
|
||||
|
||||
@@ -1442,11 +1442,20 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
"symptom", "pain", "fatigue", "edema", "overload", "dyspnea",
|
||||
"shortness of breath", "nausea", "vomiting", "weakness", "fever",
|
||||
"cough", "dyspepsia", "discomfort", "wheezing", "respiratory distress", "dysuria",
|
||||
"malaise", "lethargy", "dizziness", "lightheadedness", "loss of appetite", "anorexia",
|
||||
"chills", "rigor", "purpura", "petechiae", "headache", "constipation", "diarrhea",
|
||||
"rash", "pruritus", "itching", "hematuria", "hemoptysis", "palpitations", "jaundice", "icterus",
|
||||
]
|
||||
)
|
||||
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", "infection"])
|
||||
or any(dx in d_lower for dx in [
|
||||
"syndrome", "failure", "infarction", "disease", "disorder", "calculus",
|
||||
"lithiasis", "ulcer", "pneumonia", "infection", "carcinoma", "cancer",
|
||||
"neoplasm", "adenocarcinoma", "lymphoma", "leukemia", "sepsis", "shock", "fracture",
|
||||
"varices", "cirrhosis", "thrombosis", "embolism", "viral", "virus", "bacterial",
|
||||
"hypotension", "emergency", "injury", "trauma", "poisoning", "hemorrhage",
|
||||
])
|
||||
)
|
||||
return is_sym and not has_def
|
||||
|
||||
@@ -1454,19 +1463,15 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
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",
|
||||
r"\b(?:type\s*(?:2|ii)?\s*diabetes|diabetes\s+mellitus|essential\s+hypertension|hyperlipidemia|dyslipidemia|hypothyroidism|osteoporosis|gerd|bph|chronic\s+kidney\s+disease|ckd)\b",
|
||||
d_l,
|
||||
)
|
||||
and not re.search(
|
||||
r"\b(?:ketoacidosis|dka|hyperosmolar|crisis|emergency|urgency|acute|gangrene|severe|decompensated)\b",
|
||||
r"\b(?:ketoacidosis|dka|hyperosmolar|crisis|emergency|urgency|acute|gangrene|severe|decompensated|failure)\b",
|
||||
d_l,
|
||||
)
|
||||
)
|
||||
|
||||
has_definitive_candidates = any(
|
||||
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
|
||||
for i, (asm, s, _r_list) in enumerate(scored_candidates):
|
||||
if (
|
||||
@@ -1475,7 +1480,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):
|
||||
is_explicit_pri = any(r.startswith("Explicitly documented as PRIMARY/PRINCIPAL") for r in _r_list)
|
||||
if (_is_pure_symptom(asm) or _is_chronic_baseline(asm)) and not is_explicit_pri:
|
||||
continue
|
||||
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(asm.diagnosis, asm.evidence or "")
|
||||
if is_valid:
|
||||
@@ -1489,14 +1495,22 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
asm.temporality in (Temporality.CURRENT, "CURRENT")
|
||||
and bool(asm.evidence and asm.evidence.strip())
|
||||
):
|
||||
is_explicit_pri = any(r.startswith("Explicitly documented as PRIMARY/PRINCIPAL") for r in _r_list)
|
||||
if (_is_pure_symptom(asm) or _is_chronic_baseline(asm)) and not is_explicit_pri:
|
||||
continue
|
||||
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(asm.diagnosis, asm.evidence or "")
|
||||
if is_valid:
|
||||
chosen_primary_idx = i
|
||||
break
|
||||
|
||||
# Unconditional fallback: Rank 1 among scored_candidates
|
||||
if chosen_primary_idx is None and scored_candidates:
|
||||
chosen_primary_idx = 0
|
||||
# Explicit provider designation check if still not chosen
|
||||
if chosen_primary_idx is None:
|
||||
for i, (asm, s, _r_list) in enumerate(scored_candidates):
|
||||
if any(r.startswith("Explicitly documented as PRIMARY/PRINCIPAL") for r in _r_list):
|
||||
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(asm.diagnosis, asm.evidence or "")
|
||||
if is_valid:
|
||||
chosen_primary_idx = i
|
||||
break
|
||||
|
||||
if chosen_primary_idx is not None:
|
||||
top_asm, top_score, top_reasons = scored_candidates[chosen_primary_idx]
|
||||
@@ -1504,19 +1518,23 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
item for j, item in enumerate(scored_candidates) if j != chosen_primary_idx
|
||||
]
|
||||
else:
|
||||
top_asm, top_score, top_reasons = scored_candidates[0]
|
||||
remaining_candidates = scored_candidates[1:]
|
||||
top_asm = None
|
||||
top_score = 0.0
|
||||
top_reasons = []
|
||||
remaining_candidates = scored_candidates
|
||||
|
||||
if chosen_primary_idx is not None:
|
||||
if top_asm is not None:
|
||||
# Primary selected (either unique or prioritized under UHDDS Section II.C)
|
||||
top_ev_quote = (top_asm.evidence or "").strip()
|
||||
is_explicit = any(r.startswith("Explicitly documented as PRIMARY/PRINCIPAL") for r in top_reasons)
|
||||
designation_str = "Explicitly designated by provider" if is_explicit else "Clinically inferred principal diagnosis under UHDDS criteria"
|
||||
pri_reason = (
|
||||
f"Designated as Primary Diagnosis under UHDDS Guidelines (chief condition established after study to be responsible for occasioning admission). "
|
||||
f"Designated as Primary Diagnosis under UHDDS Guidelines ({designation_str}; 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}\"."
|
||||
f"{designation_str} occasioning admission and inpatient care: \"{top_ev_quote}\"."
|
||||
)
|
||||
classifications.append(
|
||||
ConditionClassification(
|
||||
@@ -1803,6 +1821,60 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
result, _ = self.classify_conditions(assessments, clinical_text, doc_id)
|
||||
return result
|
||||
|
||||
def classify_diagnoses(
|
||||
self,
|
||||
conditions: list[Any],
|
||||
clinical_text: str = "",
|
||||
document_id: str | None = None,
|
||||
) -> list[ConditionClassification]:
|
||||
"""Convenience and backwards-compatible classification returning list of classified conditions."""
|
||||
assessments: list[ContextAssessment] = []
|
||||
for c in conditions:
|
||||
if isinstance(c, ContextAssessment):
|
||||
assessments.append(c)
|
||||
elif hasattr(c, "normalized_description") or hasattr(c, "original_mention"):
|
||||
diag = getattr(c, "normalized_description", None) or getattr(c, "original_mention", "")
|
||||
ev = getattr(c, "evidence_text", "") or ""
|
||||
sec = getattr(c, "section", "DISCHARGE_DIAGNOSES")
|
||||
stat = getattr(c, "status", ConditionStatus.ACTIVE)
|
||||
cert = getattr(c, "certainty", Certainty.CONFIRMED)
|
||||
temp = getattr(c, "temporality", Temporality.CURRENT)
|
||||
neg = getattr(c, "negation", NegationStatus.AFFIRMATIVE)
|
||||
assessments.append(
|
||||
ContextAssessment(
|
||||
condition_id=getattr(c, "condition_id", str(uuid4())),
|
||||
diagnosis=diag,
|
||||
original_mention=getattr(c, "original_mention", diag),
|
||||
evidence=ev,
|
||||
section=sec,
|
||||
current_relevance=cert != Certainty.RULED_OUT and neg != NegationStatus.NEGATED,
|
||||
coding_candidate=cert != Certainty.RULED_OUT and neg != NegationStatus.NEGATED,
|
||||
status=stat,
|
||||
certainty=cert,
|
||||
temporality=temp,
|
||||
negation=neg,
|
||||
reason=f"Extracted from {sec}",
|
||||
)
|
||||
)
|
||||
elif isinstance(c, dict):
|
||||
diag = c.get("normalized_description") or c.get("diagnosis") or c.get("raw_term") or ""
|
||||
assessments.append(
|
||||
ContextAssessment(
|
||||
condition_id=c.get("condition_id", str(uuid4())),
|
||||
diagnosis=diag,
|
||||
original_mention=c.get("original_mention", diag),
|
||||
evidence=c.get("evidence_text") or c.get("evidence") or "",
|
||||
section=c.get("section", "DISCHARGE_DIAGNOSES"),
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=c.get("status", ConditionStatus.ACTIVE),
|
||||
certainty=c.get("certainty", Certainty.CONFIRMED),
|
||||
reason="Dict condition",
|
||||
)
|
||||
)
|
||||
res, _ = self.classify_conditions(assessments, clinical_text=clinical_text, document_id=document_id)
|
||||
return res.all_classifications
|
||||
|
||||
|
||||
class ClassificationAgent(PrimarySecondaryClassifier):
|
||||
"""Backwards-compatible agent supporting legacy analyze_context and classify_roles signatures."""
|
||||
|
||||
@@ -657,8 +657,12 @@ class EvidenceFirstFactExtractor:
|
||||
)
|
||||
if diag_prefix_m:
|
||||
clause = diag_prefix_m.group(1).strip()
|
||||
else:
|
||||
elif sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS", "SECONDARY_DIAGNOSES", "CHIEF_COMPLAINT", "IMPRESSION"):
|
||||
clause = sent_clean
|
||||
elif re.search(r"\b(?:diagnos[ei]s|impression|assessment|syndrome|failure|disease|disorder|infection|infarction|calculus|effusion|edema|pneumonia|copd|diabetes|hypertension|sepsis|varices|cirrhosis|carcinoma|cancer|fracture|stone|bleed|bleeding|pain|fever|cough|dyspnea)\b", sent_clean, re.IGNORECASE):
|
||||
clause = sent_clean
|
||||
else:
|
||||
continue
|
||||
|
||||
if clause:
|
||||
clause = re.sub(
|
||||
@@ -2538,76 +2542,76 @@ class EvidenceFirstFactExtractor:
|
||||
clean = re.sub(r",?\s*with\s+(?:significantly\s+)?elevated\s+creatinine.*$", "", clean, flags=re.IGNORECASE).strip()
|
||||
clean = re.sub(r"\s+", " ", clean).strip(".,;: ")
|
||||
|
||||
# 1. Primary oncology sites & morphology
|
||||
# 1. Primary oncology sites & morphology (grounded in clinical documentation)
|
||||
if re.search(r"\b(?:periampullary\s+(?:adenocarcinoma|carcinoma|malignancy|cancer)|ampullary\s+(?:adenocarcinoma|carcinoma|malignancy|cancer)|carcinoma\s+of\s+ampulla\s+of\s+vater)\b", clean, re.IGNORECASE):
|
||||
return "Malignant neoplasm of ampulla of Vater"
|
||||
return "Periampullary adenocarcinoma"
|
||||
|
||||
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 "Adenocarcinoma NOS"
|
||||
return "Adenocarcinoma"
|
||||
|
||||
# 2. Oncology metastatic manifestations
|
||||
# 2. Oncology metastatic manifestations (grounded in documented clinical terms)
|
||||
if re.search(
|
||||
r"\b(?:bone\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+bone|metastatic\s+bone\s+disease|bone\s*\((?:lumbar\s+)?spine|bone\s*\(pelvis|osseous\s+metastases?|skeletal\s+metastases?|osteoblastic\s+metastases?|osteoblastic\s+metastatic\s+disease|osteoblastic\s+(?:spine\s+)?lesions?|sclerotic\s+skeletal\s+lesions?|skeletal\s+lesions(?:\s+with\s+psma\s+expression)?|psma\s+expressing\s+(?:skeletal\s+lesions?|bone\s+lesions?)|metastat(?:ic|es)\s+to\s+(?:the\s+)?(?:lumbar\s+)?spine|metastat(?:ic|es)\s+to\s+(?:the\s+)?pelvis)\b",
|
||||
clean,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
return "Secondary malignant neoplasm of bone"
|
||||
return "Bone metastases"
|
||||
|
||||
if re.search(
|
||||
r"\b(?:retroperitoneal\s+(?:and\s+pelvic\s+)?lymph\s+node\s+metastases?|retroperitoneal\s+lymphadenopathy|metastat(?:ic|es)\s+(?:to|in)\s+retroperitoneal\s+lymph\s+nodes?|intra[- ]abdominal\s+lymph\s+node\s+metastases?|paraaortic\s+and\s+aortocaval\s+nodes?|aortocaval\s+nodes?|paraaortic\s+nodes?|peripancreatic.*?(?:lymph\s+)?nodes?|peri-?portal.*?(?:lymph\s+)?nodes?|precaval.*?(?:lymph\s+)?nodes?|porto-?caval.*?(?:lymph\s+)?nodes?|gastrohepatic.*?(?:lymph\s+)?nodes?|central\s+mesentric\s+vessels)\b",
|
||||
clean,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
return "Secondary and unspecified malignant neoplasm of intra-abdominal lymph nodes"
|
||||
return "Retroperitoneal lymph node metastases" if "metast" in clean.lower() or "node" in clean.lower() else "Retroperitoneal lymphadenopathy"
|
||||
|
||||
if re.search(
|
||||
r"\b(?:inguinal\s+and\s+lower\s+limb\s+lymph\s+nodes?|external\s+iliac\s+nodes?|proximal\s+femoral\s+lymph\s+node|femoral\s+lymph\s+node|external\s+iliac\s+lymph\s+nodes?|inguinal\s+lymph\s+nodes?)\b",
|
||||
clean,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
return "Secondary and unspecified malignant neoplasm of inguinal and lower limb lymph nodes"
|
||||
return "Inguinal lymph node metastases"
|
||||
|
||||
if re.search(
|
||||
r"\b(?:pelvic\s+lymph\s+node\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+pelvic\s+lymph\s+nodes?)\b",
|
||||
clean,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
return "Secondary and unspecified malignant neoplasm of intrapelvic lymph nodes"
|
||||
return "Pelvic lymph node metastases"
|
||||
|
||||
if re.search(
|
||||
r"\b(?:lymph\s+node\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+lymph\s+nodes?|nodal\s+metastases?|distant\s+lymphadenopathy)\b",
|
||||
clean,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
return "Secondary and unspecified malignant neoplasm of lymph nodes"
|
||||
return "Lymph node metastases"
|
||||
|
||||
if re.search(r"\b(?:liver\s+metastases?|hepatic\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+liver|multiple\s+lesions\s+in\s+both\s+(?:the\s+)?lobes\s+of\s+liver|discrete\s+lesions\s+in\s+both\s+lobes|metastatic\s+liver\s+disease|discrete\s+(?:heterogeneously\s+enhancing\s+)?lesions\s+involving\s+segment.*?-?\s*metastatic)\b", clean, re.IGNORECASE):
|
||||
return "Secondary malignant neoplasm of liver and intrahepatic bile duct"
|
||||
return "Liver metastases"
|
||||
|
||||
if re.search(r"\b(?:peritoneal\s+involvement|peritoneal\s+metastases?|peritoneal\s+metastasis|omental\s+fat\s+stranding.*?(?:nodularities|reticulations)|omental\s+nodularities|metastat(?:ic|es)\s+to\s+peritoneum)\b", clean, re.IGNORECASE):
|
||||
return "Secondary malignant neoplasm of retroperitoneum and peritoneum"
|
||||
return "Peritoneal metastases"
|
||||
|
||||
if re.search(r"\b(?:lung\s+metastases?|pulmonary\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+lung)\b", clean, re.IGNORECASE):
|
||||
return "Secondary malignant neoplasm of lung"
|
||||
return "Lung metastases"
|
||||
|
||||
if re.search(r"\b(?:brain\s+metastases?|cerebral\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+brain)\b", clean, re.IGNORECASE):
|
||||
return "Secondary malignant neoplasm of brain"
|
||||
return "Brain metastases"
|
||||
|
||||
if re.search(r"\b(?:pleural\s+metastases?|pleural\s+metastasis|metastasis\s+to\s+pleura|malignant\s+pleural\s+effusion|malignant\s+pleural\s+metastasis)\b", clean, re.IGNORECASE):
|
||||
return "Secondary malignant neoplasm of pleura"
|
||||
return "Pleural metastases"
|
||||
|
||||
if re.search(r"\b(?:prostate\s+cancer|prostate\s+carcinoma|adenocarcinoma\s+of\s+(?:the\s+)?prostate|prostate\s+adenocarcinoma|malignant\s+neoplasm\s+of\s+prostate)\b", clean, re.IGNORECASE):
|
||||
return "Malignant neoplasm of prostate"
|
||||
return "Prostate adenocarcinoma" if "adenocarcinoma" in clean.lower() else "Prostate cancer"
|
||||
|
||||
# 3. Urology & Renal Conditions
|
||||
if re.search(r"\b(?:vuj\s+calculus|right\s+vuj\s+calculus|vesicoureteric\s+junction\s+calculus|vesicoureteral\s+junction\s+calculus|calculus\s+near\s+the\s+vuj|tightly\s+impacted\s+stone\s+in\s+the\s+lower\s+right\s+ureter|impacted\s+stone\s+in\s+the\s+lower\s+right\s+ureter|right\s+ureteric\s+stone|ureteric\s+calculus|ureteral\s+calculus)\b", clean, re.IGNORECASE):
|
||||
return "Calculus of ureter"
|
||||
return "VUJ calculus" if "vuj" in clean.lower() else ("Ureteric calculus" if "ureter" in clean.lower() else "Calculus of ureter")
|
||||
|
||||
if re.search(r"\b(?:puj\s+calculus\s+with\s+(?:moderate\s+)?hydronephrosis|left\s+puj\s+calculus\s+with\s+(?:moderate\s+)?hydronephrosis|pelviureteric\s+junction\s+calculus\s+with\s+hydronephrosis|calculus\s+causing\s+(?:moderate\s+)?hydronephrosis|hydronephrosis\s+with\s+(?:renal\s+and\s+ureteral\s+)?calcul(?:us|ous)\s+obstruction)\b", clean, re.IGNORECASE):
|
||||
return "Hydronephrosis with renal and ureteral calculous obstruction"
|
||||
return "PUJ calculus with hydronephrosis" if "puj" in clean.lower() else ("Hydronephrosis with calculous obstruction" if "calculous obstruction" in clean.lower() else "Hydronephrosis with calculus")
|
||||
|
||||
if re.search(r"\b(?:puj\s+calculus|left\s+puj\s+calculus|pelviureteric\s+junction\s+calculus|non-obstructive\s+left\s+(?:lower\s+calyceal\s+)?renal\s+calculus|lower\s+calyceal\s+calculus|calyceal\s+calculus|renal\s+calculus|calculus\s+of\s+kidney)\b", clean, re.IGNORECASE):
|
||||
return "Calculus of kidney"
|
||||
return "PUJ calculus" if "puj" in clean.lower() else "Renal calculus"
|
||||
|
||||
if re.search(r"\b(?:hypertensive\s+emergency|severe\s+hypertension)\b", clean, re.IGNORECASE):
|
||||
return "Hypertensive emergency"
|
||||
@@ -2619,7 +2623,7 @@ class EvidenceFirstFactExtractor:
|
||||
return "Acute kidney injury"
|
||||
|
||||
if re.search(r"\b(?:acute\s+kidney\s+failure|acute\s+renal\s+failure)\b", clean, re.IGNORECASE):
|
||||
return "Acute kidney failure, unspecified"
|
||||
return "Acute kidney failure"
|
||||
|
||||
# 4. Hepatology & GI Conditions
|
||||
if re.search(r"\b(?:high[\s\-]?risk\s+esophageal\s+varices\s+with\s+bleed|esophageal\s+varices\s+with\s+bleed(?:ing)?|bleeding\s+esophageal\s+varices)\b", clean, re.IGNORECASE):
|
||||
@@ -2629,7 +2633,7 @@ class EvidenceFirstFactExtractor:
|
||||
return "Esophageal varices without bleeding"
|
||||
|
||||
if re.search(r"\b(?:chronic\s+liver\s+disease|cld\s+with\s+portal\s+hypertension|chronic\s+liver\s+disease\s+with\s+portal\s+hypertension|cirrhosis\s+of\s+liver|liver\s+cirrhosis|cld)\b", clean, re.IGNORECASE):
|
||||
return "Unspecified cirrhosis of liver"
|
||||
return "Cirrhosis of liver" if "cirrhos" in clean.lower() else "Chronic liver disease"
|
||||
|
||||
if re.search(r"\b(?:portal\s+vein\s+thrombosis|pvt)\b", clean, re.IGNORECASE) and not re.search(r"\bsmv\b", clean, re.IGNORECASE):
|
||||
return "Portal vein thrombosis"
|
||||
@@ -2641,31 +2645,59 @@ class EvidenceFirstFactExtractor:
|
||||
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"
|
||||
return "Colitis"
|
||||
|
||||
if re.search(r"\b(?:thrombocytopenia|secondary\s+thrombocytopenia|chemotherapy[\s\-]?induced\s+thrombocytopenia)\b", clean, re.IGNORECASE):
|
||||
return "Other secondary thrombocytopenia"
|
||||
return "Secondary thrombocytopenia" if ("secondary" in clean.lower() or "chemotherapy" in clean.lower()) else "Thrombocytopenia"
|
||||
|
||||
# 5. Pulmonology & Medicine
|
||||
if re.search(r"\b(?:viral\s+flu\s+like\s+illness|viral\s+lower\s+respiratory\s+tract\s+infection|viral\s+respiratory\s+infection)\b", clean, re.IGNORECASE):
|
||||
return "Unspecified acute lower respiratory infection"
|
||||
if re.search(r"\b(?:viral\s+flu\s+like\s+illness|flu\s+like\s+illness)\b", clean, re.IGNORECASE):
|
||||
return "Flu-like illness"
|
||||
|
||||
if re.search(r"\b(?:viral\s+lower\s+respiratory\s+tract\s+infection|viral\s+respiratory\s+infection)\b", clean, re.IGNORECASE):
|
||||
return "Viral respiratory infection"
|
||||
|
||||
if re.search(r"\b(?:acute\s+exacerbation\s+of\s+copd|copd\s+with\s+(?:acute\s+)?exacerbation|chronic\s+obstructive\s+pulmonary\s+disease\s+with\s+(?:acute\s+)?exacerbation)\b", clean, re.IGNORECASE):
|
||||
return "Chronic obstructive pulmonary disease with (acute) exacerbation"
|
||||
if "copd" in clean.lower():
|
||||
return "Acute exacerbation of COPD" if "acute" in clean.lower() else "COPD with acute exacerbation"
|
||||
return "Chronic obstructive pulmonary disease with acute exacerbation"
|
||||
|
||||
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"
|
||||
return "Type 2 diabetes mellitus" if ("mellitus" in clean.lower() or "t2dm" in clean.lower()) else "Type 2 diabetes"
|
||||
|
||||
if re.search(r"\bportal\s+hypertension\b", clean, re.IGNORECASE):
|
||||
return "Portal hypertension"
|
||||
|
||||
if re.search(r"\b(?:essential\s+hypertension|primary\s+hypertension|systemic\s+hypertension|arterial\s+hypertension|hypertension|htn)\b", clean, re.IGNORECASE) and not re.search(r"\b(?:portal|pulmonary|intracranial|ocular)\s+hypertension\b", clean, re.IGNORECASE):
|
||||
return "Essential hypertension"
|
||||
return "Essential hypertension" if "essential" in clean.lower() else "Hypertension"
|
||||
|
||||
if clean.lower() in ("urticarial", "urticarial rash", "rash urticarial"):
|
||||
return "Urticaria"
|
||||
return clean
|
||||
|
||||
@staticmethod
|
||||
def _is_term_negated_or_ruled_out(term: str, sentence: str) -> bool:
|
||||
"""Detect if clinical term is explicitly negated, absent, or ruled out in a sentence."""
|
||||
t_clean = term.lower().strip()
|
||||
s_lower = sentence.lower()
|
||||
if not t_clean or len(t_clean) < 2:
|
||||
return False
|
||||
absence_patterns = [
|
||||
rf"\b(?:no|not|without|denies|denied|free\s+of|negative\s+for|no\s+evidence\s+of|no\s+signs?\s+of|rules?\s+out|ruled\s+out|unlikely)\s+(?:evidence\s+of\s+|signs?\s+of\s+|acute\s+|active\s+)?{re.escape(t_clean)}\b",
|
||||
rf"\b{re.escape(t_clean)}\s+(?:is\s+|was\s+)?ruled\s+out\b",
|
||||
rf"\b{re.escape(t_clean)}\s+(?:is\s+|was\s+)?negative\b",
|
||||
]
|
||||
if any(re.search(pat, s_lower) for pat in absence_patterns):
|
||||
return True
|
||||
if "shock" in t_clean:
|
||||
shock_neg_patterns = [
|
||||
r"\b(?:normotensive\s+without\s+shock|hemodynamically\s+stable|no\s+(?:evidence\s+of\s+)?(?:septic\s+|cardiogenic\s+|hypovolemic\s+)?shock|without\s+shock|not\s+in\s+shock)\b",
|
||||
r"\bno\s+evidence\s+of\s+(?:septic\s+)?shock\b",
|
||||
]
|
||||
if any(re.search(p, s_lower) for p in shock_neg_patterns):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _corroborate_with_hospital_course_and_procedures(
|
||||
self,
|
||||
candidates: list[ClinicalDiagnosisCandidate],
|
||||
@@ -2725,6 +2757,44 @@ class EvidenceFirstFactExtractor:
|
||||
cand_norm = cand.normalized_diagnosis.lower()
|
||||
words = [w for w in cand_norm.split() if len(w) > 3 and w not in ("with", "without", "acute", "chronic", "type", "history", "disease", "disorder")]
|
||||
|
||||
combined_course_and_meds = f"{hospital_course_text} {medications_text}"
|
||||
course_sentences = [s.strip() for s in re.split(r"(?<=[.!?\n])\s+", combined_course_and_meds) if s.strip()]
|
||||
|
||||
# Check for contradiction / rule-out across clinical examination, course, and investigations
|
||||
all_contradictory_sentences: list[str] = []
|
||||
for s in course_sentences:
|
||||
if self._is_term_negated_or_ruled_out(cand.raw_term, s) or self._is_term_negated_or_ruled_out(cand.normalized_diagnosis, s):
|
||||
all_contradictory_sentences.append(s)
|
||||
if exam_text:
|
||||
for s in re.split(r"[\.\n]+", exam_text):
|
||||
if self._is_term_negated_or_ruled_out(cand.raw_term, s) or self._is_term_negated_or_ruled_out(cand.normalized_diagnosis, s):
|
||||
all_contradictory_sentences.append(s)
|
||||
|
||||
if all_contradictory_sentences:
|
||||
cand.certainty = Certainty.RULED_OUT
|
||||
cand.assertion_status = AssertionStatus.RULED_OUT
|
||||
cand.role = DiagnosisRole.RULED_OUT
|
||||
cand.is_authorized = False
|
||||
cand.scores.admitting_score = -50.0
|
||||
cand.scores.encounter_relevance = 0.0
|
||||
cand.clinical_relevance = 0.0
|
||||
cand.treatment_relevance = 0.0
|
||||
cand.encounter_relevance = 0.0
|
||||
cand.classification_reason = f"Ruled out / documented as absent in clinical evaluation: {all_contradictory_sentences[0].strip()}"
|
||||
cand.evidence.append(
|
||||
StructuredEvidence(
|
||||
text=all_contradictory_sentences[0].strip(),
|
||||
section="HOSPITAL_COURSE",
|
||||
sentence=all_contradictory_sentences[0].strip(),
|
||||
polarity=NegationStatus.NEGATED,
|
||||
certainty=Certainty.RULED_OUT,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence_type=EvidenceType.HOSPITAL_COURSE,
|
||||
clinical_relevance=0.0,
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
# Find relevant domain markers for this candidate
|
||||
relevant_markers: list[str] = []
|
||||
for cond_key, markers in condition_care_markers.items():
|
||||
@@ -2732,9 +2802,6 @@ class EvidenceFirstFactExtractor:
|
||||
relevant_markers.extend(markers)
|
||||
|
||||
# Check hospital course and medications for active inpatient care
|
||||
combined_course_and_meds = f"{hospital_course_text} {medications_text}"
|
||||
course_sentences = [s.strip() for s in re.split(r"(?<=[.!?\n])\s+", combined_course_and_meds) if s.strip()]
|
||||
|
||||
found_management_sentences: list[str] = []
|
||||
for sent in course_sentences:
|
||||
sent_lower = sent.lower()
|
||||
@@ -2872,11 +2939,31 @@ class EvidenceFirstFactExtractor:
|
||||
ruled_out_conditions: list[ClinicalDiagnosisCandidate] = []
|
||||
uncertain_conditions: list[ClinicalDiagnosisCandidate] = []
|
||||
|
||||
all_doc_text = " \n".join(s.content for s in sections).lower()
|
||||
|
||||
for cand in candidates:
|
||||
# Check ruled out
|
||||
if cand.certainty == Certainty.RULED_OUT:
|
||||
cand_term = cand.raw_term.lower().strip()
|
||||
is_explicitly_ruled_out = (
|
||||
cand.certainty == Certainty.RULED_OUT
|
||||
or cand.assertion_status == AssertionStatus.RULED_OUT
|
||||
or cand.role == DiagnosisRole.RULED_OUT
|
||||
or (
|
||||
self._is_term_negated_or_ruled_out(cand_term, all_doc_text)
|
||||
and not any(ev.section in ("FINAL_DIAGNOSES", "DISCHARGE_DIAGNOSES") for ev in cand.evidence)
|
||||
)
|
||||
)
|
||||
|
||||
if is_explicitly_ruled_out:
|
||||
cand.certainty = Certainty.RULED_OUT
|
||||
cand.assertion_status = AssertionStatus.RULED_OUT
|
||||
cand.role = DiagnosisRole.RULED_OUT
|
||||
cand.is_authorized = False
|
||||
cand.scores.admitting_score = -50.0
|
||||
cand.scores.encounter_relevance = 0.0
|
||||
cand.clinical_relevance = 0.0
|
||||
cand.treatment_relevance = 0.0
|
||||
cand.encounter_relevance = 0.0
|
||||
ruled_out_conditions.append(cand)
|
||||
continue
|
||||
|
||||
@@ -2921,7 +3008,7 @@ class EvidenceFirstFactExtractor:
|
||||
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",
|
||||
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|chronic\s+kidney\s+disease|ckd)\b",
|
||||
c_term,
|
||||
)
|
||||
and not re.search(
|
||||
@@ -2930,15 +3017,39 @@ class EvidenceFirstFactExtractor:
|
||||
)
|
||||
)
|
||||
|
||||
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)
|
||||
def _is_pure_symptom_cand(c: ClinicalDiagnosisCandidate) -> bool:
|
||||
c_term = c.normalized_diagnosis.lower()
|
||||
is_sym = any(
|
||||
sym in c_term
|
||||
for sym in [
|
||||
"symptom", "pain", "fatigue", "edema", "overload", "dyspnea",
|
||||
"shortness of breath", "nausea", "vomiting", "weakness", "fever",
|
||||
"cough", "dyspepsia", "discomfort", "wheezing", "respiratory distress",
|
||||
"malaise", "lethargy", "dizziness", "lightheadedness", "loss of appetite", "anorexia",
|
||||
]
|
||||
)
|
||||
has_def = (
|
||||
any(c_term.endswith(sfx) or f"{sfx} " in c_term for sfx in ("itis", "oma", "osis"))
|
||||
or any(dx in c_term for dx in [
|
||||
"syndrome", "failure", "infarction", "disease", "disorder", "calculus",
|
||||
"lithiasis", "ulcer", "pneumonia", "infection", "carcinoma", "cancer",
|
||||
"neoplasm", "adenocarcinoma", "lymphoma", "leukemia", "sepsis", "shock", "fracture",
|
||||
"varices", "cirrhosis", "thrombosis", "embolism", "viral", "virus", "bacterial",
|
||||
"hypotension", "emergency", "injury", "trauma", "poisoning", "hemorrhage",
|
||||
])
|
||||
)
|
||||
return is_sym and not has_def
|
||||
|
||||
has_definitive_driver = any(
|
||||
not _is_pure_symptom_cand(c) and not _is_chronic_baseline_cand(c)
|
||||
for c in valid_active
|
||||
)
|
||||
if has_acute_driver:
|
||||
if has_definitive_driver:
|
||||
for c in valid_active:
|
||||
if _is_chronic_baseline_cand(c):
|
||||
c.scores.admitting_score = min(c.scores.admitting_score, 3.5)
|
||||
c.scores.admitting_score = min(c.scores.admitting_score, 2.5)
|
||||
elif _is_pure_symptom_cand(c):
|
||||
c.scores.admitting_score = min(c.scores.admitting_score, 2.0)
|
||||
|
||||
# 2. Sort active candidates by admitting score descending
|
||||
valid_active.sort(key=lambda c: c.scores.admitting_score, reverse=True)
|
||||
@@ -2948,29 +3059,47 @@ class EvidenceFirstFactExtractor:
|
||||
if re.search(r"\b(?:acute\s+exacerbation\s+of\s+copd|copd\s+with\s+(?:acute\s+)?exacerbation|acute\s+copd\s+exacerbation)\b", full_narrative_lower):
|
||||
for cand in valid_active:
|
||||
if cand.normalized_diagnosis.lower() in ("chronic obstructive pulmonary disease", "copd", "chronic obstructive pulmonary disease, unspecified"):
|
||||
cand.normalized_diagnosis = "Chronic obstructive pulmonary disease with (acute) exacerbation"
|
||||
cand.raw_term = "Chronic obstructive pulmonary disease with (acute) exacerbation"
|
||||
cand.normalized_diagnosis = "Acute exacerbation of COPD" if "copd" in full_narrative_lower else "Chronic obstructive pulmonary disease with acute exacerbation"
|
||||
cand.raw_term = cand.normalized_diagnosis
|
||||
|
||||
if valid_active:
|
||||
# Rank 1 is unconditionally PRIMARY
|
||||
top = valid_active[0]
|
||||
top.role = DiagnosisRole.PRIMARY
|
||||
top.is_authorized = True
|
||||
top.primary_justification = f"Documented chief condition occasioning admission and inpatient treatment: {top.primary_evidence_quote}"
|
||||
primary_diag = top
|
||||
# Select the top candidate adhering to UHDDS: if definitive driver exists, pick highest definitive candidate
|
||||
chosen_idx = None
|
||||
if has_definitive_driver:
|
||||
for idx, cand in enumerate(valid_active):
|
||||
if not _is_pure_symptom_cand(cand) and not _is_chronic_baseline_cand(cand):
|
||||
chosen_idx = idx
|
||||
break
|
||||
else:
|
||||
for idx, cand in enumerate(valid_active):
|
||||
if any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in cand.evidence):
|
||||
chosen_idx = idx
|
||||
break
|
||||
|
||||
top_norm = top.normalized_diagnosis.lower()
|
||||
top_canon = self._canonicalize_term(top.normalized_diagnosis).lower()
|
||||
top_norm = ""
|
||||
top_canon = ""
|
||||
if chosen_idx is not None:
|
||||
top = valid_active.pop(chosen_idx)
|
||||
top.role = DiagnosisRole.PRIMARY
|
||||
top.is_authorized = True
|
||||
is_explicit = any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in top.evidence)
|
||||
top.clinical_attributes["explicitly_designated_primary"] = is_explicit
|
||||
top.clinical_attributes["clinically_inferred_primary"] = not is_explicit
|
||||
designation_type = "Explicitly documented provider principal diagnosis" if is_explicit else "Clinically inferred principal diagnosis under UHDDS"
|
||||
top.primary_justification = f"{designation_type} occasioning admission and inpatient treatment: {top.primary_evidence_quote}"
|
||||
primary_diag = top
|
||||
|
||||
# Rank 2..N are unconditionally SECONDARY (dropping only exact duplicates of primary/secondaries)
|
||||
for sec_cand in valid_active[1:]:
|
||||
top_norm = top.normalized_diagnosis.lower()
|
||||
top_canon = self._canonicalize_term(top.normalized_diagnosis).lower()
|
||||
|
||||
# Remaining active candidates become SECONDARY
|
||||
for sec_cand in valid_active:
|
||||
sec_norm = sec_cand.normalized_diagnosis.lower()
|
||||
sec_canon = self._canonicalize_term(sec_cand.normalized_diagnosis).lower()
|
||||
|
||||
# Exact duplicate check against top or already accepted secondary conditions
|
||||
is_exact_dup = (
|
||||
sec_norm == top_norm
|
||||
or sec_canon == top_canon
|
||||
(bool(top_norm) and (sec_norm == top_norm or sec_canon == top_canon))
|
||||
or any(sec_norm == s.normalized_diagnosis.lower() for s in secondary_diags)
|
||||
or any(sec_canon == self._canonicalize_term(s.normalized_diagnosis).lower() for s in secondary_diags)
|
||||
)
|
||||
|
||||
@@ -1044,11 +1044,12 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
logger.info("Executing Node [10/10]: Final Output Generation for doc_id=%s", doc_id)
|
||||
|
||||
validated = state.get("validated_diagnoses", [])
|
||||
validated = state.get("validated_diagnoses", []) or state.get("validated_codes", [])
|
||||
abstentions = list(state.get("abstentions", []))
|
||||
audit_trail = list(state.get("audit_trail", []))
|
||||
classified = state.get("classified_diagnoses", [])
|
||||
diag_state: ClinicalDiagnosisState | None = state.get("clinical_diagnosis_state")
|
||||
raw_doc_text = state.get("raw_text", "") or state.get("clinical_text", "") or state.get("text", "") or ""
|
||||
|
||||
primary_response: CodedDiagnosisResponse | None = None
|
||||
secondary_responses: list[CodedDiagnosisResponse] = []
|
||||
@@ -1141,20 +1142,24 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
if primary_response is None:
|
||||
clin_primary = None
|
||||
for c in classified:
|
||||
if c.role == DiagnosisRole.PRIMARY:
|
||||
c_role = getattr(c, "role", None) or getattr(c, "initial_role", None)
|
||||
if c_role == DiagnosisRole.PRIMARY:
|
||||
clin_primary = c
|
||||
break
|
||||
if not clin_primary and diag_state and diag_state.primary_diagnosis:
|
||||
clin_primary = diag_state.primary_diagnosis
|
||||
|
||||
if clin_primary:
|
||||
term = getattr(clin_primary, "normalized_diagnosis", None) or getattr(clin_primary, "raw_term", "")
|
||||
clin_primary_id = getattr(clin_primary, "diagnosis_id", "")
|
||||
term = (
|
||||
getattr(clin_primary, "normalized_diagnosis", None)
|
||||
or getattr(clin_primary, "raw_term", "")
|
||||
or getattr(clin_primary, "normalized_description", "")
|
||||
or getattr(clin_primary, "original_mention", "")
|
||||
)
|
||||
clin_primary_id = getattr(clin_primary, "diagnosis_id", "") or getattr(clin_primary, "condition_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
|
||||
primary_response = None
|
||||
else:
|
||||
c_ev = (
|
||||
getattr(clin_primary, "evidence_quote", None)
|
||||
@@ -1214,19 +1219,18 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
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,
|
||||
else:
|
||||
if 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
|
||||
primary_response = None
|
||||
|
||||
# SEPARATION OF CLINICAL DIAGNOSIS AND ICD CODE MAPPING FOR SECONDARIES
|
||||
seen_sec_terms = set()
|
||||
@@ -1409,9 +1413,8 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
seen_sec_terms.add(c_norm)
|
||||
|
||||
# Suppress Z71.1 ("feared health complaint in whom no diagnosis is made") when real clinical conditions exist
|
||||
if primary_response and primary_response.code == "Z71.1" and secondary_responses:
|
||||
primary_response = secondary_responses.pop(0)
|
||||
primary_response.role = DiagnosisRole.PRIMARY
|
||||
if primary_response and primary_response.code == "Z71.1":
|
||||
primary_response = None
|
||||
secondary_responses = [s for s in secondary_responses if s.code != "Z71.1"]
|
||||
|
||||
# Filter secondary_responses so ONLY items with verified local codes or nearest relatable matches are retained; uncoded items without matches are strictly abstained
|
||||
@@ -1508,11 +1511,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
stage=PipelineStage.VALIDATION,
|
||||
)
|
||||
)
|
||||
if secondary_responses:
|
||||
primary_response = secondary_responses.pop(0)
|
||||
primary_response.role = DiagnosisRole.PRIMARY
|
||||
else:
|
||||
primary_response = None
|
||||
primary_response = None
|
||||
|
||||
# Audit & Output Consistency: Retain all abstentions without resurrecting rejected/abstained candidates into accepted codes
|
||||
|
||||
@@ -1728,6 +1727,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
|
||||
return {
|
||||
"final_result": result,
|
||||
"final_report": result.model_dump() if hasattr(result, "model_dump") else (result.dict() if hasattr(result, "dict") else result),
|
||||
"current_stage": PipelineStage.FINALIZATION,
|
||||
}
|
||||
|
||||
|
||||
@@ -91,6 +91,22 @@ def compute_concept_match_score(
|
||||
evidence_clean = (evidence_text or "").lower()
|
||||
full_context = f"{concept_clean.lower()} {evidence_clean}"
|
||||
|
||||
# 0. Early Reverse attributes check to block hard clinical contradictions
|
||||
from medical_coding.validation.reverse_attributes import ReverseAttributeChecker
|
||||
is_attr_valid, unsupp = ReverseAttributeChecker.validate_code_attributes(
|
||||
code_description=cand_desc_clean,
|
||||
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", "hypertension", "hypotension", "shock"))
|
||||
for u in unsupp
|
||||
)
|
||||
if has_hard_fail:
|
||||
return 0.0, f"disqualified by clinical contradiction: {', '.join(unsupp)}", False
|
||||
|
||||
# 1. Normalized string comparisons
|
||||
cand_norm = normalize_for_concept_matching(cand_desc_clean)
|
||||
concept_norm = normalize_for_concept_matching(concept_clean)
|
||||
@@ -119,7 +135,7 @@ def compute_concept_match_score(
|
||||
|
||||
# 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
|
||||
return 0.0, "core clinical entity mismatch", False
|
||||
|
||||
# 3. Base score derived from core fraction and token overlap
|
||||
shared_tokens = cand_token_set & concept_token_set
|
||||
@@ -128,6 +144,11 @@ def compute_concept_match_score(
|
||||
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)})"]
|
||||
|
||||
# Canonical mapping for unspecified viral syndrome
|
||||
if candidate_code == "B34.9" and ("viral" in concept_norm or "virus" in concept_norm):
|
||||
base_score += 0.15
|
||||
rationale_parts.append("canonical ICD code for viral syndrome")
|
||||
|
||||
# If all concept tokens appear in candidate
|
||||
if concept_token_set.issubset(cand_token_set):
|
||||
base_score += 0.10
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
@@ -99,6 +99,32 @@ class ExtractedClinicalCondition(BaseModel):
|
||||
4. Cannot infer unwritten clinical facts.
|
||||
"""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def populate_compatibility_fields(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict):
|
||||
if "original_mention" not in data and "raw_term" in data:
|
||||
data["original_mention"] = data["raw_term"]
|
||||
if "normalized_description" not in data and "normalized_diagnosis" in data:
|
||||
data["normalized_description"] = data["normalized_diagnosis"]
|
||||
if "evidence_text" not in data and "evidence_quote" in data:
|
||||
data["evidence_text"] = data["evidence_quote"]
|
||||
if "section" not in data:
|
||||
if "evidence_location" in data and hasattr(data["evidence_location"], "section"):
|
||||
data["section"] = data["evidence_location"].section
|
||||
elif isinstance(data.get("evidence_location"), dict) and "section" in data["evidence_location"]:
|
||||
data["section"] = data["evidence_location"]["section"]
|
||||
else:
|
||||
data["section"] = "DISCHARGE_DIAGNOSES"
|
||||
if "role" in data and "initial_role" not in data:
|
||||
data["initial_role"] = data["role"]
|
||||
elif "initial_role" in data and "role" not in data:
|
||||
data["role"] = data["initial_role"]
|
||||
if "evidence_location" not in data:
|
||||
sec = data.get("section", "DISCHARGE_DIAGNOSES")
|
||||
data["evidence_location"] = EvidenceLocation(section=sec)
|
||||
return data
|
||||
|
||||
condition_id: str = Field(
|
||||
default_factory=lambda: str(uuid4()),
|
||||
description="Unique condition entity identifier.",
|
||||
@@ -163,6 +189,10 @@ class ExtractedClinicalCondition(BaseModel):
|
||||
default=None,
|
||||
description="Initial role identified during clinical fact extraction.",
|
||||
)
|
||||
role: DiagnosisRole | None = Field(
|
||||
default=None,
|
||||
description="Assigned role for this condition (PRIMARY, SECONDARY, etc.).",
|
||||
)
|
||||
|
||||
|
||||
class ClinicalExtractionResult(BaseModel):
|
||||
|
||||
@@ -178,9 +178,11 @@ class ICDCandidate(BaseModel):
|
||||
"fallback_token_scan",
|
||||
"vector_numpy",
|
||||
] = Field(
|
||||
default="hybrid",
|
||||
description="Algorithm that produced or consolidated this candidate.",
|
||||
)
|
||||
is_valid_billable: bool = Field(
|
||||
default=True,
|
||||
description="Indicates whether this candidate is terminal/billable in the catalog.",
|
||||
)
|
||||
semantic_score: float | None = Field(
|
||||
|
||||
@@ -234,6 +234,10 @@ GENERAL_STOPWORDS: set[str] = {
|
||||
CLINICAL_MORPHOLOGY: dict[str, list[str]] = {
|
||||
"choledocholithiasis": ["calculus of bile duct", "calculus bile duct", "gallstone bile duct", "choledocholithiasis"],
|
||||
"cancer": ["neoplasm", "carcinoma", "malignancy", "adenocarcinoma", "cancer"],
|
||||
"petechiae": ["ecchymoses", "ecchymosis", "purpura", "petechia"],
|
||||
"ecchymoses": ["petechiae", "ecchymosis", "purpura", "petechia"],
|
||||
"ecchymosis": ["petechiae", "ecchymoses", "purpura", "petechia"],
|
||||
"purpura": ["petechiae", "ecchymoses", "ecchymosis", "petechia"],
|
||||
"neoplasm": ["cancer", "carcinoma", "malignancy", "adenocarcinoma", "neoplasm"],
|
||||
"carcinoma": ["cancer", "neoplasm", "malignancy", "adenocarcinoma", "carcinoma"],
|
||||
"adenocarcinoma": ["cancer", "neoplasm", "carcinoma", "malignancy", "adenocarcinoma"],
|
||||
|
||||
@@ -107,7 +107,7 @@ METADATA_PATTERNS = [
|
||||
r"^\s*(?:bp|hr|pulse|rr|temp|spo2|gcs|creatinine|cbc|wbc|hemoglobin|hgb|platelets?)\s*(?::|=|\s+\d)\b",
|
||||
r"^\s*[\d\.\,\/]+\s*(?:mg/dl|mmol/l|g/dl|mmhg|bpm|%|cells/cumm)?\s*$",
|
||||
r"^\s*(?:ecg|ekg|cxr|chest\s+x[\s\-]?ray|ct\s+scan|mri|ultrasound|usg|2d\s+echo|cbc|bmp|cmp|lft|kft|rft|urinalysis|blood\s+culture|troponin|hba1c)\s*(?:normal|clear|pending|done|negative|reviewed)?\s*$",
|
||||
r"^\s*(?:patient\s+name|mrn|admission\s+date|discharge\s+date|admit\s+date|date\s+of\s+admission|date\s+of\s+discharge|dob|age|sex|gender)\s*[:\-–—]",
|
||||
r"^\s*(?:patient\s+name|mrn|admission\s+date|discharge\s+date|admit\s+date|date\s+of\s+admission|date\s+of\s+discharge|dob|age|sex|gender|patient\s+encounter|encounter(?:\s+id|\s+number)?|attending\s+physician|service|department)\s*[:\-–—]",
|
||||
r"^\s*metastatic\s+sites?\s*(?::\s*)?$",
|
||||
r"^\s*(?:oncology\s+attributes?(?:\s*(?:&|and)?\s*biomarkers?)?|biomarkers?\s*(?:&|and)?\s*receptor\s+status)\s*(?::\s*)?$",
|
||||
r"^\s*castration[- ]resistant\s+status(?:\s+on.*)?$",
|
||||
@@ -263,6 +263,55 @@ HYPOTHETICAL_PATTERNS = [
|
||||
r"\b(?:if\s+symptoms?\s+worsen|in\s+the\s+event\s+of|in\s+case\s+of|contingent\s+upon)\b",
|
||||
]
|
||||
|
||||
# 10. Normal exam findings, negative lab results, and routine inpatient care
|
||||
NORMAL_FINDING_PATTERNS = [
|
||||
# Normal physical examination observations
|
||||
r"\b(?:per\s+abdomen\s*:?\s*|p/a\s*:?\s*)?soft[,\s]+non[\s\-]?tender\b",
|
||||
r"\b(?:chest|lungs?)\s*:?\s*clear\b",
|
||||
r"\b(?:bilateral\s+|b/l\s+)?air\s+entry\s+equal\b",
|
||||
r"\baebe\b",
|
||||
r"\bs1[,\s]+s2\s+(?:heard\s+well|heard|present|normal)\b",
|
||||
r"\bbowel\s+sounds\s+(?:present|normal|heard)\b",
|
||||
r"\bgcs\s*(?:15(?:/15)?|is\s*15)\b",
|
||||
r"\bconscious[,\s]+alert\s+(?:and\s+oriented)?\b",
|
||||
r"\balert\s+and\s+oriented\b",
|
||||
r"\bno\s+(?:pedal\s+)?edema\b",
|
||||
r"\bno\s+organomegaly\b",
|
||||
r"\bno\s+hepatosplenomegaly\b",
|
||||
r"\bno\s+(?:icterus|jaundice|pallor|cyanosis|clubbing|lymphadenopathy)\b",
|
||||
r"\bno\s+focal\s+neuro(?:logical)?\s+deficit\b",
|
||||
r"\bpupils\s+equal\s+and\s+reactive\b",
|
||||
r"\bpearl\b",
|
||||
r"\bafebrile\b",
|
||||
r"\bhemodynamically\s+stable\b",
|
||||
r"\bvitals\s+(?:stable|normal)\b",
|
||||
|
||||
# Normal lab results / negative investigations
|
||||
r"\b(?:cbc|lft|kft|rft|bmp|cmp|urine\s+routine|cxr|ecg|echo)\s*(?:is|was)?\s*(?:normal|within\s+normal\s+limits|wnl|unremarkable)\b",
|
||||
r"\bwithin\s+normal\s+limits\b",
|
||||
r"\b(?:blood|urine|sputum)\s+culture(?:\s+shows?)?\s+(?:sterile|no\s+growth)\b",
|
||||
r"\bno\s+growth\s+(?:after\s+\d+\s+hours?|seen)\b",
|
||||
r"\b(?:covid(?:-19)?|rtpcr|hiv|hbsag|hcv)\s*(?:is|was)?\s*(?:negative|non[\s\-]?reactive)\b",
|
||||
|
||||
# Routine inpatient care, diet, nursing directives
|
||||
r"\b(?:tolerating\s+(?:oral|normal|soft|regular)\s+diet|diet\s+tolerated(?:\s+well)?)\b",
|
||||
r"\b(?:adequate\s+urine\s+output|urine\s+output\s+adequate)\b",
|
||||
r"\b(?:iv\s+fluids?|normal\s+saline|rl|dns)\s*(?:given|infused|continued|administered)?\b",
|
||||
r"\b(?:wound\s+dressing|dressing\s+change|suture\s+removal|staple\s+removal)\b",
|
||||
r"\b(?:foley\s+(?:catheter\s+)?|drain\s+|ryles\s+tube\s+)removed\b",
|
||||
r"\b(?:mobilized|ambulated|chest\s+physiotherapy|incentive\s+spirometry)\b",
|
||||
]
|
||||
|
||||
# 11. Narrative prose statements, full sentence descriptions, and clinical events (not diagnoses)
|
||||
NARRATIVE_PROSE_PATTERNS = [
|
||||
r"^\s*(?:the\s+)?patient\s+(?:is|was|had|has|achieved|tolerated|underwent|received|complained|reported|presented|denies|denied|presents|noted)\b",
|
||||
r"^\s*who\s+(?:presented|is|was|had|has|underwent|presents)\b",
|
||||
r"^\s*(?:he|she|they)\s+(?:was|is|had|has|achieved|tolerated|underwent|received|complained|reported|presented)\b",
|
||||
r"\b(?:was\s+transitioned|transitioned\s+to|fluid\s+reduction|closely\s+monitored|levels\s+and\s+renal|levels\s+were|were\s+closely\s+monitored|initiated\s+with\s+significant)\b",
|
||||
r"^\s*(?:intensive\s+|routine\s+)?(?:intravenous\s+|oral\s+)?(?:diuresis|hydration|infusion|monitoring)\s+(?:was\s+)?(?:initiated|given|started)\b",
|
||||
r"^\s*presented\s+(?:to|with)\s+",
|
||||
]
|
||||
|
||||
|
||||
class HardClinicalCandidateGate:
|
||||
"""Deterministic clinical candidate gate enforcing Section 4 & Section 11 specifications."""
|
||||
@@ -311,7 +360,7 @@ class HardClinicalCandidateGate:
|
||||
|
||||
# Check 00c: Dangling fragment starting with verb, preposition, or conjunction
|
||||
if (
|
||||
re.search(r"^\s*(?:was\s+noted\s+following|noted\s+following|following|and\s+a|and\s+an|and\s+the|with\s+a|with\s+an|is\s+seen\s+in|are\s+seen\s+in|were\s+seen\s+in|noted\s+to\s+have|found\s+to\s+have|and\s+a\s+non[\s\-]?obstructive|causing|composed\s+of|associated\s+with|associated|complaints\s+of|bouts\s+of)\b", term_lower)
|
||||
re.search(r"^\s*(?:was\s+noted\s+following|noted\s+following|following|and\s+a|and\s+an|and\s+the|with\s+a|with\s+an|is\s+seen\s+in|are\s+seen\s+in|were\s+seen\s+in|noted\s+to\s+have|found\s+to\s+have|and\s+a\s+non[\s\-]?obstructive|causing|composed\s+of|associated\s+with|associated|complaints\s+of|bouts\s+of|unspecified\s+with)\b", term_lower)
|
||||
or re.search(r"^\s*(?:of|in|at|on|for|from|with|by|and|or|as|to|like)\s+", term_lower)
|
||||
or re.search(r"\b(?:was\s+noted\s+following|noted\s+following)\b", term_lower)
|
||||
or re.search(r"^\s*(?:extent\s+of|size\s+of|interval\s+(?:increase|decrease|change|progression)|increase\s+in|decrease\s+in|change\s+in)\b", term_lower)
|
||||
@@ -345,6 +394,7 @@ class HardClinicalCandidateGate:
|
||||
"stenting", "clearance", "in situ", "stents in situ", "non-obstructive", "non obstructive",
|
||||
"minimal pneumobilia", "pneumobilia", "minimal pneumobilia in left lobe", "aerobilia",
|
||||
"viral", "bacterial", "fungal", "parasitic", "flu", "like", "illness",
|
||||
"viral illness", "viral like illness", "flu like illness", "feverish feeling",
|
||||
"acute", "chronic", "mild", "moderate", "severe",
|
||||
"proximal obstructive changes", "obstructive changes", "proximal changes",
|
||||
)
|
||||
@@ -359,15 +409,29 @@ class HardClinicalCandidateGate:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Non-clinical activity, everyday personal action, or household event: '{clean_term}'"
|
||||
|
||||
# Check 0a2: Narrative prose, sentence fragments, or event clauses
|
||||
for pat in NARRATIVE_PROSE_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Narrative prose clause or clinical event description, not a clinical diagnosis entity: '{clean_term}'"
|
||||
|
||||
# Check 0b: Generic procedural completion or intervention statements
|
||||
for pat in GENERIC_PROCEDURE_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Generic procedure statement or completion notice: '{clean_term}'"
|
||||
|
||||
# Check 1: Absence statements
|
||||
# Check 0c: Normal exam findings, negative lab results, and routine inpatient care
|
||||
for pat in NORMAL_FINDING_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Normal examination finding, benign lab result, or routine care observation: '{clean_term}'"
|
||||
|
||||
# Check 1: Absence statements (both in term and documented evidence)
|
||||
for pat in ABSENCE_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Absence statement describing absence of disease or complication: '{clean_term}'"
|
||||
if evidence_text and re.search(pat, evidence_text.lower()) and any(
|
||||
w in term_lower for w in ["complication", "adverse", "reaction", "toxicity", "event", "abnormality", "bleeding", "ischemia", "distress"]
|
||||
):
|
||||
return False, f"Candidate evidence confirms absence of disease or complication: '{clean_term}'"
|
||||
|
||||
# Check 2: Treatment instructions and monitoring
|
||||
for pat in INSTRUCTION_PATTERNS:
|
||||
@@ -732,3 +796,8 @@ class HardClinicalCandidateGate:
|
||||
def is_metadata_or_heading(cls, text: str) -> bool:
|
||||
t = text.strip().lower()
|
||||
return any(bool(re.search(pat, t)) for pat in METADATA_PATTERNS)
|
||||
|
||||
@classmethod
|
||||
def is_normal_finding(cls, text: str) -> bool:
|
||||
t = text.strip().lower()
|
||||
return any(bool(re.search(pat, t)) for pat in NORMAL_FINDING_PATTERNS)
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Targeted tests for main-fix-1 branch requirements:
|
||||
1. Noise & normal findings rejection (exam, lab, routine care).
|
||||
2. Grounded vocabulary normalization without hallucinated non-source words.
|
||||
3. Strict UHDDS primary vs secondary reasoning (no false promotion of symptoms or baseline conditions).
|
||||
4. Strengthened concept and attribute matching (core entity mismatch zeroing, laterality/site disqualification).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
||||
from medical_coding.agents.clinical_extractor import EvidenceFirstFactExtractor
|
||||
from medical_coding.agents.classifier import PrimarySecondaryClassifier
|
||||
from medical_coding.reasoning.concept_matcher import compute_concept_match_score
|
||||
from medical_coding.schemas.clinical import (
|
||||
ConditionStatus,
|
||||
ContextAssessment,
|
||||
ExtractedClinicalCondition,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
Certainty,
|
||||
DiagnosisRole,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
|
||||
|
||||
class MockLLM(BaseLocalLLM):
|
||||
def generate(self, prompt: str) -> str:
|
||||
return ""
|
||||
|
||||
def get_model_info(self) -> dict:
|
||||
return {"model_name": "mock-llm"}
|
||||
|
||||
|
||||
def test_normal_findings_rejected_by_gate():
|
||||
"""Verify normal physical exam, normal lab results, and routine nursing notes are rejected."""
|
||||
normal_phrases = [
|
||||
"per abdomen soft, non-tender",
|
||||
"P/A soft, non tender",
|
||||
"chest clear",
|
||||
"bilateral air entry equal",
|
||||
"GCS 15/15",
|
||||
"conscious, alert and oriented",
|
||||
"no pedal edema",
|
||||
"no organomegaly",
|
||||
"no icterus",
|
||||
"pupils equal and reactive",
|
||||
"hemodynamically stable",
|
||||
"CBC normal",
|
||||
"LFT within normal limits",
|
||||
"blood culture sterile",
|
||||
"tolerating oral diet",
|
||||
"adequate urine output",
|
||||
"wound dressing done",
|
||||
"foley catheter removed",
|
||||
]
|
||||
for phrase in normal_phrases:
|
||||
is_valid, reason = HardClinicalCandidateGate.evaluate_candidate(phrase)
|
||||
assert not is_valid, f"Expected '{phrase}' to be rejected as a normal finding/routine care, but passed!"
|
||||
assert HardClinicalCandidateGate.is_normal_finding(phrase) is True
|
||||
|
||||
|
||||
def test_grounded_normalization_preserves_source_vocabulary():
|
||||
"""Verify normalization does not inject words that were never written in discharge summary."""
|
||||
extractor = EvidenceFirstFactExtractor()
|
||||
|
||||
# 1. Hypertension should remain 'Hypertension', not hallucinate 'Essential'
|
||||
assert extractor._canonicalize_term("Hypertension") == "Hypertension"
|
||||
assert extractor._canonicalize_term("Essential hypertension") == "Essential hypertension"
|
||||
|
||||
# 2. Colitis should remain 'Colitis', not inject 'Noninfective gastroenteritis and colitis, unspecified'
|
||||
assert extractor._canonicalize_term("Colitis") == "Colitis"
|
||||
assert extractor._canonicalize_term("noninfective colitis") == "Colitis"
|
||||
|
||||
# 3. Thrombocytopenia should remain 'Thrombocytopenia' unless secondary is documented
|
||||
assert extractor._canonicalize_term("Thrombocytopenia") == "Thrombocytopenia"
|
||||
assert extractor._canonicalize_term("Secondary thrombocytopenia") == "Secondary thrombocytopenia"
|
||||
|
||||
# 4. PUJ calculus should remain 'PUJ calculus', not inject full ICD description
|
||||
assert extractor._canonicalize_term("Left PUJ calculus") == "PUJ calculus"
|
||||
assert extractor._canonicalize_term("Renal calculus") == "Renal calculus"
|
||||
|
||||
# 5. Flu-like illness should remain 'Flu-like illness', not inject 'Unspecified acute lower respiratory infection'
|
||||
assert extractor._canonicalize_term("Viral flu like illness") == "Flu-like illness"
|
||||
|
||||
# 6. Type 2 diabetes should remain 'Type 2 diabetes' when mellitus is omitted
|
||||
assert extractor._canonicalize_term("Type 2 diabetes") == "Type 2 diabetes"
|
||||
assert extractor._canonicalize_term("Type 2 diabetes mellitus") == "Type 2 diabetes mellitus"
|
||||
|
||||
|
||||
def test_pure_symptoms_cannot_be_falsely_promoted_to_primary():
|
||||
"""Verify UHDDS rule: pure symptoms without explicit provider designation cannot become primary."""
|
||||
classifier = PrimarySecondaryClassifier(llm=MockLLM())
|
||||
|
||||
# Patient with routine non-specific fever and baseline chronic hypertension
|
||||
c1 = ContextAssessment(
|
||||
condition_id="c1",
|
||||
diagnosis="Essential hypertension",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Known hypertension on amlodipine.",
|
||||
reason="Baseline chronic disease.",
|
||||
treated_or_managed=False,
|
||||
)
|
||||
c2 = ContextAssessment(
|
||||
condition_id="c2",
|
||||
diagnosis="Headache",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Patient complained of mild headache.",
|
||||
reason="Symptom complaint.",
|
||||
treated_or_managed=False,
|
||||
)
|
||||
|
||||
classifications = classifier.classify_diagnoses([c1, c2], clinical_text="")
|
||||
# Neither headache (symptom) nor hypertension (baseline chronic) should be falsely promoted to primary
|
||||
primaries = [c for c in classifications if c.role == DiagnosisRole.PRIMARY]
|
||||
assert len(primaries) == 0, f"Expected 0 primary diagnoses, but got: {[p.diagnosis for p in primaries]}"
|
||||
|
||||
# All should be secondary
|
||||
secondaries = [c for c in classifications if c.role == DiagnosisRole.SECONDARY]
|
||||
assert len(secondaries) == 2
|
||||
|
||||
|
||||
def test_concept_matcher_core_entity_mismatch_and_laterality():
|
||||
"""Verify strengthened concept matcher zeroes out incompatible core entities and contradictions."""
|
||||
# Core entity mismatch: Kidney stone vs Skin disorder code (L98.9)
|
||||
score, rationale, is_exact = compute_concept_match_score(
|
||||
candidate_code="L98.9",
|
||||
candidate_description="Disorder of the skin and subcutaneous tissue, unspecified",
|
||||
concept_name="Renal calculus",
|
||||
evidence_text="Patient has a 6mm renal calculus in left kidney.",
|
||||
)
|
||||
assert score == 0.0
|
||||
assert "mismatch" in rationale.lower()
|
||||
|
||||
# Laterality contradiction: Left PUJ calculus matching a right-sided code
|
||||
score_lat, rationale_lat, is_exact_lat = compute_concept_match_score(
|
||||
candidate_code="N20.1",
|
||||
candidate_description="Calculus of ureter, right",
|
||||
concept_name="Left PUJ calculus",
|
||||
evidence_text="CT revealed left PUJ calculus.",
|
||||
)
|
||||
assert score_lat == 0.0
|
||||
assert "laterality" in rationale_lat.lower()
|
||||
@@ -288,7 +288,7 @@ def test_no_arbitrary_secondary_promotion_in_finalize_output():
|
||||
the secondary diagnosis (e.g. I10 Hypertension) is strictly NOT promoted to primary."""
|
||||
state = {
|
||||
"document_id": "test-doc-001",
|
||||
"validated_codes": [
|
||||
"validated_diagnoses": [
|
||||
# Only the secondary condition could be validated
|
||||
type("MockCoded", (), {
|
||||
"raw_term": "Essential hypertension",
|
||||
@@ -640,7 +640,7 @@ def test_concept_recall_captures_symptoms_and_findings():
|
||||
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
|
||||
from medical_coding.schemas.icd import RankedSelection
|
||||
|
||||
state = {
|
||||
"document_id": "test-audit-consistency",
|
||||
|
||||
Reference in New Issue
Block a user