Fix compound diagnosis splitting, section boundaries, and attribute matching for secondary completeness

This commit is contained in:
Abhinav Gupta
2026-10-12 12:40:30 +05:30
parent 211a1bc480
commit 0b5996ad1b
19 changed files with 1563 additions and 286 deletions
+130 -79
View File
@@ -386,51 +386,73 @@ class ContextAndRelevanceAgent(BaseAgent):
enforced_list.append(asm)
continue
# Rule 3: Past Medical History alone must NOT automatically qualify as a coding candidate
is_pmh_only = "PAST" in sec or "PMH" in sec or asm.temporality == Temporality.HISTORICAL
# Rule 3: Historical or Past Medical History alone must NOT qualify as a coding candidate
is_historical_only = (
"PAST" in sec
or "PMH" in sec
or asm.temporality == Temporality.HISTORICAL
or asm.status == ConditionStatus.HISTORICAL
or (cond and cond.temporality == Temporality.HISTORICAL)
or (cond and cond.status == ConditionStatus.HISTORICAL)
or "historical" in full_context
or "childhood" in full_context
or "prior history" in full_context
or bool(re.search(r"\b\d+\s+years?\s+ago\b", full_context))
)
has_no_treatment = bool(
re.search(
r"\b(?:no\s+(?:current\s+|active\s+)?(?:treatment|medication|rx|therapy|interventions?)|not\s+(?:currently\s+)?treated|without\s+(?:current\s+|active\s+)?(?:treatment|medication|rx|therapy))\b",
full_context,
re.IGNORECASE,
)
)
has_inpatient_care = (
asm.treated_or_managed
or asm.monitored
or asm.affected_clinical_management
or asm.influenced_treatment
or (cond and cond.treatment_evidence is not None)
or any(
term in full_context
for term in [
"treated",
"adjusted",
"insulin",
"sliding scale",
"glucose",
"blood sugar",
"continued",
"withheld",
"titrated",
"protocol",
"dose",
"infusion",
"therapy",
"monitored",
"echocardiogram",
"culture",
"stent",
"started on",
"received",
"medication",
"on medication",
"treatment",
"rx",
]
not has_no_treatment
and (
asm.treated_or_managed
or asm.monitored
or asm.affected_clinical_management
or asm.influenced_treatment
or (cond and cond.treatment_evidence is not None)
or any(
term in full_context
for term in [
"treated",
"adjusted",
"insulin",
"sliding scale",
"glucose",
"blood sugar",
"continued",
"withheld",
"titrated",
"protocol",
"dose",
"infusion",
"therapy",
"monitored",
"echocardiogram",
"culture",
"stent",
"started on",
"received",
"medication",
"on medication",
"treatment",
"rx",
]
)
)
)
if is_pmh_only and not has_inpatient_care:
if is_historical_only and not has_inpatient_care:
asm.current_relevance = False
asm.coding_candidate = False
asm.temporality = Temporality.HISTORICAL
asm.status = ConditionStatus.HISTORICAL
asm.treated_or_managed = False
asm.reason = (
"Documented solely in Past Medical History without active evaluation, "
"Documented as historical/past condition without active evaluation, "
"monitoring, or treatment during admission."
)
enforced_list.append(asm)
@@ -483,33 +505,43 @@ class ContextAndRelevanceAgent(BaseAgent):
)
# Check 3: Inpatient management indicators
has_treatment = c.treatment_evidence is not None or any(
re.search(rf"\b{re.escape(term)}\b", combined_context)
for term in [
"treated",
"started on",
"received",
"adjusted",
"insulin",
"sliding scale",
"glucose",
"blood sugar",
"continued",
"withheld",
"titrated",
"protocol",
"antibiotic",
"dose",
"infusion",
"therapy",
"surgery",
"stent",
"replacement",
"medication",
"on medication",
"treatment",
"rx",
]
has_no_treatment = bool(
re.search(
r"\b(?:no\s+(?:current\s+|active\s+)?(?:treatment|medication|rx|therapy|interventions?)|not\s+(?:currently\s+)?treated|without\s+(?:current\s+|active\s+)?(?:treatment|medication|rx|therapy))\b",
combined_context,
re.IGNORECASE,
)
)
has_treatment = not has_no_treatment and (
c.treatment_evidence is not None
or any(
re.search(rf"\b{re.escape(term)}\b", combined_context)
for term in [
"treated",
"started on",
"received",
"adjusted",
"insulin",
"sliding scale",
"glucose",
"blood sugar",
"continued",
"withheld",
"titrated",
"protocol",
"antibiotic",
"dose",
"infusion",
"therapy",
"surgery",
"stent",
"replacement",
"medication",
"on medication",
"treatment",
"rx",
]
)
)
has_monitoring = any(
re.search(rf"\b{re.escape(term)}\b", combined_context)
@@ -526,9 +558,14 @@ class ContextAndRelevanceAgent(BaseAgent):
]
)
# Check 4: Past Medical History
# Check 4: Past Medical History & Historical conditions
is_pmh = (
"PAST" in sec_upper or "PMH" in sec_upper or c.temporality == Temporality.HISTORICAL
"PAST" in sec_upper
or "PMH" in sec_upper
or c.temporality == Temporality.HISTORICAL
or "historical" in combined_context
or "childhood" in combined_context
or bool(re.search(r"\b\d+\s+years?\s+ago\b", combined_context))
)
# Check 5: Resolved
@@ -596,6 +633,8 @@ class ContextAndRelevanceAgent(BaseAgent):
affected_clinical_management=False,
influenced_treatment=False,
treatment_evidence=c.treatment_evidence,
abstain_recommended=True,
abstention_reason=AbstentionReason.EXCLUDED_BY_TEMPORALITY,
)
elif is_pmh and (has_treatment or has_monitoring):
asm = ContextAssessment(
@@ -616,6 +655,27 @@ class ContextAndRelevanceAgent(BaseAgent):
influenced_treatment=has_treatment,
treatment_evidence=c.treatment_evidence,
)
elif is_resolved and has_no_treatment:
asm = ContextAssessment(
diagnosis=c.normalized_description,
condition_id=c.condition_id,
section=c.section,
current_relevance=False,
coding_candidate=False,
status=ConditionStatus.RESOLVED,
certainty=c.certainty,
temporality=Temporality.HISTORICAL,
negation=c.negation,
evidence=c.evidence_text,
reason=f"[{c.section}] Historical resolved condition without documented inpatient evaluation, monitoring, or therapy.",
treated_or_managed=False,
monitored=False,
affected_clinical_management=False,
influenced_treatment=False,
treatment_evidence=c.treatment_evidence,
abstain_recommended=True,
abstention_reason=AbstentionReason.EXCLUDED_BY_TEMPORALITY,
)
elif is_resolved:
asm = ContextAssessment(
diagnosis=c.normalized_description,
@@ -629,11 +689,10 @@ class ContextAndRelevanceAgent(BaseAgent):
negation=c.negation,
evidence=c.evidence_text,
reason=f"[{c.section}] Condition occurred during admission and resolved following inpatient management.",
treated_or_managed=has_treatment,
monitored=has_monitoring,
treated_or_managed=True,
monitored=True,
affected_clinical_management=True,
influenced_treatment=has_treatment,
treatment_evidence=c.treatment_evidence,
influenced_treatment=True,
)
else:
# Active acute/chronic condition or suspected condition preserving uncertainty
@@ -1359,16 +1418,8 @@ class PrimarySecondaryClassifier(BaseAgent):
# should not be assigned as separate secondary codes.
for asm, score, r_list in remaining_candidates:
sec_lower = asm.diagnosis.lower()
is_integral = any(
sym in sec_lower
for sym in [
"pain", "colic", "fever", "cough", "dyspnea", "shortness of breath",
"nausea", "vomiting", "dyspepsia", "indigestion", "heartburn",
"discomfort", "wheezing", "fatigue", "malaise", "respiratory distress"
]
) and not (
any(sec_lower.endswith(sfx) or f"{sfx} " in sec_lower for sfx in ("itis", "oma", "osis"))
or any(dx in sec_lower for dx in ["syndrome", "failure", "infarction", "disease", "disorder", "calculus", "lithiasis", "ulcer"])
is_integral = HardClinicalCandidateGate.is_symptom_integral_to_primary(
asm.diagnosis, top_asm.diagnosis, asm.evidence or ""
)
if is_integral:
+463 -137
View File
@@ -37,27 +37,27 @@ logger = get_logger(__name__)
# Standard section header regexes
SECTION_PATTERNS: list[tuple[str, str]] = [
("DISCHARGE_SUMMARY", r"(?:HOSPITAL\s+DISCHARGE\s+SUMMARY|DISCHARGE\s+SUMMARY|CLINICAL\s+SUMMARY)"),
("DISCHARGE_DIAGNOSES", r"(?:DISCHARGE\s+DIAGNOS[EI]S|FINAL\s+DIAGNOS[EI]S|FINAL\s+CODING\s+SUMMARY|CODING\s+SUMMARY|FINAL\s+CODING|POSTOPERATIVE\s+DIAGNOS[EI]S|DIAGNOS[EI]S\s+ON\s+DISCHARGE|DIAGNOSIS)"),
("DISCHARGE_DIAGNOSES", r"(?:DISCHARGE\s+DIAGNOS[EI]S|FINAL\s+DIAGNOS[EI]S|FINAL\s+CODING\s+SUMMARY|CODING\s+SUMMARY|FINAL\s+CODING|POSTOPERATIVE\s+DIAGNOS[EI]S|DIAGNOS[EI]S\s+ON\s+DISCHARGE|DIAGNOSIS|ACTIVE\s+PROBLEMS|PROBLEM\s+LIST|ACTIVE\s+ISSUES)"),
("PRINCIPAL_DIAGNOSIS", r"(?:PRINCIPAL\s+DIAGNOS[EI]S|PRIMARY\s+DIAGNOS[EI]S|ADMITTING\s+DIAGNOS[EI]S|ADMISSION\s+DIAGNOS[EI]S)"),
("SECONDARY_DIAGNOSES", r"(?:SECONDARY\s+DIAGNOS[EI]S|ADDITIONAL\s+DIAGNOS[EI]S|CO-?MORBIDITIES|OTHER\s+DIAGNOS[EI]S)"),
("CHIEF_COMPLAINT", r"(?:CHIEF\s+COMPLAINT|REASON\s+FOR\s+ADMISSION|PRESENTING\s+COMPLAINT|ADMITTED\s+FOR)"),
("HISTORY_OF_PRESENT_ILLNESS", r"(?:HISTORY\s+OF\s+PRESENT\s+ILLNESS|HPI)"),
("PHYSICAL_EXAMINATION", r"(?:CLINICAL\s+EXAMINATION|PHYSICAL\s+EXAMINATION|ON\s+EXAMINATION|GENERAL\s+EXAMINATION|SYSTEMIC\s+EXAMINATION)"),
("HISTORY_OF_PRESENT_ILLNESS", r"(?:HISTORY\s+OF\s+PRESENT\s+ILLNESS|HPI|SUBJECTIVE)"),
("PHYSICAL_EXAMINATION", r"(?:CLINICAL\s+EXAMINATION(?:\s+ON\s+ADMISSION)?|PHYSICAL\s+EXAMINATION(?:\s+ON\s+ADMISSION)?|ON\s+EXAMINATION|GENERAL\s+EXAMINATION|SYSTEMIC\s+EXAMINATION)"),
("HOSPITAL_COURSE", r"(?:HOSPITAL\s+COURSE|SUMMARY\s+OF\s+HOSPITAL\s+STAY|BRIEF\s+SUMMARY\s+OF\s+HOSPITAL\s+COURSE|COURSE\s+IN\s+(?:THE\s+)?HOSPITAL(?:\s+AND\s+DISCUSSION)?|CLINICAL\s+COURSE)"),
("COMPLICATIONS", r"(?:HOSPITAL\s+COMPLICATIONS|IN-?HOSPITAL\s+COMPLICATIONS|COMPLICATIONS|ADVERSE\s+EVENTS)"),
("PROCEDURES", r"(?:PROCEDURES\s+PERFORMED|OPERATIVE\s+PROCEDURES|SURGICAL\s+PROCEDURES|MAJOR\s+PROCEDURES|PROCEDURES)"),
("OPERATIVE_FINDINGS", r"(?:INTRAOPERATIVE\s+FINDINGS|OPERATIVE\s+FINDINGS|SURGICAL\s+FINDINGS|INTRA-?OPERATIVE\s+FINDINGS|OPERATIVE\s+NOTE\s+FINDINGS|FINDINGS)"),
("PROCEDURES", r"(?:PROCEDURES?\s+DETAILS|PROCEDURE\s+PERFORMED|PROCEDURES?\s+PERFORMED|OPERATIVE\s+PROCEDURES?|SURGICAL\s+PROCEDURES?|MAJOR\s+PROCEDURES?|PROCEDURES|SURGICAL\s+INTERVENTIONS?|OPERATIONS?)"),
("OPERATIVE_FINDINGS", r"(?:INTRAOPERATIVE\s+FINDINGS?|OPERATIVE\s+FINDINGS?|SURGICAL\s+FINDINGS?|INTRA-?OPERATIVE\s+FINDINGS?|OPERATIVE\s+NOTE\s+FINDINGS?|FINDINGS?)"),
("ONCOLOGY_BIOMARKERS", r"(?:BIOMARKERS\s*(?:&|AND)?\s*RECEPTOR\s+STATUS|PATHOLOGY(?:\s+REPORT)?|HISTOPATHOLOGY|RECEPTOR\s+STATUS|IMMUNOHISTOCHEMISTRY|TUMOR\s+CHARACTERISTICS)"),
("PAST_MEDICAL_HISTORY", r"(?:PAST\s+MEDICAL\s+HISTORY|PMH|MEDICAL\s+HISTORY|BACKGROUND\s+HISTORY|PAST\s+HISTORY|PERSONAL\s+HISTORY)"),
("PAST_SURGICAL_HISTORY", r"(?:PAST\s+SURGICAL\s+HISTORY|PSH|SURGICAL\s+HISTORY)"),
("INVESTIGATIONS", r"(?:RELEVANT\s+INVESTIGATIONS|INVESTIGATIONS|LABORATORY\s+DATA|PERTINENT\s+LABS|DIAGNOSTIC\s+STUDIES|IMAGING|RADIOLOGY|ECHOCARDIOGRAM|CT\s+SCAN|ULTRASOUND|MRI)"),
("INVESTIGATIONS", r"(?:RELEVANT\s+INVESTIGATIONS?|INVESTIGATIONS?|LABORATORY\s+DATA|LABORATORY\s+INVESTIGATIONS?|PERTINENT\s+LABS|DIAGNOSTIC\s+STUDIES|IMAGING|RADIOLOGY|ECHOCARDIOGRAM|CT\s+SCAN|CT\s+PNS|ULTRASOUND|MRI)"),
("MICROBIOLOGY", r"(?:MICROBIOLOGY|CULTURES?|BLOOD\s+CULTURES?|URINE\s+CULTURES?|SPUTUM\s+CULTURES?|CULTURE\s+AND\s+SENSITIVITY|MICROBIOLOGICAL\s+STUDIES)"),
("ALLERGIES", r"(?:DRUG\s+ALLERGIES|ALLERGIES|ALLERGIC\s+HISTORY|ALLERGIC\s+REACTIONS?)"),
("MEDICATIONS", r"(?:DISCHARGE\s+MEDICATIONS|MEDICATIONS\s+ON\s+DISCHARGE|ACTIVE\s+MEDICATIONS|MEDICATIONS|CURRENT\s+MEDICATIONS)"),
("ALLERGIES", r"(?:DRUG\s+ALLERG(?:Y|IES)|ALLERG(?:Y|IES)|ALLERGIC\s+HISTORY|ALLERGIC\s+REACTIONS?)"),
("MEDICATIONS", r"(?:DISCHARGE\s+MEDICATIONS?|MEDICATIONS?\s+ON\s+DISCHARGE|ACTIVE\s+MEDICATIONS?|MEDICATIONS?|CURRENT\s+MEDICATIONS?)"),
("PERTINENT_NEGATIVES", r"(?:PERTINENT\s+NEGATIVES|NEGATIONS(?:\s*/\s*AUDIT)?|DOCUMENTATION\s+AUDIT)"),
("ASSESSMENT", r"(?:ASSESSMENT\s+AND\s+PLAN|ASSESSMENT|IMPRESSION)"),
("ASSESSMENT", r"(?:ASSESSMENT\s*(?:&|AND)?\s*PLAN|ASSESSMENT|CLINICAL\s+IMPRESSION|IMPRESSION|A\s*/\s*P)"),
("PLAN", r"(?:DISCHARGE\s+PLAN|TREATMENT\s+PLAN|PLAN)"),
("DISCHARGE_INSTRUCTIONS", r"(?:DISCHARGE\s+INSTRUCTIONS|DISPOSITION|DISCHARGE\s+CONDITION|FOLLOW-?UP)"),
("DISCHARGE_INSTRUCTIONS", r"(?:STATUS\s+AT\s+DISCHARGE|CONDITION\s+AT\s+DISCHARGE|DISCHARGE\s+STATUS|DISCHARGE\s+INSTRUCTIONS|DISPOSITION|DISCHARGE\s+CONDITION|FOLLOW-?UP|SPECIAL\s+NEEDS|IN\s+CASE\s+OF\s+EMERGENCY)"),
]
NEGATION_CUES = [
@@ -143,6 +143,12 @@ class SectionSegmenter:
for sec_name, pat_str in SECTION_PATTERNS:
regex = re.compile(rf"(?:^|\n|[.;]\s*|\b(?=[A-Z\s]{{4,}}:))\s*({pat_str})\s*(?::|--|\n)", re.IGNORECASE)
for m in regex.finditer(text):
# Filter out document encounter metadata lines e.g. "Date of Admission", "Date of Procedure"
line_start = text.rfind("\n", 0, m.start(1))
line_start = 0 if line_start == -1 else line_start + 1
pre_text = text[line_start:m.start(1)].strip().lower()
if pre_text.startswith("date of") or pre_text.startswith("time of") or pre_text.startswith("type of"):
continue
matches.append({
"section_name": sec_name,
"header_text": m.group(1).strip(),
@@ -272,7 +278,23 @@ class EvidenceFirstFactExtractor:
existing.role = DiagnosisRole.PRIMARY
if item.primary_justification:
existing.primary_justification = item.primary_justification
if item.temporality == Temporality.CURRENT:
if item.temporality == Temporality.HISTORICAL:
is_existing_active = (
existing.temporality == Temporality.CURRENT
or existing.role in (DiagnosisRole.PRIMARY, DiagnosisRole.SECONDARY)
or any(ev.section in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES", "PRINCIPAL_DIAGNOSIS", "SECONDARY_DIAGNOSES", "ASSESSMENT", "ASSESSMENT_PLAN") for ev in existing.evidence)
or existing.treatment_relevance > 0
or existing.procedure_relevance > 0
)
if not is_existing_active:
existing.temporality = Temporality.HISTORICAL
existing.role = DiagnosisRole.HISTORICAL
existing.is_authorized = False
existing.clinical_relevance = 0.0
existing.encounter_relevance = 0.0
existing.scores.encounter_relevance = 0.0
existing.scores.admitting_score = -50.0
elif item.temporality == Temporality.CURRENT:
existing.temporality = Temporality.CURRENT
if existing.role == DiagnosisRole.HISTORICAL:
existing.role = DiagnosisRole.SECONDARY
@@ -336,8 +358,13 @@ class EvidenceFirstFactExtractor:
proc_lines = [l.strip() for l in sec.content.split("\n") if l.strip()]
for l in proc_lines:
l_clean = re.sub(r"^\d+[\.\)\-]\s*", "", l).strip()
l_clean = re.sub(r"^(?:procedures?\s*(?:performed|done|details)?\s*[:\-–—]\s*)", "", l_clean, flags=re.IGNORECASE).strip()
if len(l_clean) >= 3:
self._extracted_procedures.append(l_clean)
sub_procs = re.split(r"\s*(?:\+|;)\s*|\s+and\s+", l_clean)
for sp in sub_procs:
sp_c = re.sub(r"\s*(?:side\s*:\s*[^\n]+|surgeon\s*:\s*[^\n]+|anaesthesiologist\s*:\s*[^\n]+).*$", "", sp, flags=re.IGNORECASE).strip()
if len(sp_c) >= 3 and not re.match(r"^(?:side|surgeon|anaesthesiologist|type\s+of\s+anaesthesia|ga|general\s+anaesthesia)\b", sp_c, re.IGNORECASE):
self._extracted_procedures.append(sp_c)
items = self._parse_procedure_indications(sec.content, sec)
for item in items:
self._register_candidate(candidates_by_key, item)
@@ -350,9 +377,19 @@ class EvidenceFirstFactExtractor:
for item in items:
self._register_candidate(candidates_by_key, item)
# Phase 7: General Narrative Sections (General, discharge summary narrative, HPI)
# Phase 7: Narrative, Examination, Oncology, and unmapped clinical sections
handled_non_narrative = {
"DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES", "PRINCIPAL_DIAGNOSIS", "SECONDARY_DIAGNOSES",
"ASSESSMENT", "ASSESSMENT_PLAN", "CHIEF_COMPLAINT", "PAST_MEDICAL_HISTORY",
"PAST_SURGICAL_HISTORY", "HOSPITAL_COURSE", "COMPLICATIONS", "INVESTIGATIONS",
"MICROBIOLOGY", "PROCEDURES", "OPERATIVE_FINDINGS", "ALLERGIES", "MEDICATIONS",
"DISCHARGE_MEDICATIONS", "PERTINENT_NEGATIVES", "PLAN", "DISCHARGE_INSTRUCTIONS"
}
for sec in sections:
if sec.section_name in ("GENERAL", "DISCHARGE_SUMMARY", "HISTORY_OF_PRESENT_ILLNESS"):
if (
sec.section_name in ("GENERAL", "DISCHARGE_SUMMARY", "HISTORY_OF_PRESENT_ILLNESS", "PHYSICAL_EXAMINATION", "ONCOLOGY_BIOMARKERS")
or sec.section_name not in handled_non_narrative
):
items = self._parse_narrative_items(sec.content, sec)
for item in items:
self._register_candidate(candidates_by_key, item)
@@ -482,33 +519,67 @@ class EvidenceFirstFactExtractor:
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
# Skip absence statements, treatment instructions, and cross-reference boilerplate
# Skip absence statements, treatment instructions, non-clinical activities, generic procedures, and cross-reference boilerplate
if (
HardClinicalCandidateGate.is_absence_statement(sent_clean)
or HardClinicalCandidateGate.is_treatment_instruction(sent_clean)
or HardClinicalCandidateGate.is_non_clinical_activity(sent_clean)
or HardClinicalCandidateGate.is_generic_procedure(sent_clean)
or re.search(r"\b(?:symptoms?|complaints?)\s+described\s+in\b|\bdescribed\s+in\s+(?:the\s+)?final\s+diagnosis\b|\babove\s+mentioned\s+complaints\b", sent_clean, re.IGNORECASE)
):
continue
# Pattern 2: Explicit admission / diagnosis / condition clauses
# Pattern 2: Clinical condition and admission clauses
adm_match = re.search(
r"(?:patient\s+(?:was\s+)?(?:admitted\s+(?:with|for|in)|presented\s+with|diagnosed\s+with|treated\s+for|has|had)|admitted\s+(?:with|for|in)|impression\s*:\s*)\s+([^.]+)",
r"(?:patient\s+(?:was\s+)?(?:admitted\s+(?:under\s+[a-z\s]+\s+)?(?:with|for|in)|presented\s+with|diagnosed\s+with|treated\s+for|managed\s+for|evaluated\s+for|evaluation\s+of|found\s+to\s+have|noted\s+to\s+have|has|had)|admitted\s+(?:under\s+[a-z\s]+\s+)?(?:with|for|in)|presented\s+with|diagnosed\s+with|evaluation\s+of|evaluated\s+for|impression\s*:\s*|clinical\s+impression\s*:\s*|assessment\s*:\s*|active\s+problems?\s*:\s*|secondary\s+diagnos[ei]s\s*:\s*|diagnos[ei]s\s*:\s*|consistent\s+with\s+|confirmed\s+to\s+have\s+|known\s+case\s+of\s+|also\s+(?:found\s+to\s+have|noted\s+to\s+have|has|had|suffers?\s+from)|found\s+to\s+have|noted\s+to\s+have|suffers?\s+from|history\s+of\s+|hx\s+of\s+)\s+([^.]+)",
sent_clean,
re.IGNORECASE,
)
is_adm_clause = False
if adm_match:
clause = adm_match.group(1).strip()
is_adm_clause = True
else:
diag_prefix_m = re.search(
r"^(?:also\s+(?:found\s+to\s+have|noted\s+to\s+have|has|had|suffers?\s+from)|found\s+to\s+have|noted\s+to\s+have|noted\s+to\s+suffer\s+from|suffers?\s+from|developed|complicated\s+by|secondary\s+to|underwent\s+.*?\s+for|history\s+of|hx\s+of|past\s+medical\s+history\s*:?|pmh\s*:?|(?:ct|mri|x[\s\-]?ray|cxr|ultrasound|usg|echo|ekg|ecg)\s+(?:showed|revealed|demonstrated|confirmed)|noted|demonstrated|confirmed|showed|revealed)\s+([^.]+)",
sent_clean,
re.IGNORECASE,
)
if diag_prefix_m:
clause = diag_prefix_m.group(1).strip()
else:
clause = sent_clean
if clause:
clause = re.sub(
r"^(?:nose|chest|cvs|cns|rs|pa|abdomen|eye|ear|throat|skin|neck|general|local|systemic)\s*:\s*",
"",
clause,
flags=re.IGNORECASE,
).strip()
clause = re.sub(
r"^(?:(?:several|\d+)\s+(?:days?|weeks?|months?|hours?)\s+of\s+)",
"",
clause,
flags=re.IGNORECASE,
).strip()
for tail_delim in [" on ", " treated with ", " managed with ", " requiring ", " with good response", " with symptom"]:
clause = re.sub(
r"^(?:(?:for\s+)?evaluation\s+of|(?:for\s+)?eval\s+of|management\s+of|workup\s+of)\s+",
"",
clause,
flags=re.IGNORECASE,
).strip()
for tail_delim in [" treated with ", " managed with ", " requiring ", " with good response", " with symptom", " while ", " during "]:
if tail_delim in clause.lower():
idx = clause.lower().find(tail_delim)
clause = clause[:idx].strip()
on_med_m = re.search(r"\s+on\s+(?:medication|antibiotic|iv\b|steroid|infusion|dialysis|heparin|insulin|pressor|aspirin|metformin|lisinopril|lasix|statin|chemo)", clause, re.IGNORECASE)
if on_med_m:
clause = clause[:on_med_m.start()].strip()
clause = re.sub(r"\s+(?:over|across)\s+(?:the\s+)?[a-z\s]+(?=,|\s+and\s+(?:acute|epigastric|ecg|[a-z]+\s+pain|[a-z]+\s+discomfort)|$)", "", clause, flags=re.IGNORECASE).strip()
# Causal admission: "initiation of chemotherapy for DLBCL" -> "DLBCL"
causal_m = re.search(
r"(?:(?:initiation|cycle\s+\d+|course)\s+of\s+)?(?:chemotherapy|immunotherapy|radiation|treatment|therapy|infusion|management|stenting|surgery)\s+(?:for|of)\s+([^.,;\n]+)",
@@ -533,6 +604,21 @@ class EvidenceFirstFactExtractor:
continue
polarity, certainty = self._assess_polarity_and_certainty(sent_clean)
is_narrative_historical = bool(
re.search(
r"\b(?:historical\s*/\s*resolved|historical\b|completely\s+resolved|resolved\b|prior\s+history|childhood\s+asthma|no\s+current\s+treatment|no\s+current\s+medications?|\d+\s+years?\s+ago)\b",
sent_clean,
re.IGNORECASE,
)
)
cand_temp = Temporality.HISTORICAL if is_narrative_historical else Temporality.CURRENT
cand_role = (
DiagnosisRole.HISTORICAL
if is_narrative_historical
else (DiagnosisRole.PRIMARY if is_adm_clause else DiagnosisRole.SECONDARY)
)
cand_auth = (polarity != NegationStatus.NEGATED) and (not is_narrative_historical)
cand_rel = 0.0 if is_narrative_historical else 1.0
acuity = self._detect_acuity(sc)
ev = StructuredEvidence(
text=sent_clean,
@@ -540,34 +626,39 @@ class EvidenceFirstFactExtractor:
sentence=sent_clean,
polarity=polarity,
certainty=certainty,
temporality=Temporality.CURRENT,
temporality=cand_temp,
evidence_type=EvidenceType.DISCHARGE_SUMMARY,
clinical_relevance=1.0,
clinical_relevance=cand_rel,
)
admit_score = (
-50.0
if is_narrative_historical
else ((5.0 if is_adm_clause else 1.0) + (1.0 if acuity == Acuity.ACUTE else 0.0))
)
scores = MultiDimensionalScore(
evidence_score=1.0,
diagnostic_certainty=1.0 if certainty == Certainty.CONFIRMED else 0.8,
encounter_relevance=1.0,
encounter_relevance=cand_rel,
role_confidence=1.0,
semantic_match=1.0,
specificity_match=1.0,
contradiction_penalty=1.0 if polarity == NegationStatus.NEGATED else 0.0,
admitting_score=5.0 + (1.0 if acuity == Acuity.ACUTE else 0.0),
admitting_score=admit_score,
)
cand = ClinicalDiagnosisCandidate(
raw_term=sc,
normalized_diagnosis=sc,
role=DiagnosisRole.PRIMARY,
role=cand_role,
certainty=certainty,
temporality=Temporality.CURRENT,
temporality=cand_temp,
clinical_attributes=cand_attrs,
evidence=[ev],
evidence_strength=1.0,
clinical_relevance=1.0,
encounter_relevance=1.0,
clinical_relevance=cand_rel,
encounter_relevance=cand_rel,
scores=scores,
is_authorized=polarity != NegationStatus.NEGATED,
classification_reason="Identified as encounter diagnosis in clinical narrative",
is_authorized=cand_auth,
classification_reason="Historical or resolved condition documented in narrative" if is_narrative_historical else "Identified as encounter diagnosis in clinical narrative",
)
candidates.append(cand)
@@ -835,17 +926,19 @@ class EvidenceFirstFactExtractor:
has_active_rx = bool(
re.search(
r"\b(?:on\s+medication|on\s+treatment|on\s+rx|treated|managed)\b",
r"\b(?:on\s+[a-z0-9]+|taking\s+[a-z0-9]+|receiving\s+[a-z0-9]+|treated|managed|controlled|under\s+treatment|active\s+rx|prescribed|daily|mg|tab|tablet|inj|injection|infusion|inhaler|dialysis)\b",
cleaned_preamble,
re.IGNORECASE,
)
)
cleaned_concept = re.sub(
r",?\s*\b(?:on\s+medication|on\s+treatment|on\s+rx)\b.*$",
r",?\s*\b(?:on\s+medication|on\s+treatment|on\s+rx|treated\s+with|managed\s+with)\b.*$",
"",
cleaned_preamble,
flags=re.IGNORECASE,
).strip()
if not cleaned_concept or len(cleaned_concept) < 3:
cleaned_concept = cleaned_preamble
sub_items = re.split(r"\s+and\s+|\s*,\s*", cleaned_concept)
for sub_item in sub_items:
@@ -924,7 +1017,13 @@ class EvidenceFirstFactExtractor:
sentences = [s.strip() for s in re.split(r"(?<=[.!?\n])\s+", cleaned) if s.strip()]
for sent in sentences:
if len(sent) < 5 or HardClinicalCandidateGate.is_absence_statement(sent) or HardClinicalCandidateGate.is_treatment_instruction(sent):
if (
len(sent) < 5
or HardClinicalCandidateGate.is_absence_statement(sent)
or HardClinicalCandidateGate.is_treatment_instruction(sent)
or HardClinicalCandidateGate.is_non_clinical_activity(sent)
or HardClinicalCandidateGate.is_generic_procedure(sent)
):
continue
# Pattern A: Complication cues: "course was complicated by [X]", "complicated by [X]", "developed [X]", "went into [X]", "manifested [X]"
@@ -939,76 +1038,124 @@ class EvidenceFirstFactExtractor:
sent,
re.IGNORECASE,
)
# Pattern C: Specialist evaluations, consultations, and clinical conclusions
eval_match = re.search(
r"(?:(?:[a-z]+\s+)?(?:evaluation|consultation|consult|assessment|review)\s+(?:concluded|revealed|showed|noted|found|confirmed|diagnosed|suggested)\s+(?:that\s+)?|concluded\s+that\s+|noted\s+to\s+have\s+|found\s+to\s+have\s+|manifested\s+(?:with\s+)?)\s*([^.]+)",
sent,
re.IGNORECASE,
)
# Pattern D: Additional or concurrent conditions documented during course
additional_match = re.search(
r"(?:with\s+additional|and\s+additional|additional|concurrent|superimposed)\s+([^.]+)",
sent,
re.IGNORECASE,
)
matched_clauses: list[str] = []
if comp_match:
matched_clauses.append(comp_match.group(1).strip())
if treat_match:
matched_clauses.append(treat_match.group(1).strip())
if eval_match:
matched_clauses.append(eval_match.group(1).strip())
if additional_match:
matched_clauses.append(additional_match.group(1).strip())
if not matched_clauses:
gen_match = re.search(
r"(?:patient\s+(?:had|experienced|manifested|presented\s+with|developed)|also\s+(?:had|noted|developed|experienced|found)|showed|revealed|demonstrated|confirmed|diagnosed\s+as)\s+([^.]+)",
sent,
re.IGNORECASE,
)
if gen_match:
matched_clauses.append(gen_match.group(1).strip())
for clause in matched_clauses:
# Strip trailing management phrases from clause
for tail in [" requiring ", " managed with ", " treated with ", " on ", " with good response", " with symptom", " and was ", " and received "]:
for tail in [
" and advised ", " advised ", " requiring ", " managed with ",
" treated with ", " with good response", " with symptom",
" and was ", " and received ", " prescribed "
]:
if tail in clause.lower():
idx = clause.lower().find(tail)
clause = clause[:idx].strip()
# Split compound items e.g. "septic shock and diabetic ketoacidosis", "acute kidney injury secondary to dehydration"
sub_items = self._split_compound_clinical_phrase(clause)
for item_str in sub_items:
item_str = item_str.strip()
item_str = re.sub(r"^(?:a|an|the)\s+", "", item_str, flags=re.IGNORECASE).strip()
item_str, attrs = self._extract_concept_and_attributes(item_str)
if len(item_str) < 3:
continue
on_med_m = re.search(r"\s+on\s+(?:medication|antibiotic|iv\b|steroid|infusion|dialysis|heparin|insulin|pressor|aspirin|metformin|lisinopril|lasix|statin|chemo)", clause, re.IGNORECASE)
if on_med_m:
clause = clause[:on_med_m.start()].strip()
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(item_str, sent)
if not is_valid:
continue
# Decompose 'with additional [X]' or 'concurrent [X]' into multiple clauses
clause_chunks = re.split(
r",?\s*(?:with\s+additional|and\s+additional|additional|concurrent|superimposed)\s+",
clause,
flags=re.IGNORECASE,
)
for chunk in clause_chunks:
clean_chunk = chunk.strip()
clean_chunk = re.sub(r"^(?:the\s+)?(?:rash\s+was\s+)?", "", clean_chunk, flags=re.IGNORECASE).strip()
clean_chunk = re.sub(r"\s+in\s+nature$", "", clean_chunk, flags=re.IGNORECASE).strip()
if clean_chunk.lower() == "urticarial":
clean_chunk = "urticaria"
# Strip anatomical location qualifiers e.g. "over the wrists", "on the chest"
clean_chunk = re.sub(r"\s+(?:over|on)\s+(?:the\s+)?[a-z\s]+(?=\s+due\s+to|\s*$)", "", clean_chunk, flags=re.IGNORECASE).strip()
polarity, certainty = self._assess_polarity_and_certainty(sent)
acuity = self._detect_acuity(item_str)
laterality = self._detect_laterality(item_str)
if laterality and laterality != Laterality.UNSPECIFIED and "laterality" not in attrs:
attrs["laterality"] = laterality.value
# Split compound items e.g. "septic shock and diabetic ketoacidosis", "acute kidney injury secondary to dehydration"
sub_items = self._split_compound_clinical_phrase(clean_chunk)
for item_str in sub_items:
item_str = item_str.strip()
item_str = re.sub(r"^(?:a|an|the)\s+", "", item_str, flags=re.IGNORECASE).strip()
item_str, attrs = self._extract_concept_and_attributes(item_str)
if len(item_str) < 3:
continue
ev = StructuredEvidence(
text=sent,
section=sec.section_name,
sentence=sent,
polarity=polarity,
certainty=certainty,
temporality=Temporality.CURRENT,
evidence_type=EvidenceType.HOSPITAL_COURSE,
clinical_relevance=1.0,
)
scores = MultiDimensionalScore(
evidence_score=1.0,
diagnostic_certainty=1.0 if certainty == Certainty.CONFIRMED else 0.8,
encounter_relevance=1.0,
role_confidence=1.0,
semantic_match=1.0,
specificity_match=1.0,
admitting_score=4.0 + (1.0 if acuity == Acuity.ACUTE else 0.0),
)
cand = ClinicalDiagnosisCandidate(
raw_term=item_str,
normalized_diagnosis=item_str,
role=DiagnosisRole.SECONDARY,
certainty=certainty,
temporality=Temporality.CURRENT,
assertion_status=AssertionStatus.CONFIRMED if certainty == Certainty.CONFIRMED else AssertionStatus.SUSPECTED,
clinical_attributes=attrs,
evidence=[ev],
evidence_strength=1.0,
clinical_relevance=1.0,
encounter_relevance=1.0,
treatment_relevance=1.0,
scores=scores,
is_authorized=polarity != NegationStatus.NEGATED,
classification_reason=f"Active inpatient complication/event in {sec.section_name}",
)
candidates.append(cand)
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(item_str, sent)
if not is_valid:
continue
polarity, certainty = self._assess_polarity_and_certainty(sent)
acuity = self._detect_acuity(item_str)
laterality = self._detect_laterality(item_str)
if laterality and laterality != Laterality.UNSPECIFIED and "laterality" not in attrs:
attrs["laterality"] = laterality.value
ev = StructuredEvidence(
text=sent,
section=sec.section_name,
sentence=sent,
polarity=polarity,
certainty=certainty,
temporality=Temporality.CURRENT,
evidence_type=EvidenceType.HOSPITAL_COURSE,
clinical_relevance=1.0,
)
scores = MultiDimensionalScore(
evidence_score=1.0,
diagnostic_certainty=1.0 if certainty == Certainty.CONFIRMED else 0.8,
encounter_relevance=1.0,
role_confidence=1.0,
semantic_match=1.0,
specificity_match=1.0,
admitting_score=4.0 + (1.0 if acuity == Acuity.ACUTE else 0.0),
)
cand = ClinicalDiagnosisCandidate(
raw_term=item_str,
normalized_diagnosis=item_str,
role=DiagnosisRole.SECONDARY,
certainty=certainty,
temporality=Temporality.CURRENT,
assertion_status=AssertionStatus.CONFIRMED if certainty == Certainty.CONFIRMED else AssertionStatus.SUSPECTED,
clinical_attributes=attrs,
evidence=[ev],
evidence_strength=1.0,
clinical_relevance=1.0,
encounter_relevance=1.0,
treatment_relevance=1.0,
scores=scores,
is_authorized=polarity != NegationStatus.NEGATED,
classification_reason=f"Active inpatient complication/event in {sec.section_name}",
)
candidates.append(cand)
return candidates
@@ -1028,7 +1175,13 @@ class EvidenceFirstFactExtractor:
sentences = [s.strip() for s in re.split(r"(?<=[.!?\n])\s+", cleaned) if s.strip()]
for sent in sentences:
if len(sent) < 5 or HardClinicalCandidateGate.is_absence_statement(sent) or HardClinicalCandidateGate.is_treatment_instruction(sent):
if (
len(sent) < 5
or HardClinicalCandidateGate.is_absence_statement(sent)
or HardClinicalCandidateGate.is_treatment_instruction(sent)
or HardClinicalCandidateGate.is_non_clinical_activity(sent)
or HardClinicalCandidateGate.is_generic_procedure(sent)
):
continue
findings_clauses: list[str] = []
@@ -1139,7 +1292,13 @@ class EvidenceFirstFactExtractor:
lines = [line.strip() for line in cleaned.split("\n") if line.strip()]
for line in lines:
line_clean = re.sub(r"^\d+[\.\)\-]\s*", "", line).strip()
if len(line_clean) < 5 or HardClinicalCandidateGate.is_absence_statement(line_clean) or HardClinicalCandidateGate.is_treatment_instruction(line_clean):
if (
len(line_clean) < 5
or HardClinicalCandidateGate.is_absence_statement(line_clean)
or HardClinicalCandidateGate.is_treatment_instruction(line_clean)
or HardClinicalCandidateGate.is_non_clinical_activity(line_clean)
or HardClinicalCandidateGate.is_generic_procedure(line_clean)
):
continue
# Match: "[Procedure] for [Condition]" or "Indication: [Condition]"
@@ -1433,6 +1592,77 @@ class EvidenceFirstFactExtractor:
evidence=text[:200],
)
@staticmethod
def _split_adjacent_clinical_conditions(text: str) -> list[str]:
"""Decompose phrases containing adjacent independent clinical conditions.
Clinical principles:
1. When multiple distinct diagnoses appear juxtaposed without commas or conjunctions
(e.g., 'Urticaria Gastritis', 'Hypertension Diabetes Mellitus', 'Asthma Bronchitis'),
each valid independent clinical entity must be separated.
2. A split is rejected if the preceding word is an adjectival modifier
(e.g., 'acute', 'chronic', 'hypertensive', 'allergic', 'ischemic', 'ulcerative', 'contact')
which qualifies the subsequent disease.
3. A split is rejected if the subsequent part is merely a generic nosological continuation
(e.g., 'disease', 'disorder', 'syndrome', 'failure', 'mellitus', 'type 2').
4. Both decomposed halves must independently satisfy HardClinicalCandidateGate validation.
"""
words = text.strip().split()
if len(words) < 2:
return [text.strip()]
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
adjective_modifiers = {
"acute", "chronic", "subacute", "severe", "mild", "moderate",
"primary", "secondary", "recurrent", "refractory", "hypertensive",
"ischemic", "diabetic", "allergic", "ulcerative", "obstructive",
"atherosclerotic", "rheumatoid", "infectious", "congestive",
"dilated", "hypertrophic", "interstitial", "systemic", "autoimmune",
"invasive", "infiltrating", "metastatic", "benign", "malignant",
"idiopathic", "acquired", "congenital", "hereditary", "familial",
"focal", "diffuse", "bilateral", "unilateral", "left", "right",
"anterior", "posterior", "upper", "lower", "type", "grade", "stage",
"contact", "external", "internal", "deviated", "ruptured", "perforated",
"obstructed", "calcified", "stenosed", "thrombosed", "infarcted",
"fractured", "displaced", "sprained", "infected", "inflamed", "congested",
"enlarged", "narrowed", "thickened", "elevated", "depressed", "collapsed",
"atrophic", "hypoplastic", "aplastic", "gangrenous", "necrotic",
"nasal", "renal", "cardiac", "pulmonary", "hepatic", "gastric", "splenic",
"cerebral", "spinal", "thoracic", "abdominal", "pelvic", "femoral", "tibial",
"coronary", "aortic", "mitral", "tricuspid", "carotid", "jugular", "ocular",
"retinal", "aural", "otic", "vertebral", "lumbar", "cervical", "cranial",
"facial", "oral", "anal", "rectal", "colonic", "duodenal", "jejunal", "ileal",
"esophageal", "bronchial", "alveolar", "pancreatic", "biliary", "vesical",
"urethral", "ureteral", "prostatic", "testicular", "ovarian", "uterine",
"vaginal", "vulvar", "peritoneal", "pleural", "pericardial",
}
generic_suffix_nouns = {
"disease", "diseases", "disorder", "disorders", "syndrome", "syndromes",
"failure", "insufficiency", "mellitus", "infarction", "dysfunction",
"type 1", "type 2", "type i", "type ii", "status",
}
for i in range(1, len(words)):
p1 = " ".join(words[:i]).strip()
p2 = " ".join(words[i:]).strip()
last_word_p1 = words[i - 1].lower()
if last_word_p1 in adjective_modifiers:
continue
if p2.lower() in generic_suffix_nouns:
continue
v1, _ = HardClinicalCandidateGate.evaluate_candidate(p1)
v2, _ = HardClinicalCandidateGate.evaluate_candidate(p2)
if v1 and v2:
return [p1] + EvidenceFirstFactExtractor._split_adjacent_clinical_conditions(p2)
return [text.strip()]
def _split_compound_clinical_phrase(self, phrase: str) -> list[str]:
"""Split compound clinical phrases into independent clinical concepts.
@@ -1505,9 +1735,21 @@ class EvidenceFirstFactExtractor:
for i, m in enumerate(abbrev_matches):
masked = masked.replace(m.group(0), f"__ORGANISM_{i}__")
# Mask plus signs attached to receptor/immunology markers (e.g., CD4+, HER2+, ER+, PR+)
plus_matches = list(re.finditer(r"\b([A-Za-z0-9\-]+)\+", masked))
for i, pm in enumerate(plus_matches):
if pm.group(1).lower() in ("cd4", "cd8", "her2", "er", "pr", "egfr", "bcl2"):
masked = masked.replace(pm.group(0), f"__PLUS_MARKER_{i}__")
# 1. Connectors that unconditionally separate independent clinical entities
# Split on list delimiters: plus signs (+), semicolons (;), ampersands (&), and slashes (/) separating independent entities
list_delims_pattern = r"\s*(?:\+|;|\s+&\s+|\s+/\s+)\s*"
raw_splits = [p.strip() for p in re.split(list_delims_pattern, masked, flags=re.IGNORECASE) if p.strip()]
chunks: list[str] = []
causal_pattern = r",?\s*\b(?:complicated\s+by|secondary\s+to|due\s+to|resulting\s+in|manifested\s+by)\b\s*"
chunks = re.split(causal_pattern, masked, flags=re.IGNORECASE)
for seg in raw_splits:
chunks.extend([c.strip() for c in re.split(causal_pattern, seg, flags=re.IGNORECASE) if c.strip()])
# Standard ICD combination manifestations where "with" should NEVER be split
combo_manifestation_patterns = [
@@ -1541,7 +1783,21 @@ class EvidenceFirstFactExtractor:
if co_cond:
refined_chunks.append(co_cond)
else:
refined_chunks.append(chunk)
generic_with_m = re.search(r",?\s*\bwith\s+([A-Za-z0-9\s\-]+)$", chunk, re.IGNORECASE)
if generic_with_m and not is_combo_manifestation:
pre_with = chunk[:generic_with_m.start()].strip()
post_with = generic_with_m.group(1).strip()
pre_with_clean = re.sub(r"\s+to\s+(?:the\s+)?(?:left|right|bilateral)$", "", pre_with, flags=re.IGNORECASE).strip()
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
v_pre, _ = HardClinicalCandidateGate.evaluate_candidate(pre_with_clean or pre_with)
v_post, _ = HardClinicalCandidateGate.evaluate_candidate(post_with)
if v_pre and v_post:
refined_chunks.append(pre_with_clean or pre_with)
refined_chunks.append(post_with)
else:
refined_chunks.append(chunk)
else:
refined_chunks.append(chunk)
# 2. Split chunks on " and " when connecting distinct clinical entities
final_items: list[str] = []
@@ -1555,12 +1811,14 @@ class EvidenceFirstFactExtractor:
else:
final_items.append(item.strip().strip(",; "))
# Restore masked organism abbreviations and clean timing/procedural context (Section 8 & 9)
# Restore masked organism abbreviations, clean timing/procedural context, and decompose adjacent conditions
restored: list[str] = []
for res_item in final_items:
res = res_item
for i, m in enumerate(abbrev_matches):
res = res.replace(f"__ORGANISM_{i}__", m.group(0))
for i, pm in enumerate(plus_matches):
res = res.replace(f"__PLUS_MARKER_{i}__", pm.group(0))
# Strip trailing procedural or temporal timing context (e.g. "gastritis post frozen embryo transfer" -> "gastritis")
timing_m = re.search(r"\b(?:status\s+post|post|s/p|after)\s+(?:frozen\s+embryo\s+transfer|fet|chemotherapy|surgery|procedure|infusion)\b.*$", res, re.IGNORECASE)
@@ -1569,14 +1827,19 @@ class EvidenceFirstFactExtractor:
if len(base_cand) >= 3:
res = base_cand
restored.append(res.strip())
decomposed = self._split_adjacent_clinical_conditions(res.strip())
for d in decomposed:
d_clean = d.strip()
if len(d_clean) >= 3:
restored.append(d_clean)
return [r for r in restored if len(r) >= 3]
def _split_term_and_narrative(self, line: str) -> tuple[str, str]:
"""Split a clinical line into the diagnostic term and accompanying clinical explanation."""
# e.g., "Acute right emphysematous pyelonephritis - underwent DJ stenting" -> ("Acute right emphysematous pyelonephritis", "underwent DJ stenting")
for delim in [" - ", " – ", " — ", " : ", ": ", " / ", " (", "; "]:
# Narrative delimiters introduce management/course comments (e.g. " - underwent DJ stenting")
# Do not include ";" or "/" as they separate distinct clinical entities in diagnosis lists
for delim in [" - ", " – ", " — ", " : ", ": ", " ("]:
if delim in line:
parts = line.split(delim, 1)
term = parts[0].strip()
@@ -1633,6 +1896,8 @@ class EvidenceFirstFactExtractor:
# Section 21: Oncology metastatic manifestations
if re.search(r"\bpleural\s+metastasis\b|\bmetastasis\s+to\s+pleura\b|\bmalignant\s+pleural\s+metastasis\b", clean, re.IGNORECASE):
return "Secondary malignant neoplasm of pleura"
if clean.lower() in ("urticarial", "urticarial rash", "rash urticarial"):
return "Urticaria"
return clean
def _corroborate_with_hospital_course_and_procedures(
@@ -1646,6 +1911,8 @@ class EvidenceFirstFactExtractor:
investigations_text = ""
procedure_text = ""
medications_text = ""
exam_text = ""
complaint_text = ""
for sec in sections:
if sec.section_name == "HOSPITAL_COURSE":
@@ -1656,22 +1923,36 @@ class EvidenceFirstFactExtractor:
procedure_text = f"{procedure_text} {sec.content}"
elif sec.section_name in ("MEDICATIONS", "DISCHARGE_MEDICATIONS"):
medications_text = f"{medications_text} {sec.content}"
elif sec.section_name in ("PHYSICAL_EXAMINATION", "CLINICAL_EXAMINATION"):
exam_text = f"{exam_text} {sec.content}"
elif sec.section_name in ("CHIEF_COMPLAINT", "HISTORY_OF_PRESENT_ILLNESS"):
complaint_text = f"{complaint_text} {sec.content}"
active_care_verbs = [
"treated", "managed", "monitored", "administered", "started", "continued",
"withheld", "titrated", "adjusted", "sliding scale", "infusion", "dose",
"protocol", "regimen", "followed", "received", "underwent", "controlled",
"stabilized", "responded", "prescribed", "switched", "transitioned",
"requiring", "vasopressor", "norepinephrine", "antibiotic", "fluids", "support",
]
# Clinical domain indicators for chronic/PMH conditions requiring active inpatient management
condition_care_markers: dict[str, list[str]] = {
"diabetes": ["insulin", "sliding scale", "metformin", "glucose", "blood sugar", "glycemic", "dka", "hypoglycemia", "hyperglycemia", "hba1c"],
"hypertension": ["amlodipine", "antihypertensive", "blood pressure", "bp", "lisinopril", "losartan", "metoprolol", "atenolol", "hydrochlorothiazide", "furosemide"],
"kidney": ["creatinine", "gfr", "nephrology", "dialysis", "renal function", "baseline creatinine"],
"kidney": ["creatinine", "gfr", "nephrology", "dialysis", "renal function", "baseline creatinine", "aki", "acute kidney injury"],
"renal": ["creatinine", "gfr", "nephrology", "dialysis", "renal function", "aki", "acute kidney injury"],
"aki": ["fluid", "fluids", "resuscitation", "creatinine", "iv fluids", "hydration"],
"dehydration": ["fluid", "fluids", "iv fluids", "hydration", "resuscitation"],
"heart failure": ["furosemide", "lasix", "diuresis", "echo", "echocardiogram", "ejection fraction", "cardiac"],
"asthma": ["inhaler", "nebulizer", "albuterol", "ipratropium", "bronchodilator", "steroid", "prednisone"],
"copd": ["inhaler", "nebulizer", "albuterol", "ipratropium", "bronchodilator", "steroid", "prednisone", "oxygen"],
"sepsis": ["antibiotic", "ceftriaxone", "vancomycin", "vasopressor", "norepinephrine", "lactate", "blood culture", "cultures", "hypotension", "iv fluids", "resuscitation"],
"pneumonia": ["antibiotic", "ceftriaxone", "azithromycin", "sputum", "cxr", "infiltrate", "consolidation", "oxygen"],
"stemi": ["stent", "catheterization", "troponin", "pci", "aspirin", "heparin", "plavix", "ticagrelor"],
"infarction": ["stent", "catheterization", "troponin", "pci", "aspirin", "heparin", "plavix", "ticagrelor"],
"gallstones": ["cholecystectomy", "ultrasound", "biliary", "colic", "cbd"],
"cholecystitis": ["cholecystectomy", "ultrasound", "biliary", "antibiotic", "gallbladder"],
}
for cand in candidates:
@@ -1688,7 +1969,7 @@ class EvidenceFirstFactExtractor:
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_sentence = None
found_management_sentences: list[str] = []
for sent in course_sentences:
sent_lower = sent.lower()
has_cand_mention = (
@@ -1700,10 +1981,12 @@ class EvidenceFirstFactExtractor:
has_active_verb = any(v in sent_lower for v in active_care_verbs)
if (has_cand_mention or has_marker_mention) and has_active_verb:
found_management_sentence = sent
break
if sent not in found_management_sentences:
found_management_sentences.append(sent)
if len(found_management_sentences) >= 3:
break
if found_management_sentence:
for found_management_sentence in found_management_sentences:
cand.treatment_relevance = 1.0
cand.encounter_relevance = 1.0
cand.scores.encounter_relevance = 1.0
@@ -1716,34 +1999,35 @@ class EvidenceFirstFactExtractor:
cand.role = DiagnosisRole.SECONDARY
cand.classification_reason = f"Pre-existing condition actively evaluated/managed during stay: {found_management_sentence}"
# Prepend supporting structured evidence if PMH; otherwise append so discharge diagnosis evidence remains at index 0
if any(ev.section in ("PAST_MEDICAL_HISTORY", "PAST_SURGICAL_HISTORY") for ev in cand.evidence):
cand.evidence.insert(
0,
StructuredEvidence(
text=found_management_sentence,
section="HOSPITAL_COURSE",
sentence=found_management_sentence,
polarity=NegationStatus.AFFIRMATIVE,
certainty=cand.certainty,
temporality=Temporality.CURRENT,
evidence_type=EvidenceType.HOSPITAL_COURSE,
clinical_relevance=1.0,
if not any(ev.text == found_management_sentence for ev in cand.evidence):
# Prepend supporting structured evidence if PMH; otherwise append
if any(ev.section in ("PAST_MEDICAL_HISTORY", "PAST_SURGICAL_HISTORY") for ev in cand.evidence):
cand.evidence.insert(
0,
StructuredEvidence(
text=found_management_sentence,
section="HOSPITAL_COURSE",
sentence=found_management_sentence,
polarity=NegationStatus.AFFIRMATIVE,
certainty=cand.certainty,
temporality=Temporality.CURRENT,
evidence_type=EvidenceType.HOSPITAL_COURSE,
clinical_relevance=1.0,
)
)
)
else:
cand.evidence.append(
StructuredEvidence(
text=found_management_sentence,
section="HOSPITAL_COURSE",
sentence=found_management_sentence,
polarity=NegationStatus.AFFIRMATIVE,
certainty=cand.certainty,
temporality=Temporality.CURRENT,
evidence_type=EvidenceType.HOSPITAL_COURSE,
clinical_relevance=1.0,
else:
cand.evidence.append(
StructuredEvidence(
text=found_management_sentence,
section="HOSPITAL_COURSE",
sentence=found_management_sentence,
polarity=NegationStatus.AFFIRMATIVE,
certainty=cand.certainty,
temporality=Temporality.CURRENT,
evidence_type=EvidenceType.HOSPITAL_COURSE,
clinical_relevance=1.0,
)
)
)
# Check procedure text
if procedure_text:
@@ -1774,6 +2058,42 @@ class EvidenceFirstFactExtractor:
)
break
# Check physical examination for supporting objective signs
if exam_text and words and any(w in exam_text.lower() for w in words):
for sent in re.split(r"[\.\n]+", exam_text):
if any(w in sent.lower() for w in words):
cand.evidence.append(
StructuredEvidence(
text=sent.strip(),
section="PHYSICAL_EXAMINATION",
sentence=sent.strip(),
polarity=NegationStatus.AFFIRMATIVE,
certainty=Certainty.SUPPORTED,
temporality=Temporality.CURRENT,
evidence_type=EvidenceType.CLINICAL_NOTE,
clinical_relevance=0.7,
)
)
break
# Check chief complaint / HPI for documented presenting symptoms
if complaint_text and words and any(w in complaint_text.lower() for w in words):
for sent in re.split(r"[\.\n]+", complaint_text):
if any(w in sent.lower() for w in words):
cand.evidence.append(
StructuredEvidence(
text=sent.strip(),
section="CHIEF_COMPLAINT",
sentence=sent.strip(),
polarity=NegationStatus.AFFIRMATIVE,
certainty=Certainty.SUPPORTED,
temporality=Temporality.CURRENT,
evidence_type=EvidenceType.ADMISSION_REASON,
clinical_relevance=0.8,
)
)
break
def _classify_and_structure_state(
self,
candidates: list[ClinicalDiagnosisCandidate],
@@ -1837,6 +2157,16 @@ class EvidenceFirstFactExtractor:
chosen_idx = idx
break
if chosen_idx is None and active_candidates:
for idx, cand in enumerate(active_candidates):
if cand.evidence:
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(
cand.normalized_diagnosis, cand.primary_evidence_quote
)
if is_valid:
chosen_idx = idx
break
if chosen_idx is not None:
top = active_candidates[chosen_idx]
top.role = DiagnosisRole.PRIMARY
@@ -1857,8 +2187,13 @@ class EvidenceFirstFactExtractor:
"acute", "chronic", "right", "left", "bilateral", "unspecified", "severe", "mild", "stage", "with", "without"
}
# Check 1: Duplicate / generalized mention of the primary diagnosis
if sec_words and top_words and (sec_words <= top_words or (len(sec_words & top_words) >= 2 and len(sec_words - top_words) == 0)):
# Check 1: Duplicate mention of the primary diagnosis
# Only treat as duplicate if it is the EXACT same clinical condition
is_exact_dup = (
sec_norm == top_norm
or self._canonicalize_term(sec_cand.normalized_diagnosis).lower() == self._canonicalize_term(top.normalized_diagnosis).lower()
)
if is_exact_dup:
sec_cand.role = DiagnosisRole.PRIMARY
sec_cand.is_authorized = False
sec_cand.classification_reason = f"Corroborating mention of primary diagnosis '{top.normalized_diagnosis}'"
@@ -1866,17 +2201,8 @@ class EvidenceFirstFactExtractor:
continue
# Check 2: Integral symptom / sign of primary diagnosis (CMS Guideline I.B.4)
is_integral = any(
sym in sec_norm
for sym in [
"pain", "colic", "fever", "cough", "dyspnea", "shortness of breath",
"nausea", "vomiting", "dyspepsia", "indigestion", "heartburn",
"discomfort", "wheezing", "fatigue", "malaise", "respiratory distress",
"peripheral edema", "edema", "chest pain", "flank pain", "hematuria"
]
) and not (
any(sec_norm.endswith(sfx) or f"{sfx} " in sec_norm for sfx in ("itis", "oma", "osis"))
or any(dx in sec_norm for dx in ["syndrome", "failure", "infarction", "disease", "disorder", "calculus", "lithiasis", "ulcer", "pneumonia"])
is_integral = HardClinicalCandidateGate.is_symptom_integral_to_primary(
sec_cand.normalized_diagnosis, top.normalized_diagnosis, sec_cand.primary_evidence_quote
)
if is_integral:
+125 -40
View File
@@ -586,7 +586,7 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
existing_codes: set[str] = set()
# STAGE 1: Primary Hybrid Retrieval (Single fast dense+sparse search)
primary_hits = retriever.retrieve(clean_query, top_k=25)
primary_hits = retriever.retrieve(clean_query, top_k=25, system="ICD-10-CM")
for h in primary_hits:
if h.code not in existing_codes:
hits.append(h)
@@ -627,6 +627,8 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
try:
lex_hits = retriever.lexical_retriever.retrieve(lt, top_k=15)
for h in lex_hits:
if getattr(h, "coding_system", "ICD-10-CM") != "ICD-10-CM":
continue
if h.code not in existing_codes:
hits.append(h)
existing_codes.add(h.code)
@@ -722,7 +724,8 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
# Handle ICD-O for neoplasms
is_neoplasm = (
concept.disease_family in ("breast_malignancy", "lymphoma", "pleural_metastasis", "kaposi_sarcoma", "liver_sarcoma", "neuroendocrine_tumor")
or any(w in raw_query.lower() for w in ["cancer", "carcinoma", "neoplasm", "lymphoma", "tumor", "sarcoma"])
or any(w in raw_query.lower() for w in ["cancer", "carcinoma", "neoplasm", "lymphoma", "tumor", "sarcoma", "melanoma", "malignancy", "dcis"])
or bool(getattr(concept, "histology", None))
)
if is_neoplasm:
icdo_hits = retriever.retrieve(raw_query, top_k=5, system="ICD-O")
@@ -731,6 +734,29 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
final_hits.append(o_hit)
existing_codes.add(o_hit.code)
# Handle CPT for associated procedures or interventional indications
proc_keywords = [
"appendectomy", "cholecystectomy", "stent", "stenting", "catheterization",
"dialysis", "biopsy", "resection", "excision", "laparoscopy", "laparotomy",
"drainage", "angioplasty", "bypass", "surgery", "operation", "intubation",
"thoracentesis", "paracentesis", "endoscopy", "colonoscopy", "arthroplasty", "mastectomy"
]
has_proc = (
getattr(cond, "procedure_relevance", 0.0) > 0
or any(pw in raw_query.lower() or pw in ev_quote.lower() for pw in proc_keywords)
)
if has_proc:
proc_query = raw_query
for pw in proc_keywords:
if pw in ev_quote.lower() and pw not in raw_query.lower():
proc_query = f"{raw_query} {pw}"
break
cpt_hits = retriever.retrieve(proc_query, top_k=5, system="CPT")
for c_hit in cpt_hits:
if c_hit.code not in existing_codes:
final_hits.append(c_hit)
existing_codes.add(c_hit.code)
return cond.diagnosis_id, concept, match_spec, final_hits
# Parallelize retrieval across diagnoses within document
@@ -789,12 +815,11 @@ def rank_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
for cond in classified:
candidates = candidate_pool.get(cond.diagnosis_id, [])
ev_quote = getattr(cond.context.evidence, "quote", "") if hasattr(cond, "context") and hasattr(cond.context, "evidence") else ""
if hasattr(cond, "classification_reason") and cond.classification_reason:
ev_quote = f"{ev_quote} {cond.classification_reason}"
ev_quote = getattr(cond.context.evidence, "quote", "") if hasattr(cond, "context") and hasattr(cond.context, "evidence") and cond.context.evidence else ""
# Corroborate evidence across document narrative (Master Prompt Sections 4, 10, 11)
# Merge evidence spans discussing this specific condition from hospital course, exam, etc.
ev_snippets: list[str] = [s.strip() for s in ev_quote.split(" | ") if s.strip()] if ev_quote else []
cond_tokens = [
w for w in re.findall(r"\b[a-z0-9]{3,}\b", cond.raw_term.lower())
if w not in ("with", "without", "and", "the", "for", "left", "right", "acute", "chronic", "mild", "severe")
@@ -805,16 +830,17 @@ def rank_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
sent_lower = sent.lower()
matches = sum(1 for tok in cond_tokens if tok in sent_lower or any(v in sent_lower for v in CLINICAL_MORPHOLOGY.get(tok, [])))
if matches >= max(1, int(len(cond_tokens) * 0.5)):
if sent_lower not in ev_quote.lower():
ev_quote = f"{ev_quote} {sent}"
if not any(sent_lower in existing.lower() or existing.lower() in sent_lower for existing in ev_snippets):
ev_snippets.append(sent)
# If condition is an orthopedic fracture and radiographic findings describe displacement/closed status:
if "fracture" in cond.raw_term.lower() and raw_doc_text:
for phrase in ["nondisplaced", "non-displaced", "no displacement", "closed fracture"]:
if phrase in raw_doc_text.lower() and phrase not in ev_quote.lower():
ev_quote = f"{ev_quote} {phrase}"
if phrase in raw_doc_text.lower() and not any(phrase in existing.lower() for existing in ev_snippets):
ev_snippets.append(phrase)
selection = agent.rank_candidates(cond, candidates, evidence_override=ev_quote.strip() or None)
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)
ranked_selections.append(selection)
return {
@@ -986,7 +1012,15 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
else Acuity.UNSPECIFIED,
certainty=Certainty.CONFIRMED,
evidence_quote=item.evidence.quote,
evidence=[{
evidence=[
{
"quote": snippet.strip(),
"section": getattr(item.evidence, "source_section", "") or "CLINICAL_DOCUMENTATION",
"evidence_type": "CORROBORATING_EVIDENCE" if idx > 0 else "PRIMARY_EVIDENCE",
}
for idx, snippet in enumerate(item.evidence.quote.split(" | "))
if snippet.strip()
] or [{
"quote": item.evidence.quote,
"section": getattr(item.evidence, "source_section", "") or "DISCHARGE_DIAGNOSES",
"evidence_type": "CLINICAL_EVIDENCE",
@@ -1082,8 +1116,22 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
for c in classified:
if c.role == DiagnosisRole.SECONDARY and c.is_billable_candidate:
candidates_to_check: list[Any] = list(classified)
if diag_state:
for sd in getattr(diag_state, "secondary_diagnoses", []):
sd_term = getattr(sd, "normalized_diagnosis", None) or getattr(sd, "raw_term", "")
if not any(
(getattr(c, "normalized_diagnosis", None) or getattr(c, "raw_term", "") or getattr(c, "diagnosis", "")).lower() == sd_term.lower()
for c in candidates_to_check
):
candidates_to_check.append(sd)
for c in candidates_to_check:
c_role = getattr(c, "role", None)
c_billable = getattr(c, "is_billable_candidate", True)
if getattr(c, "is_authorized", True) is False:
continue
if (c_role in (DiagnosisRole.SECONDARY, "SECONDARY")) and c_billable:
c_term = (
getattr(c, "normalized_diagnosis", None)
or getattr(c, "raw_term", None)
@@ -1092,15 +1140,20 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
if not c_term:
continue
c_norm = c_term.lower()
c_words = {w for w in re.findall(r"[a-z0-9]+", c_norm) if len(w) > 3}
generic_stop_words = {
"acute", "chronic", "disease", "disorder", "syndrome", "stage",
"type", "status", "unspecified", "secondary", "primary", "severe",
"mild", "moderate", "right", "left", "bilateral", "history", "with", "without"
}
c_words = {w for w in re.findall(r"[a-z0-9]+", c_norm) if len(w) > 3 and w not in generic_stop_words}
is_already_covered = False
for s_term in seen_sec_terms:
if (s_term in c_norm or c_norm in s_term) and len(s_term) > 4:
if c_norm == s_term:
is_already_covered = True
break
s_words = {w for w in re.findall(r"[a-z0-9]+", s_term) if len(w) > 3}
s_words = {w for w in re.findall(r"[a-z0-9]+", s_term) if len(w) > 3 and w not in generic_stop_words}
shared = c_words & s_words
if len(shared) >= 2 or any(k in shared for k in ("diabetes", "hypertension", "cholecystitis", "infarction", "failure", "calculus", "hypokalemia", "hyperlipidemia", "anemia", "pancreatitis", "gastritis")):
if len(shared) >= 2 or any(k in shared for k in ("diabetes", "hypertension", "cholecystitis", "infarction", "hypokalemia", "hyperlipidemia", "anemia", "pancreatitis", "gastritis")):
is_already_covered = True
break
if is_already_covered:
@@ -1108,6 +1161,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
c_quote = (
getattr(c, "evidence_quote", None)
or getattr(c, "primary_evidence_quote", None)
or (
c.context.evidence.quote
if hasattr(c, "context") and hasattr(c.context, "evidence") and c.context.evidence
@@ -1119,6 +1173,20 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
is_valid_cand, _ = HardClinicalCandidateGate.evaluate_candidate(c_term, c_quote)
if not is_valid_cand:
continue
# Clinical condition had no matching code in authoritative database; explicitly abstain ICD code mapping
if not any(a.raw_term and a.raw_term.lower() == c_term.lower() for a in abstentions):
abstentions.append(
AbstentionRecord(
diagnosis_id=getattr(c, "diagnosis_id", "secondary"),
raw_term=c_term,
reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE,
detail=f"Condition '{c_term}' lacked verified ICD database match; abstained.",
stage=PipelineStage.RANKING,
)
)
# Preserve clinically confirmed secondary diagnosis in secondary_responses
sec_resp = CodedDiagnosisResponse(
raw_term=getattr(c, "raw_term", c_term),
normalized_diagnosis=c_term,
@@ -1126,30 +1194,25 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
database_code=None,
database_description=None,
matching_status="NO_DATABASE_MATCH",
source_section=getattr(c, "source_section", "") or "DISCHARGE_DIAGNOSES",
source_section=getattr(c, "source_section", "") or (c.context.evidence.source_section if hasattr(c, "context") and hasattr(c.context, "evidence") and c.context.evidence else "CLINICAL_DOCUMENTATION"),
source_span=getattr(c, "source_span", None),
role=DiagnosisRole.SECONDARY,
acuity=Acuity.ACUTE
if "acute" in c_term.lower()
else Acuity.CHRONIC
if "chronic" in c_term.lower()
else Acuity.UNSPECIFIED,
certainty=Certainty.CONFIRMED,
acuity=getattr(c, "acuity", Acuity.UNSPECIFIED),
certainty=getattr(c, "certainty", Certainty.CONFIRMED),
evidence_quote=c_quote,
evidence=[{
"quote": c_quote,
"section": getattr(c, "source_section", "") or "DISCHARGE_DIAGNOSES",
"section": getattr(c, "source_section", "") or "CLINICAL_DOCUMENTATION",
"evidence_type": "SECONDARY_DIAGNOSIS",
}],
confidence_score=0.70,
}] if c_quote else [],
confidence_score=getattr(c, "evidence_strength", 1.0),
is_terminal_billable=False,
icd10cm=None,
icdo=None,
cpt=None,
)
secondary_responses.append(sec_resp)
seen_sec_terms.add(c_term.lower())
seen_sec_terms.add(getattr(c, "raw_term", c_term).lower())
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:
@@ -1157,20 +1220,16 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
primary_response.role = DiagnosisRole.PRIMARY
secondary_responses = [s for s in secondary_responses if s.code != "Z71.1"]
# Enforce clean role separation: secondary section must NEVER carry mentions of the primary diagnosis
# Enforce clean role separation: secondary section must NEVER duplicate the primary diagnosis
if primary_response:
pri_code = primary_response.code
pri_words = set(re.findall(r"[a-z0-9]+", f"{(primary_response.description or '').lower()} {(primary_response.raw_term or '').lower()} {(primary_response.normalized_diagnosis or '').lower()}")) - {
"acute", "chronic", "with", "without", "and", "the", "for", "type", "stage", "unspecified", "right", "left", "bilateral"
}
pri_norm = (primary_response.normalized_diagnosis or primary_response.raw_term or primary_response.description or "").lower().strip()
filtered_sec = []
for s in secondary_responses:
if pri_code and s.code and s.code == pri_code:
continue
s_words = set(re.findall(r"[a-z0-9]+", f"{(s.description or '').lower()} {(s.raw_term or '').lower()} {(s.normalized_diagnosis or '').lower()}")) - {
"acute", "chronic", "with", "without", "and", "the", "for", "type", "stage", "unspecified", "right", "left", "bilateral"
}
if s_words and pri_words and (s_words <= pri_words or (len(s_words & pri_words) >= 2 and len(s_words - pri_words) <= 1)):
s_norm = (s.normalized_diagnosis or s.raw_term or s.description or "").lower().strip()
if s_norm and pri_norm and s_norm == pri_norm:
continue
filtered_sec.append(s)
secondary_responses = filtered_sec
@@ -1205,13 +1264,33 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
"reason": category,
})
# Verify CPT codes for encounter procedures
raw_procedures = state.get("extracted_procedures", []) or (getattr(diag_state, "procedures", []) if diag_state else [])
verified_procedures: list[str] = []
catalog, retriever = get_or_initialize_retrieval_system()
for proc in raw_procedures:
clean_p = proc.strip()
if not clean_p:
continue
if "[CPT:" in clean_p or "(CPT:" in clean_p:
verified_procedures.append(clean_p)
continue
try:
cpt_cand = retriever.retrieve(clean_p, top_k=1, system="CPT")
if cpt_cand and catalog.is_valid_code(cpt_cand[0].code, system="CPT") and cpt_cand[0].retrieval_score >= 0.50:
verified_procedures.append(f"{clean_p} [CPT: {cpt_cand[0].code}]")
else:
verified_procedures.append(clean_p)
except Exception:
verified_procedures.append(clean_p)
result = CodingResult(
document_id=doc_id,
status=status,
primary_diagnosis=primary_response,
secondary_diagnoses=secondary_responses,
abstentions=abstentions,
procedures=state.get("extracted_procedures", []) or (getattr(diag_state, "procedures", []) if diag_state else []),
procedures=verified_procedures,
operative_findings=state.get("operative_findings", []) or (getattr(diag_state, "operative_findings", []) if diag_state else []),
oncology_context=diag_state.oncology_context.model_dump() if diag_state and getattr(diag_state, "oncology_context", None) else None,
excluded_candidates=excluded_candidates,
@@ -1230,7 +1309,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
"audit_trail": audit_trail,
"validated_code_count": len(validated),
"abstention_count": len(abstentions),
"extracted_procedures": state.get("extracted_procedures", []) or (getattr(diag_state, "procedures", []) if diag_state else []),
"extracted_procedures": verified_procedures,
"operative_findings": state.get("operative_findings", []) or (getattr(diag_state, "operative_findings", []) if diag_state else []),
"oncology_context": diag_state.oncology_context.model_dump() if diag_state and getattr(diag_state, "oncology_context", None) else None,
},
@@ -1276,11 +1355,17 @@ def _extract_conditions_deterministically(
and cand.temporality == Temporality.CURRENT
)
composite_ev = getattr(cand, "composite_evidence_quote", "") or primary_ev or cand.raw_term
if treatment_ev and is_active and is_pmh:
ev_str = f"{cand.raw_term} — Inpatient management: {treatment_ev} | {composite_ev}".strip(" |")
else:
ev_str = composite_ev
cond = ExtractedClinicalCondition(
condition_id=cand.diagnosis_id,
original_mention=cand.raw_term,
normalized_description=cand.normalized_diagnosis,
evidence_text=f"{cand.raw_term} — Inpatient management: {treatment_ev}" if (treatment_ev and is_active and is_pmh) else (primary_ev or cand.raw_term),
evidence_text=ev_str,
evidence_location=EvidenceLocation(
section=sec_name,
start_char=0,
@@ -74,6 +74,12 @@ DISEASE_FAMILY_PATTERNS: list[tuple[str, list[str], str]] = [
("osteoarthritis", ["osteoarthritis", "degenerative joint disease", "oa"], "joint"),
("hypothyroidism", ["hypothyroidism", "underactive thyroid"], "thyroid"),
("acute_kidney_injury", ["acute kidney injury", "aki", "acute renal failure"], "kidney"),
("copd", ["copd", "chronic obstructive pulmonary disease", "chronic bronchitis", "emphysema"], "lung"),
("diverticulitis", ["diverticulitis", "diverticular disease", "diverticulosis with diverticulitis"], "colon"),
("syncope", ["syncope", "vasovagal syncope", "collapse", "fainting"], "brain"),
("delirium", ["delirium", "acute encephalopathy", "metabolic encephalopathy", "toxic encephalopathy"], "brain"),
("cirrhosis", ["cirrhosis", "hepatic cirrhosis", "liver cirrhosis", "end stage liver disease"], "liver"),
("sepsis", ["sepsis", "severe sepsis", "urosepsis"], "blood"),
]
@@ -71,6 +71,18 @@ FAMILY_TO_CODE_PREFIXES: dict[str, list[str]] = {
"osteoarthritis": ["M15", "M16", "M17", "M19"],
"hypothyroidism": ["E03"],
"acute_kidney_injury": ["N17"],
"copd": ["J44"],
"diverticulitis": ["K57"],
"diverticular_disease": ["K57"],
"syncope": ["R55"],
"delirium": ["F05", "G93.41"],
"cirrhosis": ["K74.6", "K74"],
"stroke": ["I63", "I67"],
"sepsis": ["A41", "R65.2"],
"gallstones": ["K80"],
"cad": ["I25"],
"pe": ["I26"],
"dvt": ["I82"],
}
+7 -1
View File
@@ -83,10 +83,16 @@ class HybridICDRetriever(BaseICDRetriever):
if hasattr(self, "_query_cache") and cache_key in self._query_cache:
return [c.model_copy() for c in self._query_cache[cache_key]]
# Expand clinical abbreviations for dense semantic query embedding
from medical_coding.retrieval.tokenizer import expand_medical_abbreviations
expanded_query = expand_medical_abbreviations(clean_query)
dense_query = f"{clean_query} {expanded_query}".strip() if expanded_query.lower() != clean_query.lower() else clean_query
# Retrieve candidates from both local engines with an expanded initial window
search_window = max(k * 10, 350)
lexical_hits = self.lexical_retriever.retrieve(clean_query, top_k=search_window)
vector_hits = self.vector_retriever.retrieve(clean_query, top_k=search_window)
vector_hits = self.vector_retriever.retrieve(dense_query, top_k=search_window)
# Merge candidate pools by authoritative code
merged: dict[str, dict[str, Any]] = {}
+21 -2
View File
@@ -49,6 +49,9 @@ CLINICAL_ABBREVIATIONS: dict[str, str] = {
"pcl": "posterior cruciate ligament",
"net": "neuroendocrine tumor carcinoid",
"fet": "frozen embryo transfer",
"dns": "deviated nasal septum",
"fess": "functional endoscopic sinus surgery sinus endoscopy",
"ith": "inferior turbinate hypertrophy",
}
# Non-informative general words (keeping critical medical distinctions: acute, chronic, type, 1, 2, without, etc.)
@@ -275,6 +278,10 @@ CLINICAL_MORPHOLOGY: dict[str, list[str]] = {
"brain": ["cerebral", "brain"],
"ocular": ["eye", "ocular"],
"eye": ["ocular", "eye"],
"turbinate": ["turbinates", "nasal", "nose"],
"turbinates": ["turbinate", "nasal", "nose"],
"nasal": ["nose", "turbinate", "turbinates", "septum"],
"septum": ["nasal", "nose"],
"pneumonia": ["pneumonitis", "pna"],
"hypertension": ["htn", "high blood pressure"],
"diabetes": ["dm", "diabetic"],
@@ -359,12 +366,24 @@ CLINICAL_MORPHOLOGY: dict[str, list[str]] = {
"sodium": ["hyponatremia"],
"anemia": ["iron", "deficiency", "blood"],
"appendicitis": ["appendix"],
"diverticulitis": ["diverticular", "colon"],
"diverticulitis": ["diverticular", "colon", "diverticulosis"],
"diverticular": ["diverticulitis", "diverticulosis", "colon"],
"pancreatitis": ["pancreas", "pancreatic"],
"pancreas": ["pancreatitis", "pancreatic"],
"pancreatic": ["pancreas", "pancreatitis"],
"fibrillation": ["atrial", "afib"],
"atherosclerosis": ["coronary", "artery", "disease", "cad"],
"atherosclerosis": ["coronary", "artery", "disease", "cad", "native", "atherosclerotic"],
"atherosclerotic": ["coronary", "cad", "atherosclerosis", "native", "artery"],
"coronary": ["cad", "atherosclerotic", "artery", "heart", "arteriosclerotic", "native"],
"cad": ["coronary", "artery", "disease", "atherosclerotic", "native"],
"stroke": ["cerebral", "infarction", "cva", "ischemic"],
"cva": ["stroke", "cerebral", "infarction"],
"syncope": ["collapse", "vasovagal", "fainting"],
"collapse": ["syncope", "vasovagal", "fainting"],
"cirrhosis": ["hepatic", "liver", "cirrhotic"],
"cirrhotic": ["cirrhosis", "liver", "hepatic"],
"delirium": ["encephalopathy", "acute", "confusional", "toxic", "metabolic"],
"encephalopathy": ["delirium", "acute", "metabolic", "toxic"],
"hypothyroidism": ["thyroid"],
"thyroid": ["hypothyroidism"],
}
+12
View File
@@ -247,6 +247,18 @@ class ClinicalDiagnosisCandidate(BaseModel):
return ev.text
return self.evidence[0].text
@property
def composite_evidence_quote(self) -> str:
"""Return all corroborated evidence quotes joined with clean separator."""
if not self.evidence:
return ""
quotes: list[str] = []
for ev in self.evidence:
q = (ev.text or ev.sentence or "").strip()
if q and q not in quotes:
quotes.append(q)
return " | ".join(quotes) if quotes else ""
class ClinicalDiagnosisState(BaseModel):
"""Encounter clinical diagnosis state established strictly prior to ICD candidate retrieval."""
+71
View File
@@ -179,6 +179,77 @@ class CodingResult(BaseModel):
raise ValueError("Secondary diagnoses cannot have role PRIMARY")
return self
def format_output(self) -> str:
"""Format strictly according to required clinical coding output:
primary diagnosis: <name>, code: <code>, evidence: <evidence quote>
secondary diagnosises:
diagnosis: <name>, code: <code>, evidence: <evidence quote>
"""
def _clean_ev(text: str | None) -> str:
if not text:
return "None"
clean = str(text).strip()
if "Designated as " in clean:
clean = clean.split("Designated as ")[0].strip(" -|:\n")
return clean if clean else "None"
def _get_cand_ev(cand: Any) -> str:
quotes: list[str] = []
ev_list = getattr(cand, "evidence", []) or []
if isinstance(ev_list, list):
for item in ev_list:
q = ""
if isinstance(item, dict):
q = _clean_ev(item.get("quote"))
elif hasattr(item, "text"):
q = _clean_ev(item.text)
elif hasattr(item, "sentence"):
q = _clean_ev(item.sentence)
elif isinstance(item, str):
q = _clean_ev(item)
if q and q != "None" and q not in quotes:
quotes.append(q)
if quotes:
return " | ".join(quotes)
return _clean_ev(getattr(cand, "evidence_quote", None))
def _get_formatted_code(cand: Any) -> str:
base_code = getattr(cand, "icd10cm", None) or cand.code or ""
extra_codes: list[str] = []
if getattr(cand, "icdo", None) and cand.icdo != base_code:
extra_codes.append(f"ICD-O: {cand.icdo}")
if getattr(cand, "cpt", None) and cand.cpt != base_code:
extra_codes.append(f"CPT: {cand.cpt}")
if base_code and extra_codes:
return f"{base_code} ({', '.join(extra_codes)})"
elif extra_codes:
return ", ".join(extra_codes)
elif base_code:
return base_code
return "None"
lines = []
if self.primary_diagnosis:
p = self.primary_diagnosis
p_name = p.normalized_diagnosis or p.raw_term or p.description
p_code = _get_formatted_code(p)
p_ev = _get_cand_ev(p)
lines.append(f"primary diagnosis: {p_name}, code: {p_code}, evidence: {p_ev}")
else:
lines.append("primary diagnosis: None, code: None, evidence: None")
if self.secondary_diagnoses:
lines.append("secondary diagnosises:")
for s in self.secondary_diagnoses:
s_name = s.normalized_diagnosis or s.raw_term or s.description
s_code = _get_formatted_code(s)
s_ev = _get_cand_ev(s)
lines.append(f"diagnosis: {s_name}, code: {s_code}, evidence: {s_ev}")
else:
lines.append("secondary diagnosises: None")
return "\n".join(lines)
class TextCodingRequest(BaseModel):
"""Input payload for clinical text coding endpoint."""
+67
View File
@@ -147,6 +147,69 @@ tab1, tab2, tab3, tab4, tab5 = st.tabs([
])
def format_coding_result(result: Any) -> str:
"""Format strictly according to required clinical coding output:
primary diagnosis: <name>, code: <code>, evidence: <evidence quote>
secondary diagnosises:
diagnosis: <name>, code: <code>, evidence: <evidence quote>
"""
def _clean_ev(text: str | None) -> str:
if not text:
return "None"
clean = str(text).strip()
if "Designated as " in clean:
clean = clean.split("Designated as ")[0].strip(" -|:\n")
return clean if clean else "None"
def _get_cand_ev(cand: Any) -> str:
quotes: list[str] = []
ev_list = getattr(cand, "evidence", []) or []
if isinstance(ev_list, list):
for item in ev_list:
q = ""
if isinstance(item, dict):
q = _clean_ev(item.get("quote"))
elif hasattr(item, "text"):
q = _clean_ev(item.text)
elif hasattr(item, "sentence"):
q = _clean_ev(item.sentence)
elif isinstance(item, str):
q = _clean_ev(item)
if q and q != "None" and q not in quotes:
quotes.append(q)
if quotes:
return " | ".join(quotes)
return _clean_ev(getattr(cand, "evidence_quote", None))
lines = []
p = getattr(result, "primary_diagnosis", None)
if p:
p_name = getattr(p, "normalized_diagnosis", None) or getattr(p, "raw_term", None) or getattr(p, "description", None) or "None"
p_code = getattr(p, "code", None) or getattr(p, "icd10cm", None) or "None"
p_ev = _get_cand_ev(p)
lines.append(f"primary diagnosis: {p_name}, code: {p_code}, evidence: {p_ev}")
else:
lines.append("primary diagnosis: None, code: None, evidence: None")
secondaries = getattr(result, "secondary_diagnoses", []) or []
if secondaries:
lines.append("secondary diagnosises:")
for s in secondaries:
s_name = getattr(s, "normalized_diagnosis", None) or getattr(s, "raw_term", None) or getattr(s, "description", None) or "None"
s_code = getattr(s, "code", None) or getattr(s, "icd10cm", None) or "None"
s_ev = _get_cand_ev(s)
lines.append(f"diagnosis: {s_name}, code: {s_code}, evidence: {s_ev}")
else:
lines.append("secondary diagnosises: None")
return "\n".join(lines)
# Ensure backward compatibility if an in-memory cached CodingResult class is loaded
if not hasattr(CodingResult, "format_output"):
setattr(CodingResult, "format_output", lambda self: format_coding_result(self))
def render_coding_session_results(
coding_result: CodingResult,
steps_data: list[dict[str, Any]],
@@ -190,6 +253,10 @@ def render_coding_session_results(
st.markdown("### 📊 Coding Decisions & Evidence Audit")
render_kpi_metrics(coding_result)
# Clean Strict Output Format
st.markdown("#### 📋 Clinical Summary Format")
st.code(format_coding_result(coding_result), language="text")
# Primary Diagnosis
render_primary_diagnosis(coding_result.primary_diagnosis)
+38 -6
View File
@@ -143,6 +143,17 @@ def render_kpi_metrics(result: CodingResult) -> None:
)
def _clean_audit_from_evidence(ev: str) -> str:
"""Clean internal audit justifications and boilerplate from display evidence strings."""
if not ev:
return ""
if "Designated as " in ev:
ev = ev.split("Designated as ")[0].strip(" -|:\n")
if "Clinical criteria:" in ev:
ev = ev.split("Clinical criteria:")[0].strip(" -|:\n")
return ev.strip()
def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
"""Render the primary diagnosis card with evidence and specificity confirmation."""
st.markdown("### 🎯 Primary Diagnosis")
@@ -178,7 +189,13 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
documented_row = f'<div style="margin: 6px 0; font-size: 14px; color: #e2e8f0;">🩺 <strong style="color: #38bdf8;">Documented Clinical Diagnosis:</strong> {html.escape(str(primary.raw_term))}</div>'
safe_desc = html.escape(primary.description or "")
safe_evidence = html.escape(primary.evidence_quote or "")
raw_quote = _clean_audit_from_evidence(primary.evidence_quote or "")
if " | " in raw_quote:
spans = [_clean_audit_from_evidence(s) for s in raw_quote.split(" | ") if _clean_audit_from_evidence(s)]
spans_html = "".join(f'<div style="margin-top: 4px; padding-left: 8px; border-left: 2px solid #38bdf8;">• <span class="evidence-quote">{html.escape(s)}</span></div>' for s in spans)
evidence_content_html = spans_html
else:
evidence_content_html = f'<span class="evidence-quote">"{html.escape(raw_quote)}"</span>'
primary_html = clean_html(
f"""
@@ -206,9 +223,9 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
</div>
<div class="evidence-box">
<span style="font-weight: 600; color: #6ee7b7; font-size: 11px; text-transform: uppercase;">
📄 Verbatim Clinical Evidence Quote:
📄 Verbatim Clinical Evidence Across Record:
</span><br/>
<span class="evidence-quote">"{safe_evidence}"</span>
{evidence_content_html}
</div>
</div>
"""
@@ -250,7 +267,13 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
documented_row = f'<div style="margin-top: 4px; font-size: 13px; color: #cbd5e1;">🩺 <strong style="color: #38bdf8;">Documented Diagnosis:</strong> {html.escape(str(diag.raw_term))}</div>'
safe_desc = html.escape(diag.description or "")
safe_evidence = html.escape(diag.evidence_quote or "")
raw_sec_quote = _clean_audit_from_evidence(diag.evidence_quote or "")
if " | " in raw_sec_quote:
spans = [_clean_audit_from_evidence(s) for s in raw_sec_quote.split(" | ") if _clean_audit_from_evidence(s)]
spans_html = "".join(f'<div style="margin-top: 4px; padding-left: 8px; border-left: 2px solid #38bdf8;">• <span class="evidence-quote">{html.escape(s)}</span></div>' for s in spans)
sec_evidence_html = spans_html
else:
sec_evidence_html = f'<span class="evidence-quote">"{html.escape(raw_sec_quote)}"</span>'
secondary_html = clean_html(
f"""
@@ -272,7 +295,7 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
<span style="font-weight: 600; color: #6ee7b7; font-size: 11px; text-transform: uppercase;">
Clinical Evidence:
</span>
<span class="evidence-quote">"{safe_evidence}"</span>
{sec_evidence_html}
</div>
</div>
"""
@@ -320,12 +343,21 @@ def render_procedures(procedures: list[str]) -> None:
proc_items_html = []
for idx, proc in enumerate(procedures, start=1):
cpt_badge = ""
display_proc = proc
cpt_m = re.search(r"\[CPT:\s*([A-Za-z0-9]+)\]", proc)
if cpt_m:
cpt_code = cpt_m.group(1)
display_proc = re.sub(r"\s*\[CPT:\s*[A-Za-z0-9]+\]", "", proc).strip()
cpt_badge = f'<span class="pill-badge badge-success" style="margin-left: 8px;">CPT: {html.escape(cpt_code)}</span>'
proc_items_html.append(
f"""
<div class="procedure-item" style="background: rgba(147, 51, 234, 0.08); border: 1px solid rgba(168, 85, 247, 0.3); border-radius: 8px; padding: 10px 14px; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center;">
<div>
<span style="font-weight: 700; color: #c084fc; margin-right: 8px;">#{idx}.</span>
<strong style="color: #f3e8ff; font-size: 14px;">{html.escape(proc)}</strong>
<strong style="color: #f3e8ff; font-size: 14px;">{html.escape(display_proc)}</strong>
{cpt_badge}
</div>
<span class="pill-badge badge-info" style="border-color: rgba(168, 85, 247, 0.5); color: #d8b4fe;">Surgical / Interventional</span>
</div>
+221 -10
View File
@@ -107,6 +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*[:\-–—]",
]
# 5. Tumor attributes / Staging markers (attributes of a neoplasm, not standalone diagnoses)
@@ -131,13 +132,66 @@ ISOLATED_ANATOMY_PATTERNS = [
# Pathological condition words that validate an anatomical mention into a true disease entity
PATHOLOGY_KEYWORDS = {
"fracture", "sprain", "strain", "pain", "cellulitis", "arthritis", "arthropathy",
"swelling", "edema", "lesion", "mass", "tumor", "carcinoma", "cancer", "neoplasm",
"swelling", "edema", "lesion", "mass", "tumor", "tumour", "carcinoma", "cancer", "neoplasm",
"infection", "calculus", "stone", "lithiasis", "stenosis", "effusion", "laceration",
"wound", "contusion", "deformity", "syndrome", "disease", "disorder", "ulcer",
"gangrene", "ischemia", "infarction", "tear", "rupture", "dislocation", "subluxation",
"injury", "trauma", "abscess", "impairment", "failure", "colic", "bacteremia",
"hypertension", "diabetes", "asthma", "copd", "cirrhosis", "hepatitis", "pancreatitis",
"gastritis", "colitis", "enteritis", "appendicitis", "cholecystitis", "pyelonephritis",
"nephritis", "sepsis", "shock", "pneumonia", "bronchitis", "anemia", "acidosis",
"alkalosis", "ischemia", "stenosis", "thrombosis", "embolism", "atherosclerosis",
"cardiomyopathy", "arrhythmia", "fibrillation", "leukemia", "lymphoma", "sarcoma",
"melanoma", "adenoma", "polyp", "cyst", "perforation", "obstruction", "ileus",
"fistula", "diverticulitis", "diverticulosis", "fibrosis", "osteomyelitis",
"gout", "neuropathy", "radiculopathy", "dementia", "adenitis", "spasm",
"metastasis", "metastases", "metastatic", "malignancy", "malignant", "carcinomatosis",
"effusion", "atelectasis", "pneumothorax", "hemothorax", "consolidation", "ascites",
"hernia", "herniation", "hernias", "dehydration", "hypovolemia", "hypervolemia",
"urticaria", "urticarial", "dermatitis", "eczema", "psoriasis", "anaphylaxis", "angioedema",
"hypothyroidism", "hyperthyroidism", "thyroiditis", "goiter", "epilepsy", "seizure",
"convulsion", "parkinson", "alzheimer", "dementia", "reflux", "gerd", "esophagitis",
"regurgitation", "insufficiency", "prolapse", "incompetence", "lupus", "erythematosus",
"sjogren", "scleroderma", "sarcoidosis", "amyloidosis", "hemophilia", "thalassemia",
"cataract", "glaucoma", "retinopathy", "tuberculosis", "malaria", "dengue", "typhoid",
"depression", "anxiety", "bipolar", "schizophrenia", "psychosis", "malformation", "anomaly",
"deviation", "deviated", "hypertrophy", "hypertrophic", "hyperplasia", "atrophy", "atrophic",
"hypoplasia", "dysplasia", "thickening", "narrowing", "collapse", "perforation", "calcification",
"sclerosis", "fibrosis", "adhesions", "dns", "mastoiditis",
}
# Clinical symptoms, signs, and patient complaints
SYMPTOM_KEYWORDS = {
"pain", "colic", "discomfort", "ache", "aching", "soreness", "tenderness",
"fever", "pyrexia", "chill", "chills", "rigor", "rigors", "sweating", "diaphoresis",
"cough", "coughing", "hemoptysis", "dyspnea", "breathlessness", "tachypnea",
"wheeze", "wheezing", "stridor", "rhonchi", "rales", "crackles",
"nausea", "vomiting", "emesis", "dyspepsia", "indigestion", "heartburn",
"dysphagia", "odynophagia", "diarrhea", "constipation", "obstipation",
"hematochezia", "melena", "hematemesis", "jaundice", "icterus",
"dizziness", "vertigo", "syncope", "presyncope", "lightheadedness",
"headache", "migraine", "cephalea", "fatigue", "malaise", "lethargy",
"weakness", "asthenia", "somnolence", "drowsiness", "insomnia",
"edema", "swelling", "swollen", "distension", "bloating", "ascites",
"rash", "erythema", "pruritus", "itching", "lesion", "lesions",
"cyanosis", "pallor", "flushing", "palpitation", "palpitations",
"tachycardia", "bradycardia", "arrhythmia", "hypotension", "hypertension",
"oliguria", "anuria", "polyuria", "hematuria", "dysuria", "nocturia",
"incontinence", "retention", "urgency", "frequency",
"confusion", "delirium", "altered", "encephalopathy", "seizure", "seizures", "convulsion",
"tremor", "ataxia", "numbness", "paresthesia", "tingling", "hypesthesia",
"paralysis", "paresis", "plegia", "spasticity", "rigidity", "stiffness",
"anorexia", "cachexia", "weight loss", "weight gain",
}
# Recognized medical pathology, morphology, and clinical suffixes
MEDICAL_CONDITION_SUFFIXES = (
"itis", "oma", "osis", "emia", "aemia", "pathy", "algia", "dynia",
"pnea", "uria", "stenosis", "megaly", "penia", "cytosis", "iasis",
"spasm", "derma", "ectasis", "malacia", "necrosis", "rrhea", "rrhagia",
"cele", "ptosis", "lysis", "plegia", "paresis", "sclerosis",
"ism", "ia", "ence", "ency", "lapse",
)
# 7. Procedure and surgical keywords (Section 11 Procedure Firewall)
PROCEDURE_TERMS = {
@@ -151,12 +205,31 @@ PROCEDURE_TERMS = {
"lymphadenectomy", "axillary dissection", "lymph node dissection",
"sentinel node biopsy", "sentinel lymph node biopsy", "cystectomy",
"adhesiolysis", "lysis of adhesions", "ablation", "cauterization",
"procedure", "surgery", "operation", "intervention", "surgical procedure",
"surgical intervention", "procedure done", "surgery done", "operation done",
}
PROCEDURE_SUFFIXES = (
"ectomy", "otomy", "ostomy", "plasty", "pexy", "scopy", "centesis", "rrhaphy",
)
# Generic procedural completion / performance notices lacking underlying disease
GENERIC_PROCEDURE_PATTERNS = [
r"^\s*(?:elective\s+|major\s+|minor\s+|surgical\s+|operative\s+|bedside\s+|diagnostic\s+)?(?:procedure|surgery|operation|intervention)\s*(?:done|performed|completed|tolerated|undertaken|successful|finished|noted)?\s*$",
r"\b(?:procedure\s+done|surgery\s+done|operation\s+done|procedure\s+performed|surgery\s+performed|operation\s+performed|intervention\s+done)\b",
r"^\s*(?:procedure|surgery|operation|intervention)\s*$",
]
# Non-clinical activities, everyday events, personal actions, and bodily functions without pathology
NON_CLINICAL_ACTIVITY_PATTERNS = [
r"\b(?:towel|blanket|bedsheet|pillow|napkin|tissue|clothes|linen|tray|remote|phone|call\s*bell)\b",
r"\b(?:picked\s*up|picking\s*up|pick\s*up|put\s*down|dropped|wiped|cleaned|folded|reached\s*for)\b",
r"\b(?:i\s+)?(?:pooped|pooping|bowel\s*movement|peed|peeing|urinated|urination|voided|defecated)\b",
r"\b(?:i\s+pooped|patient\s+pooped|i\s+peed|patient\s+peed|towel\s+picked\s+up|picked\s+up\s+towel)\b",
r"^\s*(?:i|we|he|she|pt|patient)?\s*(?:ate|eating|eats|drank|drinking|drinks|slept|sleeping|sleeps|walked|walking|walks|ambulated|ambulating|sat|sitting|sits|stood|standing|stands|woke|waking|bathed|bathing|showered|showering|brushed|brushing|dressed|dressing)\b",
r"^\s*(?:i|we)\s+[a-z]+",
]
# 8. Investigation names lacking pathological findings
INVESTIGATION_TERMS = {
"ct", "ct scan", "mri", "cxr", "chest x-ray", "ultrasound", "usg",
@@ -207,6 +280,16 @@ class HardClinicalCandidateGate:
if len(clean_term) < 2:
return False, "Term is too short to be a clinical condition"
# Check 0a: Non-clinical activities, daily living actions, and personal events
for pat in NON_CLINICAL_ACTIVITY_PATTERNS:
if re.search(pat, term_lower):
return False, f"Non-clinical activity, everyday personal action, or household event: '{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
for pat in ABSENCE_PATTERNS:
if re.search(pat, term_lower):
@@ -219,11 +302,10 @@ class HardClinicalCandidateGate:
# Check 3: Pharmaceutical dosage forms or prescription syntax (Section 9)
is_dosage_form = any(re.search(pat, term_lower) for pat in DOSAGE_FORM_PATTERNS)
has_prescription_syntax = (
any(re.search(pat, term_lower) for pat in PRESCRIPTION_SYNTAX_PATTERNS)
or any(re.search(pat, evidence_text.lower()) for pat in PRESCRIPTION_SYNTAX_PATTERNS)
)
if is_dosage_form or (has_prescription_syntax and any(w in evidence_text.lower() for w in ["medication", "dose", "tablet", "syrup", "capsule", "injection", "take", "prn"])):
has_prescription_syntax = any(re.search(pat, term_lower) for pat in PRESCRIPTION_SYNTAX_PATTERNS)
if is_dosage_form or has_prescription_syntax:
return False, f"Pharmaceutical dosage form or prescription instruction: '{clean_term}'"
if any(w in term_lower for w in ["tablet", "syrup", "capsule", "injection", "mg po", "mg iv", "mcg", "tablets", "capsules", "lozenges"]):
return False, f"Pharmaceutical dosage form or prescription instruction: '{clean_term}'"
# Check 4: Section headings, metadata, allergy statements, lab values
@@ -258,7 +340,12 @@ class HardClinicalCandidateGate:
return False, f"Negative finding / absence clause: '{clean_term}'"
# Check 8: Explicit metadata keywords
if any(term_lower == meta for meta in ["classification of fracture", "classification of fracture: not applicable", "not applicable", "n/a", "na", "biomarkers & receptor status", "biomarkers", "receptor status"]):
term_no_punct = re.sub(r"[:\s]+$", "", term_lower).strip()
if (
term_no_punct.startswith("classification of")
or term_no_punct.startswith("type of fracture")
or any(term_no_punct == meta for meta in ["classification", "not applicable", "n/a", "na", "biomarkers & receptor status", "biomarkers", "receptor status"])
):
return False, f"Metadata or template header artifact: '{clean_term}'"
# Check 9: Pure surgical or procedural interventions (Section 11 Procedure Firewall)
@@ -288,8 +375,120 @@ class HardClinicalCandidateGate:
if re.search(pat, term_lower):
return False, f"Hypothetical or contingent clinical statement: '{clean_term}'"
# Check 13: Clinical Medical Entity Validation (Strict Disease or Symptom Requirement)
# Every candidate MUST carry a disease, disorder, pathology, infection, neoplasm, injury, or clinical symptom/sign.
term_words = set(re.findall(r"[a-z0-9]+", term_lower))
has_pathology = bool(term_words.intersection(PATHOLOGY_KEYWORDS))
has_symptom = bool(term_words.intersection(SYMPTOM_KEYWORDS))
has_med_suffix = any(any(w.endswith(sfx) for sfx in MEDICAL_CONDITION_SUFFIXES) for w in term_words if len(w) > 4)
has_microbiology = any(org in term_lower for org in ["e. coli", "escherichia coli", "klebsiella", "pseudomonas", "staphylococcus", "streptococcus", "candida", "h. pylori", "helicobacter", "rhinovirus", "influenza", "coronavirus", "bacteremia"])
has_lab_abnormality = any(lab in term_lower for lab in ["leukocytosis", "thrombocytopenia", "hypokalemia", "hyperkalemia", "hyponatremia", "acidosis", "alkalosis", "anemia", "creatinine", "troponin", "hyperglycemia", "hypoglycemia", "elevated"])
CLINICAL_ROOTS = (
"stone", "calcul", "lithias", "itis", "oma", "osis", "emia", "pathy", "algia",
"pnea", "uria", "stenos", "megaly", "penia", "cytos", "spasm", "infect",
"fractur", "sprain", "strain", "ulcer", "injur", "trauma", "wound", "syndrom",
"diseas", "disorder", "failur", "ischemi", "infarct", "cancer", "carcinom",
"tumor", "tumour", "neoplasm", "abscess", "cellulit", "aneurysm", "thrombos",
"embol", "anemi", "diabet", "asthma", "copd", "cirrhos", "fibros", "gout",
"neuropath", "pain", "fever", "cough", "nausea", "vomit", "dyspnea", "headache",
"edema", "swelling", "rash", "bleed", "hemorrhag", "diarrhea", "constipat",
"colic", "jaundic", "syncope", "dizzin", "vertigo", "fatigue", "malaise",
"seizur", "convuls", "tremor", "ataxia", "paralys", "paresis", "hypertens",
"hypotens", "arrhythm", "tachycard", "bradycard", "fibrillat", "cardiomyopath",
"adenit", "gangren", "necros", "perforat", "obstruct", "ileus", "fistul",
"deform", "impair", "calculi", "polyp", "cyst", "adenom", "sarcom", "lymphom",
"leukem", "melanom", "dementi", "deliri", "encephalopath", "acidosis", "alkalosis",
"shock", "sepsis", "bacteremi", "pyelonephrit", "cholecystit", "pancreatit",
"gastrit", "colit", "enterit", "hepatit", "appendicit", "pneumon", "spasm",
"lacerat", "contus", "ruptur", "dislocat", "subluxat", "metasta", "malignan",
"effus", "atelecta", "pneumothor", "hemothor", "ascit", "herni", "dehydrat", "hypovolem",
"urticar", "dermatit", "eczema", "psorias", "anaphyla", "angioedem",
"thyroid", "goiter", "epilep", "parkinson", "alzheimer", "reflux", "esophag",
"regurgitat", "insufficien", "prolaps", "incompeten", "lupus", "erythemat",
"hemophil", "thalassem", "cataract", "glaucom", "retinopath", "tuberculos",
"malari", "dengue", "typhoid", "depress", "anxiet", "bipolar", "schizophren",
"psychos", "malformat", "anomal", "dysplas", "deviat", "hypertroph", "hyperplas",
"atroph", "thicken", "narrow", "calcif",
)
has_clinical_root = any(r in term_lower for r in CLINICAL_ROOTS)
if not (has_pathology or has_symptom or has_med_suffix or has_microbiology or has_lab_abnormality or has_clinical_root):
# If the phrase has no clinical terms at all, reject it as a non-diagnostic statement
return False, f"Phrase does not describe a clinical disease, disorder, pathology, or symptom: '{clean_term}'"
return True, "Valid clinical diagnosis entity"
@classmethod
def is_symptom_integral_to_primary(
cls, symptom_term: str, primary_term: str, evidence: str = ""
) -> bool:
"""Evaluate whether a clinical symptom is an expected integral manifestation of a primary diagnosis under CMS Guideline I.B.4.
Principles:
1. A symptom is ONLY integral if it is a standard physiological manifestation within the SAME organ system as the primary disease.
2. Cross-system conditions (e.g. chest pain in skin disease, epigastric pain in urticaria, rash in heart disease) are NOT integral.
3. If a symptom was explicitly evaluated, investigated (e.g. ECG changes, endoscopy), or diagnosed, it is not integral.
"""
sym = symptom_term.lower().strip()
pri = primary_term.lower().strip()
# Check if sym is even a symptom
symptom_indicators = [
"pain", "colic", "fever", "cough", "dyspnea", "shortness of breath",
"nausea", "vomiting", "dyspepsia", "indigestion", "heartburn",
"discomfort", "wheezing", "fatigue", "malaise", "respiratory distress",
"rash", "pruritus", "itching", "edema", "swelling", "cyanosis",
]
is_sym = any(s in sym for s in symptom_indicators)
has_definitive_dx = (
any(sym.endswith(sfx) or f"{sfx} " in sym for sfx in ("itis", "oma", "osis", "emia", "pathy"))
or any(dx in sym for dx in ["syndrome", "failure", "infarction", "disease", "disorder", "calculus", "lithiasis", "ulcer", "pneumonia", "dermatitis"])
)
if not is_sym or has_definitive_dx:
return False
# Organ system mapping
# 1. Skin
is_skin_sym = any(w in sym for w in ["rash", "pruritus", "itching", "erythema", "hive", "wheal"])
is_skin_pri = any(w in pri for w in ["urticaria", "dermatitis", "eczema", "psoriasis", "cellulitis", "impetigo"])
if is_skin_sym and is_skin_pri:
return True
# 2. Heart failure (dyspnea, shortness of breath, fluid overload, peripheral edema)
is_hf_sym = any(w in sym for w in ["dyspnea", "shortness of breath", "edema", "peripheral edema", "fluid overload", "orthopnea"])
is_hf_pri = any(w in pri for w in ["heart failure", "chf", "congestive heart", "systolic heart", "diastolic heart"])
if is_hf_sym and is_hf_pri:
return True
# 3. Gastrointestinal & Acute Abdominal Inflammation
is_gi_sym = any(w in sym for w in ["abdominal pain", "rlq pain", "llq pain", "ruq pain", "luq pain", "pain", "colic", "epigastric pain", "epigastric discomfort", "dyspepsia", "nausea", "vomiting", "heartburn", "indigestion", "diarrhea"])
is_gi_pri = any(w in pri for w in ["gastritis", "appendicitis", "cholecystitis", "pancreatitis", "ulcer", "diverticulitis", "gastroenteritis", "colitis", "crohn", "ileus"])
if is_gi_sym and is_gi_pri:
return True
if "fever" in sym and any(w in pri for w in ["appendicitis", "cholecystitis", "diverticulitis", "pyelonephritis", "abscess"]):
return True
# 4. Respiratory
is_resp_sym = any(w in sym for w in ["cough", "wheezing", "dyspnea", "shortness of breath", "stridor", "sputum", "hemoptysis", "respiratory distress"])
is_resp_pri = any(w in pri for w in ["pneumonia", "asthma", "copd", "bronchitis", "pneumothorax", "pulmonary edema", "respiratory failure"])
if is_resp_sym and is_resp_pri:
return True
# 5. Cardiovascular
is_cardiac_sym = any(w in sym for w in ["chest pain", "angina", "palpitation", "palpitations"])
is_cardiac_pri = any(w in pri for w in ["infarction", "stemi", "nstemi", "angina", "coronary", "pericarditis", "myocarditis", "ischemic heart"])
if is_cardiac_sym and is_cardiac_pri:
return True
# 6. Genitourinary
is_gu_sym = any(w in sym for w in ["dysuria", "hematuria", "flank pain", "frequency", "urgency"])
is_gu_pri = any(w in pri for w in ["pyelonephritis", "cystitis", "calculus", "lithiasis", "uti", "urinary tract infection", "nephritis"])
if is_gu_sym and is_gu_pri:
return True
return False
@classmethod
def classify_entity_type(cls, term: str, evidence_text: str = "") -> ClinicalEntityType:
"""Classify any clinical phrase into the Universal Clinical Entity Taxonomy (Section 2)."""
@@ -382,6 +581,10 @@ class HardClinicalCandidateGate:
def get_rejection_category(cls, term: str, _evidence_text: str = "") -> str:
"""Classify the deterministic rejection category for audit reporting."""
term_lower = term.strip().lower()
if any(re.search(pat, term_lower) for pat in NON_CLINICAL_ACTIVITY_PATTERNS):
return "NON_CLINICAL"
if any(re.search(pat, term_lower) for pat in GENERIC_PROCEDURE_PATTERNS) or any(re.search(rf"\b{re.escape(proc)}\b", term_lower) for proc in PROCEDURE_TERMS) or any(term_lower.endswith(sfx) for sfx in PROCEDURE_SUFFIXES):
return "PROCEDURE"
if any(term_lower == m or re.search(pat, term_lower) for pat in METADATA_PATTERNS for m in ["classification of fracture", "not applicable", "n/a", "biomarkers & receptor status", "biomarkers", "receptor status"]):
return "METADATA"
if any(re.search(pat, term_lower) for pat in STANDALONE_ATTRIBUTE_PATTERNS):
@@ -392,13 +595,21 @@ class HardClinicalCandidateGate:
return "MEDICATION"
if any(re.search(pat, term_lower) for pat in INSTRUCTION_PATTERNS):
return "INSTRUCTION"
if any(re.search(rf"\b{re.escape(proc)}\b", term_lower) for proc in PROCEDURE_TERMS) or any(term_lower.endswith(sfx) for sfx in PROCEDURE_SUFFIXES):
return "PROCEDURE"
if any(re.search(pat, term_lower) for pat in ISOLATED_ANATOMY_PATTERNS):
return "ANATOMY"
if any(sym in term_lower for sym in ["pain", "cough", "fever", "dyspnea", "wheezing", "discomfort"]):
return "SYMPTOM"
return "METADATA"
return "NON_CLINICAL"
@classmethod
def is_non_clinical_activity(cls, text: str) -> bool:
t = text.strip().lower()
return any(bool(re.search(pat, t)) for pat in NON_CLINICAL_ACTIVITY_PATTERNS)
@classmethod
def is_generic_procedure(cls, text: str) -> bool:
t = text.strip().lower()
return any(bool(re.search(pat, t)) for pat in GENERIC_PROCEDURE_PATTERNS)
@classmethod
def is_absence_statement(cls, text: str) -> bool:
+58 -4
View File
@@ -212,9 +212,46 @@ class DeterministicValidator:
)
cand_sys = getattr(candidate, "coding_system", None) or "ICD-10-CM"
icd10cm_val = selection.selected_icd10cm or (code if cand_sys == "ICD-10-CM" else None)
icdo_val = selection.selected_icdo or (code if cand_sys == "ICD-O" else None)
cpt_val = selection.selected_cpt or (code if cand_sys == "CPT" else None)
icd10cm_val = code if cand_sys == "ICD-10-CM" else selection.selected_icd10cm
icdo_val = code if cand_sys == "ICD-O" else selection.selected_icdo
cpt_val = code if cand_sys == "CPT" else selection.selected_cpt
if icdo_val:
if not self.catalog.is_valid_code(icdo_val, system="ICD-O"):
icdo_val = None
else:
checks.append(
ValidationCheck(
rule_name="ICDO_CatalogMatch",
passed=True,
details=f"ICD-O morphology code '{icdo_val}' verified in authoritative catalog.",
)
)
if cpt_val:
if not self.catalog.is_valid_code(cpt_val, system="CPT"):
cpt_val = None
else:
checks.append(
ValidationCheck(
rule_name="CPT_CatalogMatch",
passed=True,
details=f"CPT procedural code '{cpt_val}' verified in authoritative catalog.",
)
)
# Preserve rich multi-span corroborated evidence from ranking & clinical extraction
final_ev = condition.context.evidence.model_copy() if hasattr(condition, "context") and hasattr(condition.context, "evidence") and condition.context.evidence else None
if selection.supporting_evidence and selection.supporting_evidence[0]:
merged_quote = " | ".join(s for s in selection.supporting_evidence if s).strip()
if final_ev:
final_ev.quote = merged_quote
else:
from medical_coding.schemas.clinical import EvidenceSnippet
final_ev = EvidenceSnippet(
quote=merged_quote,
source_section=getattr(selection, "source_section", "") or "DISCHARGE_DIAGNOSES",
)
validated = ValidatedDiagnosis(
diagnosis_id=condition.diagnosis_id,
@@ -222,7 +259,7 @@ class DeterministicValidator:
code=code,
description=candidate.description,
role=condition.role,
evidence=condition.context.evidence,
evidence=final_ev or condition.context.evidence,
confidence_score=selection.ranking_score,
checks=checks,
icd10cm=icd10cm_val,
@@ -919,12 +956,29 @@ class CandidateRankingDeterministicValidator:
decision="REJECTED_LOW_CONFIDENCE",
)
cand_system = getattr(matching_candidate, "coding_system", None) or "ICD-10-CM"
icd10cm_val = matching_candidate.code if cand_system == "ICD-10-CM" else selection.selected_icd10cm
icdo_val = matching_candidate.code if cand_system == "ICD-O" else selection.selected_icdo
cpt_val = matching_candidate.code if cand_system == "CPT" else selection.selected_cpt
for c in candidates:
c_sys = getattr(c, "coding_system", None)
if c_sys == "ICD-10-CM" and not icd10cm_val:
icd10cm_val = c.code
elif c_sys == "ICD-O" and not icdo_val:
icdo_val = c.code
elif c_sys == "CPT" and not cpt_val:
cpt_val = c.code
# 9. Successfully accepted
return RankedSelection(
diagnosis_id=selection.diagnosis_id,
raw_term=selection.raw_term or clean_diagnosis,
selected_code=matching_candidate.code,
selected_description=matching_candidate.description,
selected_icd10cm=icd10cm_val,
selected_icdo=icdo_val,
selected_cpt=cpt_val,
selected_candidate=matching_candidate,
ranking_reason=selection.ranking_reason
or f"Selected candidate '{matching_candidate.code}' is best supported by documented clinical evidence.",
@@ -28,6 +28,9 @@ NON_SPECIFICITY_WORDS: set[str] = {
"secondary", "neoplasm", "neoplasms", "tumor", "tumour", "intrahepatic", "bile", "duct",
"coronary", "artery", "arteries", "vessel", "vessels", "wall", "vein", "veins",
"essential", "uncomplicated",
"native", "atherosclerotic", "atherosclerosis", "arteriosclerotic", "gallbladder",
"collapse", "failure", "pneumonia",
"septicemia", "shock", "bacteremia", "systemic",
}
# Clinical attribute qualifiers mapped to documentary confirmation tokens/synonyms
@@ -377,13 +380,15 @@ class ReverseAttributeChecker:
):
unsupported.append("type 2")
# Male vs Female breast/genitourinary specificity (Master Prompt Section 5)
if re.search(r"\bmale\b", desc_lower) and not re.search(
r"\b(?:male|man|men|boy|gentleman)\b", combined_evidence
):
unsupported.append("male")
# Universal Clinical Modifier Entailment (CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY)
without_matches = re.findall(r"\bwithout\s+([a-z0-9\-]+(?:\s+[a-z0-9\-]+)?)", desc_lower)
for w_phrase in without_matches:
w_phrase_clean = w_phrase.strip()
if w_phrase_clean in ("mention", "evidence", "complication", "complications"):
continue
if has_positive_mention(w_phrase_clean, combined_evidence):
unsupported.append(f"without {w_phrase_clean}")
# Strips negative 'without' expressions so absences are not required
desc_clean = re.sub(
r"\bwithout\s+(?:mention\s+of\s+|evidence\s+of\s+|any\s+)?[a-z0-9\-]+(?:\s+[a-z0-9\-]+)?\b",
@@ -393,7 +398,6 @@ class ReverseAttributeChecker:
# Strip parenthetical nonessential modifiers and bracketed synonyms (CMS Guidelines I.A.4 & I.A.7)
desc_clean = re.sub(r"[\(\[][^\)\]]*[\)\]]", "", desc_clean)
# Strip parent taxonomy phrases for well-defined syndromic terms
# E.g. "Severe sepsis with septic shock" -> septic shock is the clinical manifestation
if re.search(r"\bseptic\s+shock\b", combined_evidence):
desc_clean = re.sub(r"\bsevere\s+sepsis\s+with\s+septic\s+shock\b", "septic shock", desc_clean)
raw_code_tokens = re.findall(r"[a-z0-9]+", desc_clean)