fix(pipeline): enforce Master Directive clinical reasoning, taxonomy, hard candidate gate, and generic query synthesis on extraction-fix

This commit is contained in:
Abhinav Gupta
2026-10-06 17:08:45 +05:30
parent 58cb6662f1
commit f5ec8a66de
9 changed files with 713 additions and 316 deletions
+208 -241
View File
@@ -24,14 +24,8 @@
"confidence_score": 1.0 "confidence_score": 1.0
} }
], ],
"abstention_count": 3, "abstention_count": 2,
"abstentions": [ "abstentions": [
{
"diagnosis": "Appendectomy in 2005.",
"reason": "EXCLUDED_BY_NEGATION",
"detail": "Excluded from coding: [PAST_MEDICAL_HISTORY] Past Medical History alone without documented inpatient evaluation, monitoring, or therapy.",
"stage": "CLASSIFICATION"
},
{ {
"diagnosis": "Resolved seasonal allergic rhinitis.", "diagnosis": "Resolved seasonal allergic rhinitis.",
"reason": "EXCLUDED_BY_NEGATION", "reason": "EXCLUDED_BY_NEGATION",
@@ -48,41 +42,7 @@
"audit_trail_sample": [ "audit_trail_sample": [
{ {
"document_id": "CASE-01-STANDARD-ADMISSION", "document_id": "CASE-01-STANDARD-ADMISSION",
"diagnosis_id": "164e94a9-2b73-4039-a068-1d9c4d32e82f", "diagnosis_id": "858c704c-b4d1-4ce8-8aed-19bca0d0ca3a",
"raw_term": "Appendectomy in 2005.",
"evidence": "1. Appendectomy in 2005.",
"context": {
"certainty": "CONFIRMED",
"temporality": "HISTORICAL",
"negation": "AFFIRMATIVE",
"acuity": "UNSPECIFIED"
},
"classification": {
"role": "EXCLUDED",
"is_billable": false,
"reason": "Excluded from coding: [PAST_MEDICAL_HISTORY] Past Medical History alone without documented inpatient evaluation, monitoring, or therapy."
},
"retrieved_candidates": [],
"selected_candidate": {
"code": null,
"description": null,
"confidence": 0.0,
"reason": "Candidate pool was empty; no matching local ICD code.",
"decision": "ABSTAINED"
},
"validation": {
"status": "REJECTED_OR_ABSTAINED",
"checks": []
},
"final_result": {
"code": null,
"description": null,
"role": null
}
},
{
"document_id": "CASE-01-STANDARD-ADMISSION",
"diagnosis_id": "435e53a7-b9e1-4b0c-a034-78076e40d297",
"raw_term": "Resolved seasonal allergic rhinitis.", "raw_term": "Resolved seasonal allergic rhinitis.",
"evidence": "2. Resolved seasonal allergic rhinitis.", "evidence": "2. Resolved seasonal allergic rhinitis.",
"context": { "context": {
@@ -113,6 +73,177 @@
"description": null, "description": null,
"role": null "role": null
} }
},
{
"document_id": "CASE-01-STANDARD-ADMISSION",
"diagnosis_id": "80165556-6c96-4cb9-85cc-fb71a656e79d",
"raw_term": "Acute systolic heart failure",
"evidence": "1. Acute systolic heart failure - Patient admitted with acute exacerbation of systolic congestive heart failure. Echo demonstrated EF 20%. Treated with intravenous furosemide diuresis with marked symptomatic improvement.",
"context": {
"certainty": "CONFIRMED",
"temporality": "CURRENT",
"negation": "AFFIRMATIVE",
"acuity": "ACUTE"
},
"classification": {
"role": "PRIMARY",
"is_billable": true,
"reason": "Selected as unique Primary Diagnosis (score=11.0): Identified as principal condition occasioning admission (+6.0); Active intravenous / intensive therapeutic management administered (+2.0); Acute presentation (+2.0); Confirmed diagnostic certainty (+1.0)"
},
"retrieved_candidates": [
{
"code": "I50.21",
"description": "Acute systolic (congestive) heart failure",
"score": 0.9148
},
{
"code": "I50.23",
"description": "Acute on chronic systolic (congestive) heart failure",
"score": 0.85
},
{
"code": "I50.20",
"description": "Unspecified systolic (congestive) heart failure",
"score": 0.85
},
{
"code": "I50.22",
"description": "Chronic systolic (congestive) heart failure",
"score": 0.85
},
{
"code": "I50.89",
"description": "Other heart failure",
"score": 0.85
},
{
"code": "I50.9",
"description": "Heart failure, unspecified",
"score": 0.85
},
{
"code": "I50.31",
"description": "Acute diastolic (congestive) heart failure",
"score": 0.75
},
{
"code": "I50.33",
"description": "Acute on chronic diastolic (congestive) heart failure",
"score": 0.75
},
{
"code": "I50.30",
"description": "Unspecified diastolic (congestive) heart failure",
"score": 0.8
},
{
"code": "I50.32",
"description": "Chronic diastolic (congestive) heart failure",
"score": 0.8
},
{
"code": "I50.82",
"description": "Biventricular heart failure",
"score": 0.8
},
{
"code": "I50.811",
"description": "Acute right heart failure",
"score": 0.7291
},
{
"code": "I50.41",
"description": "Acute combined systolic (congestive) and diastolic (congestive) heart failure",
"score": 0.7197
},
{
"code": "I50.43",
"description": "Acute on chronic combined systolic (congestive) and diastolic (congestive) heart failure",
"score": 0.6894
},
{
"code": "I50.813",
"description": "Acute on chronic right heart failure",
"score": 0.65
},
{
"code": "I50.40",
"description": "Unspecified combined systolic (congestive) and diastolic (congestive) heart failure",
"score": 0.65
},
{
"code": "I50.42",
"description": "Chronic combined systolic (congestive) and diastolic (congestive) heart failure",
"score": 0.65
},
{
"code": "I50.810",
"description": "Right heart failure, unspecified",
"score": 0.8
},
{
"code": "I50.812",
"description": "Chronic right heart failure",
"score": 0.8
},
{
"code": "I50.1",
"description": "Left ventricular failure, unspecified",
"score": 0.75
},
{
"code": "I50.83",
"description": "High output heart failure",
"score": 0.8
},
{
"code": "I50.84",
"description": "End stage heart failure",
"score": 0.8
},
{
"code": "I50.814",
"description": "Right heart failure due to left heart failure",
"score": 0.5818
},
{
"code": "T86.22",
"description": "Heart transplant failure",
"score": 0.545
},
{
"code": "I97.130",
"description": "Postprocedural heart failure following cardiac surgery",
"score": 0.5852
}
],
"selected_candidate": {
"code": "I50.21",
"description": "Acute systolic (congestive) heart failure",
"confidence": 1.0,
"reason": "Candidate 'I50.21' (Acute systolic (congestive) heart failure) best supported by documentation (core diagnostic entity match (3/3), acute acuity match).",
"decision": "ACCEPTED"
},
"validation": {
"status": "PASSED",
"checks": [
{
"rule_name": "CatalogExistence",
"passed": true,
"details": "Code 'I50.21' exists in local authoritative catalog."
},
{
"rule_name": "TerminalSpecificity",
"passed": true,
"details": "Code 'I50.21' is at terminal billable specificity."
}
]
},
"final_result": {
"code": "I50.21",
"description": "Acute systolic (congestive) heart failure",
"role": "PRIMARY"
}
} }
] ]
}, },
@@ -139,7 +270,7 @@
"audit_trail_sample": [ "audit_trail_sample": [
{ {
"document_id": "CASE-02-UNSUPPORTED-SPECIFICITY", "document_id": "CASE-02-UNSUPPORTED-SPECIFICITY",
"diagnosis_id": "a949862f-d67f-4567-b3ee-afe50e8be353", "diagnosis_id": "3a1b04c7-2cd6-4abb-83ec-2ce5eb614316",
"raw_term": "Heart failure", "raw_term": "Heart failure",
"evidence": "1. Heart failure - Patient has documented history of heart failure. Maintenance oral furosemide was continued. No echocardiogram was performed during admission and ejection fraction was not documented.", "evidence": "1. Heart failure - Patient has documented history of heart failure. Maintenance oral furosemide was continued. No echocardiogram was performed during admission and ejection fraction was not documented.",
"context": { "context": {
@@ -310,7 +441,7 @@
}, },
{ {
"document_id": "CASE-02-UNSUPPORTED-SPECIFICITY", "document_id": "CASE-02-UNSUPPORTED-SPECIFICITY",
"diagnosis_id": "73d2563b-65bf-4d4b-adeb-c702ae244c35", "diagnosis_id": "e93bc4bc-1e42-4491-8224-26be11e409bb",
"raw_term": "Fatigue and peripheral edema", "raw_term": "Fatigue and peripheral edema",
"evidence": "Fatigue and peripheral edema", "evidence": "Fatigue and peripheral edema",
"context": { "context": {
@@ -367,7 +498,7 @@
"audit_trail_sample": [ "audit_trail_sample": [
{ {
"document_id": "CASE-03-RULED-OUT-CONDITION", "document_id": "CASE-03-RULED-OUT-CONDITION",
"diagnosis_id": "6b589cd9-5213-40e0-b136-22313b8c60ea", "diagnosis_id": "2e7e84ee-0a27-41ea-b1c0-c767223116b7",
"raw_term": "Non-cardiac chest pain", "raw_term": "Non-cardiac chest pain",
"evidence": "1. Non-cardiac chest pain - Evaluated for acute coronary syndrome. Acute myocardial infarction was definitively ruled out by serial negative high-sensitivity troponins and normal ECG.", "evidence": "1. Non-cardiac chest pain - Evaluated for acute coronary syndrome. Acute myocardial infarction was definitively ruled out by serial negative high-sensitivity troponins and normal ECG.",
"context": { "context": {
@@ -401,7 +532,7 @@
}, },
{ {
"document_id": "CASE-03-RULED-OUT-CONDITION", "document_id": "CASE-03-RULED-OUT-CONDITION",
"diagnosis_id": "55ee1709-c1a4-4b90-87d1-35c9a23127f5", "diagnosis_id": "29adba3a-9803-4a25-9c85-b48ad4b884a5",
"raw_term": "Acute substernal chest discomfort", "raw_term": "Acute substernal chest discomfort",
"evidence": "Acute substernal chest discomfort", "evidence": "Acute substernal chest discomfort",
"context": { "context": {
@@ -466,6 +597,16 @@
"description": "Neoplasm related pain (acute) (chronic)", "description": "Neoplasm related pain (acute) (chronic)",
"score": 0.75 "score": 0.75
}, },
{
"code": "H53.149",
"description": "Visual discomfort, unspecified",
"score": 0.75
},
{
"code": "R10.24",
"description": "Suprapubic pain",
"score": 0.75
},
{ {
"code": "L03.323", "code": "L03.323",
"description": "Acute lymphangitis of chest wall", "description": "Acute lymphangitis of chest wall",
@@ -486,10 +627,25 @@
"description": "Sickle-cell thalassemia, unspecified, with acute chest syndrome", "description": "Sickle-cell thalassemia, unspecified, with acute chest syndrome",
"score": 0.55 "score": 0.55
}, },
{
"code": "H53.143",
"description": "Visual discomfort, bilateral",
"score": 0.55
},
{ {
"code": "D57.451", "code": "D57.451",
"description": "Sickle-cell thalassemia beta plus with acute chest syndrome", "description": "Sickle-cell thalassemia beta plus with acute chest syndrome",
"score": 0.5 "score": 0.5
},
{
"code": "H53.141",
"description": "Visual discomfort, right eye",
"score": 0.5066
},
{
"code": "H53.142",
"description": "Visual discomfort, left eye",
"score": 0.5066
} }
], ],
"selected_candidate": { "selected_candidate": {
@@ -526,38 +682,15 @@
"case_id": "CASE-04-HISTORICAL-PMH-ONLY", "case_id": "CASE-04-HISTORICAL-PMH-ONLY",
"title": "Past Medical History Without Inpatient Care (Remote CVA)", "title": "Past Medical History Without Inpatient Care (Remote CVA)",
"expected_behavior": "Guardrail 5: Historical-only conditions cannot automatically become coded secondary diagnoses.", "expected_behavior": "Guardrail 5: Historical-only conditions cannot automatically become coded secondary diagnoses.",
"status": "PARTIAL_SUCCESS", "status": "SUCCESS",
"primary_diagnosis": { "primary_diagnosis": null,
"code": "",
"description": "Elective repair of inguinal hernia",
"confidence_score": 1.0
},
"secondary_diagnoses": [], "secondary_diagnoses": [],
"abstention_count": 3, "abstention_count": 0,
"abstentions": [ "abstentions": [],
{
"diagnosis": "Remote stroke in 2014 without residual neurological deficit.",
"reason": "EXCLUDED_BY_NEGATION",
"detail": "Excluded from coding: [PAST_MEDICAL_HISTORY] Past Medical History alone without documented inpatient evaluation, monitoring, or therapy.",
"stage": "CLASSIFICATION"
},
{
"diagnosis": "Elective repair of inguinal hernia",
"reason": "NO_MATCHING_ICD_CANDIDATE",
"detail": "Unsupported specificity: Candidate 'K40.90' requires gangrene, unilateral, recurrent, which is not documented in clinical evidence.",
"stage": "RANKING"
},
{
"diagnosis": "Inguinal hernia repair",
"reason": "NO_MATCHING_ICD_CANDIDATE",
"detail": "Unsupported specificity: Candidate 'K40.90' requires gangrene, unilateral, recurrent, which is not documented in clinical evidence.",
"stage": "RANKING"
}
],
"audit_trail_sample": [ "audit_trail_sample": [
{ {
"document_id": "CASE-04-HISTORICAL-PMH-ONLY", "document_id": "CASE-04-HISTORICAL-PMH-ONLY",
"diagnosis_id": "fc58d184-3d23-431d-86bc-9a33e5aff293", "diagnosis_id": "8efa00aa-a42d-43be-9c32-aea64f8f7752",
"raw_term": "Remote stroke in 2014 without residual neurological deficit.", "raw_term": "Remote stroke in 2014 without residual neurological deficit.",
"evidence": "1. Remote stroke in 2014 without residual neurological deficit.", "evidence": "1. Remote stroke in 2014 without residual neurological deficit.",
"context": { "context": {
@@ -572,173 +705,7 @@
"reason": "Excluded from coding: [PAST_MEDICAL_HISTORY] Past Medical History alone without documented inpatient evaluation, monitoring, or therapy." "reason": "Excluded from coding: [PAST_MEDICAL_HISTORY] Past Medical History alone without documented inpatient evaluation, monitoring, or therapy."
}, },
"retrieved_candidates": [], "retrieved_candidates": [],
"selected_candidate": { "selected_candidate": null,
"code": null,
"description": null,
"confidence": 0.0,
"reason": "Candidate pool was empty; no matching local ICD code.",
"decision": "ABSTAINED"
},
"validation": {
"status": "REJECTED_OR_ABSTAINED",
"checks": []
},
"final_result": {
"code": null,
"description": null,
"role": null
}
},
{
"document_id": "CASE-04-HISTORICAL-PMH-ONLY",
"diagnosis_id": "ba8d4016-2393-4b5f-a158-642c33a2947b",
"raw_term": "Elective repair of inguinal hernia",
"evidence": "1. Elective repair of inguinal hernia.",
"context": {
"certainty": "CONFIRMED",
"temporality": "CURRENT",
"negation": "AFFIRMATIVE",
"acuity": "ACUTE"
},
"classification": {
"role": "PRIMARY",
"is_billable": true,
"reason": "Selected as unique Primary Diagnosis (score=7.5): Explicitly documented under discharge / final diagnoses (+5.0); Actively managed and treated during hospitalization (+1.5); Confirmed diagnostic certainty (+1.0)"
},
"retrieved_candidates": [
{
"code": "K42.9",
"description": "Umbilical hernia without obstruction or gangrene",
"score": 0.8
},
{
"code": "K43.9",
"description": "Ventral hernia without obstruction or gangrene",
"score": 0.8
},
{
"code": "K42.0",
"description": "Umbilical hernia with obstruction, without gangrene",
"score": 0.75
},
{
"code": "K42.1",
"description": "Umbilical hernia with gangrene",
"score": 0.75
},
{
"code": "K43.0",
"description": "Incisional hernia with obstruction, without gangrene",
"score": 0.75
},
{
"code": "K43.1",
"description": "Incisional hernia with gangrene",
"score": 0.75
},
{
"code": "K43.2",
"description": "Incisional hernia without obstruction or gangrene",
"score": 0.75
},
{
"code": "K43.3",
"description": "Parastomal hernia with obstruction, without gangrene",
"score": 0.75
},
{
"code": "K43.4",
"description": "Parastomal hernia with gangrene",
"score": 0.75
},
{
"code": "K43.5",
"description": "Parastomal hernia without obstruction or gangrene",
"score": 0.75
},
{
"code": "K43.6",
"description": "Other and unspecified ventral hernia with obstruction, without gangrene",
"score": 0.75
},
{
"code": "K43.7",
"description": "Other and unspecified ventral hernia with gangrene",
"score": 0.75
},
{
"code": "K40.90",
"description": "Unilateral inguinal hernia, without obstruction or gangrene, not specified as recurrent",
"score": 0.85
},
{
"code": "K40.30",
"description": "Unilateral inguinal hernia, with obstruction, without gangrene, not specified as recurrent",
"score": 0.8
},
{
"code": "K40.31",
"description": "Unilateral inguinal hernia, with obstruction, without gangrene, recurrent",
"score": 0.8
},
{
"code": "K40.40",
"description": "Unilateral inguinal hernia, with gangrene, not specified as recurrent",
"score": 0.8
},
{
"code": "K40.41",
"description": "Unilateral inguinal hernia, with gangrene, recurrent",
"score": 0.8
},
{
"code": "K40.91",
"description": "Unilateral inguinal hernia, without obstruction or gangrene, recurrent",
"score": 0.8
},
{
"code": "K40.11",
"description": "Bilateral inguinal hernia, with gangrene, recurrent",
"score": 0.5252
},
{
"code": "K40.00",
"description": "Bilateral inguinal hernia, with obstruction, without gangrene, not specified as recurrent",
"score": 0.8
},
{
"code": "K40.01",
"description": "Bilateral inguinal hernia, with obstruction, without gangrene, recurrent",
"score": 0.8
},
{
"code": "K40.10",
"description": "Bilateral inguinal hernia, with gangrene, not specified as recurrent",
"score": 0.8
},
{
"code": "K40.20",
"description": "Bilateral inguinal hernia, without obstruction or gangrene, not specified as recurrent",
"score": 0.8
},
{
"code": "K40.21",
"description": "Bilateral inguinal hernia, without obstruction or gangrene, recurrent",
"score": 0.8
},
{
"code": "K41.90",
"description": "Unilateral femoral hernia, without obstruction or gangrene, not specified as recurrent",
"score": 0.8
}
],
"selected_candidate": {
"code": null,
"description": null,
"confidence": 0.0,
"reason": "Unsupported specificity: Candidate 'K40.90' requires gangrene, unilateral, recurrent, which is not documented in clinical evidence.",
"decision": "ABSTAINED"
},
"validation": { "validation": {
"status": "REJECTED_OR_ABSTAINED", "status": "REJECTED_OR_ABSTAINED",
"checks": [] "checks": []
@@ -29,6 +29,7 @@ from medical_coding.schemas.evidence import (
StructuredEvidence, StructuredEvidence,
) )
from medical_coding.utils.logging import get_logger from medical_coding.utils.logging import get_logger
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
logger = get_logger(__name__) logger = get_logger(__name__)
@@ -194,15 +195,32 @@ class EvidenceFirstFactExtractor:
item: ClinicalDiagnosisCandidate, item: ClinicalDiagnosisCandidate,
) -> None: ) -> None:
"""Register, validate, and corroborate a candidate in the clinical inventory.""" """Register, validate, and corroborate a candidate in the clinical inventory."""
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate # Strip procedural wrapper if candidate is phrased as a surgical procedure for a disease (Section 11 & 12)
proc_wrapper_m = re.match(
r"^(?:(?:elective|open|laparoscopic|robotic|urgent|emergency|bilateral|unilateral|primary|revision)\s+)?"
r"(?:repair|resection|excision|stenting|mastectomy|cholecystectomy|appendectomy|biopsy|replacement|arthroplasty|fusion|drainage|decompression|catheterization|bypass|angioplasty|amputation|debridement)\s+(?:of|for)\s+(.+)$",
item.raw_term.strip(),
re.IGNORECASE,
)
if proc_wrapper_m:
underlying_disease = proc_wrapper_m.group(1).strip()
if len(underlying_disease) >= 3:
item.raw_term = underlying_disease
item.normalized_diagnosis = underlying_disease
item.procedure_relevance = 1.0
# Check candidate validity with Hard Gate # Check candidate validity with Hard Gate
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate( is_valid, reject_reason = HardClinicalCandidateGate.evaluate_candidate(
item.raw_term, item.primary_evidence_quote item.raw_term, item.primary_evidence_quote
) )
if not is_valid: if not is_valid:
logger.debug("Candidate gate rejected '%s': %s", item.raw_term, reject_reason)
return return
item.entity_type = HardClinicalCandidateGate.classify_entity_type(
item.raw_term, item.primary_evidence_quote
)
raw_t = item.raw_term.strip() raw_t = item.raw_term.strip()
# Handle question mark shorthand or uncertainty (?early evolving renal abscess) # Handle question mark shorthand or uncertainty (?early evolving renal abscess)
is_questionable = ( is_questionable = (
+29 -42
View File
@@ -581,54 +581,41 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
# LEVEL 1: Exact query hybrid retrieval # LEVEL 1: Exact query hybrid retrieval
queries_to_run = [query] queries_to_run = [query]
# LEVEL 2: Synonym / Abbreviation Expansion (Master Prompt Section 23) # LEVEL 2: Universal Concept & Token Morphology Expansion (Master Directive Sections 17 & 23)
from medical_coding.retrieval.tokenizer import CLINICAL_ABBREVIATIONS from medical_coding.retrieval.tokenizer import (
CLINICAL_ABBREVIATIONS,
get_expanded_query_tokens,
)
query_lower = query.lower() query_lower = query.lower()
expanded_terms: list[str] = [] expanded_terms: list[str] = []
# A. Normalized canonical concept name
if concept.canonical_name and concept.canonical_name.lower() != query_lower:
expanded_terms.append(concept.canonical_name)
# B. Generic abbreviation expansion
for ab, full in CLINICAL_ABBREVIATIONS.items(): for ab, full in CLINICAL_ABBREVIATIONS.items():
if re.search(rf"\b{re.escape(ab)}\b", query_lower): if re.search(rf"\b{re.escape(ab)}\b", query_lower):
expanded_terms.append(re.sub(rf"\b{re.escape(ab)}\b", full, query_lower)) expanded_terms.append(re.sub(rf"\b{re.escape(ab)}\b", full, query_lower))
if "acl" in query_lower: # C. Concept attribute combination query
expanded_terms.extend([ if concept.metastatic_status and concept.body_site:
"sprain of anterior cruciate ligament of knee", expanded_terms.append(f"secondary malignant neoplasm of {concept.body_site}")
"anterior cruciate ligament tear", expanded_terms.append(f"secondary neoplasm of {concept.body_site}")
"tear of anterior cruciate ligament", elif concept.histology and concept.body_site:
]) expanded_terms.append(f"{concept.histology} of {concept.body_site}")
if "sarcoma" in query_lower and "liver" in query_lower: expanded_terms.append(f"malignant neoplasm of {concept.body_site}")
expanded_terms.extend([
"other sarcomas of liver", if concept.acuity and concept.canonical_name:
"sarcoma of liver", expanded_terms.append(f"{concept.acuity} {concept.canonical_name}")
"malignant neoplasm of liver",
]) # D. Generic morphological query tokens
if "neuroendocrine" in query_lower or "net" in query_lower: exp_tokens = get_expanded_query_tokens(query)
expanded_terms.extend([ if exp_tokens and len(exp_tokens) > 1:
"carcinoid tumor of ascending colon", morph_query = " ".join(exp_tokens[:6])
"malignant carcinoid tumor of ascending colon", if morph_query not in expanded_terms:
"malignant carcinoid tumor colon", expanded_terms.append(morph_query)
])
if "urticaria" in query_lower:
expanded_terms.extend([
"other urticaria",
"urticaria unspecified",
])
if "pyelonephritis" in query_lower:
expanded_terms.extend([
"acute pyelonephritis",
"pyelonephritis",
])
if "gastritis" in query_lower and "bleeding" not in query_lower:
expanded_terms.extend([
"gastritis without bleeding",
"unspecified gastritis without bleeding",
])
if any(w in query_lower for w in ("metastasis", "metastases", "metastatic", "mets")):
site = concept.body_site or ("liver" if "liver" in query_lower else ("pleura" if "pleura" in query_lower else ("bone" if "bone" in query_lower else ("brain" if "brain" in query_lower else ""))))
if site:
expanded_terms.extend([
f"secondary malignant neoplasm of {site}",
f"secondary neoplasm of {site}",
])
for exp in expanded_terms: for exp in expanded_terms:
if exp not in queries_to_run: if exp not in queries_to_run:
@@ -10,6 +10,7 @@ Conforms to Master Specification Section 5 & 6:
import re import re
from typing import Any from typing import Any
from medical_coding.schemas.enums import ClinicalEntityType
from medical_coding.schemas.reasoning import ClinicalConcept from medical_coding.schemas.reasoning import ClinicalConcept
from medical_coding.utils.logging import get_logger from medical_coding.utils.logging import get_logger
@@ -214,27 +215,46 @@ class ClinicalConceptReasoner:
if getattr(candidate, "temporality", None) in ("HISTORICAL", "RESOLVED"): if getattr(candidate, "temporality", None) in ("HISTORICAL", "RESOLVED"):
temporality = str(candidate.temporality) temporality = str(candidate.temporality)
cid = getattr(candidate, "diagnosis_id", None) or getattr(candidate, "condition_id", None) or "" entity_type = getattr(candidate, "entity_type", None) or "DIAGNOSIS"
if isinstance(entity_type, str):
try:
entity_type = ClinicalEntityType(entity_type)
except ValueError:
entity_type = ClinicalEntityType.DIAGNOSIS
cid = getattr(candidate, "diagnosis_id", None) or getattr(candidate, "condition_id", None) or getattr(candidate, "id", "") or ""
return ClinicalConcept( return ClinicalConcept(
concept_id=str(cid) if cid else None, concept_id=str(cid) if cid else None,
id=str(cid) if cid else None,
canonical_name=raw_term, canonical_name=raw_term,
canonical_concept=raw_term,
normalized_concept=getattr(candidate, "normalized_diagnosis", raw_term),
entity_type=entity_type,
disease_family=matched_family, disease_family=matched_family,
body_site=detected_site, body_site=detected_site,
anatomy=detected_site,
laterality=detected_laterality, laterality=detected_laterality,
etiology=etiology, etiology=etiology,
histology=histology, histology=histology,
severity=None, severity=None,
complication=None, complication=None,
acuity=getattr(candidate, "acuity", None),
temporal_status=temporality, temporal_status=temporality,
temporality=temporality,
assertion_status=assertion, assertion_status=assertion,
role_hint=str(getattr(candidate, "role", "SECONDARY")), role_hint=str(getattr(candidate, "role", "SECONDARY")),
role=str(getattr(candidate, "role", "SECONDARY")),
metastatic_status=is_metastatic, metastatic_status=is_metastatic,
metastatic_sites=metastatic_sites, metastatic_sites=metastatic_sites,
evidence_spans=[quote] if quote else [], evidence_spans=[quote] if quote else [],
supporting_evidence=[quote] if quote else [],
supporting_sections=[getattr(candidate, "source_section", "DISCHARGE_DIAGNOSES") or "DISCHARGE_DIAGNOSES"], supporting_sections=[getattr(candidate, "source_section", "DISCHARGE_DIAGNOSES") or "DISCHARGE_DIAGNOSES"],
source_sections=[getattr(candidate, "source_section", "DISCHARGE_DIAGNOSES") or "DISCHARGE_DIAGNOSES"],
supported_attributes=supported_attributes, supported_attributes=supported_attributes,
unknown_attributes=unknown_attributes, unknown_attributes=unknown_attributes,
contradictory_attributes=[], contradictory_attributes=[],
contradiction_evidence=[],
confidence=float(getattr(candidate, "confidence_score", 1.0) or 1.0), confidence=float(getattr(candidate, "confidence_score", 1.0) or 1.0),
clinical_confidence=float(getattr(candidate, "confidence_score", 1.0) or 1.0),
) )
+11 -8
View File
@@ -61,14 +61,6 @@ class MatchSpecBuilder:
def build_match_spec(cls, concept: ClinicalConcept) -> MatchSpec: def build_match_spec(cls, concept: ClinicalConcept) -> MatchSpec:
"""Construct MatchSpec with allowed code families and attribute firewalls.""" """Construct MatchSpec with allowed code families and attribute firewalls."""
allowed_prefixes = list(FAMILY_TO_CODE_PREFIXES.get(concept.disease_family, [])) allowed_prefixes = list(FAMILY_TO_CODE_PREFIXES.get(concept.disease_family, []))
name_lower = concept.canonical_name.lower()
if concept.disease_family == "sprain_ankle_ligament":
if "deltoid" in name_lower:
allowed_prefixes = ["S93.42", "S93.4"]
elif "calcaneofibular" in name_lower:
allowed_prefixes = ["S93.41", "S93.4"]
required_attrs: dict[str, Any] = {} required_attrs: dict[str, Any] = {}
forbidden_attrs: list[str] = [] forbidden_attrs: list[str] = []
@@ -154,4 +146,15 @@ class MatchSpecBuilder:
forbidden_attributes=forbidden_attrs, forbidden_attributes=forbidden_attrs,
unknown_attributes=concept.unknown_attributes, unknown_attributes=concept.unknown_attributes,
target_coding_system="ICD-10-CM", target_coding_system="ICD-10-CM",
concept_family=concept.disease_family,
anatomical_site=concept.body_site or concept.anatomy,
laterality=concept.laterality,
etiology=concept.etiology,
histology=concept.histology,
severity=concept.severity,
complication=concept.complication,
temporal_status=concept.temporality.value if hasattr(concept.temporality, "value") else str(concept.temporality),
encounter_context=concept.encounter_context,
relationship_constraints=[],
coding_system="ICD-10-CM",
) )
+51 -2
View File
@@ -79,18 +79,66 @@ class Laterality(StrEnum):
class ClinicalEntityType(StrEnum): class ClinicalEntityType(StrEnum):
"""Categorization of extracted clinical entities.""" """Universal Clinical Entity Taxonomy conforming to Master Directive Section 2.
Classifies every extracted clinical phrase into exactly one primary entity category prior to database retrieval.
"""
DIAGNOSIS = "DIAGNOSIS" DIAGNOSIS = "DIAGNOSIS"
SYMPTOM = "SYMPTOM" SYMPTOM = "SYMPTOM"
SIGN = "SIGN" SIGN = "SIGN"
CLINICAL_FINDING = "CLINICAL_FINDING"
COMPLICATION = "COMPLICATION"
INJURY = "INJURY"
NEOPLASM = "NEOPLASM"
INFECTION = "INFECTION"
CHRONIC_CONDITION = "CHRONIC_CONDITION"
COMORBIDITY = "COMORBIDITY"
PROCEDURE = "PROCEDURE"
SURGERY = "SURGERY"
TREATMENT = "TREATMENT"
MEDICATION = "MEDICATION"
INVESTIGATION = "INVESTIGATION"
LAB_RESULT = "LAB_RESULT"
IMAGING_FINDING = "IMAGING_FINDING"
PATHOLOGY_FINDING = "PATHOLOGY_FINDING"
ANATOMICAL_SITE = "ANATOMICAL_SITE"
CLINICAL_ATTRIBUTE = "CLINICAL_ATTRIBUTE"
TEMPORAL_CONTEXT = "TEMPORAL_CONTEXT"
ENCOUNTER_CONTEXT = "ENCOUNTER_CONTEXT"
ADMINISTRATIVE_TEXT = "ADMINISTRATIVE_TEXT"
INSTRUCTION = "INSTRUCTION"
NEGATED_CONDITION = "NEGATED_CONDITION"
FAMILY_HISTORY = "FAMILY_HISTORY"
OTHER_NON_CODABLE_TEXT = "OTHER_NON_CODABLE_TEXT"
PROCEDURAL_FINDING = "PROCEDURAL_FINDING" PROCEDURAL_FINDING = "PROCEDURAL_FINDING"
UNKNOWN = "UNKNOWN" UNKNOWN = "UNKNOWN"
class EvidenceType(StrEnum): class EvidenceType(StrEnum):
"""Clinical evidence category providing documentary authorization.""" """Clinical evidence category providing documentary authorization (Section 3)."""
# Section 3 fine-grained clinical evidence types
EXPLICIT_DIAGNOSIS = "explicit_diagnosis"
DISCHARGE_DIAGNOSIS = "discharge_diagnosis"
ADMISSION_DIAGNOSIS = "admission_diagnosis"
PHYSICIAN_ASSESSMENT = "physician_assessment"
PATHOLOGY_CONFIRMATION = "pathology_confirmation"
IMAGING_CONFIRMATION = "imaging_confirmation"
LABORATORY_CONFIRMATION = "laboratory_confirmation"
OPERATIVE_CONFIRMATION = "operative_confirmation"
TREATMENT_FOR_CONDITION = "treatment_for_condition"
DOCUMENTED_ACTIVE_MANAGEMENT = "documented_active_management"
HISTORICAL_DOCUMENTATION = "historical_documentation"
SYMPTOM_ONLY = "symptom_only"
INCIDENTAL_FINDING = "incidental_finding"
PROCEDURE_CONTEXT = "procedure_context"
MEDICATION_CONTEXT = "medication_context"
INSTRUCTION_CONTEXT = "instruction_context"
NEGATIVE_STATEMENT = "negative_statement"
SUSPECTED_STATEMENT = "suspected_statement"
RULED_OUT_STATEMENT = "ruled_out_statement"
# Uppercase aliases preserved for backward compatibility
DISCHARGE_SUMMARY = "DISCHARGE_SUMMARY" DISCHARGE_SUMMARY = "DISCHARGE_SUMMARY"
ADMISSION_REASON = "ADMISSION_REASON" ADMISSION_REASON = "ADMISSION_REASON"
CHIEF_COMPLAINT = "CHIEF_COMPLAINT" CHIEF_COMPLAINT = "CHIEF_COMPLAINT"
@@ -98,6 +146,7 @@ class EvidenceType(StrEnum):
PROCEDURE = "PROCEDURE" PROCEDURE = "PROCEDURE"
IMAGING = "IMAGING" IMAGING = "IMAGING"
LAB = "LAB" LAB = "LAB"
LABORATORY = "LAB"
HISTORY = "HISTORY" HISTORY = "HISTORY"
CLINICAL_NOTE = "CLINICAL_NOTE" CLINICAL_NOTE = "CLINICAL_NOTE"
OTHER = "OTHER" OTHER = "OTHER"
+5
View File
@@ -8,6 +8,7 @@ from pydantic import BaseModel, Field, model_validator
from medical_coding.schemas.enums import ( from medical_coding.schemas.enums import (
AssertionStatus, AssertionStatus,
Certainty, Certainty,
ClinicalEntityType,
DiagnosisRole, DiagnosisRole,
EvidenceType, EvidenceType,
NegationStatus, NegationStatus,
@@ -128,6 +129,10 @@ class ClinicalDiagnosisCandidate(BaseModel):
min_length=1, min_length=1,
description="Canonical medical description without ICD code assumptions.", description="Canonical medical description without ICD code assumptions.",
) )
entity_type: ClinicalEntityType = Field(
default=ClinicalEntityType.DIAGNOSIS,
description="Primary taxonomy category from Universal Entity Taxonomy (Section 2).",
)
role: DiagnosisRole = Field( role: DiagnosisRole = Field(
default=DiagnosisRole.SECONDARY, default=DiagnosisRole.SECONDARY,
description="PRIMARY, SECONDARY, HISTORICAL, SYMPTOM, INCIDENTAL, RULED_OUT, UNCERTAIN.", description="PRIMARY, SECONDARY, HISTORICAL, SYMPTOM, INCIDENTAL, RULED_OUT, UNCERTAIN.",
+207 -18
View File
@@ -13,38 +13,80 @@ from pydantic import BaseModel, Field
class ClinicalConcept(BaseModel): class ClinicalConcept(BaseModel):
"""Normalized clinical concept derived from clinical evidence prior to database retrieval. """Generic Clinical Concept conforming to Master Directive Section 26.
Enforces the fundamental clinical invariant: Enforces the fundamental clinical invariant:
CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY
Attributes not supported by explicit documentation remain in unknown_attributes. Attributes not supported by explicit documentation remain in unknown_attributes.
""" """
concept_id: str = Field( id: str = Field(
default_factory=lambda: str(uuid4()), default_factory=lambda: str(uuid4()),
description="Unique concept identifier linking back to diagnosis candidate.", description="Unique concept identifier linking back to diagnosis candidate.",
) )
canonical_name: str = Field( concept_id: str = Field(
default="",
description="Alias for concept id.",
)
raw_mentions: list[str] = Field(
default_factory=list,
description="Original text spans from the document.",
)
canonical_concept: str = Field(
default="",
description="Normalized clinical diagnosis name without database code assumptions.", description="Normalized clinical diagnosis name without database code assumptions.",
) )
canonical_name: str = Field(
default="",
description="Alias for canonical concept.",
)
normalized_concept: str = Field(
default="",
description="Fully normalized clinical concept string.",
)
entity_type: str = Field(
default="DIAGNOSIS",
description="Category from Universal Clinical Entity Taxonomy (Section 2).",
)
disease_family: str = Field( disease_family: str = Field(
description="High-level clinical disease family (e.g. 'breast_malignancy', 'renal_calculus', 'gastritis').", default="",
description="High-level clinical disease family (e.g. 'breast_malignancy', 'renal_calculus').",
)
anatomy: str | None = Field(
default=None,
description="Primary anatomical site (e.g. 'breast', 'kidney', 'knee', 'liver').",
) )
body_site: str | None = Field( body_site: str | None = Field(
default=None, default=None,
description="Primary anatomical site (e.g. 'breast', 'kidney', 'ureter', 'stomach', 'fibula').", description="Alias for anatomical site.",
) )
laterality: str | None = Field( laterality: str | None = Field(
default=None, default=None,
description="Documented anatomical laterality: 'left', 'right', 'bilateral', or None.", description="Documented anatomical laterality: 'left', 'right', 'bilateral', or None.",
) )
subsite: str | None = Field(
default=None,
description="Specific anatomical subsite if documented.",
)
etiology: str | None = Field( etiology: str | None = Field(
default=None, default=None,
description="Etiological organism or causal factor (e.g. 'helicobacter_pylori', 'e_coli').", description="Etiological organism or causal factor (e.g. 'helicobacter_pylori', 'e_coli').",
) )
organism: str | None = Field(
default=None,
description="Specific infectious pathogen if documented.",
)
histology: str | None = Field( histology: str | None = Field(
default=None, default=None,
description="Pathological histology (e.g. 'carcinoma', 'dlbcl', 'adenocarcinoma').", description="Pathological histology (e.g. 'carcinoma', 'dlbcl', 'sarcoma', 'carcinoid').",
)
grade: str | None = Field(
default=None,
description="Pathologic or histologic grade.",
)
stage: str | None = Field(
default=None,
description="Clinical or pathological stage.",
) )
severity: str | None = Field( severity: str | None = Field(
default=None, default=None,
@@ -52,19 +94,35 @@ class ClinicalConcept(BaseModel):
) )
complication: str | None = Field( complication: str | None = Field(
default=None, default=None,
description="Associated manifestation or complication (e.g. 'septic_shock', 'renal_colic').", description="Associated manifestation or complication.",
) )
temporal_status: str = Field( acuity: str | None = Field(
default="CURRENT", default=None,
description="CURRENT, HISTORICAL, RESOLVED, or UNCLEAR.", description="Acuity profile: 'acute', 'chronic', 'acute_on_chronic', 'unspecified'.",
)
encounter_context: str | None = Field(
default=None,
description="Encounter context: 'initial', 'subsequent', 'sequela'.",
) )
assertion_status: str = Field( assertion_status: str = Field(
default="CONFIRMED", default="CONFIRMED",
description="CONFIRMED, SUSPECTED, RULED_OUT, or NEGATED.", description="CONFIRMED, SUSPECTED, UNCERTAIN, RULED_OUT, NEGATED, HISTORICAL, etc.",
)
temporality: str = Field(
default="CURRENT",
description="CURRENT, HISTORICAL, RESOLVED, FUTURE, UNCLEAR.",
)
temporal_status: str = Field(
default="CURRENT",
description="Alias for temporality.",
)
role: str = Field(
default="SECONDARY",
description="Inferred initial clinical role: PRIMARY, SECONDARY, or NON_CODABLE.",
) )
role_hint: str = Field( role_hint: str = Field(
default="SECONDARY", default="SECONDARY",
description="Inferred initial clinical role: PRIMARY, SECONDARY, or EXCLUDED.", description="Alias for role.",
) )
metastatic_status: bool = Field( metastatic_status: bool = Field(
default=False, default=False,
@@ -72,16 +130,40 @@ class ClinicalConcept(BaseModel):
) )
metastatic_sites: list[str] = Field( metastatic_sites: list[str] = Field(
default_factory=list, default_factory=list,
description="Explicitly documented secondary/metastatic anatomical sites (e.g. ['pleura']).", description="Explicitly documented secondary/metastatic anatomical sites.",
) )
evidence_spans: list[str] = Field( evidence_spans: list[str] = Field(
default_factory=list, default_factory=list,
description="Verbatim textual evidence quotes supporting this clinical concept.", description="Verbatim textual evidence quotes supporting this clinical concept.",
) )
supporting_sections: list[str] = Field( source_sections: list[str] = Field(
default_factory=list, default_factory=list,
description="Sections where mentions of this concept occurred.", description="Sections where mentions of this concept occurred.",
) )
supporting_sections: list[str] = Field(
default_factory=list,
description="Alias for source sections.",
)
supporting_evidence: list[dict[str, Any] | str] = Field(
default_factory=list,
description="Detailed structured evidence objects or text strings.",
)
contradiction_evidence: list[str] = Field(
default_factory=list,
description="Evidence statements contradicting this candidate.",
)
related_concepts: list[str] = Field(
default_factory=list,
description="Concepts related to this entity in the clinical evidence graph.",
)
treatment_support: list[str] = Field(
default_factory=list,
description="Documented treatments or active therapies supporting this condition.",
)
diagnostic_support: list[str] = Field(
default_factory=list,
description="Diagnostic investigations or pathology corroborating this condition.",
)
supported_attributes: list[str] = Field( supported_attributes: list[str] = Field(
default_factory=list, default_factory=list,
description="Attributes explicitly supported by clinical documentation.", description="Attributes explicitly supported by clinical documentation.",
@@ -90,20 +172,81 @@ class ClinicalConcept(BaseModel):
default_factory=list, default_factory=list,
description="Attributes relevant to the disease family that are NOT documented.", description="Attributes relevant to the disease family that are NOT documented.",
) )
contradictory_attributes: list[str] = Field( contradicted_attributes: list[str] = Field(
default_factory=list, default_factory=list,
description="Attributes contradicted or ruled out by clinical evidence.", description="Attributes contradicted or ruled out by clinical evidence.",
) )
confidence: float = Field( contradictory_attributes: list[str] = Field(
default_factory=list,
description="Alias for contradicted_attributes.",
)
clinical_confidence: float = Field(
default=1.0, default=1.0,
ge=0.0, ge=0.0,
le=1.0, le=1.0,
description="Clinical confidence score for this concept.", description="Clinical confidence score for this concept.",
) )
confidence: float = Field(
default=1.0,
ge=0.0,
le=1.0,
description="Alias for clinical_confidence.",
)
coding_system: str = Field(
default="ICD-10-CM",
description="Target coding system: 'ICD-10-CM', 'ICD-O', 'CPT'.",
)
database_candidates: list[Any] = Field(
default_factory=list,
description="Candidates retrieved from the authoritative local database.",
)
selected_database_record: Any | None = Field(
default=None,
description="Final selected database record after ranking and validation.",
)
validation_status: str = Field(
default="VALIDATED",
description="Validation outcome: 'VALIDATED', 'DOWNGRADED', 'REJECTED', 'ABSTAINED'.",
)
def model_post_init(self, __context: Any) -> None:
"""Synchronize aliases after initialization."""
if not self.concept_id and self.id:
self.concept_id = self.id
elif not self.id and self.concept_id:
self.id = self.concept_id
if not self.canonical_concept and self.canonical_name:
self.canonical_concept = self.canonical_name
elif not self.canonical_name and self.canonical_concept:
self.canonical_name = self.canonical_concept
if not self.normalized_concept and self.canonical_concept:
self.normalized_concept = self.canonical_concept
if not self.anatomy and self.body_site:
self.anatomy = self.body_site
elif not self.body_site and self.anatomy:
self.body_site = self.anatomy
if not self.temporality and self.temporal_status:
self.temporality = self.temporal_status
elif not self.temporal_status and self.temporality:
self.temporal_status = self.temporality
if not self.role and self.role_hint:
self.role = self.role_hint
elif not self.role_hint and self.role:
self.role_hint = self.role
if not self.source_sections and self.supporting_sections:
self.source_sections = list(self.supporting_sections)
elif not self.supporting_sections and self.source_sections:
self.supporting_sections = list(self.source_sections)
if not self.contradicted_attributes and self.contradictory_attributes:
self.contradicted_attributes = list(self.contradictory_attributes)
elif not self.contradictory_attributes and self.contradicted_attributes:
self.contradictory_attributes = list(self.contradicted_attributes)
if self.clinical_confidence != self.confidence:
self.confidence = self.clinical_confidence
class MatchSpec(BaseModel): class MatchSpec(BaseModel):
"""Deterministic database retrieval constraint built from ClinicalConcept. """Deterministic database retrieval constraint built from ClinicalConcept (Sections 16 & 26).
Constrains database retrieval so vector similarity operates ONLY within Constrains database retrieval so vector similarity operates ONLY within
clinically compatible candidate subsets. clinically compatible candidate subsets.
@@ -118,6 +261,38 @@ class MatchSpec(BaseModel):
disease_family: str = Field( disease_family: str = Field(
description="Disease family classification.", description="Disease family classification.",
) )
anatomical_site: str | None = Field(
default=None,
description="Target anatomical site constraint.",
)
laterality: str | None = Field(
default=None,
description="Target anatomical laterality constraint.",
)
etiology: str | None = Field(
default=None,
description="Documented etiology constraint.",
)
histology: str | None = Field(
default=None,
description="Pathological histology constraint.",
)
severity: str | None = Field(
default=None,
description="Severity qualifier constraint.",
)
complication: str | None = Field(
default=None,
description="Associated complication constraint.",
)
temporal_status: str = Field(
default="CURRENT",
description="Temporal status constraint.",
)
encounter_context: str | None = Field(
default=None,
description="Encounter context constraint (initial, subsequent, sequela).",
)
allowed_code_families: list[str] = Field( allowed_code_families: list[str] = Field(
default_factory=list, default_factory=list,
description="ICD-10-CM code category prefixes permitted for this concept (e.g. ['C50.*']).", description="ICD-10-CM code category prefixes permitted for this concept (e.g. ['C50.*']).",
@@ -134,10 +309,24 @@ class MatchSpec(BaseModel):
default_factory=list, default_factory=list,
description="Attributes not supported by evidence; codes requiring them must be rejected.", description="Attributes not supported by evidence; codes requiring them must be rejected.",
) )
target_coding_system: str = Field( relationship_constraints: list[str] | dict[str, Any] = Field(
default_factory=list,
description="Constraints on clinical relationships (e.g. ['primary_only', 'secondary_only']).",
)
coding_system: str = Field(
default="ICD-10-CM", default="ICD-10-CM",
description="Target database coding system: 'ICD-10-CM', 'ICD-O', or 'CPT'.", description="Target database coding system: 'ICD-10-CM', 'ICD-O', or 'CPT'.",
) )
target_coding_system: str = Field(
default="ICD-10-CM",
description="Alias for coding_system.",
)
def model_post_init(self, __context: Any) -> None:
if not self.coding_system and self.target_coding_system:
self.coding_system = self.target_coding_system
elif not self.target_coding_system and self.coding_system:
self.target_coding_system = self.coding_system
class CompatibilityResult(BaseModel): class CompatibilityResult(BaseModel):
+161 -2
View File
@@ -11,6 +11,8 @@ Strictly rejects:
import re import re
from medical_coding.schemas.enums import ClinicalEntityType
# 1. Statements describing the ABSENCE of disease, complications, or adverse events # 1. Statements describing the ABSENCE of disease, complications, or adverse events
ABSENCE_PATTERNS = [ ABSENCE_PATTERNS = [
r"^\s*no\s+(?:acute|major|significant|active|obvious|evident|apparent|new|further)?\s*(?:complications?|adverse\s+(?:events?|reactions?|effects?)|reactions?|bleeding|ulceration|ischemia|infarction|recurrence|toxicity|decompensation|sequelae|abnormality|distress|complaints?)\b", r"^\s*no\s+(?:acute|major|significant|active|obvious|evident|apparent|new|further)?\s*(?:complications?|adverse\s+(?:events?|reactions?|effects?)|reactions?|bleeding|ulceration|ischemia|infarction|recurrence|toxicity|decompensation|sequelae|abnormality|distress|complaints?)\b",
@@ -111,12 +113,60 @@ PATHOLOGY_KEYWORDS = {
} }
# 7. Procedure and surgical keywords (Section 11 Procedure Firewall)
PROCEDURE_TERMS = {
"mastectomy", "reconstruction", "endoscopy", "colonoscopy", "stenting", "stent",
"biopsy", "laparoscopy", "excision", "resection", "debridement", "incision",
"repair", "intubation", "catheterization", "cannulation", "grafting", "arthroscopy",
"cholecystectomy", "appendectomy", "hysterectomy", "lumpectomy", "angioplasty",
"bypass", "dialysis", "hemodialysis", "paracentesis", "thoracentesis", "fet",
"frozen embryo transfer", "infusion", "chemotherapy", "radiotherapy", "radiation",
}
PROCEDURE_SUFFIXES = (
"ectomy", "otomy", "ostomy", "plasty", "pexy", "scopy", "centesis", "rrhaphy",
)
# 8. Investigation names lacking pathological findings
INVESTIGATION_TERMS = {
"ct", "ct scan", "mri", "cxr", "chest x-ray", "ultrasound", "usg",
"echocardiogram", "echo", "ecg", "ekg", "xray", "x-ray", "eeg", "emg", "urinalysis",
}
# 9. Family history and hypothetical cues
FAMILY_HISTORY_PATTERNS = [
r"\b(?:family\s+history|fhx|mother\s+(?:had|with)|father\s+(?:had|with)|sister\s+(?:had|with)|brother\s+(?:had|with))\b",
]
HYPOTHETICAL_PATTERNS = [
r"\b(?:if\s+symptoms?\s+worsen|in\s+the\s+event\s+of|in\s+case\s+of|contingent\s+upon)\b",
]
class HardClinicalCandidateGate: class HardClinicalCandidateGate:
"""Deterministic clinical candidate gate enforcing Section 3, 5 & 8 requirements.""" """Deterministic clinical candidate gate enforcing Section 4 & Section 11 specifications."""
@classmethod @classmethod
def evaluate_candidate(cls, term: str, evidence_text: str = "") -> tuple[bool, str]: def evaluate_candidate(cls, term: str, evidence_text: str = "") -> tuple[bool, str]:
"""Evaluate whether an extracted term is a genuine clinical diagnosis. """Evaluate whether an extracted term is a genuine clinical diagnosis (Section 4).
A candidate MUST satisfy:
1. It represents a clinical condition or codable clinical concept.
2. It has identifiable evidence in the source document.
3. The evidence is attributable to the patient.
4. The evidence is not merely a heading or section label.
5. The evidence is not merely a procedure.
6. The evidence is not merely a medication.
7. The evidence is not merely a treatment instruction.
8. The evidence is not merely an investigation name.
9. The evidence is not merely an anatomical site.
10. The evidence is not merely a disease attribute.
11. The evidence is not negated.
12. The evidence is not purely family history.
13. The evidence is not hypothetical.
14. The evidence is not merely a rule-out diagnosis.
15. The candidate does not depend on unsupported inference.
16. The candidate is not generated solely from database retrieval.
Returns: Returns:
Tuple of (is_valid, rejection_reason). Tuple of (is_valid, rejection_reason).
@@ -171,8 +221,115 @@ class HardClinicalCandidateGate:
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"]): 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"]):
return False, f"Metadata or template header artifact: '{clean_term}'" return False, f"Metadata or template header artifact: '{clean_term}'"
# Check 9: Pure surgical or procedural interventions (Section 11 Procedure Firewall)
is_pure_procedure = (
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)
)
if is_pure_procedure:
words = set(re.findall(r"[a-z]+", term_lower))
if not words.intersection(PATHOLOGY_KEYWORDS):
return False, f"Procedure or surgical intervention, not an independent clinical diagnosis: '{clean_term}'"
# Check 10: Pure investigation names lacking findings
is_pure_investigation = any(term_lower == inv or term_lower.startswith(f"{inv} of ") for inv in INVESTIGATION_TERMS)
if is_pure_investigation:
words = set(re.findall(r"[a-z]+", term_lower))
if not words.intersection(PATHOLOGY_KEYWORDS):
return False, f"Investigation or diagnostic test name lacking pathological finding: '{clean_term}'"
# Check 11: Family history
for pat in FAMILY_HISTORY_PATTERNS:
if re.search(pat, term_lower):
return False, f"Family medical history, not personal patient condition: '{clean_term}'"
# Check 12: Hypothetical statements
for pat in HYPOTHETICAL_PATTERNS:
if re.search(pat, term_lower):
return False, f"Hypothetical or contingent clinical statement: '{clean_term}'"
return True, "Valid clinical diagnosis entity" return True, "Valid clinical diagnosis entity"
@classmethod
def classify_entity_type(cls, term: str, evidence_text: str = "") -> ClinicalEntityType:
"""Classify any clinical phrase into the Universal Clinical Entity Taxonomy (Section 2)."""
term_lower = term.strip().lower()
ev_lower = evidence_text.strip().lower()
# 1. Negated
if any(re.search(pat, term_lower) for pat in ABSENCE_PATTERNS) or term_lower.startswith("no ") or "ruled out" in term_lower or "negative for" in term_lower:
return ClinicalEntityType.NEGATED_CONDITION
# 2. Family History
if any(re.search(pat, term_lower) for pat in FAMILY_HISTORY_PATTERNS) or "family history" in ev_lower:
return ClinicalEntityType.FAMILY_HISTORY
# 3. Instruction
if any(re.search(pat, term_lower) for pat in INSTRUCTION_PATTERNS):
return ClinicalEntityType.INSTRUCTION
# 4. Administrative Text
if any(term_lower == m or re.search(pat, term_lower) for pat in METADATA_PATTERNS for m in ["not applicable", "n/a", "biomarkers & receptor status"]):
return ClinicalEntityType.ADMINISTRATIVE_TEXT
# 5. Clinical Attribute
if any(re.search(pat, term_lower) for pat in STANDALONE_ATTRIBUTE_PATTERNS):
return ClinicalEntityType.CLINICAL_ATTRIBUTE
# 6. Anatomical Site
if any(re.search(pat, term_lower) for pat in ISOLATED_ANATOMY_PATTERNS):
return ClinicalEntityType.ANATOMICAL_SITE
# 7. Medication
if any(re.search(pat, term_lower) for pat in DOSAGE_FORM_PATTERNS) or any(re.search(pat, term_lower) for pat in PRESCRIPTION_SYNTAX_PATTERNS):
return ClinicalEntityType.MEDICATION
# 8. Surgery & Procedure
is_procedure = (
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)
)
if is_procedure:
words = set(re.findall(r"[a-z]+", term_lower))
if not words.intersection(PATHOLOGY_KEYWORDS):
if any(surg in term_lower for surg in ("mastectomy", "resection", "excision", "cholecystectomy", "appendectomy", "repair", "bypass")):
return ClinicalEntityType.SURGERY
return ClinicalEntityType.PROCEDURE
# 9. Investigation
if any(term_lower == inv or term_lower.startswith(f"{inv} of ") for inv in INVESTIGATION_TERMS):
words = set(re.findall(r"[a-z]+", term_lower))
if not words.intersection(PATHOLOGY_KEYWORDS):
return ClinicalEntityType.INVESTIGATION
# 10. Symptoms & Signs
if any(sym in term_lower for sym in ["pain", "cough", "nausea", "vomiting", "dyspnea", "shortness of breath", "fatigue", "malaise", "colic", "dizziness"]):
return ClinicalEntityType.SYMPTOM
if any(sign in term_lower for sign in ["tachycardia", "tachypnea", "fever", "hypotension", "wheezing", "rales", "edema", "swelling"]):
return ClinicalEntityType.SIGN
# 11. Neoplasms
if any(neo in term_lower for neo in ["carcinoma", "sarcoma", "lymphoma", "cancer", "neoplasm", "tumor", "carcinoid", "adenoma", "malignancy"]):
return ClinicalEntityType.NEOPLASM
# 12. Injuries
if any(inj in term_lower for inj in ["fracture", "tear", "sprain", "strain", "rupture", "dislocation", "laceration", "contusion", "injury"]):
return ClinicalEntityType.INJURY
# 13. Infections
if any(inf in term_lower for inf in ["infection", "pyelonephritis", "pneumonia", "uti", "sepsis", "cellulitis", "candidiasis", "abscess", "bacteremia"]):
return ClinicalEntityType.INFECTION
# 14. Chronic Conditions
if any(chr_c in term_lower for chr_c in ["hypertension", "diabetes", "asthma", "copd", "ckd", "chronic"]):
return ClinicalEntityType.CHRONIC_CONDITION
# 15. Complications
if any(comp in term_lower for comp in ["septic shock", "dka", "ketoacidosis", "acute kidney injury", "hemorrhage"]):
return ClinicalEntityType.COMPLICATION
return ClinicalEntityType.DIAGNOSIS
@classmethod @classmethod
def get_rejection_category(cls, term: str, _evidence_text: str = "") -> str: def get_rejection_category(cls, term: str, _evidence_text: str = "") -> str:
"""Classify the deterministic rejection category for audit reporting.""" """Classify the deterministic rejection category for audit reporting."""
@@ -186,6 +343,8 @@ class HardClinicalCandidateGate:
if any(re.search(pat, term_lower) for pat in DOSAGE_FORM_PATTERNS) or any(re.search(pat, term_lower) for pat in PRESCRIPTION_SYNTAX_PATTERNS): if any(re.search(pat, term_lower) for pat in DOSAGE_FORM_PATTERNS) or any(re.search(pat, term_lower) for pat in PRESCRIPTION_SYNTAX_PATTERNS):
return "MEDICATION" return "MEDICATION"
if any(re.search(pat, term_lower) for pat in INSTRUCTION_PATTERNS): 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" return "PROCEDURE"
if any(re.search(pat, term_lower) for pat in ISOLATED_ANATOMY_PATTERNS): if any(re.search(pat, term_lower) for pat in ISOLATED_ANATOMY_PATTERNS):
return "ANATOMY" return "ANATOMY"