fix(pipeline): enforce Master Directive clinical reasoning, taxonomy, hard candidate gate, and generic query synthesis on extraction-fix
This commit is contained in:
@@ -29,6 +29,7 @@ from medical_coding.schemas.evidence import (
|
||||
StructuredEvidence,
|
||||
)
|
||||
from medical_coding.utils.logging import get_logger
|
||||
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -194,15 +195,32 @@ class EvidenceFirstFactExtractor:
|
||||
item: ClinicalDiagnosisCandidate,
|
||||
) -> None:
|
||||
"""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
|
||||
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(
|
||||
is_valid, reject_reason = HardClinicalCandidateGate.evaluate_candidate(
|
||||
item.raw_term, item.primary_evidence_quote
|
||||
)
|
||||
if not is_valid:
|
||||
logger.debug("Candidate gate rejected '%s': %s", item.raw_term, reject_reason)
|
||||
return
|
||||
|
||||
item.entity_type = HardClinicalCandidateGate.classify_entity_type(
|
||||
item.raw_term, item.primary_evidence_quote
|
||||
)
|
||||
|
||||
raw_t = item.raw_term.strip()
|
||||
# Handle question mark shorthand or uncertainty (?early evolving renal abscess)
|
||||
is_questionable = (
|
||||
|
||||
@@ -581,54 +581,41 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
# LEVEL 1: Exact query hybrid retrieval
|
||||
queries_to_run = [query]
|
||||
|
||||
# LEVEL 2: Synonym / Abbreviation Expansion (Master Prompt Section 23)
|
||||
from medical_coding.retrieval.tokenizer import CLINICAL_ABBREVIATIONS
|
||||
# LEVEL 2: Universal Concept & Token Morphology Expansion (Master Directive Sections 17 & 23)
|
||||
from medical_coding.retrieval.tokenizer import (
|
||||
CLINICAL_ABBREVIATIONS,
|
||||
get_expanded_query_tokens,
|
||||
)
|
||||
|
||||
query_lower = query.lower()
|
||||
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():
|
||||
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))
|
||||
|
||||
if "acl" in query_lower:
|
||||
expanded_terms.extend([
|
||||
"sprain of anterior cruciate ligament of knee",
|
||||
"anterior cruciate ligament tear",
|
||||
"tear of anterior cruciate ligament",
|
||||
])
|
||||
if "sarcoma" in query_lower and "liver" in query_lower:
|
||||
expanded_terms.extend([
|
||||
"other sarcomas of liver",
|
||||
"sarcoma of liver",
|
||||
"malignant neoplasm of liver",
|
||||
])
|
||||
if "neuroendocrine" in query_lower or "net" in query_lower:
|
||||
expanded_terms.extend([
|
||||
"carcinoid tumor of ascending colon",
|
||||
"malignant carcinoid tumor of ascending colon",
|
||||
"malignant carcinoid tumor colon",
|
||||
])
|
||||
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}",
|
||||
])
|
||||
# C. Concept attribute combination query
|
||||
if concept.metastatic_status and concept.body_site:
|
||||
expanded_terms.append(f"secondary malignant neoplasm of {concept.body_site}")
|
||||
expanded_terms.append(f"secondary neoplasm of {concept.body_site}")
|
||||
elif concept.histology and concept.body_site:
|
||||
expanded_terms.append(f"{concept.histology} of {concept.body_site}")
|
||||
expanded_terms.append(f"malignant neoplasm of {concept.body_site}")
|
||||
|
||||
if concept.acuity and concept.canonical_name:
|
||||
expanded_terms.append(f"{concept.acuity} {concept.canonical_name}")
|
||||
|
||||
# D. Generic morphological query tokens
|
||||
exp_tokens = get_expanded_query_tokens(query)
|
||||
if exp_tokens and len(exp_tokens) > 1:
|
||||
morph_query = " ".join(exp_tokens[:6])
|
||||
if morph_query not in expanded_terms:
|
||||
expanded_terms.append(morph_query)
|
||||
|
||||
for exp in expanded_terms:
|
||||
if exp not in queries_to_run:
|
||||
|
||||
@@ -10,6 +10,7 @@ Conforms to Master Specification Section 5 & 6:
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.schemas.enums import ClinicalEntityType
|
||||
from medical_coding.schemas.reasoning import ClinicalConcept
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
@@ -214,27 +215,46 @@ class ClinicalConceptReasoner:
|
||||
if getattr(candidate, "temporality", None) in ("HISTORICAL", "RESOLVED"):
|
||||
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(
|
||||
concept_id=str(cid) if cid else None,
|
||||
id=str(cid) if cid else None,
|
||||
canonical_name=raw_term,
|
||||
canonical_concept=raw_term,
|
||||
normalized_concept=getattr(candidate, "normalized_diagnosis", raw_term),
|
||||
entity_type=entity_type,
|
||||
disease_family=matched_family,
|
||||
body_site=detected_site,
|
||||
anatomy=detected_site,
|
||||
laterality=detected_laterality,
|
||||
etiology=etiology,
|
||||
histology=histology,
|
||||
severity=None,
|
||||
complication=None,
|
||||
acuity=getattr(candidate, "acuity", None),
|
||||
temporal_status=temporality,
|
||||
temporality=temporality,
|
||||
assertion_status=assertion,
|
||||
role_hint=str(getattr(candidate, "role", "SECONDARY")),
|
||||
role=str(getattr(candidate, "role", "SECONDARY")),
|
||||
metastatic_status=is_metastatic,
|
||||
metastatic_sites=metastatic_sites,
|
||||
evidence_spans=[quote] if quote else [],
|
||||
supporting_evidence=[quote] if quote else [],
|
||||
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,
|
||||
unknown_attributes=unknown_attributes,
|
||||
contradictory_attributes=[],
|
||||
contradiction_evidence=[],
|
||||
confidence=float(getattr(candidate, "confidence_score", 1.0) or 1.0),
|
||||
clinical_confidence=float(getattr(candidate, "confidence_score", 1.0) or 1.0),
|
||||
)
|
||||
|
||||
@@ -61,14 +61,6 @@ class MatchSpecBuilder:
|
||||
def build_match_spec(cls, concept: ClinicalConcept) -> MatchSpec:
|
||||
"""Construct MatchSpec with allowed code families and attribute firewalls."""
|
||||
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] = {}
|
||||
forbidden_attrs: list[str] = []
|
||||
|
||||
@@ -154,4 +146,15 @@ class MatchSpecBuilder:
|
||||
forbidden_attributes=forbidden_attrs,
|
||||
unknown_attributes=concept.unknown_attributes,
|
||||
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",
|
||||
)
|
||||
|
||||
@@ -79,18 +79,66 @@ class Laterality(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"
|
||||
SYMPTOM = "SYMPTOM"
|
||||
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"
|
||||
UNKNOWN = "UNKNOWN"
|
||||
|
||||
|
||||
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"
|
||||
ADMISSION_REASON = "ADMISSION_REASON"
|
||||
CHIEF_COMPLAINT = "CHIEF_COMPLAINT"
|
||||
@@ -98,6 +146,7 @@ class EvidenceType(StrEnum):
|
||||
PROCEDURE = "PROCEDURE"
|
||||
IMAGING = "IMAGING"
|
||||
LAB = "LAB"
|
||||
LABORATORY = "LAB"
|
||||
HISTORY = "HISTORY"
|
||||
CLINICAL_NOTE = "CLINICAL_NOTE"
|
||||
OTHER = "OTHER"
|
||||
|
||||
@@ -8,6 +8,7 @@ from pydantic import BaseModel, Field, model_validator
|
||||
from medical_coding.schemas.enums import (
|
||||
AssertionStatus,
|
||||
Certainty,
|
||||
ClinicalEntityType,
|
||||
DiagnosisRole,
|
||||
EvidenceType,
|
||||
NegationStatus,
|
||||
@@ -128,6 +129,10 @@ class ClinicalDiagnosisCandidate(BaseModel):
|
||||
min_length=1,
|
||||
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(
|
||||
default=DiagnosisRole.SECONDARY,
|
||||
description="PRIMARY, SECONDARY, HISTORICAL, SYMPTOM, INCIDENTAL, RULED_OUT, UNCERTAIN.",
|
||||
|
||||
@@ -13,38 +13,80 @@ from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
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:
|
||||
CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY
|
||||
Attributes not supported by explicit documentation remain in unknown_attributes.
|
||||
"""
|
||||
|
||||
concept_id: str = Field(
|
||||
id: str = Field(
|
||||
default_factory=lambda: str(uuid4()),
|
||||
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.",
|
||||
)
|
||||
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(
|
||||
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(
|
||||
default=None,
|
||||
description="Primary anatomical site (e.g. 'breast', 'kidney', 'ureter', 'stomach', 'fibula').",
|
||||
description="Alias for anatomical site.",
|
||||
)
|
||||
laterality: str | None = Field(
|
||||
default=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(
|
||||
default=None,
|
||||
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(
|
||||
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(
|
||||
default=None,
|
||||
@@ -52,19 +94,35 @@ class ClinicalConcept(BaseModel):
|
||||
)
|
||||
complication: str | None = Field(
|
||||
default=None,
|
||||
description="Associated manifestation or complication (e.g. 'septic_shock', 'renal_colic').",
|
||||
description="Associated manifestation or complication.",
|
||||
)
|
||||
temporal_status: str = Field(
|
||||
default="CURRENT",
|
||||
description="CURRENT, HISTORICAL, RESOLVED, or UNCLEAR.",
|
||||
acuity: str | None = Field(
|
||||
default=None,
|
||||
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(
|
||||
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(
|
||||
default="SECONDARY",
|
||||
description="Inferred initial clinical role: PRIMARY, SECONDARY, or EXCLUDED.",
|
||||
description="Alias for role.",
|
||||
)
|
||||
metastatic_status: bool = Field(
|
||||
default=False,
|
||||
@@ -72,16 +130,40 @@ class ClinicalConcept(BaseModel):
|
||||
)
|
||||
metastatic_sites: list[str] = Field(
|
||||
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(
|
||||
default_factory=list,
|
||||
description="Verbatim textual evidence quotes supporting this clinical concept.",
|
||||
)
|
||||
supporting_sections: list[str] = Field(
|
||||
source_sections: list[str] = Field(
|
||||
default_factory=list,
|
||||
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(
|
||||
default_factory=list,
|
||||
description="Attributes explicitly supported by clinical documentation.",
|
||||
@@ -90,20 +172,81 @@ class ClinicalConcept(BaseModel):
|
||||
default_factory=list,
|
||||
description="Attributes relevant to the disease family that are NOT documented.",
|
||||
)
|
||||
contradictory_attributes: list[str] = Field(
|
||||
contradicted_attributes: list[str] = Field(
|
||||
default_factory=list,
|
||||
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,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
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):
|
||||
"""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
|
||||
clinically compatible candidate subsets.
|
||||
@@ -118,6 +261,38 @@ class MatchSpec(BaseModel):
|
||||
disease_family: str = Field(
|
||||
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(
|
||||
default_factory=list,
|
||||
description="ICD-10-CM code category prefixes permitted for this concept (e.g. ['C50.*']).",
|
||||
@@ -134,10 +309,24 @@ class MatchSpec(BaseModel):
|
||||
default_factory=list,
|
||||
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",
|
||||
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):
|
||||
|
||||
@@ -11,6 +11,8 @@ Strictly rejects:
|
||||
|
||||
import re
|
||||
|
||||
from medical_coding.schemas.enums import ClinicalEntityType
|
||||
|
||||
# 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",
|
||||
@@ -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:
|
||||
"""Deterministic clinical candidate gate enforcing Section 3, 5 & 8 requirements."""
|
||||
"""Deterministic clinical candidate gate enforcing Section 4 & Section 11 specifications."""
|
||||
|
||||
@classmethod
|
||||
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:
|
||||
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"]):
|
||||
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"
|
||||
|
||||
@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
|
||||
def get_rejection_category(cls, term: str, _evidence_text: str = "") -> str:
|
||||
"""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):
|
||||
return "MEDICATION"
|
||||
if any(re.search(pat, term_lower) for pat in INSTRUCTION_PATTERNS):
|
||||
return "INSTRUCTION"
|
||||
if any(re.search(rf"\b{re.escape(proc)}\b", term_lower) for proc in PROCEDURE_TERMS) or any(term_lower.endswith(sfx) for sfx in PROCEDURE_SUFFIXES):
|
||||
return "PROCEDURE"
|
||||
if any(re.search(pat, term_lower) for pat in ISOLATED_ANATOMY_PATTERNS):
|
||||
return "ANATOMY"
|
||||
|
||||
Reference in New Issue
Block a user