fix(pipeline): correct output arrangement, isolate noise, and properly assign primary vs secondary diagnoses
This commit is contained in:
@@ -416,6 +416,10 @@ class ContextAndRelevanceAgent(BaseAgent):
|
||||
"stent",
|
||||
"started on",
|
||||
"received",
|
||||
"medication",
|
||||
"on medication",
|
||||
"treatment",
|
||||
"rx",
|
||||
]
|
||||
)
|
||||
)
|
||||
@@ -501,6 +505,10 @@ class ContextAndRelevanceAgent(BaseAgent):
|
||||
"surgery",
|
||||
"stent",
|
||||
"replacement",
|
||||
"medication",
|
||||
"on medication",
|
||||
"treatment",
|
||||
"rx",
|
||||
]
|
||||
)
|
||||
has_monitoring = any(
|
||||
@@ -1042,6 +1050,35 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
score += 2.0
|
||||
reasons.append("Detailed in history of present illness (+2.0)")
|
||||
|
||||
# Secondary / Historical Section Hierarchy:
|
||||
if sec_lower in ("past medical history", "personal history", "pmh", "medical history"):
|
||||
score -= 10.0
|
||||
reasons.append("Documented under past/personal history (-10.0)")
|
||||
|
||||
# Complication vs Primary Etiology distinction (e.g. Acute pyelonephritis complicated by septic shock):
|
||||
is_complication = bool(
|
||||
re.search(rf"\b(?:complicated\s+by)\b[^\n.;]*?{re.escape(diag_lower)}", full_context)
|
||||
or (doc_lower and re.search(rf"\b(?:complicated\s+by)\b[^\n.;]*?{re.escape(diag_lower)}", doc_lower))
|
||||
or "complicated by" in (asm.reason or "").lower()
|
||||
)
|
||||
is_leading_primary = bool(
|
||||
is_explicit_primary and not is_complication and (
|
||||
re.search(rf"{re.escape(diag_lower)}[^\n.;]*?\b(?:with|complicated\s+by)\b", full_context)
|
||||
or (doc_lower and re.search(rf"{re.escape(diag_lower)}[^\n.;]*?\b(?:with|complicated\s+by)\b", doc_lower))
|
||||
)
|
||||
)
|
||||
if is_complication:
|
||||
score -= 2.0
|
||||
reasons.append("Documented as secondary complication rather than underlying primary disease (-2.0)")
|
||||
elif is_leading_primary:
|
||||
score += 2.0
|
||||
reasons.append("Underlying occasioning primary condition prior to complications (+2.0)")
|
||||
|
||||
# Injury coding precedence: skeletal fractures outrank co-occurring ligament sprains/strains (CMS Guideline 19.b)
|
||||
if any(sp in diag_lower for sp in ["sprain", "strain"]) and any("fracture" in c.diagnosis.lower() for c in assessments):
|
||||
score -= 2.0
|
||||
reasons.append("Ligament sprain secondary to co-occurring skeletal fracture (-2.0)")
|
||||
|
||||
# 2. Major Interventions & Procedures
|
||||
if any(
|
||||
term in full_context
|
||||
|
||||
@@ -41,10 +41,11 @@ SECTION_PATTERNS: list[tuple[str, str]] = [
|
||||
("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)"),
|
||||
("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+HOSPITAL|CLINICAL\s+COURSE)"),
|
||||
("PHYSICAL_EXAMINATION", r"(?:CLINICAL\s+EXAMINATION|PHYSICAL\s+EXAMINATION|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)"),
|
||||
("PAST_MEDICAL_HISTORY", r"(?:PAST\s+MEDICAL\s+HISTORY|PMH|MEDICAL\s+HISTORY|BACKGROUND\s+HISTORY|PAST\s+HISTORY)"),
|
||||
("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)"),
|
||||
("MICROBIOLOGY", r"(?:MICROBIOLOGY|CULTURES?|BLOOD\s+CULTURES?|URINE\s+CULTURES?|SPUTUM\s+CULTURES?|CULTURE\s+AND\s+SENSITIVITY|MICROBIOLOGICAL\s+STUDIES)"),
|
||||
@@ -137,12 +138,12 @@ class SectionSegmenter:
|
||||
# Find all section header matches
|
||||
matches: list[dict[str, Any]] = []
|
||||
for sec_name, pat_str in SECTION_PATTERNS:
|
||||
regex = re.compile(rf"(?:^|\n)\s*({pat_str})\s*(?::|--|\n)", re.IGNORECASE)
|
||||
regex = re.compile(rf"(?:^|\n|[.;]\s*|\b(?=[A-Z\s]{{4,}}:))\s*({pat_str})\s*(?::|--|\n)", re.IGNORECASE)
|
||||
for m in regex.finditer(text):
|
||||
matches.append({
|
||||
"section_name": sec_name,
|
||||
"header_text": m.group(1).strip(),
|
||||
"start_pos": m.start(),
|
||||
"start_pos": m.start(1),
|
||||
"content_start": m.end(),
|
||||
})
|
||||
|
||||
@@ -539,7 +540,7 @@ class EvidenceFirstFactExtractor:
|
||||
candidates: list[ClinicalDiagnosisCandidate] = []
|
||||
lines = [line.strip() for line in content.split("\n") if line.strip()]
|
||||
|
||||
for line in lines:
|
||||
for line_idx, line in enumerate(lines):
|
||||
# Strip list numbering e.g. "1. Acute right emphysematous pyelonephritis - underwent DJ stenting"
|
||||
cleaned_line = re.sub(r"^\d+[\.\)\-]\s*", "", line).strip()
|
||||
# Strip structural role prefixes (e.g., "Primary:", "Principal Diagnosis -", "Secondary:")
|
||||
@@ -605,7 +606,7 @@ class EvidenceFirstFactExtractor:
|
||||
if is_explicit_historical
|
||||
else (
|
||||
DiagnosisRole.PRIMARY
|
||||
if (sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and sub_idx == 0)
|
||||
if (sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and line_idx == 0 and sub_idx == 0)
|
||||
else DiagnosisRole.SECONDARY
|
||||
)
|
||||
)
|
||||
@@ -625,9 +626,9 @@ class EvidenceFirstFactExtractor:
|
||||
if is_explicit_historical:
|
||||
base_admitting = -50.0
|
||||
elif sec.section_name in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS"):
|
||||
base_admitting = 15.0 if sub_idx == 0 else 5.0
|
||||
base_admitting = 15.0 if (line_idx == 0 and sub_idx == 0) else 5.0
|
||||
elif sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES"):
|
||||
base_admitting = 10.0 if sub_idx == 0 else 4.0
|
||||
base_admitting = 10.0 if (line_idx == 0 and sub_idx == 0) else 4.0
|
||||
elif sec.section_name in ("SECONDARY_DIAGNOSES", "ADDITIONAL_DIAGNOSES"):
|
||||
base_admitting = 3.0
|
||||
else:
|
||||
@@ -758,43 +759,86 @@ class EvidenceFirstFactExtractor:
|
||||
cleaned = re.sub(r"^\d+[\.\)\-]\s*", "", line).strip()
|
||||
if not cleaned or len(cleaned) < 3:
|
||||
continue
|
||||
term, _ = self._split_term_and_narrative(cleaned)
|
||||
term, pmh_attrs = self._extract_concept_and_attributes(term)
|
||||
if not term or len(term) < 3:
|
||||
continue
|
||||
polarity, certainty = self._assess_polarity_and_certainty(cleaned)
|
||||
is_resolved = "resolved" in cleaned.lower() or "remote" in cleaned.lower()
|
||||
|
||||
ev = StructuredEvidence(
|
||||
text=line,
|
||||
section="PAST_MEDICAL_HISTORY",
|
||||
sentence=line,
|
||||
polarity=polarity,
|
||||
certainty=certainty,
|
||||
temporality=Temporality.RESOLVED if is_resolved else Temporality.HISTORICAL,
|
||||
evidence_type=EvidenceType.HISTORY,
|
||||
clinical_relevance=0.2,
|
||||
cleaned_preamble = re.sub(
|
||||
r"^(?:known\s+case\s+of|k/c/o|history\s+of|h/o|patient\s+is\s+a\s+known\s+case\s+of)\s*",
|
||||
"",
|
||||
cleaned,
|
||||
flags=re.IGNORECASE,
|
||||
).strip()
|
||||
|
||||
has_active_rx = bool(
|
||||
re.search(
|
||||
r"\b(?:on\s+medication|on\s+treatment|on\s+rx|treated|managed)\b",
|
||||
cleaned_preamble,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
)
|
||||
scores = MultiDimensionalScore(
|
||||
evidence_score=0.8,
|
||||
diagnostic_certainty=1.0,
|
||||
encounter_relevance=0.0,
|
||||
role_confidence=0.0,
|
||||
admitting_score=-10.0,
|
||||
)
|
||||
cand = ClinicalDiagnosisCandidate(
|
||||
raw_term=term,
|
||||
normalized_diagnosis=term,
|
||||
role=DiagnosisRole.HISTORICAL,
|
||||
certainty=certainty,
|
||||
temporality=Temporality.RESOLVED if is_resolved else Temporality.HISTORICAL,
|
||||
clinical_attributes=pmh_attrs,
|
||||
evidence=[ev],
|
||||
scores=scores,
|
||||
is_authorized=False,
|
||||
classification_reason="Past medical history condition without documented active inpatient care",
|
||||
)
|
||||
candidates.append(cand)
|
||||
cleaned_concept = re.sub(
|
||||
r",?\s*\b(?:on\s+medication|on\s+treatment|on\s+rx)\b.*$",
|
||||
"",
|
||||
cleaned_preamble,
|
||||
flags=re.IGNORECASE,
|
||||
).strip()
|
||||
|
||||
sub_items = re.split(r"\s+and\s+|\s*,\s*", cleaned_concept)
|
||||
for sub_item in sub_items:
|
||||
term, _ = self._split_term_and_narrative(sub_item)
|
||||
term, pmh_attrs = self._extract_concept_and_attributes(term)
|
||||
if not term or len(term) < 3:
|
||||
continue
|
||||
|
||||
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
||||
is_valid_cand, _ = HardClinicalCandidateGate.evaluate_candidate(term, line)
|
||||
if not is_valid_cand:
|
||||
continue
|
||||
|
||||
polarity, certainty = self._assess_polarity_and_certainty(cleaned)
|
||||
is_resolved = "resolved" in cleaned.lower() or "remote" in cleaned.lower()
|
||||
|
||||
if has_active_rx and not is_resolved and polarity != NegationStatus.NEGATED:
|
||||
cand_temp = Temporality.CURRENT
|
||||
cand_role = DiagnosisRole.SECONDARY
|
||||
is_auth = True
|
||||
base_admitting = 3.0
|
||||
reason = "Pre-existing chronic comorbidity on active medication therapy"
|
||||
else:
|
||||
cand_temp = Temporality.RESOLVED if is_resolved else Temporality.HISTORICAL
|
||||
cand_role = DiagnosisRole.HISTORICAL
|
||||
is_auth = False
|
||||
base_admitting = -10.0
|
||||
reason = "Past medical history condition without documented active inpatient care"
|
||||
|
||||
ev = StructuredEvidence(
|
||||
text=line,
|
||||
section="PAST_MEDICAL_HISTORY",
|
||||
sentence=line,
|
||||
polarity=polarity,
|
||||
certainty=certainty,
|
||||
temporality=cand_temp,
|
||||
evidence_type=EvidenceType.HISTORY,
|
||||
clinical_relevance=1.0 if has_active_rx else 0.2,
|
||||
)
|
||||
scores = MultiDimensionalScore(
|
||||
evidence_score=1.0 if has_active_rx else 0.8,
|
||||
diagnostic_certainty=1.0,
|
||||
encounter_relevance=1.0 if has_active_rx else 0.0,
|
||||
role_confidence=0.8 if has_active_rx else 0.0,
|
||||
admitting_score=base_admitting,
|
||||
)
|
||||
cand = ClinicalDiagnosisCandidate(
|
||||
raw_term=term,
|
||||
normalized_diagnosis=term,
|
||||
role=cand_role,
|
||||
certainty=certainty,
|
||||
temporality=cand_temp,
|
||||
clinical_attributes=pmh_attrs,
|
||||
evidence=[ev],
|
||||
scores=scores,
|
||||
is_authorized=is_auth,
|
||||
classification_reason=reason,
|
||||
)
|
||||
candidates.append(cand)
|
||||
|
||||
return candidates
|
||||
|
||||
|
||||
@@ -644,8 +644,14 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
desc_tokens = set(re.findall(r"\b[a-z0-9]+\b", rec.description.lower()))
|
||||
overlap = len(expanded_q_tokens.intersection(desc_tokens))
|
||||
frac = overlap / len(expanded_q_tokens) if expanded_q_tokens else 0.5
|
||||
if rec.code.endswith(".9") or rec.code.endswith(".919") or rec.code.endswith(".90"):
|
||||
frac += 0.20
|
||||
if "left" in clean_query.lower() and "left" in rec.description.lower():
|
||||
frac += 0.25
|
||||
elif "right" in clean_query.lower() and "right" in rec.description.lower():
|
||||
frac += 0.25
|
||||
elif ("left" in clean_query.lower() or "right" in clean_query.lower()) and "unspecified" in rec.description.lower():
|
||||
frac -= 0.20
|
||||
elif rec.code.endswith(".9") or rec.code.endswith(".919") or rec.code.endswith(".90"):
|
||||
frac += 0.10
|
||||
scored_recs.append((frac, rec))
|
||||
scored_recs.sort(key=lambda x: x[0], reverse=True)
|
||||
|
||||
@@ -1143,6 +1149,12 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
seen_sec_terms.add(c_term.lower())
|
||||
seen_sec_terms.add(getattr(c, "raw_term", c_term).lower())
|
||||
|
||||
# Suppress Z71.1 ("feared health complaint in whom no diagnosis is made") when real clinical conditions exist
|
||||
if primary_response and primary_response.code == "Z71.1" and secondary_responses:
|
||||
primary_response = secondary_responses.pop(0)
|
||||
primary_response.role = DiagnosisRole.PRIMARY
|
||||
secondary_responses = [s for s in secondary_responses if s.code != "Z71.1"]
|
||||
|
||||
# Determine execution status
|
||||
if primary_response or secondary_responses:
|
||||
status = ExecutionStatus.SUCCESS if not abstentions else ExecutionStatus.PARTIAL_SUCCESS
|
||||
|
||||
@@ -167,7 +167,11 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
|
||||
<strong style="color: #38bdf8;">{conf_pct}%</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div class="primary-desc">{primary.description}</div>
|
||||
<div class="primary-desc">
|
||||
<span style="font-size: 13px; color: #94a3b8; display: block; margin-bottom: 2px;">📖 Matched Database Concept:</span>
|
||||
{primary.description}
|
||||
</div>
|
||||
{f'<div style="margin: 6px 0; font-size: 14px; color: #e2e8f0;">🩺 <strong style="color: #38bdf8;">Documented Clinical Diagnosis:</strong> {primary.raw_term}</div>' if primary.raw_term and primary.raw_term.lower() != (primary.description or "").lower() else ''}
|
||||
<div style="display: flex; gap: 8px; margin: 10px 0; flex-wrap: wrap;">
|
||||
{acuity_badge}
|
||||
{certainty_badge}
|
||||
@@ -223,6 +227,7 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
|
||||
<div>
|
||||
<strong style="font-size: 18px; color: #38bdf8;">#{idx}. {sec_code_display}</strong>
|
||||
<span style="font-size: 15px; font-weight: 600; color: #f8fafc; margin-left: 10px;">{diag.description}</span>
|
||||
{f'<div style="margin-top: 4px; font-size: 13px; color: #cbd5e1;">🩺 <strong style="color: #38bdf8;">Documented Diagnosis:</strong> {diag.raw_term}</div>' if diag.raw_term and diag.raw_term.lower() != (diag.description or "").lower() else ''}
|
||||
</div>
|
||||
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
|
||||
{billable_badge}
|
||||
|
||||
@@ -69,6 +69,22 @@ METADATA_PATTERNS = [
|
||||
r"^\s*final\s+coding\s+summary\b",
|
||||
r"^\s*general\s+condition\b",
|
||||
r"^\s*physical\s+examination\b",
|
||||
r"^\s*(?:clinical|general|systemic)\s+examination\b",
|
||||
r"^\s*course\s+in\s+(?:the\s+)?hospital(?:\s+and\s+discussion)?\b",
|
||||
r"^\s*personal\s+history\b",
|
||||
r"^\s*discussion\b",
|
||||
# Physical exam findings, vitals, and normal systemic observations
|
||||
r"\bpatient\s+alert\s+and\s+responsive\b",
|
||||
r"\b(?:alert\s+and\s+responsive|conscious\s+and\s+oriented)\b",
|
||||
r"\b(?:rs\s*:\s*aebe|cvs\s*:\s*s1|cns\s*:\s*nad|pa\s*:\s*soft)\b",
|
||||
r"\b(?:temperature\s*:|pulse\s*:|respiratory\s+rate\s*:|bp\s*:|spo2\s*:)\b",
|
||||
r"\b(?:soft[,\s]+non[\s\-]?tender|heard\s+well)\b",
|
||||
# Administrative phrases and non-disease encounter boilerplate
|
||||
r"\b(?:patient\s+was\s+)?admitted\s+with\s+above\s+mentioned\s+complaints\b",
|
||||
r"\b(?:admitted\s+for\s+)?further\s+management\b",
|
||||
r"\babove\s+mentioned\s+complaints\b",
|
||||
r"\bfeared\s+health\s+complaint\b",
|
||||
r"\bcomplaint\s+in\s+whom\s+no\s+diagnosis\s+is\s+made\b",
|
||||
# Allergy statements and negative metadata (Section 3)
|
||||
r"^\s*(?:drug\s+)?allerg(?:y|ies)(?:\s*:)?\s*(?:none|nkda|no\s+known\s+(?:drug\s+)?allergies|nil|na|n/a)?\s*$",
|
||||
r"^\s*(?:no\s+known\s+(?:drug\s+)?allergies|nkda)\s*$",
|
||||
@@ -204,6 +220,10 @@ class HardClinicalCandidateGate:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Section heading, metadata, allergy, or clinical status artifact: '{clean_term}'"
|
||||
|
||||
# Check 4b: Physical exam, vital signs, systemic examination noise
|
||||
if any(w in term_lower for w in ["patient alert", "responsive temperature", "temperature :", "pulse :", "respiratory rate :", "bp :", "spo2 :", "rs :", "cvs :", "cns :", "pa :", "aebe", "s1, s2 heard well", "soft, non tender", "further management", "above mentioned complaints"]):
|
||||
return False, f"Physical exam, vital sign, or administrative boilerplate artifact: '{clean_term}'"
|
||||
|
||||
# Check 5: Standalone tumor staging or genetic attributes
|
||||
for pat in STANDALONE_ATTRIBUTE_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
|
||||
@@ -27,6 +27,7 @@ NON_SPECIFICITY_WORDS: set[str] = {
|
||||
"acute", "chronic", "subacute", "spontaneous", "disruption", "injury", "sites",
|
||||
"secondary", "neoplasm", "neoplasms", "tumor", "tumour", "intrahepatic", "bile", "duct",
|
||||
"coronary", "artery", "arteries", "vessel", "vessels", "wall", "vein", "veins",
|
||||
"essential", "uncomplicated",
|
||||
}
|
||||
|
||||
# Clinical attribute qualifiers mapped to documentary confirmation tokens/synonyms
|
||||
|
||||
Reference in New Issue
Block a user