feat(pipeline): complete healing and hardening of clinical reasoning and matching pipeline
- Implement soft dimensional compatibility and 3-way attribute logic (SUPPORTED, CONTRADICTED, UNKNOWN) - Replace binary hardwall rejection with nuanced compatibility scoring - Isolate context per diagnosis to prevent cross-condition contamination (MD Sec 41) - Generalize disease families (liver sarcoma, net, asthma, acl) and category priors - Add regex word boundary acuity checking and laterality alignment scoring in ranker - Fix candidate sort by sorting on unconstrained multi-factor raw score before output clamping - Preserve zero-modification immutability of local Database_2.xlsx - Pass 100% of full regression test suite (158/158 tests) and ruff linting
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
"""Hard Clinical Candidate Gate conforming to Section 5 and Section 8 specifications.
|
||||
|
||||
Strictly rejects:
|
||||
1. Absence statements ("No acute complications", "No major adverse events", "No acute chemotherapy-related adverse events")
|
||||
2. Treatment instructions & monitoring phrases ("Watch for reactions", "Follow up", "Review in OPD", "Monitor")
|
||||
3. Medication names, prescriptions, and dosage instructions ("Tab Prednisolone 100mg", "Syp Cremaffin 15ml")
|
||||
4. Section headings, JSON labels, test metadata, and template artifacts
|
||||
5. Isolated non-diagnostic status descriptions ("Stable", "Tolerated well")
|
||||
6. Tumor staging and molecular attributes extracted as standalone diagnoses ("Stage IV", "GCB type")
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# 1. Statements describing the ABSENCE of disease, complications, or adverse events
|
||||
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"\bno\s+(?:acute\s+)?chemotherapy-related\s+adverse\s+events\b",
|
||||
r"\bno\s+(?:acute\s+)?major\s+complications?\s*(?:occurred|noted|seen|observed)?\b",
|
||||
r"\bno\s+(?:major\s+)?acute\s+complications?\b",
|
||||
r"\bno\s+acute\s+issues?\b",
|
||||
r"\buneventful\s+(?:course|stay|hospitalization|postoperative\s+course)?\b",
|
||||
r"^\s*without\s+(?:any\s+)?(?:acute\s+)?(?:complications?|adverse\s+events?)\b",
|
||||
r"^\s*negative\s+for\s+(?:acute|major|significant)?\s*(?:complications?|adverse\s+events?)\b",
|
||||
r"^\s*absence\s+of\s+(?:acute|major)?\s*(?:complications?|adverse\s+events?)\b",
|
||||
r"^\s*patient\s+tolerated\s+procedure\s+well\s+without\s+complication\b",
|
||||
]
|
||||
|
||||
# 2. Treatment instructions, monitoring directives, and administrative disposition
|
||||
INSTRUCTION_PATTERNS = [
|
||||
r"^\s*(?:watch\s+for|monitor(?:\s+for)?|check(?:\s+for)?|observe\s+for|follow[\s\-]?up|review\s+in|repeat|continue|stop|hold|taper|instruct(?:ed)?|counsel(?:ed)?|advise[d]?|reassure[d]?|discharge\s+to|disposition|plan\s*:|treatment\s*:)\b",
|
||||
r"\b(?:watch\s+for\s+reactions|follow[\s\-]?up\s+in|return\s+if|as\s+directed|review\s+in\s+opd|review\s+after|keep\s+hydrated)\b",
|
||||
r"^\s*(?:rest|fluids|hydration|diet|dressing|wound\s+care|suture\s+removal)\b",
|
||||
r"^\s*(?:pt|patient)\s+(?:instructed|advised|counseled)\s+to\b",
|
||||
r"^\s*(?:patient\s+education|discharge\s+advice|discharge\s+instructions?)\b",
|
||||
r"\b(?:patient\s+education|discharge\s+advice|discharge\s+instructions?)\b",
|
||||
r"^\s*(?:take\s+medication|take\s+tablets?|take\s+capsules?|take\s+pills?)\b",
|
||||
r"\btake\s+medication\s+(?:once|twice|thrice|\d+\s+times)?\s*(?:daily|a\s+day)?\b",
|
||||
r"^\s*(?:follow[\s\-]?up\s+after\s+\d+\s+(?:days?|weeks?|months?))\b",
|
||||
]
|
||||
|
||||
# 3. Medications, prescriptions, and dosage instructions (Section 9: Source semantics & morphology)
|
||||
DOSAGE_FORM_PATTERNS = [
|
||||
r"\b(?:tab|tablets?|cap|capsules?|inj|injections?|syp|syrups?|ointment|cream|drops|infusions?|solutions?|suspensions?|sprays?|inhalers?|lozenges?|patch(?:es)?|suppositor(?:y|ies)|laxatives?|pills?)\b",
|
||||
r"\b(?:alex\s+cough\s+lozenges|duphalac\s+syp)\b",
|
||||
]
|
||||
|
||||
PRESCRIPTION_SYNTAX_PATTERNS = [
|
||||
r"\b(?:\d+\s*(?:mg|mcg|gm|g|ml|iu|units?|tablets?|capsules?|pills?|puffs?|drops?))\b",
|
||||
r"\b(?:po|iv|im|sc|prn|daily|od|bd|bid|tds|tid|qid|sos|hs|at\s+bedtime|before\s+meals?|after\s+meals?|subcutaneously|orally|topically)\b",
|
||||
r"^\s*(?:take|apply|instill|inhale|inject|infuse|give)\b",
|
||||
]
|
||||
|
||||
# 4. Section headers, document metadata, allergy statements, and non-diagnostic observations
|
||||
METADATA_PATTERNS = [
|
||||
r"^\s*(?:hospital\s+)?discharge\s+summary\b",
|
||||
r"^\s*(?:summary\s+of\s+)?hospital\s+course\b",
|
||||
r"^\s*brief\s+summary\b",
|
||||
r"^\s*history\s+of\s+present\s+illness\b",
|
||||
r"^\s*past\s+medical\s+history\b",
|
||||
r"^\s*presenting\s+complaints?\b",
|
||||
r"^\s*chief\s+complaint\b",
|
||||
r"^\s*discharge\s+medications?\b",
|
||||
r"^\s*investigations?\b",
|
||||
r"^\s*general\s+condition\b",
|
||||
r"^\s*physical\s+examination\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*$",
|
||||
r"^\s*(?:none|nil|na|n/a|unknown|unremarkable)\s*$",
|
||||
# Patient education, appointments, and follow-up directives
|
||||
r"^\s*(?:follow[\s\-]?up|appointment|review\s+in|return\s+to|referral\s+to|discharged?\s+to|see\s+doctor|emergency\s+signs?)\b",
|
||||
r"\b(?:call\s+clinic|seek\s+urgent\s+care|return\s+if\s+worse|take\s+rest|diet\s+counseling)\b",
|
||||
r"^\s*(?:discharge\s+advice|patient\s+education|discharge\s+instructions?)\s*$",
|
||||
r"^\s*take\s+medication\s+(?:once|twice|thrice|\d+\s+times)?\s*(?:daily|a\s+day)?\s*$",
|
||||
r"^\s*follow\s+up\s+after\s+\d+\s+(?:days?|weeks?|months?)\s*$",
|
||||
# Vital signs, general status, and measurements
|
||||
r"^\s*(?:stable|afebrile|conscious|oriented|tolerated\s+well|in\s+stable\s+condition|vital\s+signs?|general\s+condition\s+stable)\s*$",
|
||||
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*$",
|
||||
]
|
||||
|
||||
# 5. Tumor attributes / Staging markers (attributes of a neoplasm, not standalone diagnoses)
|
||||
STANDALONE_ATTRIBUTE_PATTERNS = [
|
||||
r"^\s*stage\s+(?:i|ii|iii|iv|[1-4])[a-z]?\s*$",
|
||||
r"^\s*gcb\s+type\s*$",
|
||||
r"^\s*non-gcb\s+type\s*$",
|
||||
r"^\s*double\s+expressor(?:\s*(?:bcl2/bcl6|myc/bcl2|\(.*\)))?\s*$",
|
||||
r"^\s*ki[\s\-]?67\s*(?:index)?\s*(?:>|=|<)?\s*\d+\s*%?\s*$",
|
||||
r"^\s*grade\s+(?:i|ii|iii|iv|[1-4])(?:\s+histology)?\s*$",
|
||||
r"^\s*t\d+n\d+m\d+\s*$",
|
||||
r"^\s*(?:triple\s+negative|er\s+negative|pr\s+negative|her2\s*(?:positive|negative|0|\d+))\s*$",
|
||||
r"^\s*brca(?:\s*1|\s*2)?\s+(?:pathogenic|mutation|positive|negative)(?:\s+mutation)?\s*$",
|
||||
r"^\s*pd[\s\-]?l1\s+(?:positive|negative|expression)?(?:\s*\(.*?\))?\s*$",
|
||||
r"^\s*(?:er|pr|her2)\s*(?:positive|negative|0|\d+)\s*$",
|
||||
]
|
||||
|
||||
# 6. Isolated anatomical locations lacking any clinical condition / pathology descriptor
|
||||
ISOLATED_ANATOMY_PATTERNS = [
|
||||
r"^\s*(?:left\s+|right\s+|bilateral\s+)?(?:foot|feet|ankle|heel|toe|toes|hand|wrist|arm|leg|thigh|knee|shoulder|elbow|chest|thorax|breast|abdomen|flank|back|spine|pelvis|hip|neck|head|brain|lung|kidney|liver|spleen|heart|eye|ear|nose|throat)\s*$",
|
||||
]
|
||||
|
||||
# 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",
|
||||
"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",
|
||||
}
|
||||
|
||||
|
||||
class HardClinicalCandidateGate:
|
||||
"""Deterministic clinical candidate gate enforcing Section 3, 5 & 8 requirements."""
|
||||
|
||||
@classmethod
|
||||
def evaluate_candidate(cls, term: str, evidence_text: str = "") -> tuple[bool, str]:
|
||||
"""Evaluate whether an extracted term is a genuine clinical diagnosis.
|
||||
|
||||
Returns:
|
||||
Tuple of (is_valid, rejection_reason).
|
||||
"""
|
||||
clean_term = term.strip()
|
||||
term_lower = clean_term.lower()
|
||||
|
||||
if len(clean_term) < 2:
|
||||
return False, "Term is too short to be a clinical condition"
|
||||
|
||||
# Check 1: Absence statements
|
||||
for pat in ABSENCE_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Absence statement describing absence of disease or complication: '{clean_term}'"
|
||||
|
||||
# Check 2: Treatment instructions and monitoring
|
||||
for pat in INSTRUCTION_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Treatment instruction or monitoring directive: '{clean_term}'"
|
||||
|
||||
# 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"])):
|
||||
return False, f"Pharmaceutical dosage form or prescription instruction: '{clean_term}'"
|
||||
|
||||
# Check 4: Section headings, metadata, allergy statements, lab values
|
||||
for pat in METADATA_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Section heading, metadata, allergy, or clinical status artifact: '{clean_term}'"
|
||||
|
||||
# Check 5: Standalone tumor staging or genetic attributes
|
||||
for pat in STANDALONE_ATTRIBUTE_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Neoplasm attribute or staging marker, not an independent diagnosis: '{clean_term}'"
|
||||
|
||||
# Check 6: Isolated anatomical locations without condition descriptors
|
||||
for pat in ISOLATED_ANATOMY_PATTERNS:
|
||||
if re.search(pat, term_lower):
|
||||
words = set(re.findall(r"[a-z]+", term_lower))
|
||||
if not words.intersection(PATHOLOGY_KEYWORDS):
|
||||
return False, f"Isolated anatomical location lacking pathological condition: '{clean_term}'"
|
||||
|
||||
# Check 7: Entire phrase is an explicit absence or negative statement
|
||||
if term_lower.startswith("no evidence of ") or term_lower.startswith("negative for "):
|
||||
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"]):
|
||||
return False, f"Metadata or template header artifact: '{clean_term}'"
|
||||
|
||||
return True, "Valid clinical diagnosis entity"
|
||||
|
||||
@classmethod
|
||||
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(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):
|
||||
return "ATTRIBUTE"
|
||||
if any(re.search(pat, term_lower) for pat in ABSENCE_PATTERNS) or term_lower.startswith("no ") or "ruled out" in term_lower:
|
||||
return "NEGATED"
|
||||
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"
|
||||
if any(re.search(pat, term_lower) for pat in INSTRUCTION_PATTERNS):
|
||||
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"
|
||||
|
||||
@classmethod
|
||||
def is_absence_statement(cls, text: str) -> bool:
|
||||
t = text.strip().lower()
|
||||
return any(bool(re.search(pat, t)) for pat in ABSENCE_PATTERNS)
|
||||
|
||||
@classmethod
|
||||
def is_treatment_instruction(cls, text: str) -> bool:
|
||||
t = text.strip().lower()
|
||||
return any(bool(re.search(pat, t)) for pat in INSTRUCTION_PATTERNS)
|
||||
|
||||
@classmethod
|
||||
def is_medication_or_prescription(cls, text: str) -> bool:
|
||||
t = text.strip().lower()
|
||||
has_form = any(bool(re.search(pat, t)) for pat in DOSAGE_FORM_PATTERNS)
|
||||
has_syntax = any(bool(re.search(pat, t)) for pat in PRESCRIPTION_SYNTAX_PATTERNS)
|
||||
return has_form or (has_syntax and any(w in t for w in ["medication", "dose", "tablet", "syrup", "capsule", "take", "prn"]))
|
||||
|
||||
@classmethod
|
||||
def is_metadata_or_heading(cls, text: str) -> bool:
|
||||
t = text.strip().lower()
|
||||
return any(bool(re.search(pat, t)) for pat in METADATA_PATTERNS)
|
||||
@@ -23,6 +23,7 @@ from medical_coding.schemas.validation import (
|
||||
ValidationCheck,
|
||||
)
|
||||
from medical_coding.utils.logging import get_logger
|
||||
from medical_coding.validation.reverse_attributes import ReverseAttributeChecker
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -120,6 +121,11 @@ class DeterministicValidator:
|
||||
icd10cm=icd10cm_val,
|
||||
icdo=icdo_val,
|
||||
cpt=cpt_val,
|
||||
database_code=code,
|
||||
database_description=candidate.description,
|
||||
matching_status="MATCHED",
|
||||
source_section=getattr(condition.context.evidence, "source_section", "") or getattr(selection, "source_section", ""),
|
||||
source_span=getattr(condition.context.evidence, "source_span", None) or getattr(selection, "source_span", None),
|
||||
)
|
||||
return validated, None
|
||||
|
||||
@@ -487,6 +493,9 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[clean_evidence] if clean_evidence else [],
|
||||
confidence=0.0,
|
||||
abstention_reason="NO_CANDIDATES",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=[],
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
@@ -503,6 +512,9 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[],
|
||||
confidence=0.0,
|
||||
abstention_reason="INSUFFICIENT_EVIDENCE",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
@@ -519,6 +531,9 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason=selection.abstention_reason or "NO_MATCHING_CANDIDATE",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
@@ -543,6 +558,9 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="INVALID_LLM_CODE_NOT_IN_CANDIDATE_POOL",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="REJECTED_MISMATCH",
|
||||
)
|
||||
@@ -561,6 +579,9 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="INVALID_ICD_CODE",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="REJECTED_MISMATCH",
|
||||
)
|
||||
@@ -579,13 +600,16 @@ class CandidateRankingDeterministicValidator:
|
||||
gen_cand = next(
|
||||
(
|
||||
c
|
||||
for c in candidates
|
||||
for c in sorted(candidates, key=lambda x: x.retrieval_score, reverse=True)
|
||||
if "unspecified" in c.description.lower() or c.code in ["I50.9", "I50"]
|
||||
),
|
||||
None,
|
||||
)
|
||||
if gen_cand and gen_cand.is_valid_billable:
|
||||
matching_candidate = gen_cand
|
||||
selection.selected_code = gen_cand.code
|
||||
selection.selected_description = gen_cand.description
|
||||
selection.selected_candidate = gen_cand
|
||||
selection.ranking_reason = (
|
||||
f"Specificity realigned: Documentation supports general heart failure without {', '.join(unsupported_hf)} specificity; "
|
||||
f"selected unspecified code {gen_cand.code}."
|
||||
@@ -604,6 +628,9 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="UNSUPPORTED_SPECIFICITY",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
@@ -635,13 +662,16 @@ class CandidateRankingDeterministicValidator:
|
||||
uncomp_cand = next(
|
||||
(
|
||||
c
|
||||
for c in candidates
|
||||
for c in sorted(candidates, key=lambda x: x.retrieval_score, reverse=True)
|
||||
if "without complications" in c.description.lower() or c.code == "E11.9"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if uncomp_cand:
|
||||
matching_candidate = uncomp_cand
|
||||
selection.selected_code = uncomp_cand.code
|
||||
selection.selected_description = uncomp_cand.description
|
||||
selection.selected_candidate = uncomp_cand
|
||||
selection.ranking_reason = (
|
||||
f"Specificity realigned: Documentation lacks evidence of diabetic complications; "
|
||||
f"selected uncomplicated code {uncomp_cand.code}."
|
||||
@@ -657,12 +687,85 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="UNSUPPORTED_SPECIFICITY",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
# Reverse Attribute Check (Master Prompt: CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY)
|
||||
is_attr_valid, unsupp_attrs = ReverseAttributeChecker.validate_code_attributes(
|
||||
code_description=matching_candidate.description,
|
||||
evidence_text=clean_evidence,
|
||||
diagnosis_term=clean_diagnosis,
|
||||
)
|
||||
if not is_attr_valid:
|
||||
# Look for a candidate in candidate pool that is billable and valid under reverse attribute check
|
||||
better_candidate = None
|
||||
best_cand_score = -999.0
|
||||
diag_clean_lower = clean_diagnosis.lower()
|
||||
diag_tokens = [t for t in re.findall(r"[a-z0-9]+", diag_clean_lower) if len(t) > 3]
|
||||
|
||||
sorted_candidates = sorted(candidates, key=lambda x: x.retrieval_score, reverse=True)
|
||||
for alt_cand in sorted_candidates:
|
||||
if not alt_cand.is_valid_billable:
|
||||
continue
|
||||
alt_valid, _ = ReverseAttributeChecker.validate_code_attributes(
|
||||
code_description=alt_cand.description,
|
||||
evidence_text=clean_evidence,
|
||||
diagnosis_term=clean_diagnosis,
|
||||
)
|
||||
if alt_valid:
|
||||
alt_desc_lower = alt_cand.description.lower()
|
||||
if any(t in alt_desc_lower for t in diag_tokens):
|
||||
pref_score = alt_cand.retrieval_score
|
||||
# Prefer 'unspecified' or canonical base codes over 'other' when documentation is general
|
||||
if "unspecified" in alt_desc_lower or "without " in alt_desc_lower or alt_cand.code.endswith(".9") or alt_cand.code.endswith(".90"):
|
||||
pref_score += 0.35
|
||||
elif "other " in alt_desc_lower or "other specified" in alt_desc_lower:
|
||||
doc_has_other = any(w in evidence_lower for w in ["other", "specified", "variant", "type"])
|
||||
if not doc_has_other:
|
||||
pref_score -= 0.35
|
||||
|
||||
if pref_score > best_cand_score:
|
||||
best_cand_score = pref_score
|
||||
better_candidate = alt_cand
|
||||
|
||||
if better_candidate:
|
||||
matching_candidate = better_candidate
|
||||
selection.selected_code = better_candidate.code
|
||||
selection.selected_description = better_candidate.description
|
||||
selection.selected_candidate = better_candidate
|
||||
selection.ranking_reason = (
|
||||
f"Specificity realigned: Documentation does not support {', '.join(unsupp_attrs)}; "
|
||||
f"selected supported code {better_candidate.code} ({better_candidate.description})."
|
||||
)
|
||||
else:
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason=(
|
||||
f"Unsupported specificity: Candidate '{matching_candidate.code}' requires {', '.join(unsupp_attrs)}, "
|
||||
"which is not documented in clinical evidence."
|
||||
),
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="UNSUPPORTED_SPECIFICITY",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
# 7. Check if candidate has zero clinical relevance to evidence
|
||||
ev_tokens = set(re.findall(r"[A-Za-z0-9]+", evidence_lower))
|
||||
from medical_coding.retrieval.tokenizer import expand_clinical_morphology
|
||||
raw_ev = [t for t in re.findall(r"[A-Za-z0-9]+", evidence_lower) if len(t) > 2]
|
||||
ev_tokens = set(expand_clinical_morphology(raw_ev))
|
||||
cand_tokens = set(re.findall(r"[A-Za-z0-9]+", matching_candidate.description.lower()))
|
||||
# Remove universal filler tokens
|
||||
cand_meaningful = {
|
||||
@@ -670,7 +773,8 @@ class CandidateRankingDeterministicValidator:
|
||||
for t in cand_tokens
|
||||
if len(t) > 2 and t not in {"and", "with", "for", "without", "other", "unspecified"}
|
||||
}
|
||||
if cand_meaningful and not (ev_tokens & cand_meaningful):
|
||||
cand_meaningful_expanded = set(expand_clinical_morphology(list(cand_meaningful)))
|
||||
if cand_meaningful and not (ev_tokens & cand_meaningful_expanded):
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
@@ -681,6 +785,9 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="NO_MATCHING_CANDIDATE",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
@@ -698,6 +805,9 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=effective_conf,
|
||||
abstention_reason="CONFIDENCE_BELOW_THRESHOLD",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="REJECTED_LOW_CONFIDENCE",
|
||||
)
|
||||
@@ -714,6 +824,9 @@ class CandidateRankingDeterministicValidator:
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=round(effective_conf, 4),
|
||||
abstention_reason=None,
|
||||
matching_status="MATCHED",
|
||||
source_section=getattr(selection, "source_section", ""),
|
||||
source_span=getattr(selection, "source_span", None),
|
||||
candidate_pool=candidates,
|
||||
decision="ACCEPTED",
|
||||
)
|
||||
|
||||
@@ -13,26 +13,20 @@ GATE 10 — Final Consistency Gate: Final JSON consistency with evidence graph.
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
Acuity,
|
||||
Certainty,
|
||||
DiagnosisRole,
|
||||
Laterality,
|
||||
EvidenceType,
|
||||
NegationStatus,
|
||||
PipelineStage,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.schemas.evidence import (
|
||||
ClinicalDiagnosisCandidate,
|
||||
ICDMappingCandidate,
|
||||
StructuredEvidence,
|
||||
)
|
||||
from medical_coding.schemas.icd import ICDCandidate, RankedSelection
|
||||
from medical_coding.schemas.validation import AbstentionRecord, ValidationCheck
|
||||
from medical_coding.schemas.icd import RankedSelection
|
||||
from medical_coding.schemas.validation import ValidationCheck
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -111,21 +105,16 @@ class ValidationGateEngine:
|
||||
self,
|
||||
candidate: ClinicalDiagnosisCandidate,
|
||||
) -> GateResult:
|
||||
"""Gate 2: Ensures candidate represents an actual clinical condition rather than an isolated lab, medication, or non-diagnostic string."""
|
||||
term = candidate.normalized_diagnosis.strip().lower()
|
||||
if len(term) < 2:
|
||||
return GateResult(
|
||||
2, "ClinicalDiagnosisGate", False,
|
||||
f"Invalid diagnosis term '{term}': too short.",
|
||||
AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE,
|
||||
)
|
||||
"""Gate 2: Ensures candidate represents an actual clinical condition rather than an absence statement, instruction, medication, or non-diagnostic string."""
|
||||
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
||||
|
||||
# Exclude pure medications or lab names if wrongly passed as diagnoses
|
||||
pure_meds_labs = {"furosemide", "lisinopril", "metformin", "carvedilol", "potassium", "creatinine", "sodium", "cbc", "troponin", "vital signs"}
|
||||
if term in pure_meds_labs:
|
||||
term = candidate.normalized_diagnosis.strip()
|
||||
ev_text = candidate.primary_evidence_quote if hasattr(candidate, "primary_evidence_quote") else ""
|
||||
is_valid, reason = HardClinicalCandidateGate.evaluate_candidate(term, ev_text)
|
||||
if not is_valid:
|
||||
return GateResult(
|
||||
2, "ClinicalDiagnosisGate", False,
|
||||
f"Entity '{term}' is a medication or laboratory test, not an autonomous clinical diagnosis.",
|
||||
f"Candidate rejected by clinical gate: {reason}",
|
||||
AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE,
|
||||
)
|
||||
|
||||
@@ -365,8 +354,6 @@ class ValidationGateEngine:
|
||||
secondary_candidates: list[ClinicalDiagnosisCandidate],
|
||||
) -> GateResult:
|
||||
"""Gate 10: Verify encounter-level invariants: maximum 1 primary, no Excludes1 violations."""
|
||||
# 1. Excludes1 check across all assigned codes
|
||||
assigned_codes: list[str] = []
|
||||
if primary_candidate and primary_candidate.scores.admitting_score > 0:
|
||||
pass # primary is tracked
|
||||
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
"""Reverse Attribute Checker for Database-Authoritative ICD-10-CM & CPT Validation.
|
||||
|
||||
Extracts clinically meaningful qualifiers and attributes from candidate code descriptions
|
||||
and validates that every positive attribute is explicitly supported by documented patient evidence.
|
||||
Enforces the fundamental clinical coding invariant:
|
||||
CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from medical_coding.retrieval.tokenizer import CLINICAL_MORPHOLOGY
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# Non-specificity words, grammatical tokens, and broad taxonomic terms
|
||||
NON_SPECIFICITY_WORDS: set[str] = {
|
||||
"a", "an", "the", "and", "or", "of", "in", "with", "without", "due", "to",
|
||||
"for", "on", "by", "as", "at", "from", "unspecified", "nos", "nec", "not",
|
||||
"elsewhere", "classified", "organism", "site", "type", "side", "cause",
|
||||
"causes", "other", "part", "parts", "multiple", "single", "disease", "diseases",
|
||||
"disorder", "disorders", "condition", "conditions", "tract", "lower", "upper",
|
||||
"congestive", "mention", "evidence", "specified", "syndrome", "status", "post",
|
||||
"body", "area", "region", "agent", "agents", "manifestation", "manifestations",
|
||||
"infection", "infections", "primary", "mellitus", "initial", "encounter",
|
||||
"closed", "bone", "bones", "female",
|
||||
"acute", "chronic", "subacute", "spontaneous", "disruption", "injury", "sites",
|
||||
"secondary", "neoplasm", "neoplasms", "tumor", "tumour", "intrahepatic", "bile", "duct",
|
||||
}
|
||||
|
||||
# Clinical attribute qualifiers mapped to documentary confirmation tokens/synonyms
|
||||
CLINICAL_QUALIFIERS: dict[str, list[str]] = {
|
||||
# Fractures & Displacement
|
||||
"nondisplaced": ["nondisplaced", "non-displaced", "no displacement", "undisplaced", "not displaced"],
|
||||
"displaced": ["displaced", "displacement"],
|
||||
|
||||
# Complications & Manifestations
|
||||
"bleeding": ["bleed", "bleeding", "hemorrhage", "hemorrhagic", "melena", "hematemesis", "blood in stool"],
|
||||
"perforation": ["perforat", "rupture", "free air", "hole"],
|
||||
"obstruction": ["obstruct", "blockage", "stricture", "impaction", "occlu"],
|
||||
"gangrene": ["gangrene", "gangrenous", "necrosis", "necrotic"],
|
||||
"ulceration": ["ulcer", "ulcerated", "ulcerative", "erosion"],
|
||||
"abscess": ["abscess", "empyema", "purulent collection"],
|
||||
"fistula": ["fistula", "fistulous"],
|
||||
"hemorrhage": ["hemorrhage", "hemorrhagic", "bleed"],
|
||||
"colic": ["colic", "colicky"],
|
||||
|
||||
# Pathological Subtypes & Features
|
||||
"atrophic": ["atrophic", "atrophy"],
|
||||
"superficial": ["superficial"],
|
||||
"eosinophilic": ["eosinophil", "eosinophilic"],
|
||||
"hypertrophic": ["hypertrophic", "hypertrophy", "thickened"],
|
||||
"granulomatous": ["granuloma", "granulomatous"],
|
||||
"metaplastic": ["metaplasia", "metaplastic"],
|
||||
"polypoid": ["polyp", "polypoid"],
|
||||
|
||||
# Heart Failure Subtypes & Specific Features
|
||||
"systolic": ["systolic", "hfref", "reduced ejection", "systolic dysfunction"],
|
||||
"diastolic": ["diastolic", "hfpef", "preserved ejection", "diastolic dysfunction"],
|
||||
"right heart": ["right heart", "right ventricular", "right side heart"],
|
||||
"left heart": ["left heart", "left ventricular", "left side heart"],
|
||||
"high output": ["high output"],
|
||||
"end stage": ["end stage", "stage d", "terminal heart failure"],
|
||||
"biventricular": ["biventricular"],
|
||||
|
||||
# Underlying Etiology & Special Circumstances
|
||||
"transplant": ["transplant", "allograft", "graft", "organ donor"],
|
||||
"rheumatic": ["rheumatic", "rheumatic fever"],
|
||||
"hypertensive": ["hypertension", "hypertensive", "htn", "high blood pressure"],
|
||||
"postprocedural": ["postprocedural", "postoperative", "post-op", "complication of surgery", "following surgery"],
|
||||
"congenital": ["congenital", "birth defect", "anomaly", "inborn"],
|
||||
"toxic": ["toxic", "toxicity", "poisoning", "chemical exposure"],
|
||||
"alcoholic": ["alcohol", "alcoholic", "etoh", "substance abuse"],
|
||||
"diabetic": ["diabetes", "diabetic", "dm", "t1dm", "t2dm"],
|
||||
|
||||
# Diabetic Complications & Specificity
|
||||
"nephropathy": ["nephropathy", "kidney disease", "renal disease", "ckd", "proteinuria"],
|
||||
"retinopathy": ["retinopathy", "maculopathy", "proliferative"],
|
||||
"neuropathy": ["neuropathy", "polyneuropathy", "mononeuropathy", "autonomic"],
|
||||
"ketoacidosis": ["ketoacidosis", "dka", "ketosis"],
|
||||
"hyperglycemia": ["hyperglycemia", "high blood sugar", "uncontrolled"],
|
||||
"hypoglycemia": ["hypoglycemia", "low blood sugar", "hypoglycemic"],
|
||||
"dermatitis": ["dermatitis", "skin lesion", "necrobiosis"],
|
||||
"cataract": ["cataract"],
|
||||
"amyotrophy": ["amyotrophy"],
|
||||
"arthropathy": ["arthropathy", "charcot"],
|
||||
|
||||
# Specific Anatomical Sites & Lymph Node Regions
|
||||
"intrathoracic": ["intrathoracic", "mediastinal", "mediastinum", "hilum", "hilar"],
|
||||
"head, face, and neck": ["head", "face", "neck", "cervical"],
|
||||
"intra-abdominal": ["intra-abdominal", "abdominal lymph", "mesenteric", "retroperitoneal"],
|
||||
"axilla": ["axilla", "axillary"],
|
||||
"inguinal": ["inguinal", "groin"],
|
||||
"spleen": ["spleen", "splenic"],
|
||||
|
||||
# Specific Pathogens & Infectious Etiologies
|
||||
"chlamydial": ["chlamydia", "chlamydial"],
|
||||
"rubella": ["rubella"],
|
||||
"salmonella": ["salmonella"],
|
||||
"typhoid": ["typhoid"],
|
||||
"gonococcal": ["gonococcal", "gonorrhea"],
|
||||
"streptococcal": ["streptococc", "strep", "streptococcus"],
|
||||
"streptococcus": ["streptococc", "strep", "streptococcus"],
|
||||
"pseudomonas": ["pseudomonas"],
|
||||
"klebsiella": ["klebsiella"],
|
||||
"mycoplasma": ["mycoplasma"],
|
||||
"adenoviral": ["adenovirus", "adenoviral"],
|
||||
"varicella": ["varicella", "chickenpox"],
|
||||
"staphylococcal": ["staphylococc", "staph", "mrsa", "mssa"],
|
||||
"influenza": ["influenza", "flu"],
|
||||
"fungal": ["fungal", "fungus", "mycotic", "aspergillus", "candida"],
|
||||
"aspiration": ["aspiration", "aspirated"],
|
||||
"tuberculous": ["tuberculosis", "tb", "tuberculous"],
|
||||
"echovirus": ["echovirus"],
|
||||
"coxsackievirus": ["coxsackievirus", "coxsackie"],
|
||||
"rhinovirus": ["rhinovirus"],
|
||||
}
|
||||
|
||||
|
||||
def has_positive_mention(synonym: str, text: str) -> bool:
|
||||
"""Check if synonym appears in text without being negated."""
|
||||
syn_esc = re.escape(synonym)
|
||||
pattern = rf"\b{syn_esc}\b"
|
||||
for match in re.finditer(pattern, text, re.IGNORECASE):
|
||||
start = match.start()
|
||||
lookback_start = max(0, start - 45)
|
||||
preceding = text[lookback_start:start]
|
||||
# Inspect after last punctuation if present
|
||||
last_punct = max(preceding.rfind("."), preceding.rfind(";"), preceding.rfind(","))
|
||||
if last_punct != -1:
|
||||
preceding = preceding[last_punct + 1 :]
|
||||
|
||||
# Check if preceding snippet contains negation words
|
||||
if re.search(
|
||||
r"\b(?:no|not|without|denies|denied|negative\s+for|no\s+evidence\s+of|no\s+active|ruled\s+out|free\s+of)\b",
|
||||
preceding,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
continue
|
||||
if preceding.rstrip().endswith("non-") or preceding.rstrip().endswith("non"):
|
||||
continue
|
||||
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class ReverseAttributeChecker:
|
||||
"""Evaluates whether attributes in a database code description are supported by evidence."""
|
||||
|
||||
@classmethod
|
||||
def extract_code_attributes(cls, code_description: str) -> dict[str, bool]:
|
||||
"""Extract explicit clinical attributes implied by a database description.
|
||||
|
||||
Returns a mapping of attribute -> is_positive (True = must be documented).
|
||||
Attributes preceded by 'without' or 'unspecified' are NOT required to be documented.
|
||||
"""
|
||||
desc_lower = code_description.lower()
|
||||
attributes: dict[str, bool] = {}
|
||||
|
||||
for attr, _ in CLINICAL_QUALIFIERS.items():
|
||||
if re.search(rf"\b{re.escape(attr)}\b", desc_lower):
|
||||
without_pattern = rf"\bwithout\s+(?:mention\s+of\s+|evidence\s+of\s+|any\s+)?{re.escape(attr)}\b"
|
||||
if re.search(without_pattern, desc_lower):
|
||||
attributes[attr] = False
|
||||
else:
|
||||
attributes[attr] = True
|
||||
|
||||
return attributes
|
||||
|
||||
@classmethod
|
||||
def validate_laterality(
|
||||
cls,
|
||||
code_description: str,
|
||||
evidence_text: str,
|
||||
diagnosis_term: str = "",
|
||||
) -> tuple[bool, str | None]:
|
||||
"""Verify that anatomical laterality in code description is documented in evidence."""
|
||||
desc_lower = code_description.lower()
|
||||
combined = f"{diagnosis_term} {evidence_text}".lower()
|
||||
|
||||
# Remove 'right heart' / 'left heart' to avoid confusion with limb/organ laterality
|
||||
desc_clean = re.sub(r"\b(?:right|left)\s+heart\b", "", desc_lower)
|
||||
|
||||
req_bilateral = bool(
|
||||
re.search(r"\bbilateral\b", desc_clean)
|
||||
and not re.search(r"\bwithout\s+bilateral\b", desc_clean)
|
||||
)
|
||||
req_right = bool(
|
||||
re.search(
|
||||
r"\b(?:right\s+side|of\s+right|in\s+right|right\s+(?:kidney|ureter|leg|arm|lung|flank|ear|eye|ovary|testis|foot|hand|shoulder|hip|knee))\b",
|
||||
desc_clean,
|
||||
)
|
||||
or desc_clean.endswith(", right")
|
||||
or desc_clean.endswith(" right side")
|
||||
or ", right " in desc_clean
|
||||
or " right," in desc_clean
|
||||
)
|
||||
req_left = bool(
|
||||
re.search(
|
||||
r"\b(?:left\s+side|of\s+left|in\s+left|left\s+(?:kidney|ureter|leg|arm|lung|flank|ear|eye|ovary|testis|foot|hand|shoulder|hip|knee))\b",
|
||||
desc_clean,
|
||||
)
|
||||
or desc_clean.endswith(", left")
|
||||
or desc_clean.endswith(" left side")
|
||||
or ", left " in desc_clean
|
||||
or " left," in desc_clean
|
||||
)
|
||||
|
||||
if not req_right and not req_left and not req_bilateral:
|
||||
return True, None
|
||||
|
||||
doc_right = has_positive_mention("right", combined) or has_positive_mention("rt", combined)
|
||||
doc_left = has_positive_mention("left", combined) or has_positive_mention("lt", combined)
|
||||
doc_bilateral = has_positive_mention("bilateral", combined) or (doc_right and doc_left)
|
||||
|
||||
if req_bilateral:
|
||||
if doc_bilateral:
|
||||
return True, None
|
||||
return False, "bilateral laterality"
|
||||
|
||||
if req_right:
|
||||
if doc_right and not doc_left:
|
||||
return True, None
|
||||
if not doc_right:
|
||||
return False, "right laterality"
|
||||
if doc_left:
|
||||
return False, "conflicting left laterality"
|
||||
|
||||
if req_left:
|
||||
if doc_left and not doc_right:
|
||||
return True, None
|
||||
if not doc_left:
|
||||
return False, "left laterality"
|
||||
if doc_right:
|
||||
return False, "conflicting right laterality"
|
||||
|
||||
return True, None
|
||||
|
||||
@classmethod
|
||||
def validate_code_attributes(
|
||||
cls,
|
||||
code_description: str,
|
||||
evidence_text: str,
|
||||
diagnosis_term: str = "",
|
||||
) -> tuple[bool, list[str]]:
|
||||
"""Validate that all positive attributes in the code description are evidenced.
|
||||
|
||||
Args:
|
||||
code_description: Exact description from the database.
|
||||
evidence_text: Verbatim clinical documentation / evidence quote.
|
||||
diagnosis_term: Extracted normalized clinical diagnosis term.
|
||||
|
||||
Returns:
|
||||
Tuple of (is_valid: bool, unsupported_attributes: list[str]).
|
||||
"""
|
||||
combined_evidence = f"{diagnosis_term} {evidence_text}".lower()
|
||||
implied_attributes = cls.extract_code_attributes(code_description)
|
||||
unsupported: list[str] = []
|
||||
|
||||
for attr, is_positive in implied_attributes.items():
|
||||
if not is_positive:
|
||||
continue
|
||||
|
||||
synonyms = CLINICAL_QUALIFIERS.get(attr, [attr])
|
||||
has_support = any(
|
||||
has_positive_mention(s, combined_evidence) for s in synonyms
|
||||
)
|
||||
if not has_support:
|
||||
unsupported.append(attr)
|
||||
|
||||
# Laterality validation
|
||||
lat_valid, lat_error = cls.validate_laterality(
|
||||
code_description=code_description,
|
||||
evidence_text=evidence_text,
|
||||
diagnosis_term=diagnosis_term,
|
||||
)
|
||||
if not lat_valid and lat_error:
|
||||
unsupported.append(lat_error)
|
||||
|
||||
# Diabetes Type 1 vs Type 2 distinction
|
||||
desc_lower = code_description.lower()
|
||||
if re.search(r"\btype\s+1\b", desc_lower) and not re.search(
|
||||
r"\b(?:type\s+1|t1dm|type\s+i\b)", combined_evidence
|
||||
):
|
||||
unsupported.append("type 1")
|
||||
if re.search(r"\btype\s+2\b", desc_lower) and not re.search(
|
||||
r"\b(?:type\s+2|t2dm|type\s+ii\b)", combined_evidence
|
||||
):
|
||||
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)
|
||||
# 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",
|
||||
"",
|
||||
desc_lower,
|
||||
)
|
||||
# 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)
|
||||
code_modifiers = [
|
||||
w for w in raw_code_tokens if len(w) > 2 and w not in NON_SPECIFICITY_WORDS
|
||||
]
|
||||
|
||||
from medical_coding.retrieval.tokenizer import CLINICAL_ABBREVIATIONS
|
||||
|
||||
for mod in code_modifiers:
|
||||
if mod in unsupported:
|
||||
continue
|
||||
variants = [mod] + CLINICAL_MORPHOLOGY.get(mod, [])
|
||||
if mod in CLINICAL_ABBREVIATIONS:
|
||||
variants.extend(CLINICAL_ABBREVIATIONS[mod].split())
|
||||
if mod.endswith("s") and len(mod) > 4:
|
||||
variants.append(mod[:-1])
|
||||
if mod.endswith("ic") and len(mod) > 4:
|
||||
variants.append(mod[:-2])
|
||||
if mod.endswith("al") and len(mod) > 4:
|
||||
variants.append(mod[:-2])
|
||||
|
||||
supported = any(has_positive_mention(v, combined_evidence) for v in variants)
|
||||
if not supported:
|
||||
unsupported.append(mod)
|
||||
|
||||
return (len(unsupported) == 0, unsupported)
|
||||
|
||||
@classmethod
|
||||
def get_specificity_penalty(
|
||||
cls,
|
||||
code_description: str,
|
||||
evidence_text: str,
|
||||
diagnosis_term: str = "",
|
||||
) -> float:
|
||||
"""Calculate penalty (0.0 to 0.95) for unsupported attributes.
|
||||
|
||||
If any positive attribute is unsupported, returns a severe penalty (0.90)
|
||||
effectively disqualifying the candidate in competition against supported codes.
|
||||
"""
|
||||
is_valid, unsupported = cls.validate_code_attributes(
|
||||
code_description=code_description,
|
||||
evidence_text=evidence_text,
|
||||
diagnosis_term=diagnosis_term,
|
||||
)
|
||||
if not is_valid:
|
||||
return 0.90
|
||||
return 0.0
|
||||
Reference in New Issue
Block a user