fix(normalization,classification): resolve primary diagnosis identification, parenthetical preservation, and prevent secondary-to-primary promotion
This commit is contained in:
@@ -322,6 +322,8 @@ class ContextAndRelevanceAgent(BaseAgent):
|
||||
treatment_evidence=item.get("treatment_evidence") or None,
|
||||
abstain_recommended=bool(item.get("abstain_recommended", False)),
|
||||
abstention_reason=None,
|
||||
initial_role=matched_cond.initial_role if matched_cond else None,
|
||||
original_mention=matched_cond.original_mention if matched_cond else None,
|
||||
)
|
||||
assessments.append(assessment)
|
||||
|
||||
@@ -693,6 +695,8 @@ class ContextAndRelevanceAgent(BaseAgent):
|
||||
monitored=True,
|
||||
affected_clinical_management=True,
|
||||
influenced_treatment=True,
|
||||
initial_role=c.initial_role,
|
||||
original_mention=c.original_mention,
|
||||
)
|
||||
else:
|
||||
# Active acute/chronic condition or suspected condition preserving uncertainty
|
||||
@@ -713,6 +717,8 @@ class ContextAndRelevanceAgent(BaseAgent):
|
||||
affected_clinical_management=True,
|
||||
influenced_treatment=has_treatment,
|
||||
treatment_evidence=c.treatment_evidence,
|
||||
initial_role=c.initial_role,
|
||||
original_mention=c.original_mention,
|
||||
)
|
||||
|
||||
assessments.append(asm)
|
||||
@@ -999,11 +1005,12 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
|
||||
for asm in assessments:
|
||||
diag_lower = asm.diagnosis.lower()
|
||||
orig_lower = (getattr(asm, "original_mention", None) or "").lower()
|
||||
ev_lower = (asm.evidence or "").lower()
|
||||
treat_lower = (asm.treatment_evidence or "").lower()
|
||||
reason_lower = (asm.reason or "").lower()
|
||||
sec_lower = (getattr(asm, "section", "") or "").lower().replace("_", " ")
|
||||
full_context = f"{diag_lower} {ev_lower} {treat_lower} {reason_lower} {sec_lower}"
|
||||
full_context = f"{diag_lower} {orig_lower} {ev_lower} {treat_lower} {reason_lower} {sec_lower}"
|
||||
|
||||
# Gate: Hard clinical candidate check (reject absence statements, instructions, medications)
|
||||
is_valid_diag, gate_reason = HardClinicalCandidateGate.evaluate_candidate(asm.diagnosis, ev_lower)
|
||||
@@ -1041,6 +1048,7 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
# Under UHDDS, condition established after study chiefly responsible for occasioning admission
|
||||
# or underlying condition occasioning procedural/medical inpatient therapy
|
||||
from medical_coding.utils.text import normalize_diagnosis_name
|
||||
from medical_coding.retrieval.tokenizer import expand_medical_abbreviations, CLINICAL_MORPHOLOGY
|
||||
|
||||
def _is_etiological_primary(term: str) -> bool:
|
||||
t = term.lower().strip()
|
||||
@@ -1051,44 +1059,111 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
t,
|
||||
))
|
||||
|
||||
is_etio_primary = _is_etiological_primary(diag_lower)
|
||||
is_etio_primary = _is_etiological_primary(diag_lower) or _is_etiological_primary(orig_lower)
|
||||
|
||||
# Function to test whether diag_lower is the direct primary diagnosis mention in an explicit provider header
|
||||
def _check_primary_match(text: str, target_diag: str) -> bool:
|
||||
# Require explicit 'principal diagnosis' or 'primary diagnosis' header (never naked 'primary:')
|
||||
for match in re.finditer(rf"\b(?:principal(?:\s+diagnos[ei]s)?|primary\s+diagnos[ei]s|admitting\s+(?:primary|principal)\s+diagnos[ei]s)\s*[:\-–—]\s*([^\n.;]+)", text, re.IGNORECASE):
|
||||
clause = match.group(1).lower().strip()
|
||||
# Strip subsequent conditions attached by "with", "complicated by", "secondary to", ","
|
||||
PRIMARY_HEADER_PATTERN = re.compile(
|
||||
r"\b(?:"
|
||||
r"principal(?:\s+diagnos[ei]s)?"
|
||||
r"|primary\s+diagnos[ei]s"
|
||||
r"|admitting\s+(?:primary\s+|principal\s+)?diagnos[ei]s"
|
||||
r"|admission\s+(?:primary\s+|principal\s+)?diagnos[ei]s"
|
||||
r"|admit\s+diagnos[ei]s"
|
||||
r"|diagnos[ei]s\s+on\s+admission"
|
||||
r"|reason\s+for\s+(?:admission|visit|hospitalization)"
|
||||
r")\s*[:\-–—]\s*([^\n;]+)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
def _clinical_match_clause(target: str, orig: str, clause: str) -> bool:
|
||||
# Clean subsequent conditions attached by delimiters
|
||||
for delim in [" with ", " complicated by ", " secondary to ", ","]:
|
||||
if delim in clause:
|
||||
clause = clause[:clause.find(delim)].strip()
|
||||
if re.search(rf"\b{re.escape(target_diag)}\b", clause):
|
||||
t_norm = normalize_diagnosis_name(target).lower()
|
||||
c_norm = normalize_diagnosis_name(clause).lower()
|
||||
o_norm = normalize_diagnosis_name(orig).lower() if orig else ""
|
||||
|
||||
if not t_norm or not c_norm:
|
||||
return False
|
||||
|
||||
# 1. Exact string matches
|
||||
if t_norm == c_norm or (o_norm and o_norm == c_norm):
|
||||
return True
|
||||
if re.search(rf"\b{re.escape(t_norm)}\b", c_norm) or re.search(rf"\b{re.escape(c_norm)}\b", t_norm):
|
||||
return True
|
||||
if o_norm and (re.search(rf"\b{re.escape(o_norm)}\b", c_norm) or re.search(rf"\b{re.escape(c_norm)}\b", o_norm)):
|
||||
return True
|
||||
|
||||
# 2. Acronym expansion match
|
||||
t_exp = expand_medical_abbreviations(t_norm)
|
||||
c_exp = expand_medical_abbreviations(c_norm)
|
||||
if t_exp == c_exp or re.search(rf"\b{re.escape(t_exp)}\b", c_exp) or re.search(rf"\b{re.escape(c_exp)}\b", t_exp):
|
||||
return True
|
||||
|
||||
# 3. Core semantic clinical token overlap
|
||||
ignore_words = {"type", "with", "acute", "chronic", "left", "right", "bilateral", "unspecified", "stage", "organism", "primary", "secondary", "and", "the", "for", "due", "status", "post"}
|
||||
t_words = [w for w in re.findall(r"\b[a-z]{3,}\b", t_exp) if w not in ignore_words]
|
||||
c_words = [w for w in re.findall(r"\b[a-z]{3,}\b", c_exp) if w not in ignore_words]
|
||||
if not t_words or not c_words:
|
||||
return False
|
||||
|
||||
def _word_in_clause(w: str, words_set: set[str]) -> bool:
|
||||
if w in words_set:
|
||||
return True
|
||||
for syn in CLINICAL_MORPHOLOGY.get(w, []):
|
||||
if any(sw in words_set for sw in syn.split()):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_secondary_match(text: str, target_diag: str) -> bool:
|
||||
c_words_set = set(c_words)
|
||||
matching_words = [w for w in t_words if _word_in_clause(w, c_words_set)]
|
||||
if len(matching_words) == len(t_words) or (len(t_words) >= 2 and len(matching_words) / len(t_words) >= 0.7):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_primary_match(text: str, target: str, orig: str) -> bool:
|
||||
if not text:
|
||||
return False
|
||||
for match in PRIMARY_HEADER_PATTERN.finditer(text):
|
||||
clause = match.group(1).lower().strip()
|
||||
if _clinical_match_clause(target, orig, clause):
|
||||
return True
|
||||
# Multiline matches: Header followed by newline with bullet or diagnosis on line 1
|
||||
for match in re.finditer(r"\b(?:principal(?:\s+diagnos[ei]s)?|primary\s+diagnos[ei]s|admitting\s+(?:primary\s+|principal\s+)?diagnos[ei]s|admission\s+(?:primary\s+|principal\s+)?diagnos[ei]s|reason\s+for\s+admission|final\s+diagnos[ei]s|discharge\s+diagnos[ei]s)\s*[:\-–—]\s*\n\s*(?:(?:\d+[\.\)]|\*|\-|\u2022)\s*)?([^\n;]+)", text, re.IGNORECASE):
|
||||
clause = match.group(1).lower().strip()
|
||||
if _clinical_match_clause(target, orig, clause):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_secondary_match(text: str, target: str, orig: str) -> bool:
|
||||
if not text:
|
||||
return False
|
||||
for match in re.finditer(rf"\bsecondary(?:\s+diagnos[ei]s)?\s*[:\-–—]\s*([^\n.;]+)", text, re.IGNORECASE):
|
||||
clause = match.group(1).lower().strip()
|
||||
if re.search(rf"\b{re.escape(target_diag)}\b", clause):
|
||||
if _clinical_match_clause(target, orig, clause):
|
||||
return True
|
||||
return False
|
||||
|
||||
is_explicit_primary = bool(
|
||||
_check_primary_match(full_context, diag_lower)
|
||||
or (doc_lower and _check_primary_match(doc_lower, diag_lower))
|
||||
or sec_lower in ("principal diagnosis", "primary diagnosis", "principal diagnoses", "primary diagnoses")
|
||||
_check_primary_match(full_context, diag_lower, orig_lower)
|
||||
or (doc_lower and _check_primary_match(doc_lower, diag_lower, orig_lower))
|
||||
or sec_lower in (
|
||||
"principal diagnosis", "primary diagnosis", "principal diagnoses", "primary diagnoses",
|
||||
"admitting diagnosis", "admission diagnosis", "admit diagnosis", "reason for admission",
|
||||
)
|
||||
or getattr(asm, "initial_role", None) in (DiagnosisRole.PRIMARY, "PRIMARY")
|
||||
or getattr(asm, "role", None) in (DiagnosisRole.PRIMARY, "PRIMARY")
|
||||
or getattr(asm, "is_primary", False)
|
||||
)
|
||||
|
||||
# Guardrail: If condition carries 'Primary' as an etiological label (e.g. Primary hypertension, Primary osteoarthritis)
|
||||
# do not allow it to be marked as explicit primary unless provider explicitly documented it under a true principal diagnosis header
|
||||
if is_etio_primary and not (_check_primary_match(full_context, diag_lower) or (doc_lower and _check_primary_match(doc_lower, diag_lower))):
|
||||
if is_etio_primary and not (_check_primary_match(full_context, diag_lower, orig_lower) or (doc_lower and _check_primary_match(doc_lower, diag_lower, orig_lower))):
|
||||
is_explicit_primary = False
|
||||
|
||||
is_explicit_secondary = bool(
|
||||
_check_secondary_match(full_context, diag_lower)
|
||||
or (doc_lower and _check_secondary_match(doc_lower, diag_lower))
|
||||
_check_secondary_match(full_context, diag_lower, orig_lower)
|
||||
or (doc_lower and _check_secondary_match(doc_lower, diag_lower, orig_lower))
|
||||
or sec_lower in ("secondary diagnosis", "secondary diagnoses", "additional diagnoses")
|
||||
)
|
||||
is_admission_driver = False
|
||||
@@ -1096,23 +1171,14 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
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(
|
||||
adm_clauses = re.findall(
|
||||
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 ""),
|
||||
f"{full_context} {doc_lower}",
|
||||
)
|
||||
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", "organism", "primary", "secondary")]
|
||||
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 any(re.search(rf"\b{re.escape(edw)}\b", adm_clause) for edw in expanded_dwords)
|
||||
):
|
||||
for adm_c in adm_clauses:
|
||||
if _clinical_match_clause(diag_lower, orig_lower, adm_c):
|
||||
is_admission_driver = True
|
||||
break
|
||||
|
||||
# Etiological 'Primary' in condition name is not inherently an admission driver
|
||||
if is_etio_primary and not any(term in full_context for term in ["emergency", "crisis", "urgency", "malignant hypertension", "acute exacerbation"]):
|
||||
@@ -1200,7 +1266,7 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
reasons.append("Ligament sprain secondary to co-occurring skeletal fracture (-2.0)")
|
||||
|
||||
# 2. Major Interventions & Procedures
|
||||
if any(
|
||||
has_procedure = any(
|
||||
term in full_context
|
||||
for term in [
|
||||
"stent",
|
||||
@@ -1218,7 +1284,15 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
"procedure",
|
||||
"intervention",
|
||||
]
|
||||
):
|
||||
)
|
||||
is_chronic_cond = (
|
||||
asm.status == ConditionStatus.CHRONIC
|
||||
or "chronic" in diag_lower
|
||||
or any(m in full_context for m in ["home medication", "home regimen", "continued on", "baseline", "longstanding", "routine control", "past history", "history of"])
|
||||
)
|
||||
# Guard against comorbid condition falsely inheriting procedural score from main surgery
|
||||
is_unrelated_chronic = is_chronic_cond and not is_explicit_primary and not is_admission_driver
|
||||
if has_procedure and not is_unrelated_chronic:
|
||||
score += 3.5
|
||||
reasons.append("Primary procedural or operative intervention performed (+3.5)")
|
||||
elif any(
|
||||
@@ -1231,7 +1305,7 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
"nebulized",
|
||||
"antibiotic",
|
||||
]
|
||||
):
|
||||
) and not is_unrelated_chronic:
|
||||
score += 2.0
|
||||
reasons.append(
|
||||
"Active intravenous / intensive therapeutic management administered (+2.0)"
|
||||
@@ -1283,12 +1357,9 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
reasons.append("Supplementary etiologic organism code secondary to primary organ pathology (-2.0)")
|
||||
|
||||
# Chronic baseline conditions without acute exacerbation
|
||||
is_chronic = (
|
||||
asm.status == ConditionStatus.CHRONIC
|
||||
or "chronic" in diag_lower
|
||||
or any(m in full_context for m in ["home medication", "home regimen", "continued on", "baseline", "longstanding", "routine control", "past history", "history of"])
|
||||
)
|
||||
if is_chronic and "acute" not in full_context and not is_explicit_primary and not is_admission_driver:
|
||||
if is_chronic_cond and not is_explicit_primary and not is_admission_driver:
|
||||
has_acute_crisis = any(ac in full_context for ac in ["crisis", "emergency", "urgency", "malignant hypertension", "acute exacerbation", "decompensated", "ketoacidosis", "dka"])
|
||||
if not has_acute_crisis:
|
||||
score -= 1.5
|
||||
reasons.append("Chronic background condition without acute exacerbation (-1.5)")
|
||||
|
||||
@@ -1370,12 +1441,12 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
for sym in [
|
||||
"symptom", "pain", "fatigue", "edema", "overload", "dyspnea",
|
||||
"shortness of breath", "nausea", "vomiting", "weakness", "fever",
|
||||
"cough", "dyspepsia", "discomfort", "wheezing", "respiratory distress",
|
||||
"cough", "dyspepsia", "discomfort", "wheezing", "respiratory distress", "dysuria",
|
||||
]
|
||||
)
|
||||
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"])
|
||||
or any(dx in d_lower for dx in ["syndrome", "failure", "infarction", "disease", "disorder", "calculus", "lithiasis", "ulcer", "pneumonia", "infection"])
|
||||
)
|
||||
return is_sym and not has_def
|
||||
|
||||
|
||||
@@ -1104,10 +1104,22 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
nearest_cand = None
|
||||
for cand in retrieved:
|
||||
if catalog.is_valid_code(cand.code) and catalog.is_billable_code(cand.code):
|
||||
cand_desc_lower = cand.description.lower()
|
||||
term_lower = term.lower()
|
||||
from medical_coding.retrieval.tokenizer import expand_medical_abbreviations, CLINICAL_MORPHOLOGY
|
||||
t_exp = expand_medical_abbreviations(term_lower)
|
||||
c_exp = expand_medical_abbreviations(cand_desc_lower)
|
||||
ignore_w = {"primary", "secondary", "acute", "chronic", "type", "with", "unspecified", "disease", "syndrome", "disorder", "essential"}
|
||||
term_words = [w for w in re.findall(r"\b[a-z]{3,}\b", t_exp) if w not in ignore_w]
|
||||
desc_words = set(w for w in re.findall(r"\b[a-z]{3,}\b", c_exp) if w not in ignore_w)
|
||||
has_core_overlap = any(
|
||||
tw in desc_words or any(syn in desc_words for syn in CLINICAL_MORPHOLOGY.get(tw, []))
|
||||
for tw in term_words
|
||||
) if term_words else False
|
||||
score_val = getattr(cand, "retrieval_score", 0.0)
|
||||
if has_core_overlap and score_val >= 0.45:
|
||||
nearest_cand = cand
|
||||
break
|
||||
if not nearest_cand and retrieved:
|
||||
nearest_cand = retrieved[0]
|
||||
|
||||
if nearest_cand and c_ev:
|
||||
is_icdo = bool(getattr(nearest_cand, "coding_system", None) == "ICD-O" or nearest_cand.code.startswith("M"))
|
||||
@@ -1149,10 +1161,6 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
stage=PipelineStage.VALIDATION,
|
||||
)
|
||||
)
|
||||
if not primary_response and secondary_responses:
|
||||
# Promote top coded secondary to primary role
|
||||
primary_response = secondary_responses.pop(0)
|
||||
primary_response.role = DiagnosisRole.PRIMARY
|
||||
|
||||
# SEPARATION OF CLINICAL DIAGNOSIS AND ICD CODE MAPPING FOR SECONDARIES
|
||||
seen_sec_terms = set()
|
||||
@@ -1754,6 +1762,7 @@ def _extract_conditions_deterministically(
|
||||
section=sec_name,
|
||||
treatment_evidence=treatment_ev,
|
||||
confidence_score=cand.scores.evidence_score,
|
||||
initial_role=cand.role,
|
||||
)
|
||||
extracted.append(cond)
|
||||
|
||||
|
||||
@@ -159,6 +159,10 @@ class ExtractedClinicalCondition(BaseModel):
|
||||
le=1.0,
|
||||
description="Extraction confidence score.",
|
||||
)
|
||||
initial_role: DiagnosisRole | None = Field(
|
||||
default=None,
|
||||
description="Initial role identified during clinical fact extraction.",
|
||||
)
|
||||
|
||||
|
||||
class ClinicalExtractionResult(BaseModel):
|
||||
@@ -262,6 +266,14 @@ class ContextAssessment(BaseModel):
|
||||
default=None,
|
||||
description="Explicit reason for abstention if recommended.",
|
||||
)
|
||||
initial_role: DiagnosisRole | None = Field(
|
||||
default=None,
|
||||
description="Initial role identified during clinical fact extraction.",
|
||||
)
|
||||
original_mention: str | None = Field(
|
||||
default=None,
|
||||
description="Verbatim original mention before normalization.",
|
||||
)
|
||||
|
||||
|
||||
# Pipeline legacy models (preserved for LangGraph compatibility)
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
CLINICAL_ABBREVIATIONS: dict[str, str] = {
|
||||
"hf": "heart failure",
|
||||
"chf": "congestive heart failure",
|
||||
"hfref": "heart failure reduced ejection fraction systolic",
|
||||
"hfpef": "heart failure preserved ejection fraction diastolic",
|
||||
"hfref": "heart failure with reduced ejection fraction",
|
||||
"hfpef": "heart failure with preserved ejection fraction",
|
||||
"dm": "diabetes mellitus",
|
||||
"t1dm": "type 1 diabetes mellitus",
|
||||
"t2dm": "type 2 diabetes mellitus",
|
||||
@@ -25,13 +25,13 @@ CLINICAL_ABBREVIATIONS: dict[str, str] = {
|
||||
"dvt": "deep vein thrombosis",
|
||||
"pe": "pulmonary embolism",
|
||||
"gerd": "gastroesophageal reflux disease",
|
||||
"cva": "cerebrovascular accident stroke",
|
||||
"cva": "cerebrovascular accident",
|
||||
"tia": "transient ischemic attack",
|
||||
"uti": "urinary tract infection",
|
||||
"pna": "pneumonia",
|
||||
"cap": "pneumonia",
|
||||
"pud": "peptic ulcer disease",
|
||||
"sob": "shortness of breath dyspnea",
|
||||
"sob": "shortness of breath",
|
||||
"bph": "benign prostatic hyperplasia",
|
||||
"osa": "obstructive sleep apnea",
|
||||
"ra": "rheumatoid arthritis",
|
||||
@@ -39,31 +39,30 @@ CLINICAL_ABBREVIATIONS: dict[str, str] = {
|
||||
"dlbcl": "diffuse large b cell lymphoma",
|
||||
"dka": "diabetic ketoacidosis",
|
||||
"hiv": "human immunodeficiency virus",
|
||||
"hbv": "hepatitis b virus viral hepatitis b",
|
||||
"hcv": "hepatitis c virus viral hepatitis c",
|
||||
"hav": "hepatitis a virus viral hepatitis a",
|
||||
"hbv": "hepatitis b virus",
|
||||
"hcv": "hepatitis c virus",
|
||||
"hav": "hepatitis a virus",
|
||||
"ks": "kaposi sarcoma",
|
||||
"acl": "anterior cruciate ligament",
|
||||
"pcl": "posterior cruciate ligament",
|
||||
"net": "neuroendocrine tumor carcinoid",
|
||||
"net": "neuroendocrine tumor",
|
||||
"fet": "frozen embryo transfer",
|
||||
"dns": "deviated nasal septum",
|
||||
"fess": "functional endoscopic sinus surgery sinus endoscopy",
|
||||
"fess": "functional endoscopic sinus surgery",
|
||||
"ith": "inferior turbinate hypertrophy",
|
||||
"coli": "escherichia coli",
|
||||
"pylori": "helicobacter pylori",
|
||||
"choledocholithiasis": "calculus bile duct gallstone",
|
||||
"mrsa": "methicillin resistant staphylococcus aureus",
|
||||
"pbc": "primary biliary cholangitis",
|
||||
"psc": "primary sclerosing cholangitis",
|
||||
"poag": "primary open angle glaucoma",
|
||||
"pah": "pulmonary arterial hypertension",
|
||||
"phtn": "pulmonary hypertension",
|
||||
"ehtn": "essential primary hypertension",
|
||||
"crf": "chronic renal failure chronic kidney disease",
|
||||
"ehtn": "essential hypertension",
|
||||
"crf": "chronic renal failure",
|
||||
"cag": "coronary artery disease",
|
||||
"ihd": "ischemic heart disease coronary artery disease",
|
||||
"ashd": "atherosclerotic heart disease coronary artery disease",
|
||||
"ihd": "ischemic heart disease",
|
||||
"ashd": "atherosclerotic heart disease",
|
||||
"niddm": "type 2 diabetes mellitus",
|
||||
"iddm": "type 1 diabetes mellitus",
|
||||
"sle": "systemic lupus erythematosus",
|
||||
@@ -74,8 +73,8 @@ CLINICAL_ABBREVIATIONS: dict[str, str] = {
|
||||
"ards": "acute respiratory distress syndrome",
|
||||
"sbo": "small bowel obstruction",
|
||||
"lbo": "large bowel obstruction",
|
||||
"pvd": "peripheral vascular disease peripheral arterial disease",
|
||||
"pad": "peripheral arterial disease peripheral vascular disease",
|
||||
"pvd": "peripheral vascular disease",
|
||||
"pad": "peripheral arterial disease",
|
||||
"ugib": "upper gastrointestinal bleeding",
|
||||
"lgib": "lower gastrointestinal bleeding",
|
||||
"hl": "hodgkin lymphoma",
|
||||
@@ -224,6 +223,13 @@ 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"],
|
||||
"neoplasm": ["cancer", "carcinoma", "malignancy", "adenocarcinoma", "neoplasm"],
|
||||
"carcinoma": ["cancer", "neoplasm", "malignancy", "adenocarcinoma", "carcinoma"],
|
||||
"adenocarcinoma": ["cancer", "neoplasm", "carcinoma", "malignancy", "adenocarcinoma"],
|
||||
"prostate": ["prostatic", "prostate"],
|
||||
"prostatic": ["prostate", "prostatic"],
|
||||
"ureter": ["ureteric", "ureteral"],
|
||||
"ureteric": ["ureter", "ureteral"],
|
||||
"ureteral": ["ureter", "ureteric"],
|
||||
|
||||
@@ -109,6 +109,29 @@ QUALIFIERS_TO_STRIP_FOR_CORE = {
|
||||
}
|
||||
|
||||
|
||||
def _is_administrative_parenthetical(content: str) -> bool:
|
||||
"""Check if parenthetical content is an administrative artifact (dates, codes, MRN) rather than clinical qualifiers."""
|
||||
c = content.strip().lower()
|
||||
if not c:
|
||||
return True
|
||||
# Pure numbering or single index letters e.g. (1), (a), (iv)
|
||||
if re.fullmatch(r"[0-9ivxabcde]+", c):
|
||||
return True
|
||||
# Dates e.g. (12/05/2023), (2022-04-10), (15 jan 2024), (may 2021)
|
||||
if re.search(r"\b(?:\d{1,4}[/\-\.]\d{1,2}[/\-\.]\d{1,4}|\d{1,2}\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{2,4}|(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{4})\b", c):
|
||||
return True
|
||||
# ICD / CPT code citations e.g. (icd-10: i10), (icd: e11.9), (code c61), (icd10-cm: ...)
|
||||
if re.search(r"\b(?:icd(?:-?10)?(?:-?cm)?|cpt|hcpcs|code|drg|billing)\s*[:#]?\s*[a-z0-9\.]+", c):
|
||||
return True
|
||||
# Pure ICD code like (i10), (e11.9), (k80.20), (c61), (z99.81)
|
||||
if re.fullmatch(r"[a-tv-z][0-9]{2}(?:\.[0-9a-z]{1,4})?", c):
|
||||
return True
|
||||
# Administrative records e.g. (mrn: 12345), (patient id: 55), (chart #99)
|
||||
if re.search(r"\b(?:mrn|patient\s+id|record\s+id|chart|page|pg\.?)\s*[:#]?\s*\d+", c):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def normalize_diagnosis_name(text: str) -> str:
|
||||
"""Strengthened clinical diagnosis normalizer.
|
||||
|
||||
@@ -138,16 +161,14 @@ def normalize_diagnosis_name(text: str) -> str:
|
||||
# Step 3: Strip trailing medication attachments
|
||||
cleaned = MEDICATION_ATTACHMENT_PATTERN.sub("", cleaned).strip()
|
||||
|
||||
# Step 4: Handle parentheticals
|
||||
# Step 4: Handle parentheticals (preserve clinical qualifiers, strip purely administrative artifacts)
|
||||
def _clean_paren(m: re.Match[str]) -> str:
|
||||
inside = m.group(1).strip()
|
||||
# Keep clinical entity words like primary, essential, acute, chronic, bilateral, type 1, type 2
|
||||
if any(w in inside.lower() for w in ["primary", "essential", "acute", "chronic", "type", "bilateral", "left", "right", "congestive", "systolic", "diastolic", "organism"]):
|
||||
return f" {inside} "
|
||||
# Strip notes like dates, non-informative parentheticals
|
||||
if _is_administrative_parenthetical(inside):
|
||||
return " "
|
||||
return f" {inside} "
|
||||
|
||||
cleaned = re.sub(r"\(([^)]+)\)", _clean_paren, cleaned)
|
||||
cleaned = re.sub(r"[\(\[\{]([^\)\]\}]+)[\)\]\}]", _clean_paren, cleaned)
|
||||
|
||||
# Step 5: Expand clinical abbreviations
|
||||
from medical_coding.retrieval.tokenizer import expand_medical_abbreviations
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
"""Unit and regression tests for clinical normalization, parenthetical preservation,
|
||||
admission header matching, and secondary comorbidity non-promotion guardrails.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from medical_coding.schemas.clinical import (
|
||||
ConditionStatus,
|
||||
ContextAssessment,
|
||||
ExtractedClinicalCondition,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
Acuity,
|
||||
Certainty,
|
||||
DiagnosisRole,
|
||||
Laterality,
|
||||
NegationStatus,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.schemas.response import CodedDiagnosisResponse, CodingResult
|
||||
from medical_coding.utils.text import (
|
||||
_is_administrative_parenthetical,
|
||||
normalize_diagnosis_name,
|
||||
extract_search_query_variations,
|
||||
)
|
||||
from medical_coding.utils.clinical_lexicon import CLINICAL_ABBREVIATIONS, CLINICAL_MORPHOLOGY
|
||||
from medical_coding.agents.classifier import PrimarySecondaryClassifier
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
from medical_coding.graph.nodes import finalize_output_node
|
||||
|
||||
|
||||
class DummyLLM(BaseLocalLLM):
|
||||
def generate(self, prompt: str) -> str:
|
||||
return ""
|
||||
|
||||
def get_model_info(self) -> dict:
|
||||
return {"model_name": "dummy"}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 1. Normalization & Parenthetical Preservation Tests
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_administrative_parenthetical_detection():
|
||||
"""Verify administrative artifacts (dates, codes, MRN) are detected for stripping,
|
||||
while critical clinical qualifiers are preserved."""
|
||||
# Administrative artifacts -> True (strip)
|
||||
assert _is_administrative_parenthetical("12/05/2023") is True
|
||||
assert _is_administrative_parenthetical("2022-04-10") is True
|
||||
assert _is_administrative_parenthetical("15 jan 2024") is True
|
||||
assert _is_administrative_parenthetical("ICD-10: I10") is True
|
||||
assert _is_administrative_parenthetical("icd: e11.9") is True
|
||||
assert _is_administrative_parenthetical("code C61") is True
|
||||
assert _is_administrative_parenthetical("I10") is True
|
||||
assert _is_administrative_parenthetical("E11.9") is True
|
||||
assert _is_administrative_parenthetical("K80.20") is True
|
||||
assert _is_administrative_parenthetical("MRN: 12345") is True
|
||||
assert _is_administrative_parenthetical("1") is True
|
||||
assert _is_administrative_parenthetical("iv") is True
|
||||
|
||||
# Clinical qualifiers -> False (preserve!)
|
||||
assert _is_administrative_parenthetical("HFrEF") is False
|
||||
assert _is_administrative_parenthetical("stage 3b") is False
|
||||
assert _is_administrative_parenthetical("calculous") is False
|
||||
assert _is_administrative_parenthetical("paroxysmal") is False
|
||||
assert _is_administrative_parenthetical("lumbar spine, pelvis") is False
|
||||
assert _is_administrative_parenthetical("Gleason 4+4=8") is False
|
||||
assert _is_administrative_parenthetical("mild intermittent") is False
|
||||
assert _is_administrative_parenthetical("gangrenous") is False
|
||||
|
||||
|
||||
def test_normalize_diagnosis_name_preserves_clinical_parentheticals():
|
||||
"""Verify that clinical parentheticals are unwrapped cleanly into the diagnosis name
|
||||
rather than destroyed, and administrative parentheticals are stripped."""
|
||||
# Clinical parentheticals preserved
|
||||
assert "calculous" in normalize_diagnosis_name("Acute cholecystitis (calculous)").lower()
|
||||
assert "stage 3b" in normalize_diagnosis_name("Chronic kidney disease (stage 3b)").lower()
|
||||
assert "paroxysmal" in normalize_diagnosis_name("Atrial fibrillation (paroxysmal)").lower()
|
||||
assert "lumbar spine" in normalize_diagnosis_name("Metastatic carcinoma (lumbar spine, pelvis)").lower()
|
||||
assert "gleason" in normalize_diagnosis_name("Adenocarcinoma of prostate (Gleason 4+4=8)").lower()
|
||||
|
||||
# Administrative parentheticals stripped
|
||||
assert "i10" not in normalize_diagnosis_name("Essential hypertension (ICD-10: I10)").lower()
|
||||
assert "2023" not in normalize_diagnosis_name("Type 2 diabetes (diagnosed 12/04/2023)").lower()
|
||||
assert "mrn" not in normalize_diagnosis_name("Hypertension (MRN: 98765)").lower()
|
||||
|
||||
|
||||
def test_clean_abbreviation_expansions():
|
||||
"""Verify abbreviations expand to standard clinical phrases without synonym soups."""
|
||||
# CVA should be cerebrovascular accident, not concatenated with stroke
|
||||
cva_exp = CLINICAL_ABBREVIATIONS.get("cva")
|
||||
assert cva_exp == "cerebrovascular accident"
|
||||
|
||||
# SOB should be shortness of breath, not concatenated with dyspnea
|
||||
sob_exp = CLINICAL_ABBREVIATIONS.get("sob")
|
||||
assert sob_exp == "shortness of breath"
|
||||
|
||||
# choledocholithiasis is not an abbreviation; must not be mapped to synonym soup in CLINICAL_ABBREVIATIONS
|
||||
assert "choledocholithiasis" not in CLINICAL_ABBREVIATIONS
|
||||
|
||||
# choledocholithiasis has appropriate morphological synonyms
|
||||
assert "choledocholithiasis" in CLINICAL_MORPHOLOGY
|
||||
assert any("calculus" in syn for syn in CLINICAL_MORPHOLOGY["choledocholithiasis"])
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 2. Primary Diagnosis Classification & Admission Driver Tests
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_classifier_identifies_admitting_diagnosis_header():
|
||||
"""Verify ADMITTING DIAGNOSIS header is recognized and outranks chronic comorbidities."""
|
||||
classifier = PrimarySecondaryClassifier(llm=DummyLLM())
|
||||
|
||||
note = (
|
||||
"ADMITTING DIAGNOSIS: Ca prostate\n"
|
||||
"PAST MEDICAL HISTORY: Essential hypertension on amlodipine, type 2 diabetes.\n"
|
||||
"HOSPITAL COURSE: Patient underwent robotic prostatectomy. Home amlodipine continued.\n"
|
||||
"DISCHARGE DIAGNOSES: Ca prostate, essential hypertension, type 2 diabetes."
|
||||
)
|
||||
|
||||
assessments = [
|
||||
ContextAssessment(
|
||||
diagnosis="Malignant neoplasm of prostate",
|
||||
condition_id="c-prostate",
|
||||
section="DISCHARGE_DIAGNOSES",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACTIVE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
evidence="ADMITTING DIAGNOSIS: Ca prostate | robotic prostatectomy",
|
||||
reason="Malignant prostate neoplasm requiring surgical resection",
|
||||
treated_or_managed=True,
|
||||
original_mention="Ca prostate",
|
||||
),
|
||||
ContextAssessment(
|
||||
diagnosis="Essential hypertension",
|
||||
condition_id="c-htn",
|
||||
section="PAST_MEDICAL_HISTORY",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
evidence="PAST MEDICAL HISTORY: Essential hypertension on amlodipine",
|
||||
reason="Chronic baseline comorbidity continued on home medication",
|
||||
treated_or_managed=True,
|
||||
original_mention="Essential hypertension",
|
||||
),
|
||||
ContextAssessment(
|
||||
diagnosis="Type 2 diabetes mellitus",
|
||||
condition_id="c-dm",
|
||||
section="PAST_MEDICAL_HISTORY",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
evidence="type 2 diabetes",
|
||||
reason="Chronic baseline comorbidity",
|
||||
treated_or_managed=False,
|
||||
original_mention="type 2 diabetes",
|
||||
),
|
||||
]
|
||||
|
||||
res, _ = classifier.classify_conditions(assessments, clinical_text=note)
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.diagnosis == "Malignant neoplasm of prostate"
|
||||
assert res.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
|
||||
# Secondary diagnoses must NOT be primary
|
||||
sec_names = [d.diagnosis for d in res.secondary_diagnoses]
|
||||
assert "Essential hypertension" in sec_names
|
||||
assert all(d.role == DiagnosisRole.SECONDARY for d in res.secondary_diagnoses)
|
||||
|
||||
|
||||
def test_classifier_etiological_primary_guardrail():
|
||||
"""Verify 'Primary hypertension' in condition name does NOT trigger primary role
|
||||
when patient was admitted for an acute admission driver (e.g. Pneumonia)."""
|
||||
classifier = PrimarySecondaryClassifier(llm=DummyLLM())
|
||||
|
||||
note = (
|
||||
"CHIEF COMPLAINT: Severe cough and fever.\n"
|
||||
"REASON FOR ADMISSION: Acute community acquired pneumonia.\n"
|
||||
"PAST MEDICAL HISTORY: Primary hypertension, well controlled.\n"
|
||||
"HOSPITAL COURSE: Started on IV ceftriaxone for pneumonia."
|
||||
)
|
||||
|
||||
assessments = [
|
||||
ContextAssessment(
|
||||
diagnosis="Pneumonia",
|
||||
condition_id="c-pna",
|
||||
section="REASON_FOR_ADMISSION",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
evidence="REASON FOR ADMISSION: Acute community acquired pneumonia",
|
||||
reason="Acute occasioning condition",
|
||||
treated_or_managed=True,
|
||||
original_mention="Acute community acquired pneumonia",
|
||||
),
|
||||
ContextAssessment(
|
||||
diagnosis="Primary hypertension",
|
||||
condition_id="c-phtn",
|
||||
section="PAST_MEDICAL_HISTORY",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
evidence="PAST MEDICAL HISTORY: Primary hypertension, well controlled",
|
||||
reason="Comorbidity",
|
||||
treated_or_managed=False,
|
||||
original_mention="Primary hypertension",
|
||||
),
|
||||
]
|
||||
|
||||
res, _ = classifier.classify_conditions(assessments, clinical_text=note)
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.diagnosis == "Pneumonia"
|
||||
assert res.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
|
||||
htn_diag = next(d for d in res.secondary_diagnoses if "hypertension" in d.diagnosis.lower())
|
||||
assert htn_diag.role == DiagnosisRole.SECONDARY
|
||||
|
||||
|
||||
def test_initial_role_preserved_from_clinical_extractor():
|
||||
"""Verify that when initial_role=DiagnosisRole.PRIMARY is set on ContextAssessment,
|
||||
the classifier honors the clinically established primary driver."""
|
||||
classifier = PrimarySecondaryClassifier(llm=DummyLLM())
|
||||
|
||||
assessments = [
|
||||
ContextAssessment(
|
||||
diagnosis="Acute cholecystitis",
|
||||
condition_id="c-chole",
|
||||
section="DISCHARGE_DIAGNOSES",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
evidence="Acute cholecystitis occasioning laparoscopic cholecystectomy",
|
||||
reason="Occasioning admission",
|
||||
treated_or_managed=True,
|
||||
initial_role=DiagnosisRole.PRIMARY,
|
||||
),
|
||||
ContextAssessment(
|
||||
diagnosis="Essential hypertension",
|
||||
condition_id="c-htn",
|
||||
section="PAST_MEDICAL_HISTORY",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
evidence="Hypertension on lisinopril",
|
||||
reason="Comorbidity",
|
||||
treated_or_managed=True,
|
||||
initial_role=DiagnosisRole.SECONDARY,
|
||||
),
|
||||
]
|
||||
|
||||
res, _ = classifier.classify_conditions(assessments, clinical_text="")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.diagnosis == "Acute cholecystitis"
|
||||
assert res.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 3. Finalize Output & Secondary Non-Promotion Guardrails
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_no_arbitrary_secondary_promotion_in_finalize_output():
|
||||
"""Verify that when the clinical primary diagnosis cannot be coded (or abstains),
|
||||
the secondary diagnosis (e.g. I10 Hypertension) is strictly NOT promoted to primary."""
|
||||
state = {
|
||||
"document_id": "test-doc-001",
|
||||
"validated_codes": [
|
||||
# Only the secondary condition could be validated
|
||||
type("MockCoded", (), {
|
||||
"raw_term": "Essential hypertension",
|
||||
"code": "I10",
|
||||
"description": "Essential (primary) hypertension",
|
||||
"role": DiagnosisRole.SECONDARY,
|
||||
"confidence_score": 0.95,
|
||||
"icd10cm": "I10",
|
||||
"icdo": None,
|
||||
"cpt": None,
|
||||
"source_section": "PAST_MEDICAL_HISTORY",
|
||||
"source_span": None,
|
||||
"matching_status": "MATCHED",
|
||||
"evidence": type("MockEv", (), {"quote": "Hypertension on medication", "source_section": "PAST_MEDICAL_HISTORY", "source_span": None})(),
|
||||
})(),
|
||||
],
|
||||
"classified_diagnoses": [
|
||||
# A primary condition existed clinically, but had no verified code
|
||||
type("MockClassified", (), {
|
||||
"diagnosis_id": "c-unmapped-primary",
|
||||
"diagnosis": "Rare obscure primary disease syndrome",
|
||||
"raw_term": "Rare obscure primary disease syndrome",
|
||||
"normalized_diagnosis": "Rare obscure primary disease syndrome",
|
||||
"role": DiagnosisRole.PRIMARY,
|
||||
"evidence_quote": "Admitted for rare obscure primary disease syndrome",
|
||||
"source_section": "PRINCIPAL_DIAGNOSIS",
|
||||
})(),
|
||||
type("MockClassified", (), {
|
||||
"diagnosis_id": "c-htn",
|
||||
"diagnosis": "Essential hypertension",
|
||||
"raw_term": "Essential hypertension",
|
||||
"normalized_diagnosis": "Essential hypertension",
|
||||
"role": DiagnosisRole.SECONDARY,
|
||||
"evidence_quote": "Hypertension on medication",
|
||||
"source_section": "PAST_MEDICAL_HISTORY",
|
||||
})(),
|
||||
],
|
||||
"abstentions": [],
|
||||
}
|
||||
|
||||
output = finalize_output_node(state)
|
||||
result: CodingResult = output["final_result"]
|
||||
|
||||
# CRITICAL: Secondary diagnosis I10 MUST NOT be promoted to primary!
|
||||
# If primary had no valid code match, secondary must remain SECONDARY.
|
||||
assert all(d.database_code != "I10" or d.role == DiagnosisRole.SECONDARY for d in result.secondary_diagnoses)
|
||||
if result.primary_diagnosis:
|
||||
assert result.primary_diagnosis.database_code != "I10"
|
||||
assert result.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
else:
|
||||
# If primary abstained, primary_diagnosis is None and abstention is recorded
|
||||
assert any("obscure" in a.detail.lower() or "obscure" in (a.raw_term or "").lower() for a in result.abstentions)
|
||||
assert len(result.secondary_diagnoses) == 1
|
||||
assert result.secondary_diagnoses[0].database_code == "I10"
|
||||
assert result.secondary_diagnoses[0].role == DiagnosisRole.SECONDARY
|
||||
Reference in New Issue
Block a user