feat(classifier): strengthen primary diagnosis reasoning, multi-round abstention recovery, and clinical normalization
This commit is contained in:
@@ -1040,9 +1040,23 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
# 1. Section / Reason for Admission Context (UHDDS Authority Hierarchy)
|
||||
# Under UHDDS, condition established after study chiefly responsible for occasioning admission
|
||||
# or underlying condition occasioning procedural/medical inpatient therapy
|
||||
# Function to test whether diag_lower is the direct primary diagnosis mention in a clause
|
||||
from medical_coding.utils.text import normalize_diagnosis_name
|
||||
|
||||
def _is_etiological_primary(term: str) -> bool:
|
||||
t = term.lower().strip()
|
||||
return bool(re.search(
|
||||
r"\bprimary\s+(?:hypertension|essential\s+hypertension|osteoarthritis|biliary|sclerosing|"
|
||||
r"open[\s\-]?angle|aldosteronism|hyperparathyroidism|pulmonary\s+hypertension|progressive|"
|
||||
r"spontaneous\s+pneumothorax|amyloidosis|insomnia|cough\s+headache|polycythemia|thrombocythemia)\b",
|
||||
t,
|
||||
))
|
||||
|
||||
is_etio_primary = _is_etiological_primary(diag_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:
|
||||
for match in re.finditer(rf"\b(?:principal|primary)(?:\s+diagnos[ei]s)?\s*[:\-–—]\s*([^\n.;]+)", text, re.IGNORECASE):
|
||||
# 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", ","
|
||||
for delim in [" with ", " complicated by ", " secondary to ", ","]:
|
||||
@@ -1066,6 +1080,12 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
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))):
|
||||
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))
|
||||
@@ -1083,7 +1103,7 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
)
|
||||
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")]
|
||||
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:
|
||||
@@ -1094,12 +1114,19 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
):
|
||||
is_admission_driver = True
|
||||
|
||||
# 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"]):
|
||||
is_admission_driver = False
|
||||
|
||||
if is_explicit_primary:
|
||||
score += 10.0
|
||||
reasons.append("Explicitly documented as PRIMARY/PRINCIPAL DIAGNOSIS by provider (+10.0)")
|
||||
elif is_admission_driver:
|
||||
score += 6.0
|
||||
reasons.append("Identified as principal condition occasioning admission (+6.0)")
|
||||
elif is_etio_primary:
|
||||
# Clarify that 'primary' is etiological, not role
|
||||
reasons.append("Etiological 'Primary' in condition name denotes idiopathic etiology; evaluated as comorbidity")
|
||||
|
||||
if is_explicit_secondary and not is_explicit_primary:
|
||||
score -= 5.0
|
||||
@@ -1562,6 +1589,28 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
)
|
||||
)
|
||||
|
||||
# UHDDS Guardrail: Verify if LLM marked an etiological 'Primary' condition (e.g. Primary hypertension)
|
||||
# as the PRIMARY role when another acute occasioning condition is present
|
||||
primaries = [c for c in classifications if c.role == DiagnosisRole.PRIMARY]
|
||||
if len(primaries) == 1:
|
||||
p = primaries[0]
|
||||
p_name = p.diagnosis.lower()
|
||||
is_etio = bool(re.search(
|
||||
r"\bprimary\s+(?:hypertension|essential\s+hypertension|osteoarthritis|biliary|sclerosing|"
|
||||
r"open[\s\-]?angle|aldosteronism|hyperparathyroidism|pulmonary\s+hypertension|progressive|"
|
||||
r"spontaneous\s+pneumothorax|amyloidosis|insomnia|cough\s+headache|polycythemia|thrombocythemia)\b",
|
||||
p_name,
|
||||
))
|
||||
if is_etio:
|
||||
acute_other = next((c for c in classifications if c != p and c.role == DiagnosisRole.SECONDARY and (
|
||||
any(w in c.diagnosis.lower() for w in ["acute", "infarction", "fracture", "appendicitis", "cholecystitis", "sepsis", "stroke", "pneumonia"])
|
||||
)), None)
|
||||
if acute_other:
|
||||
p.role = DiagnosisRole.SECONDARY
|
||||
p.classification_reason = f"Etiological 'Primary' in condition name denotes idiopathic etiology; reclassified as Secondary comorbidity under UHDDS guidelines. {p.classification_reason}"
|
||||
acute_other.role = DiagnosisRole.PRIMARY
|
||||
acute_other.primary_justification = f"Acute condition occasioning inpatient admission: {acute_other.evidence_quote}"
|
||||
|
||||
return classifications if len(classifications) > 0 else None
|
||||
|
||||
# LangGraph Node execution
|
||||
|
||||
@@ -566,9 +566,9 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
else ""
|
||||
)
|
||||
|
||||
# 1. Clean query for core clinical entity (strip trailing medications, status, or parentheticals)
|
||||
clean_query = re.sub(r"\s*\([^)]*\)", "", raw_query).strip()
|
||||
clean_query = re.split(r"\s*[-–—]\s*|\s*;\s*|\s*:\s*", clean_query)[0].strip()
|
||||
# 1. Clean query using strengthened clinical normalization
|
||||
from medical_coding.utils.text import extract_search_query_variations, normalize_diagnosis_name
|
||||
clean_query = normalize_diagnosis_name(raw_query)
|
||||
if not clean_query:
|
||||
clean_query = raw_query
|
||||
|
||||
@@ -585,8 +585,8 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
hits: list[ICDCandidate] = []
|
||||
existing_codes: set[str] = set()
|
||||
|
||||
# STAGE 1: Primary Hybrid Retrieval (Single fast dense+sparse search)
|
||||
primary_hits = retriever.retrieve(clean_query, top_k=25, system="ICD-10-CM")
|
||||
# STAGE 1: Primary Hybrid Retrieval with Multi-Round Retry Checking
|
||||
primary_hits = retriever.retrieve_with_retry(clean_query, evidence=ev_quote, top_k=25, system="ICD-10-CM")
|
||||
for h in primary_hits:
|
||||
if h.code not in existing_codes:
|
||||
hits.append(h)
|
||||
@@ -841,10 +841,33 @@ def rank_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
|
||||
clean_evidence_quote = " | ".join(ev_snippets).strip() if ev_snippets else ev_quote
|
||||
selection = agent.rank_candidates(cond, candidates, evidence_override=clean_evidence_quote.strip() or None)
|
||||
|
||||
# Multi-round re-checking for conditions with positive evidence that were not identified on initial pass
|
||||
if (
|
||||
selection.selected_code is None
|
||||
and bool(clean_evidence_quote.strip())
|
||||
and cond.role in (DiagnosisRole.PRIMARY, DiagnosisRole.SECONDARY)
|
||||
and getattr(cond, "is_billable_candidate", True)
|
||||
):
|
||||
logger.info("Condition '%s' with positive evidence lacked code; re-checking with multi-round BM25 and vector search...", cond.raw_term)
|
||||
_, retry_retriever = get_or_initialize_retrieval_system()
|
||||
retry_candidates = retry_retriever.retrieve_with_retry(
|
||||
cond.raw_term,
|
||||
evidence=clean_evidence_quote,
|
||||
top_k=20,
|
||||
min_score=0.20,
|
||||
)
|
||||
if retry_candidates:
|
||||
re_selection = agent.rank_candidates(cond, retry_candidates, evidence_override=clean_evidence_quote.strip() or None)
|
||||
if re_selection.selected_code is not None:
|
||||
selection = re_selection
|
||||
candidate_pool[cond.diagnosis_id] = retry_candidates
|
||||
|
||||
ranked_selections.append(selection)
|
||||
|
||||
return {
|
||||
"ranked_selections": ranked_selections,
|
||||
"candidate_pool": candidate_pool,
|
||||
"current_stage": PipelineStage.RANKING,
|
||||
}
|
||||
|
||||
@@ -1269,7 +1292,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
coded_secondaries.append(s)
|
||||
elif s.evidence_quote:
|
||||
s_name = s.normalized_diagnosis or s.raw_term or s.description or ""
|
||||
retrieved = retriever.retrieve(s_name, top_k=5) if s_name else []
|
||||
retrieved = retriever.retrieve_with_retry(s_name, evidence=s.evidence_quote, top_k=5, min_score=0.20) if s_name else []
|
||||
if retrieved:
|
||||
top_r = retrieved[0]
|
||||
s.icd10cm = top_r.code
|
||||
@@ -1308,7 +1331,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
if not p_code or p_code == "None" or primary_response.matching_status == "NO_DATABASE_MATCH":
|
||||
p_name = primary_response.normalized_diagnosis or primary_response.raw_term or primary_response.description or ""
|
||||
if primary_response.evidence_quote and p_name:
|
||||
retrieved = retriever.retrieve(p_name, top_k=5)
|
||||
retrieved = retriever.retrieve_with_retry(p_name, evidence=primary_response.evidence_quote, top_k=5, min_score=0.20)
|
||||
if retrieved:
|
||||
top_r = retrieved[0]
|
||||
primary_response.icd10cm = top_r.code
|
||||
@@ -1333,6 +1356,125 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
else:
|
||||
primary_response = None
|
||||
|
||||
# Multi-round checking for abstentions with positive evidence
|
||||
from medical_coding.utils.text import normalize_diagnosis_name
|
||||
rechecked_abstentions: list[AbstentionRecord] = []
|
||||
for abst in abstentions:
|
||||
a_term = abst.raw_term or ""
|
||||
a_detail = abst.detail or ""
|
||||
is_negated_or_ruled_out = (
|
||||
abst.reason in (
|
||||
AbstentionReason.EXCLUDED_BY_NEGATION,
|
||||
AbstentionReason.EXCLUDED_BY_TEMPORALITY,
|
||||
AbstentionReason.CONTRADICTORY_DOCUMENTATION,
|
||||
)
|
||||
or "ruled out" in a_detail.lower()
|
||||
or "ruled-out" in a_detail.lower()
|
||||
or "negat" in a_detail.lower()
|
||||
or "past medical history alone without" in a_detail.lower()
|
||||
)
|
||||
if is_negated_or_ruled_out or not a_term:
|
||||
rechecked_abstentions.append(abst)
|
||||
continue
|
||||
|
||||
ev_quote = ""
|
||||
matching_cond = next((
|
||||
c for c in classified
|
||||
if (getattr(c, "diagnosis", None) or getattr(c, "raw_term", "")).lower() == a_term.lower()
|
||||
), None)
|
||||
if matching_cond:
|
||||
ev_quote = getattr(matching_cond, "evidence_quote", "") or (
|
||||
matching_cond.context.evidence.quote
|
||||
if hasattr(matching_cond, "context") and hasattr(matching_cond.context, "evidence") and matching_cond.context.evidence
|
||||
else ""
|
||||
)
|
||||
if not ev_quote and diag_state:
|
||||
matching_diag = next((
|
||||
d for d in diag_state.all_candidates
|
||||
if d.raw_term.lower() == a_term.lower() or (d.normalized_diagnosis and d.normalized_diagnosis.lower() == a_term.lower())
|
||||
), None)
|
||||
if matching_diag:
|
||||
ev_quote = matching_diag.primary_evidence_quote or ""
|
||||
if not ev_quote:
|
||||
raw_doc = state.get("raw_text", "")
|
||||
if a_term.lower() in raw_doc.lower():
|
||||
ev_quote = a_term
|
||||
|
||||
if not ev_quote:
|
||||
rechecked_abstentions.append(abst)
|
||||
continue
|
||||
|
||||
is_valid_cand, _ = HardClinicalCandidateGate.evaluate_candidate(a_term, ev_quote)
|
||||
if not is_valid_cand:
|
||||
rechecked_abstentions.append(abst)
|
||||
continue
|
||||
|
||||
norm_a = normalize_diagnosis_name(a_term)
|
||||
retry_hits = retriever.retrieve_with_retry(
|
||||
norm_a or a_term,
|
||||
evidence=ev_quote,
|
||||
top_k=5,
|
||||
min_score=0.20,
|
||||
)
|
||||
|
||||
valid_hit = None
|
||||
for h in retry_hits:
|
||||
if catalog.is_valid_code(h.code) and catalog.is_billable_code(h.code):
|
||||
valid_hit = h
|
||||
break
|
||||
if not valid_hit and retry_hits:
|
||||
valid_hit = retry_hits[0]
|
||||
|
||||
if valid_hit:
|
||||
hit_code = valid_hit.code
|
||||
is_dup = (
|
||||
(primary_response and primary_response.code == hit_code)
|
||||
or any(s.code == hit_code for s in secondary_responses)
|
||||
)
|
||||
if not is_dup:
|
||||
is_icdo = bool(getattr(valid_hit, "coding_system", None) == "ICD-O" or valid_hit.code.startswith("M"))
|
||||
is_cpt = bool(getattr(valid_hit, "coding_system", None) == "CPT" or (valid_hit.code.isdigit() and len(valid_hit.code) in (4, 5)))
|
||||
icd10_val = valid_hit.code if not is_icdo and not is_cpt else None
|
||||
icdo_val = valid_hit.code if is_icdo else None
|
||||
cpt_val = valid_hit.code if is_cpt else None
|
||||
|
||||
promoted = CodedDiagnosisResponse(
|
||||
raw_term=a_term,
|
||||
normalized_diagnosis=norm_a or a_term,
|
||||
description=valid_hit.description,
|
||||
database_code=valid_hit.code,
|
||||
database_description=valid_hit.description,
|
||||
matching_status="MATCHED" if valid_hit.retrieval_score >= 0.40 else "NEAREST_MATCH",
|
||||
source_section=getattr(matching_cond, "source_section", "") or "CLINICAL_DOCUMENTATION",
|
||||
role=DiagnosisRole.SECONDARY if primary_response else DiagnosisRole.PRIMARY,
|
||||
acuity=Acuity.ACUTE if "acute" in norm_a.lower() else (Acuity.CHRONIC if "chronic" in norm_a.lower() else Acuity.UNSPECIFIED),
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote=ev_quote,
|
||||
evidence=[{
|
||||
"quote": ev_quote,
|
||||
"section": getattr(matching_cond, "source_section", "") or "CLINICAL_DOCUMENTATION",
|
||||
"evidence_type": "CLINICAL_EVIDENCE",
|
||||
}],
|
||||
confidence_score=max(0.40, valid_hit.retrieval_score),
|
||||
is_terminal_billable=True,
|
||||
icd10cm=icd10_val,
|
||||
icdo=icdo_val,
|
||||
cpt=cpt_val,
|
||||
)
|
||||
if not primary_response:
|
||||
primary_response = promoted
|
||||
else:
|
||||
secondary_responses.append(promoted)
|
||||
logger.info(
|
||||
"Re-check success: Promoted abstained condition '%s' with positive evidence to %s (code '%s')",
|
||||
a_term, promoted.role.value, valid_hit.code
|
||||
)
|
||||
continue
|
||||
|
||||
rechecked_abstentions.append(abst)
|
||||
|
||||
abstentions = rechecked_abstentions
|
||||
|
||||
# Enforce clean role separation: secondary section must NEVER duplicate the primary diagnosis
|
||||
if primary_response:
|
||||
pri_code = primary_response.code
|
||||
|
||||
@@ -19,20 +19,38 @@ CRITICAL CODING RULES:
|
||||
- If two or more conditions equally meet the criteria for primary diagnosis and the documentation does not distinguish which one occasioned the admission, do NOT arbitrarily choose one. Flag as an ambiguous primary requiring abstention.
|
||||
- If no defensible primary condition exists, do NOT force one.
|
||||
|
||||
2. ZERO OR MORE SECONDARY DIAGNOSES:
|
||||
2. CRITICAL REASONING ON "PRIMARY" IN DISEASE ENTITY NAMES:
|
||||
- Many clinical diseases contain the word "Primary" as an etiological designation (meaning idiopathic, non-secondary, or essential), including:
|
||||
* "Primary hypertension" (essential hypertension)
|
||||
* "Primary osteoarthritis" (degenerative joint disease)
|
||||
* "Primary biliary cholangitis" / "Primary biliary cirrhosis"
|
||||
* "Primary open-angle glaucoma"
|
||||
* "Primary progressive multiple sclerosis"
|
||||
* "Primary pulmonary hypertension"
|
||||
* "Primary aldosteronism"
|
||||
* "Primary hyperparathyroidism"
|
||||
* "Primary spontaneous pneumothorax"
|
||||
* "Primary sclerosing cholangitis"
|
||||
- Having "Primary" in the disease entity name DOES NOT MAKE IT the encounter's Primary Diagnosis!
|
||||
- Under UHDDS guidelines, the Primary Diagnosis is strictly the condition that occasioned the inpatient admission and was the chief driver of acute inpatient care or surgery.
|
||||
- Chronic baseline conditions like "Primary hypertension" or "Primary osteoarthritis" are almost always SECONDARY (comorbid) diagnoses, UNLESS the encounter documentation explicitly proves the patient was admitted specifically for an acute emergency thereof (such as an acute hypertensive emergency/crisis).
|
||||
- If an acute occasioning condition is present (e.g. Acute myocardial infarction, Acute appendicitis, Cholecystitis, Stroke, Fracture, Sepsis, Pneumonia), that acute condition is the PRIMARY diagnosis, while any chronic disease with "Primary" in its name must be assigned role SECONDARY.
|
||||
- You must provide clinical reasoning in "classification_reason" demonstrating how you determined the condition occasioning admission and why any condition with "Primary" in its name was properly classified.
|
||||
|
||||
3. ZERO OR MORE SECONDARY DIAGNOSES:
|
||||
- A co-existing condition qualifies as a secondary diagnosis when documented evidence shows that it was:
|
||||
* clinically relevant
|
||||
* actively managed or treated
|
||||
* monitored (serial labs, diagnostic workup, vitals)
|
||||
* influencing clinical care or increasing nursing care during the stay.
|
||||
|
||||
3. EXCLUDED CONDITIONS (DO NOT CODE):
|
||||
4. EXCLUDED CONDITIONS (DO NOT CODE):
|
||||
- Historical-only conditions without documented inpatient care.
|
||||
- Definitively ruled-out or negated conditions.
|
||||
- Symptoms that are integral to a confirmed underlying diagnosis.
|
||||
- Assign role: "EXCLUDED" and is_billable_candidate: false.
|
||||
|
||||
4. NO ICD CODES:
|
||||
5. NO ICD CODES:
|
||||
- You must NEVER generate, suggest, or assign ICD codes. Only assign billing roles ("PRIMARY", "SECONDARY", "EXCLUDED") with explicit clinical reasons.
|
||||
|
||||
Output valid JSON strictly conforming to:
|
||||
|
||||
@@ -223,3 +223,64 @@ class HybridICDRetriever(BaseICDRetriever):
|
||||
"ICD-O": self.retrieve(query, top_k=top_k, min_score=min_score, system="ICD-O"),
|
||||
"CPT": self.retrieve(query, top_k=top_k, min_score=min_score, system="CPT"),
|
||||
}
|
||||
|
||||
def retrieve_with_retry(
|
||||
self,
|
||||
query: str,
|
||||
evidence: str = "",
|
||||
top_k: int | None = None,
|
||||
min_score: float | None = None,
|
||||
system: str | None = None,
|
||||
max_rounds: int = 3,
|
||||
) -> list[ICDCandidate]:
|
||||
"""Multi-round iterative BM25 lexical and dense vector search across query variations.
|
||||
|
||||
Re-checks candidates for conditions with positive evidence that were not identified
|
||||
on the first pass.
|
||||
|
||||
Round 1: Standard query retrieval.
|
||||
Round 2: Normalized query variations (core clinical entities, synonyms, expanded acronyms).
|
||||
Round 3: Evidence-anchored keywords and relaxed threshold matching.
|
||||
"""
|
||||
k = top_k if top_k is not None else self.default_top_k
|
||||
threshold = min_score if min_score is not None else self.min_score_threshold
|
||||
|
||||
# Round 1: Standard retrieval with original query
|
||||
round1_hits = self.retrieve(query, top_k=k, min_score=threshold, system=system)
|
||||
if round1_hits and round1_hits[0].retrieval_score >= threshold:
|
||||
return round1_hits
|
||||
|
||||
from medical_coding.utils.text import extract_search_query_variations
|
||||
|
||||
variations = extract_search_query_variations(query, evidence=evidence)
|
||||
merged_candidates: dict[str, ICDCandidate] = {c.code: c for c in round1_hits}
|
||||
|
||||
# Round 2: Query variations with slightly relaxed threshold
|
||||
if max_rounds >= 2 and variations:
|
||||
relaxed_threshold_r2 = max(0.20, threshold - 0.10)
|
||||
for var in variations:
|
||||
if var.lower().strip() == query.lower().strip():
|
||||
continue
|
||||
var_hits = self.retrieve(var, top_k=k, min_score=relaxed_threshold_r2, system=system)
|
||||
for h in var_hits:
|
||||
if h.code not in merged_candidates or h.retrieval_score > merged_candidates[h.code].retrieval_score:
|
||||
merged_candidates[h.code] = h
|
||||
|
||||
if merged_candidates:
|
||||
ranked = sorted(merged_candidates.values(), key=lambda c: c.retrieval_score, reverse=True)
|
||||
if ranked[0].retrieval_score >= threshold:
|
||||
return ranked[:k]
|
||||
|
||||
# Round 3: Evidence-anchored search and relaxed threshold
|
||||
if max_rounds >= 3:
|
||||
relaxed_threshold_r3 = max(0.15, threshold - 0.15)
|
||||
# Try evidence text directly if available
|
||||
if evidence:
|
||||
ev_hits = self.retrieve(evidence[:120], top_k=k, min_score=relaxed_threshold_r3, system=system)
|
||||
for h in ev_hits:
|
||||
if h.code not in merged_candidates or h.retrieval_score > merged_candidates[h.code].retrieval_score:
|
||||
merged_candidates[h.code] = h
|
||||
|
||||
ranked = sorted(merged_candidates.values(), key=lambda c: c.retrieval_score, reverse=True)
|
||||
return ranked[:k] if ranked else []
|
||||
|
||||
|
||||
@@ -56,6 +56,47 @@ CLINICAL_ABBREVIATIONS: dict[str, str] = {
|
||||
"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",
|
||||
"cag": "coronary artery disease",
|
||||
"ihd": "ischemic heart disease coronary artery disease",
|
||||
"ashd": "atherosclerotic heart disease coronary artery disease",
|
||||
"niddm": "type 2 diabetes mellitus",
|
||||
"iddm": "type 1 diabetes mellitus",
|
||||
"sle": "systemic lupus erythematosus",
|
||||
"tb": "tuberculosis",
|
||||
"uri": "upper respiratory tract infection",
|
||||
"urti": "upper respiratory tract infection",
|
||||
"lrti": "lower respiratory tract infection",
|
||||
"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",
|
||||
"ugib": "upper gastrointestinal bleeding",
|
||||
"lgib": "lower gastrointestinal bleeding",
|
||||
"hl": "hodgkin lymphoma",
|
||||
"nhl": "non hodgkin lymphoma",
|
||||
"all": "acute lymphoblastic leukemia",
|
||||
"aml": "acute myeloid leukemia",
|
||||
"cll": "chronic lymphocytic leukemia",
|
||||
"cml": "chronic myeloid leukemia",
|
||||
"mm": "multiple myeloma",
|
||||
"nsclc": "non small cell lung cancer",
|
||||
"sclc": "small cell lung cancer",
|
||||
"rcc": "renal cell carcinoma",
|
||||
"hcc": "hepatocellular carcinoma",
|
||||
"crc": "colorectal cancer",
|
||||
"itp": "immune thrombocytopenic purpura",
|
||||
"sah": "subarachnoid hemorrhage",
|
||||
"sdh": "subdural hematoma",
|
||||
"edh": "epidural hematoma",
|
||||
"ich": "intracerebral hemorrhage",
|
||||
}
|
||||
|
||||
# Non-informative general words (keeping critical medical distinctions: acute, chronic, type, 1, 2, without, etc.)
|
||||
@@ -398,6 +439,19 @@ CLINICAL_MORPHOLOGY: dict[str, list[str]] = {
|
||||
"encephalopathy": ["delirium", "acute", "metabolic", "toxic"],
|
||||
"hypothyroidism": ["thyroid"],
|
||||
"thyroid": ["hypothyroidism"],
|
||||
"primary": ["essential", "idiopathic"],
|
||||
"essential": ["primary", "idiopathic"],
|
||||
"osteoarthritis": ["osteoarthrosis", "degenerative", "joint", "disease", "oa"],
|
||||
"glaucoma": ["open-angle", "poag", "ocular"],
|
||||
"cholangitis": ["biliary", "cirrhosis"],
|
||||
"biliary": ["cholangitis", "gallbladder", "cholecystitis", "cholelithiasis"],
|
||||
"pneumothorax": ["spontaneous", "collapsed", "lung"],
|
||||
"aldosteronism": ["hyperaldosteronism", "conn"],
|
||||
"hyperparathyroidism": ["parathyroid"],
|
||||
"sclerosis": ["multiple", "sclerosis", "ppms"],
|
||||
"infection": ["infectious", "infective"],
|
||||
"thrombosis": ["thrombus", "thrombotic", "clot", "dvt"],
|
||||
"embolism": ["embolus", "embolic", "pe"],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -73,3 +73,175 @@ def is_valid_icd_format(code: str) -> bool:
|
||||
return False
|
||||
# First char must be a letter, second must be a digit, followed by alphanumeric
|
||||
return bool(re.match(r"^[A-Z][0-9][0-9A-Z]{1,5}$", clean))
|
||||
|
||||
|
||||
CLINICAL_PREAMBLE_PATTERN = re.compile(
|
||||
r"^\s*(?:"
|
||||
r"(?:\d+[\.\)]|\*|\-|\u2022|\([a-z0-9]\))\s*)*"
|
||||
r"(?:"
|
||||
r"known\s+case\s+of|k/?c/?o\b|kco\b|"
|
||||
r"history\s+of|h/?o\b|p/?h/?o\b|past\s+medical\s+history\s+of|past\s+history\s+of|"
|
||||
r"status\s+post|s/?p\b|status-post|"
|
||||
r"c/?o\b|complaining\s+of|complaints\s+of|chief\s+complaint\s+of|"
|
||||
r"admitted\s+(?:for|with|due\s+to)|presented\s+with|presents\s+with|"
|
||||
r"diagnosed\s+with|diagnosis\s*:|diagnoses\s*:|impression\s*:|assessment\s*:|"
|
||||
r"discharge\s+diagnosis\s*:|final\s+diagnosis\s*:|principal\s+diagnosis\s*:|secondary\s+diagnosis\s*:|"
|
||||
r"features\s+(?:suggestive\s+of|of)|findings\s+(?:suggestive\s+of|compatible\s+with|of)|"
|
||||
r"evidence\s+of|signs\s+of|s/?o\b|suggestive\s+of|"
|
||||
r"likely|probable|possibly|suspected|rule\s+out|r/?o\b|\?|presumed|underlying"
|
||||
r")\s*[:\-–—]?\s*",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
MEDICATION_ATTACHMENT_PATTERN = re.compile(
|
||||
r"\s*[-–—:,;]?\s*(?:"
|
||||
r"on\s+(?:tab|tablets?|cap|capsules?|inj|injections?|syp|syrups?|medication|rx|treatment|dialysis|insulin|metformin|aspirin|statin|steroids?|antibiotics?)|"
|
||||
r"taking\s+|treated\s+with|started\s+on|prescribed|dosage"
|
||||
r").*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
QUALIFIERS_TO_STRIP_FOR_CORE = {
|
||||
"mild", "moderate", "severe", "stage", "1", "2", "3", "4", "5", "i", "ii", "iii", "iv",
|
||||
"compensated", "decompensated", "routine", "unspecified", "uncontrolled", "controlled",
|
||||
"status", "post", "acute", "chronic", "subacute", "left", "right", "bilateral",
|
||||
}
|
||||
|
||||
|
||||
def normalize_diagnosis_name(text: str) -> str:
|
||||
"""Strengthened clinical diagnosis normalizer.
|
||||
|
||||
1. Strips leading list bullets, indices, and whitespace.
|
||||
2. Strips medical preambles (K/C/O, H/O, S/P, C/O, impression of, etc.).
|
||||
3. Strips trailing prescription / medication attachments.
|
||||
4. Cleans and integrates useful parentheticals (e.g. 'Essential (primary) hypertension').
|
||||
5. Expands common clinical abbreviations and acronyms.
|
||||
6. Normalizes whitespace and casing.
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
cleaned = text.strip()
|
||||
|
||||
# Step 1: Strip leading bullets, numbering, dashes
|
||||
cleaned = re.sub(r"^\s*(?:\d+[\.\)]|\*|\-|\u2022|\([a-z0-9]\))\s*", "", cleaned)
|
||||
|
||||
# Step 2: Strip clinical preambles iteratively (e.g. 'K/C/O H/O HTN')
|
||||
for _ in range(3):
|
||||
match = CLINICAL_PREAMBLE_PATTERN.match(cleaned)
|
||||
if match:
|
||||
cleaned = cleaned[match.end():].strip()
|
||||
else:
|
||||
break
|
||||
|
||||
# Step 3: Strip trailing medication attachments
|
||||
cleaned = MEDICATION_ATTACHMENT_PATTERN.sub("", cleaned).strip()
|
||||
|
||||
# Step 4: Handle parentheticals
|
||||
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
|
||||
return " "
|
||||
|
||||
cleaned = re.sub(r"\(([^)]+)\)", _clean_paren, cleaned)
|
||||
|
||||
# Step 5: Expand clinical abbreviations
|
||||
from medical_coding.retrieval.tokenizer import expand_medical_abbreviations
|
||||
cleaned = expand_medical_abbreviations(cleaned)
|
||||
|
||||
# Step 6: Normalize whitespace and trailing punctuation
|
||||
cleaned = re.sub(r"[,\-–—:;]+$", "", cleaned).strip()
|
||||
cleaned = normalize_whitespace(cleaned)
|
||||
|
||||
return cleaned
|
||||
|
||||
|
||||
def extract_search_query_variations(raw_term: str, evidence: str = "") -> list[str]:
|
||||
"""Generate prioritized query variations for robust multi-round BM25 and vector search.
|
||||
|
||||
Produces:
|
||||
1. Fully normalized diagnosis name.
|
||||
2. Standard clinical query with expanded abbreviations.
|
||||
3. Core diagnostic entity (stripped of peripheral severity/acuity/laterality qualifiers).
|
||||
4. Clinical and morphological synonyms (e.g. primary hypertension -> essential hypertension).
|
||||
5. Evidence-anchored diagnostic entities (if evidence quote provided).
|
||||
"""
|
||||
if not raw_term:
|
||||
return []
|
||||
|
||||
variations: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def _add(q: str) -> None:
|
||||
clean = normalize_whitespace(q.strip().lower())
|
||||
if clean and clean not in seen and len(clean) >= 2:
|
||||
variations.append(clean)
|
||||
seen.add(clean)
|
||||
|
||||
# 1. Normalized primary term
|
||||
norm_term = normalize_diagnosis_name(raw_term)
|
||||
_add(norm_term)
|
||||
_add(raw_term)
|
||||
|
||||
# 2. Etiological & Primary Name Specific Variations
|
||||
# For diagnoses carrying "Primary", ensure essential/idiopathic forms are checked
|
||||
norm_lower = norm_term.lower()
|
||||
if "primary hypertension" in norm_lower:
|
||||
_add("essential primary hypertension")
|
||||
_add("essential hypertension")
|
||||
_add("hypertension")
|
||||
elif "essential hypertension" in norm_lower:
|
||||
_add("essential primary hypertension")
|
||||
_add("primary hypertension")
|
||||
_add("hypertension")
|
||||
elif "primary osteoarthritis" in norm_lower:
|
||||
_add("osteoarthritis")
|
||||
_add("degenerative joint disease")
|
||||
_add("polyosteoarthritis")
|
||||
elif "primary biliary" in norm_lower:
|
||||
_add("primary biliary cholangitis")
|
||||
_add("primary biliary cirrhosis")
|
||||
_add("biliary cholangitis")
|
||||
elif "primary open-angle" in norm_lower or "primary open angle" in norm_lower:
|
||||
_add("primary open angle glaucoma")
|
||||
_add("open angle glaucoma")
|
||||
elif "primary pulmonary hypertension" in norm_lower:
|
||||
_add("idiopathic pulmonary arterial hypertension")
|
||||
_add("pulmonary arterial hypertension")
|
||||
elif "primary spontaneous pneumothorax" in norm_lower:
|
||||
_add("spontaneous pneumothorax")
|
||||
_add("pneumothorax")
|
||||
|
||||
# 3. Core diagnostic entity tokens (strip qualifiers like mild, acute, left, etc.)
|
||||
words = re.findall(r"[a-z0-9]+", norm_lower)
|
||||
core_words = [w for w in words if w not in QUALIFIERS_TO_STRIP_FOR_CORE]
|
||||
if core_words and len(core_words) != len(words):
|
||||
_add(" ".join(core_words))
|
||||
|
||||
# 4. Morphological synonyms
|
||||
from medical_coding.retrieval.tokenizer import CLINICAL_MORPHOLOGY
|
||||
syn_words: list[str] = []
|
||||
has_syn = False
|
||||
for w in (core_words or words):
|
||||
if w in CLINICAL_MORPHOLOGY:
|
||||
has_syn = True
|
||||
syn_words.append(CLINICAL_MORPHOLOGY[w][0])
|
||||
else:
|
||||
syn_words.append(w)
|
||||
if has_syn:
|
||||
_add(" ".join(syn_words))
|
||||
|
||||
# 5. Evidence-anchored keywords
|
||||
if evidence:
|
||||
ev_clean = normalize_diagnosis_name(evidence)
|
||||
ev_words = re.findall(r"[a-z0-9]{4,}", ev_clean.lower())
|
||||
diag_words_set = set(words)
|
||||
matching_ev_words = [w for w in ev_words if w in diag_words_set or any(v in diag_words_set for v in CLINICAL_MORPHOLOGY.get(w, []))]
|
||||
if matching_ev_words and len(matching_ev_words) >= 2:
|
||||
_add(" ".join(matching_ev_words[:4]))
|
||||
|
||||
return variations
|
||||
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
"""Unit tests for demo-fix-1 improvements:
|
||||
1) Reasoning for conditions carrying 'Primary' in their name vs UHDDS Primary Diagnosis.
|
||||
2) Multi-round re-checking of abstentions with positive evidence via BM25 and vector search.
|
||||
3) Strengthened clinical diagnosis normalization logic and query variations.
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
import pytest
|
||||
|
||||
from medical_coding.agents.classifier import PrimarySecondaryClassifier
|
||||
from medical_coding.retrieval.hybrid import HybridICDRetriever
|
||||
from medical_coding.retrieval.lexical import BM25ICDRetriever
|
||||
from medical_coding.retrieval.vector import FAISSICDRetriever
|
||||
from medical_coding.models.factory import FastLocalEmbeddings
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
from medical_coding.schemas.clinical import ContextAssessment
|
||||
from medical_coding.schemas.enums import (
|
||||
Certainty,
|
||||
ConditionStatus,
|
||||
DiagnosisRole,
|
||||
NegationStatus,
|
||||
Temporality,
|
||||
AbstentionReason,
|
||||
)
|
||||
from medical_coding.schemas.icd import ICDCodeRecord
|
||||
from medical_coding.schemas.validation import AbstentionRecord
|
||||
from medical_coding.utils.text import (
|
||||
extract_search_query_variations,
|
||||
normalize_diagnosis_name,
|
||||
)
|
||||
from medical_coding.graph.nodes import finalize_output_node
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 1. NORMALIZATION TESTS
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_normalize_diagnosis_name_strips_preambles_and_medications() -> None:
|
||||
"""Test that medical preambles (K/C/O, H/O, S/P, C/O) and medications are stripped."""
|
||||
# Case 1: K/C/O and medication attachment
|
||||
raw1 = "1. K/C/O Essential (primary) hypertension on Tab Telmisartan 40mg"
|
||||
norm1 = normalize_diagnosis_name(raw1)
|
||||
assert "essential" in norm1.lower()
|
||||
assert "primary" in norm1.lower()
|
||||
assert "hypertension" in norm1.lower()
|
||||
assert "k/c/o" not in norm1.lower()
|
||||
assert "telmisartan" not in norm1.lower()
|
||||
|
||||
# Case 2: H/O and clinical impression
|
||||
raw2 = "Impression: H/O Acute cholecystitis with cholelithiasis"
|
||||
norm2 = normalize_diagnosis_name(raw2)
|
||||
assert "cholecystitis" in norm2.lower()
|
||||
assert "impression" not in norm2.lower()
|
||||
assert "h/o" not in norm2.lower()
|
||||
|
||||
# Case 3: S/P and bullet
|
||||
raw3 = "• S/P Appendectomy"
|
||||
norm3 = normalize_diagnosis_name(raw3)
|
||||
assert "appendectomy" in norm3.lower()
|
||||
assert "s/p" not in norm3.lower()
|
||||
|
||||
# Case 4: C/O with abbreviation expansion
|
||||
raw4 = "C/O SOB and CP secondary to CHF"
|
||||
norm4 = normalize_diagnosis_name(raw4)
|
||||
assert "c/o" not in norm4.lower()
|
||||
assert "shortness of breath" in norm4.lower()
|
||||
assert "congestive heart failure" in norm4.lower()
|
||||
|
||||
|
||||
def test_extract_search_query_variations() -> None:
|
||||
"""Test generating prioritized query variations for multi-round retrieval."""
|
||||
raw = "Primary hypertension"
|
||||
variations = extract_search_query_variations(raw)
|
||||
assert len(variations) >= 3
|
||||
# Should include etiological synonym variations
|
||||
assert any("essential" in v for v in variations)
|
||||
assert any(v == "hypertension" for v in variations)
|
||||
|
||||
# Test with clinical noise and evidence
|
||||
raw2 = "Known case of T2DM with peripheral neuropathy on Metformin"
|
||||
variations2 = extract_search_query_variations(raw2, evidence="Patient has diabetic peripheral neuropathy")
|
||||
assert any("type 2 diabetes mellitus" in v for v in variations2)
|
||||
assert any("neuropathy" in v for v in variations2)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 2. 'PRIMARY' IN DISEASE NAME VS UHDDS PRIMARY DIAGNOSIS TESTS
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_primary_hypertension_is_secondary_when_acute_appendicitis_occasions_admission() -> None:
|
||||
"""Verify condition carrying 'Primary' in name is classified as Secondary when acute admission driver exists."""
|
||||
mock_llm = MagicMock()
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
|
||||
acute_app = ContextAssessment(
|
||||
condition_id="app-1",
|
||||
diagnosis="Acute appendicitis",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Patient presented with acute right lower quadrant pain, admitted for acute appendicitis. Underwent urgent appendectomy.",
|
||||
reason="Acute condition occasioning admission.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
)
|
||||
|
||||
pri_htn = ContextAssessment(
|
||||
condition_id="htn-1",
|
||||
diagnosis="Primary hypertension",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Past history of Primary hypertension, maintained on daily amlodipine during hospitalization.",
|
||||
reason="Chronic baseline condition monitored during stay.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
)
|
||||
|
||||
result, abstentions = classifier.classify_conditions(
|
||||
[acute_app, pri_htn],
|
||||
clinical_text="Admitted for acute appendicitis. History: Primary hypertension on amlodipine.",
|
||||
)
|
||||
|
||||
assert result.has_unique_primary is True
|
||||
assert result.primary_diagnosis is not None
|
||||
assert result.primary_diagnosis.diagnosis == "Acute appendicitis"
|
||||
assert result.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
|
||||
# Primary hypertension must be SECONDARY, not PRIMARY
|
||||
sec_names = [s.diagnosis for s in result.secondary_diagnoses]
|
||||
assert "Primary hypertension" in sec_names
|
||||
for sec in result.secondary_diagnoses:
|
||||
if sec.diagnosis == "Primary hypertension":
|
||||
assert sec.role == DiagnosisRole.SECONDARY
|
||||
|
||||
|
||||
def test_llm_confusion_guardrail_reclassifies_primary_hypertension_to_secondary() -> None:
|
||||
"""If LLM erroneously assigns PRIMARY to 'Primary hypertension' over Acute MI, guardrail enforces UHDDS."""
|
||||
mock_llm = MagicMock()
|
||||
llm_response = """
|
||||
{
|
||||
"classifications": [
|
||||
{
|
||||
"diagnosis_id": "htn-1",
|
||||
"diagnosis": "Primary hypertension",
|
||||
"role": "PRIMARY",
|
||||
"classification_reason": "Contains Primary in name"
|
||||
},
|
||||
{
|
||||
"diagnosis_id": "mi-1",
|
||||
"diagnosis": "Acute myocardial infarction",
|
||||
"role": "SECONDARY",
|
||||
"classification_reason": "Treated with coronary stent"
|
||||
}
|
||||
]
|
||||
}
|
||||
"""
|
||||
mock_llm.invoke.return_value = llm_response
|
||||
mock_llm.generate.return_value = llm_response
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
|
||||
mi = ContextAssessment(
|
||||
condition_id="mi-1",
|
||||
diagnosis="Acute myocardial infarction",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Patient presented with crushing chest pain, admitted for acute STEMI. Underwent emergent PCI.",
|
||||
reason="Acute condition occasioning admission.",
|
||||
treated_or_managed=True,
|
||||
)
|
||||
htn = ContextAssessment(
|
||||
condition_id="htn-1",
|
||||
diagnosis="Primary hypertension",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Known primary hypertension on lisinopril.",
|
||||
reason="Chronic comorbidity.",
|
||||
treated_or_managed=True,
|
||||
)
|
||||
|
||||
result, _ = classifier.classify_conditions([mi, htn])
|
||||
assert result.has_unique_primary is True
|
||||
# Guardrail must demote Primary hypertension and make Acute MI the Primary diagnosis
|
||||
assert result.primary_diagnosis is not None
|
||||
assert result.primary_diagnosis.diagnosis == "Acute myocardial infarction"
|
||||
assert result.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 3. MULTI-ROUND RE-CHECKING FOR ABSTENTIONS WITH EVIDENCE TESTS
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mini_icd_system() -> tuple[LocalICDCatalog, HybridICDRetriever]:
|
||||
catalog = LocalICDCatalog()
|
||||
records = [
|
||||
ICDCodeRecord(
|
||||
code="I10",
|
||||
unformatted_code="I10",
|
||||
description="Essential primary hypertension",
|
||||
is_valid_billable=True,
|
||||
category="I10",
|
||||
synonyms=["primary hypertension", "essential hypertension", "HTN"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="K35.80",
|
||||
unformatted_code="K3580",
|
||||
description="Unspecified acute appendicitis",
|
||||
is_valid_billable=True,
|
||||
category="K35",
|
||||
synonyms=["acute appendicitis"],
|
||||
),
|
||||
]
|
||||
for r in records:
|
||||
catalog.add_record(r)
|
||||
catalog._initialized = True
|
||||
|
||||
bm25 = BM25ICDRetriever()
|
||||
bm25.build_index(records)
|
||||
embeddings = FastLocalEmbeddings(dim=384)
|
||||
faiss_ret = FAISSICDRetriever(embeddings=embeddings)
|
||||
faiss_ret.build_index(records)
|
||||
|
||||
hybrid = HybridICDRetriever(
|
||||
lexical_retriever=bm25,
|
||||
vector_retriever=faiss_ret,
|
||||
catalog=catalog,
|
||||
min_score_threshold=0.35,
|
||||
)
|
||||
return catalog, hybrid
|
||||
|
||||
|
||||
def test_retrieve_with_retry_finds_code_via_normalized_variations(
|
||||
mini_icd_system: tuple[LocalICDCatalog, HybridICDRetriever],
|
||||
) -> None:
|
||||
"""Verify retrieve_with_retry resolves complex phrasing via normalization variations."""
|
||||
_, hybrid = mini_icd_system
|
||||
noisy_query = "K/C/O High blood pressure (primary) on Tab Telmisartan 40mg"
|
||||
results = hybrid.retrieve_with_retry(
|
||||
noisy_query,
|
||||
evidence="Patient has primary hypertension managed with medication",
|
||||
top_k=3,
|
||||
)
|
||||
assert len(results) > 0
|
||||
assert results[0].code == "I10"
|
||||
|
||||
|
||||
def test_finalize_output_node_rechecks_abstentions_with_positive_evidence(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
mini_icd_system: tuple[LocalICDCatalog, HybridICDRetriever],
|
||||
) -> None:
|
||||
"""Verify finalize_output_node re-checks abstentions that carry positive evidence and promotes them."""
|
||||
catalog, hybrid = mini_icd_system
|
||||
import medical_coding.graph.nodes as nodes_mod
|
||||
monkeypatch.setattr(nodes_mod, "get_or_initialize_retrieval_system", lambda: (catalog, hybrid))
|
||||
|
||||
# Construct pipeline state where an abstention exists with positive evidence
|
||||
abstention_with_ev = AbstentionRecord(
|
||||
diagnosis_id="htn-abstained",
|
||||
raw_term="K/C/O Primary hypertension on medication",
|
||||
reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE,
|
||||
detail="No matching code on first pass",
|
||||
stage=nodes_mod.PipelineStage.VALIDATION,
|
||||
)
|
||||
|
||||
state = {
|
||||
"document_id": "test-doc-01",
|
||||
"raw_text": "History: K/C/O Primary hypertension on medication. Given amlodipine.",
|
||||
"validated_diagnoses": [],
|
||||
"classified_diagnoses": [],
|
||||
"abstentions": [abstention_with_ev],
|
||||
"ranked_selections": [],
|
||||
"candidate_pool": {},
|
||||
}
|
||||
|
||||
out = finalize_output_node(state)
|
||||
res = out["final_result"]
|
||||
|
||||
# The abstained condition with evidence must be recovered and promoted!
|
||||
coded_all = []
|
||||
if res.primary_diagnosis:
|
||||
coded_all.append(res.primary_diagnosis)
|
||||
coded_all.extend(res.secondary_diagnoses)
|
||||
|
||||
assert any(c.database_code == "I10" for c in coded_all)
|
||||
# Abstention list must be cleared of the recovered condition
|
||||
assert not any(a.raw_term == "K/C/O Primary hypertension on medication" for a in res.abstentions)
|
||||
@@ -150,9 +150,9 @@ async def test_full_pipeline_multi_condition_formatting() -> None:
|
||||
assert any("diabetes" in n for n in sec_names)
|
||||
assert any("hypertension" in n for n in sec_names)
|
||||
|
||||
# Conditions without local code match are strictly put into abstentions
|
||||
# Conditions without local code match are strictly put into abstentions; if recovered via retry, in secondaries
|
||||
abst_terms = [(a.raw_term or "").lower() for a in final_result.abstentions]
|
||||
assert any("choledocholithiasis" in t for t in abst_terms)
|
||||
assert any("choledocholithiasis" in n or "calculus" in n for n in sec_names) or any("choledocholithiasis" in t for t in abst_terms)
|
||||
|
||||
output = final_result.format_output()
|
||||
assert "primary diagnosis: " in output
|
||||
|
||||
Reference in New Issue
Block a user