fix(oncology): resolve metastatic concept normalization, reverse attributes, and profile latency
This commit is contained in:
@@ -300,6 +300,8 @@ class EvidenceFirstFactExtractor:
|
||||
item.normalized_diagnosis = raw_t
|
||||
|
||||
canon = self._canonicalize_term(item.raw_term)
|
||||
if canon and canon != item.raw_term:
|
||||
item.normalized_diagnosis = canon
|
||||
lat = item.clinical_attributes.get("laterality", "") if item.clinical_attributes else ""
|
||||
key = f"{canon.lower().strip()}_{lat}".strip("_")
|
||||
if not key or len(key) < 2:
|
||||
@@ -593,6 +595,12 @@ class EvidenceFirstFactExtractor:
|
||||
clause,
|
||||
flags=re.IGNORECASE,
|
||||
).strip()
|
||||
clause = re.sub(
|
||||
r"^(?:patient\s+is\s+an?\s+(?:\d+[\s\-]year[\s\-]old\s+)?(?:male|female|gentleman|lady|man|woman)\s+(?:admitted\s+)?with\s+|patient\s+is\s+a\s+known\s+case\s+of\s+|patient\s+presents?\s+(?:to\s+.*?\s+)?with\s+|pt\s+is\s+an?\s+.*?\s+with\s+)",
|
||||
"",
|
||||
clause,
|
||||
flags=re.IGNORECASE,
|
||||
).strip()
|
||||
clause = re.sub(
|
||||
r"^(?:(?:several|\d+)\s+(?:days?|weeks?|months?|hours?)\s+of\s+)",
|
||||
"",
|
||||
@@ -719,9 +727,9 @@ class EvidenceFirstFactExtractor:
|
||||
)
|
||||
# Strip list numbering e.g. "1. Acute right emphysematous pyelonephritis - underwent DJ stenting"
|
||||
cleaned_line = re.sub(r"^\d+[\.\)\-]\s*", "", line).strip()
|
||||
# Strip structural role prefixes (e.g., "Primary:", "Principal Diagnosis -", "Secondary:")
|
||||
# Strip structural role and metadata prefixes (e.g., "Primary:", "Principal Diagnosis -", "Secondary:", "Metastatic sites:")
|
||||
cleaned_line = re.sub(
|
||||
r"^(?:(?:primary|principal|secondary|final|admitting)\s*(?:diagnosis|diagnoses|condition)?|(?:diagnosis|diagnoses|condition))\s*[:\-–—]\s*",
|
||||
r"^(?:(?:primary|principal|secondary|final|admitting)\s*(?:diagnosis|diagnoses|condition)?|(?:diagnosis|diagnoses|condition)|metastatic\s+sites?|sites?\s+of\s+metastat\w+|distant\s+sites?|oncology\s+attributes?|biomarkers?)\s*[:\-–—]\s*",
|
||||
"",
|
||||
cleaned_line,
|
||||
flags=re.IGNORECASE,
|
||||
@@ -1511,9 +1519,13 @@ class EvidenceFirstFactExtractor:
|
||||
return None
|
||||
|
||||
# 1. Primary Site
|
||||
primary_site = "breast" if "breast" in text_lower else "unknown"
|
||||
if primary_site == "unknown":
|
||||
for site in ["ovary", "ovarian", "colon", "lung", "prostate", "cervix", "uterus", "kidney"]:
|
||||
primary_site = "unknown"
|
||||
if re.search(r"\bprostat(?:e|ic)\b", text_lower):
|
||||
primary_site = "prostate"
|
||||
elif "breast" in text_lower:
|
||||
primary_site = "breast"
|
||||
else:
|
||||
for site in ["ovary", "ovarian", "colon", "lung", "cervix", "uterus", "kidney"]:
|
||||
if site in text_lower:
|
||||
primary_site = site
|
||||
break
|
||||
@@ -1527,11 +1539,11 @@ class EvidenceFirstFactExtractor:
|
||||
laterality = "left"
|
||||
elif re.search(rf"\bbilateral\s+(?:\w+\s+)?{site_pat}\b|\b{site_pat}\b[^\n,.]*?\bbilateral\b", text_lower):
|
||||
laterality = "bilateral"
|
||||
elif "right" in text_lower and "left" not in text_lower:
|
||||
elif "right" in text_lower and "left" not in text_lower and primary_site in ("breast", "lung", "kidney", "ovary"):
|
||||
laterality = "right"
|
||||
elif "left" in text_lower and "right" not in text_lower:
|
||||
elif "left" in text_lower and "right" not in text_lower and primary_site in ("breast", "lung", "kidney", "ovary"):
|
||||
laterality = "left"
|
||||
elif "bilateral" in text_lower:
|
||||
elif "bilateral" in text_lower and primary_site in ("breast", "lung", "kidney", "ovary"):
|
||||
laterality = "bilateral"
|
||||
|
||||
# 3. Histology
|
||||
@@ -1544,6 +1556,8 @@ class EvidenceFirstFactExtractor:
|
||||
r"\bdcis\b",
|
||||
r"\bhigh[- ]grade\s+serous\s+carcinoma\b",
|
||||
r"\bserous\s+carcinoma\b",
|
||||
r"\bacinar\s+adenocarcinoma\b",
|
||||
r"\bprostatic\s+adenocarcinoma\b",
|
||||
r"\badenocarcinoma\b",
|
||||
r"\bsquamous\s+cell\s+carcinoma\b",
|
||||
]:
|
||||
@@ -1552,13 +1566,35 @@ class EvidenceFirstFactExtractor:
|
||||
histology = m.group(0).title()
|
||||
break
|
||||
|
||||
# 4. Grade
|
||||
# 4. Grade, Gleason Score, and Grade Group
|
||||
grade = None
|
||||
grade_m = re.search(r"\b(?:grade\s*([1-3]|i{1,3})|poorly\s+differentiated|moderately\s+differentiated|well\s+differentiated)\b", text_lower)
|
||||
gleason_score = None
|
||||
grade_group = None
|
||||
|
||||
gleason_m = re.search(
|
||||
r"\bgleason(?:\s+score)?\s*(?::|=|\s+is|\s+was)?\s*([0-9]+(?:\s*(?:\+|\/|\=|\(.*?\))\s*[0-9]+)?)\b",
|
||||
text,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
if gleason_m:
|
||||
gleason_score = gleason_m.group(1).strip()
|
||||
|
||||
gg_m = re.search(r"\bgrade\s+group\s*([1-5])\b", text, re.IGNORECASE)
|
||||
if gg_m:
|
||||
grade_group = f"Grade Group {gg_m.group(1)}"
|
||||
|
||||
grade_m = re.search(
|
||||
r"\b(?:grade\s*([1-3]|i{1,3})|poorly\s+differentiated|moderately\s+differentiated|well\s+differentiated)\b",
|
||||
text_lower,
|
||||
)
|
||||
if grade_m:
|
||||
grade = grade_m.group(0).capitalize()
|
||||
elif grade_group:
|
||||
grade = grade_group
|
||||
elif gleason_score:
|
||||
grade = f"Gleason {gleason_score}"
|
||||
|
||||
# 5. Receptor Status (ER, PR, HER2)
|
||||
# 5. Receptor Status (ER, PR, HER2, PSA)
|
||||
receptor_status: dict[str, str] = {}
|
||||
er_m = re.search(r"\ber\s*(?:[:=]|\s+is|\s+was)?\s*([><=]?\s*\d+%\s*(?:positive|\+)|positive|\+|negative|\-|equivocal|[><=]?\s*\d+%)", text, re.IGNORECASE)
|
||||
if er_m:
|
||||
@@ -1578,7 +1614,27 @@ class EvidenceFirstFactExtractor:
|
||||
receptor_status["HER2"] = v
|
||||
receptor_status["her2"] = v
|
||||
|
||||
# 6. Ki-67 Proliferation Index
|
||||
psa_level = None
|
||||
psa_m = re.search(
|
||||
r"\bpsa(?:\s+level)?\s*(?::|=|\s+is|\s+was)?\s*([><=]?\s*[\d\.\,]+(?:\s*ng\s*/\s*m[lL])?)\b",
|
||||
text,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
if psa_m:
|
||||
psa_level = psa_m.group(1).strip()
|
||||
if "ng/ml" not in psa_level.lower() and re.match(r"^[\d\.\,]+$", psa_level):
|
||||
psa_level = f"{psa_level} ng/mL"
|
||||
receptor_status["PSA"] = psa_level
|
||||
receptor_status["psa"] = psa_level
|
||||
|
||||
# 6. Castration Status (mCRPC vs Castration-sensitive)
|
||||
castration_status = None
|
||||
if re.search(r"\b(?:metastatic\s+)?castrat(?:ion|e)[- ]resistant(?:\s+(?:status|state|prostate\s+cancer))?\b|\bmcrpc\b|\bcrpc\b", text_lower):
|
||||
castration_status = "Castration-resistant"
|
||||
elif re.search(r"\bcastrat(?:ion|e)[- ]sensitive\b|\bhormone[- ]sensitive\b|\bmhspc\b", text_lower):
|
||||
castration_status = "Castration-sensitive"
|
||||
|
||||
# 7. Ki-67 Proliferation Index
|
||||
ki67 = None
|
||||
ki67_m = re.search(
|
||||
r"\bki-?67(?:\s+(?:proliferation\s+index|labeling\s+index|index))?\s*(?:[:=]|\s+is|\s+was)?\s*([><=]?\s*\d+%(?:\s*(?:high|low))?|high|low)",
|
||||
@@ -1588,33 +1644,46 @@ class EvidenceFirstFactExtractor:
|
||||
if ki67_m:
|
||||
ki67 = ki67_m.group(1).strip()
|
||||
|
||||
# 7. Metastatic Status & Sites
|
||||
# 8. Metastatic Status & Sites
|
||||
met_sites: list[str] = []
|
||||
if re.search(r"\bno\s+(?:evidence\s+of\s+)?(?:distant\s+)?metastases\b|\bnon[- ]metastatic\b|\bm0\b", text_lower):
|
||||
met_status = "NON_METASTATIC"
|
||||
elif re.search(r"\bmetastat(?:ic|es)\b|\bm1\b", text_lower):
|
||||
met_status = "METASTATIC"
|
||||
for site in ["bone", "liver", "lung", "brain", "pleura", "peritoneum", "adrenal", "lymph node"]:
|
||||
for site in ["bone", "liver", "lung", "brain", "pleura", "peritoneum", "adrenal", "lymph node", "spine", "pelvis"]:
|
||||
if site in text_lower:
|
||||
met_sites.append(site)
|
||||
norm_site = "bone" if site in ("spine", "pelvis") else site
|
||||
if norm_site not in met_sites:
|
||||
met_sites.append(norm_site)
|
||||
else:
|
||||
met_status = "UNKNOWN"
|
||||
|
||||
# 8. Prior Treatments
|
||||
# 9. Prior Treatments
|
||||
prior_tx: list[str] = []
|
||||
for tx_pat in [
|
||||
r"\bandrogen\s+deprivation\s+therapy\b|\badt\b",
|
||||
r"\bleuprolide\b|\blupron\b",
|
||||
r"\benzalutamide\b|\bxtandi\b",
|
||||
r"\babiraterone\b|\bzytiga\b",
|
||||
r"\bbicalutamide\b|\bcasodex\b",
|
||||
r"\bdenosumab\b|\bxgeva\b|\bprolia\b",
|
||||
r"\bdocetaxel\b|\btaxotere\b",
|
||||
r"\bcabazitaxel\b|\bjevtana\b",
|
||||
r"\bradium-?223\b|\bxofigo\b",
|
||||
r"\bneoadjuvant\s+chemotherapy\b",
|
||||
r"\badjuvant\s+chemotherapy\b",
|
||||
r"\bradiotherapy\b|\bradiation\b",
|
||||
r"\bpalliative\s+radiotherapy\b|\bradiotherapy\b|\bradiation\b",
|
||||
r"\btamoxifen\b",
|
||||
r"\bletrozole\b",
|
||||
r"\banastrozole\b",
|
||||
r"\btrastuzumab\b|\bherceptin\b",
|
||||
r"\bprostatectomy\b|\bradical\s+prostatectomy\b",
|
||||
]:
|
||||
if re.search(tx_pat, text_lower):
|
||||
prior_tx.append(re.search(tx_pat, text_lower).group(0))
|
||||
m = re.search(tx_pat, text_lower)
|
||||
if m:
|
||||
prior_tx.append(m.group(0))
|
||||
|
||||
# 9. Response to Treatment
|
||||
# 10. Response to Treatment
|
||||
resp = None
|
||||
for resp_pat in [
|
||||
r"\bpathologic(?:al)?\s+complete\s+response\b|\bpcr\b",
|
||||
@@ -1641,6 +1710,10 @@ class EvidenceFirstFactExtractor:
|
||||
receptor_status=receptor_status,
|
||||
ki67=ki67,
|
||||
treatment_response=resp,
|
||||
gleason_score=gleason_score,
|
||||
grade_group=grade_group,
|
||||
psa_level=psa_level,
|
||||
castration_status=castration_status,
|
||||
prior_treatments=prior_tx,
|
||||
evidence=text[:200],
|
||||
)
|
||||
@@ -1689,6 +1762,10 @@ class EvidenceFirstFactExtractor:
|
||||
"esophageal", "bronchial", "alveolar", "pancreatic", "biliary", "vesical",
|
||||
"urethral", "ureteral", "prostatic", "testicular", "ovarian", "uterine",
|
||||
"vaginal", "vulvar", "peritoneal", "pleural", "pericardial",
|
||||
"prostate", "breast", "lung", "kidney", "liver", "colon", "bone", "bladder",
|
||||
"thyroid", "pancreas", "stomach", "brain", "spine", "pelvis", "ovary", "testis", "heart", "skin",
|
||||
"castration-resistant", "castrate-resistant", "hormone-refractory", "hormone-sensitive",
|
||||
"castration-sensitive", "resistant", "recurrent", "refractory",
|
||||
}
|
||||
|
||||
generic_suffix_nouns = {
|
||||
@@ -1790,6 +1867,16 @@ class EvidenceFirstFactExtractor:
|
||||
for i, m in enumerate(abbrev_matches):
|
||||
masked = masked.replace(m.group(0), f"__ORGANISM_{i}__")
|
||||
|
||||
# Mask parentheticals to prevent internal splitting on commas or plus signs (e.g. '(4+5)', '(lumbar spine, pelvis)')
|
||||
paren_matches = list(re.finditer(r"\([^\)]*\)|\[[^\]]*\]", masked))
|
||||
for i, pm in enumerate(paren_matches):
|
||||
masked = masked.replace(pm.group(0), f"__PAREN_EXPR_{i}__")
|
||||
|
||||
# Mask plus signs attached to numbers (e.g., Gleason 4+5)
|
||||
plus_num_matches = list(re.finditer(r"\b\d+\+\d+\b", masked))
|
||||
for i, pnm in enumerate(plus_num_matches):
|
||||
masked = masked.replace(pnm.group(0), f"__PLUS_NUM_{i}__")
|
||||
|
||||
# Mask plus signs attached to receptor/immunology markers (e.g., CD4+, HER2+, ER+, PR+)
|
||||
plus_matches = list(re.finditer(r"\b([A-Za-z0-9\-]+)\+", masked))
|
||||
for i, pm in enumerate(plus_matches):
|
||||
@@ -1825,6 +1912,38 @@ class EvidenceFirstFactExtractor:
|
||||
if not chunk:
|
||||
continue
|
||||
|
||||
# Strip metadata headers if embedded in chunk
|
||||
chunk = re.sub(
|
||||
r"^(?:metastatic\s+sites?|oncology\s+attributes?(?:\s*(?:&|and)?\s*biomarkers?)?|biomarkers?(?:\s*&|\s*and)?\s*receptor\s+status)\s*[:\-–—]\s*",
|
||||
"",
|
||||
chunk,
|
||||
flags=re.IGNORECASE,
|
||||
).strip()
|
||||
if not chunk:
|
||||
continue
|
||||
|
||||
# Handle "metastatic to site1 and site2" or "metastases to site1 and site2"
|
||||
met_to_m = re.search(r"^(.*?)\s*,?\s*\b(metastat(?:ic|es)\s+to)\s+([^.,;\n]+)$", chunk, re.IGNORECASE)
|
||||
if met_to_m:
|
||||
pri_part = met_to_m.group(1).strip()
|
||||
met_pfx = met_to_m.group(2).strip()
|
||||
met_targets = met_to_m.group(3).strip()
|
||||
if pri_part and len(pri_part) >= 3:
|
||||
refined_chunks.append(pri_part)
|
||||
targets = re.split(r",\s*|\s+and\s+", met_targets)
|
||||
for t in targets:
|
||||
t_clean = t.strip()
|
||||
if t_clean and len(t_clean) >= 2:
|
||||
refined_chunks.append(f"{met_pfx} {t_clean}")
|
||||
continue
|
||||
|
||||
# Handle "[adj1] and [adj2] lymph node metastases"
|
||||
adj_noun_m = re.search(r"^([a-z\-]+)\s+and\s+([a-z\-]+)\s+(lymph\s+node\s+metastases?|osseous\s+metastases?|bone\s+metastases?)$", chunk, re.IGNORECASE)
|
||||
if adj_noun_m:
|
||||
refined_chunks.append(f"{adj_noun_m.group(1)} {adj_noun_m.group(3)}")
|
||||
refined_chunks.append(f"{adj_noun_m.group(2)} {adj_noun_m.group(3)}")
|
||||
continue
|
||||
|
||||
is_combo_manifestation = any(re.search(pat, chunk, re.IGNORECASE) for pat in combo_manifestation_patterns)
|
||||
with_match = re.search(independent_with_pattern, chunk, re.IGNORECASE)
|
||||
|
||||
@@ -1877,6 +1996,10 @@ class EvidenceFirstFactExtractor:
|
||||
res = res.replace(f"__ORGANISM_{i}__", m.group(0))
|
||||
for i, pm in enumerate(plus_matches):
|
||||
res = res.replace(f"__PLUS_MARKER_{i}__", pm.group(0))
|
||||
for i, pnm in enumerate(plus_num_matches):
|
||||
res = res.replace(f"__PLUS_NUM_{i}__", pnm.group(0))
|
||||
for i, pm in enumerate(paren_matches):
|
||||
res = res.replace(f"__PAREN_EXPR_{i}__", pm.group(0))
|
||||
|
||||
# Strip trailing procedural or temporal timing context (e.g. "gastritis post frozen embryo transfer" -> "gastritis")
|
||||
timing_m = re.search(r"\b(?:status\s+post|post|s/p|after)\s+(?:frozen\s+embryo\s+transfer|fet|chemotherapy|surgery|procedure|infusion)\b.*$", res, re.IGNORECASE)
|
||||
@@ -1895,13 +2018,22 @@ class EvidenceFirstFactExtractor:
|
||||
|
||||
def _split_term_and_narrative(self, line: str) -> tuple[str, str]:
|
||||
"""Split a clinical line into the diagnostic term and accompanying clinical explanation."""
|
||||
# If line begins with metadata/label prefix, strip it so the clinical entity is the term
|
||||
label_prefix_m = re.match(
|
||||
r"^\s*(?:metastatic\s+sites?|sites?\s+of\s+metastat\w+|distant\s+sites?|oncology\s+attributes?|biomarkers?|pathology|histology)\s*[:\-–—]\s*",
|
||||
line,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
if label_prefix_m:
|
||||
line = line[label_prefix_m.end():].strip()
|
||||
|
||||
# Narrative delimiters introduce management/course comments (e.g. " - underwent DJ stenting")
|
||||
# Do not include ";" or "/" as they separate distinct clinical entities in diagnosis lists
|
||||
for delim in [" - ", " – ", " — ", " : ", ": ", " ("]:
|
||||
for delim in [" - ", " – ", " — ", " : ", ": "]:
|
||||
if delim in line:
|
||||
parts = line.split(delim, 1)
|
||||
term = parts[0].strip()
|
||||
narrative = parts[1].rstrip(")").strip()
|
||||
narrative = parts[1].strip()
|
||||
if len(term) >= 3:
|
||||
return term, narrative
|
||||
|
||||
@@ -1951,9 +2083,57 @@ class EvidenceFirstFactExtractor:
|
||||
def _canonicalize_term(self, term: str) -> str:
|
||||
clean = re.sub(r"^\d+[\.\)\-]\s*", "", term).strip()
|
||||
clean = re.sub(r"\s+", " ", clean).strip(".,;: ")
|
||||
|
||||
# Section 21: Oncology metastatic manifestations
|
||||
if re.search(r"\bpleural\s+metastasis\b|\bmetastasis\s+to\s+pleura\b|\bmalignant\s+pleural\s+metastasis\b", clean, re.IGNORECASE):
|
||||
if re.search(
|
||||
r"\b(?:bone\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+bone|metastatic\s+bone\s+disease|bone\s*\((?:lumbar\s+)?spine|bone\s*\(pelvis|osseous\s+metastases?|skeletal\s+metastases?|osteoblastic\s+metastases?|osteoblastic\s+metastatic\s+disease|osteoblastic\s+(?:spine\s+)?lesions?|metastat(?:ic|es)\s+to\s+(?:the\s+)?(?:lumbar\s+)?spine|metastat(?:ic|es)\s+to\s+(?:the\s+)?pelvis)\b",
|
||||
clean,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
return "Secondary malignant neoplasm of bone"
|
||||
|
||||
if re.search(
|
||||
r"\b(?:retroperitoneal\s+(?:and\s+pelvic\s+)?lymph\s+node\s+metastases?|retroperitoneal\s+lymphadenopathy|metastat(?:ic|es)\s+(?:to|in)\s+retroperitoneal\s+lymph\s+nodes?|intra[- ]abdominal\s+lymph\s+node\s+metastases?)\b",
|
||||
clean,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
return "Secondary and unspecified malignant neoplasm of intra-abdominal lymph nodes"
|
||||
|
||||
if re.search(
|
||||
r"\b(?:pelvic\s+lymph\s+node\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+pelvic\s+lymph\s+nodes?)\b",
|
||||
clean,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
return "Secondary and unspecified malignant neoplasm of intrapelvic lymph nodes"
|
||||
|
||||
if re.search(
|
||||
r"\b(?:lymph\s+node\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+lymph\s+nodes?|nodal\s+metastases?|distant\s+lymphadenopathy)\b",
|
||||
clean,
|
||||
re.IGNORECASE,
|
||||
):
|
||||
return "Secondary and unspecified malignant neoplasm of lymph nodes"
|
||||
|
||||
if re.search(r"\b(?:liver\s+metastases?|hepatic\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+liver)\b", clean, re.IGNORECASE):
|
||||
return "Secondary malignant neoplasm of liver"
|
||||
|
||||
if re.search(r"\b(?:lung\s+metastases?|pulmonary\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+lung)\b", clean, re.IGNORECASE):
|
||||
return "Secondary malignant neoplasm of lung"
|
||||
|
||||
if re.search(r"\b(?:brain\s+metastases?|cerebral\s+metastases?|metastat(?:ic|es)\s+(?:to|in)\s+brain)\b", clean, re.IGNORECASE):
|
||||
return "Secondary malignant neoplasm of brain"
|
||||
|
||||
if re.search(r"\b(?:pleural\s+metastases?|pleural\s+metastasis|metastasis\s+to\s+pleura|malignant\s+pleural\s+effusion|malignant\s+pleural\s+metastasis)\b", clean, re.IGNORECASE):
|
||||
return "Secondary malignant neoplasm of pleura"
|
||||
|
||||
if re.search(r"\b(?:prostate\s+cancer|prostate\s+carcinoma|adenocarcinoma\s+of\s+(?:the\s+)?prostate|prostate\s+adenocarcinoma|malignant\s+neoplasm\s+of\s+prostate)\b", clean, re.IGNORECASE):
|
||||
return "Malignant neoplasm of prostate"
|
||||
|
||||
if re.search(r"\b(?:type\s+2\s+diabetes|t2dm|diabetes\s+mellitus\s+type\s+2|type\s+ii\s+diabetes)\b", clean, re.IGNORECASE):
|
||||
return "Type 2 diabetes mellitus"
|
||||
|
||||
if re.search(r"\b(?:essential\s+hypertension|primary\s+hypertension|systemic\s+hypertension|hypertension|htn)\b", clean, re.IGNORECASE):
|
||||
return "Essential hypertension"
|
||||
|
||||
if clean.lower() in ("urticarial", "urticarial rash", "rash urticarial"):
|
||||
return "Urticaria"
|
||||
return clean
|
||||
@@ -2297,6 +2477,18 @@ class EvidenceFirstFactExtractor:
|
||||
primary_diag.clinical_attributes["ki67"] = oncology_context.ki67
|
||||
if oncology_context.treatment_response:
|
||||
primary_diag.clinical_attributes["treatment_response"] = oncology_context.treatment_response
|
||||
if oncology_context.gleason_score:
|
||||
primary_diag.clinical_attributes["gleason_score"] = oncology_context.gleason_score
|
||||
if oncology_context.grade_group:
|
||||
primary_diag.clinical_attributes["grade_group"] = oncology_context.grade_group
|
||||
if oncology_context.psa_level:
|
||||
primary_diag.clinical_attributes["psa_level"] = oncology_context.psa_level
|
||||
if oncology_context.castration_status:
|
||||
primary_diag.clinical_attributes["castration_status"] = oncology_context.castration_status
|
||||
if oncology_context.metastatic_status:
|
||||
primary_diag.clinical_attributes["metastatic_status"] = oncology_context.metastatic_status
|
||||
if oncology_context.metastatic_sites:
|
||||
primary_diag.clinical_attributes["metastatic_sites"] = oncology_context.metastatic_sites
|
||||
if oncology_context.prior_treatments:
|
||||
primary_diag.clinical_attributes["prior_treatments"] = oncology_context.prior_treatments
|
||||
|
||||
|
||||
@@ -471,17 +471,33 @@ class CandidateRankingAgent(BaseAgent):
|
||||
if not core_diag_tokens:
|
||||
core_diag_tokens = term_tokens
|
||||
|
||||
# Expand abbreviations (e.g. ACL -> anterior cruciate ligament, NET -> neuroendocrine tumor)
|
||||
# Expand abbreviations and anatomical equivalences (e.g. retroperitoneal -> intra-abdominal)
|
||||
expanded_core_tokens = list(core_diag_tokens)
|
||||
ANATOMICAL_EQUIVALENCES: dict[str, list[str]] = {
|
||||
"retroperitoneal": ["intra-abdominal", "intraabdominal", "abdominal"],
|
||||
"pelvic": ["intrapelvic", "pelvis"],
|
||||
"spine": ["bone", "vertebra", "vertebral"],
|
||||
"lumbar": ["bone", "spine", "vertebra"],
|
||||
}
|
||||
for ct in core_diag_tokens:
|
||||
if ct in CLINICAL_ABBREVIATIONS:
|
||||
for ab_word in CLINICAL_ABBREVIATIONS[ct].split():
|
||||
if ab_word not in QUALIFIERS_TO_IGNORE and ab_word not in expanded_core_tokens:
|
||||
expanded_core_tokens.append(ab_word)
|
||||
if ct in ANATOMICAL_EQUIVALENCES:
|
||||
for eq_word in ANATOMICAL_EQUIVALENCES[ct]:
|
||||
for w in re.findall(r"[a-z0-9]+", eq_word):
|
||||
if w not in QUALIFIERS_TO_IGNORE and w not in expanded_core_tokens:
|
||||
expanded_core_tokens.append(w)
|
||||
|
||||
scored_candidates: list[tuple[ICDCandidate, float, str]] = []
|
||||
|
||||
for cand in candidates:
|
||||
# 0. CPT procedure codes cannot be selected as diagnosis codes
|
||||
is_cpt = getattr(cand, "coding_system", None) == "CPT" or (cand.code.isdigit() and len(cand.code) in (4, 5))
|
||||
if is_cpt:
|
||||
continue
|
||||
|
||||
score = cand.retrieval_score
|
||||
desc_lower = cand.description.lower()
|
||||
rationale_parts: list[str] = []
|
||||
@@ -616,6 +632,16 @@ class CandidateRankingAgent(BaseAgent):
|
||||
bool(re.search(rf"\b{re.escape(site_w)}\b", desc_lower)) and bool(re.search(rf"\b{re.escape(site_w)}\b", full_context))
|
||||
for site_w in ["anterior", "inferior", "lateral", "posterior", "apical", "subendocardial", "tarsal", "metatarsal", "malleolus", "femur", "tibia", "fibula", "radius", "ulna", "humerus"]
|
||||
)
|
||||
is_unspec_code = (
|
||||
cand.code.endswith(".9")
|
||||
or cand.code.endswith(".90")
|
||||
or cand.code.endswith(".99")
|
||||
or "unspecified site" in desc_lower
|
||||
or "unspecified location" in desc_lower
|
||||
or "lymph node, unspecified" in desc_lower
|
||||
or "unspecified lymph node" in desc_lower
|
||||
or ("unspecified" in desc_lower and not any(spec in desc_lower for spec in ["intra-abdominal", "intrathoracic", "intrapelvic", "head", "neck", "axilla", "inguinal", "upper limb", "lower limb"]))
|
||||
)
|
||||
if ("other " in desc_lower or "other specified" in desc_lower) and not has_matching_site:
|
||||
doc_has_other_detail = any(
|
||||
w in full_context for w in ["other", "specified", "variant", "type"]
|
||||
@@ -623,26 +649,39 @@ class CandidateRankingAgent(BaseAgent):
|
||||
if not doc_has_other_detail:
|
||||
score -= 0.20
|
||||
rationale_parts.append("other specified code without documented detail")
|
||||
elif "unspecified" in desc_lower or "without " in desc_lower or cand.code.endswith(".9") or cand.code.endswith(".90"):
|
||||
elif is_unspec_code or "without " in desc_lower:
|
||||
missing_core_tokens = [
|
||||
ct for ct in expanded_core_tokens
|
||||
if ct not in cand_tokens_set and not any(v in cand_tokens_set for v in CLINICAL_MORPHOLOGY.get(ct, []))
|
||||
]
|
||||
doc_has_specific_site = any(
|
||||
site_w in full_context
|
||||
for site_w in ["anterior", "inferior", "lateral", "posterior", "apical", "subendocardial", "tarsal", "metatarsal", "malleolus"]
|
||||
for site_w in ["anterior", "inferior", "lateral", "posterior", "apical", "subendocardial", "tarsal", "metatarsal", "malleolus", "retroperitoneal", "spine", "lumbar"]
|
||||
)
|
||||
cand_unspec_site = "unspecified" in desc_lower and any(w in desc_lower for w in ["site", "wall", "artery", "bone", "location"])
|
||||
cand_unspec_site = "unspecified" in desc_lower and any(w in desc_lower for w in ["site", "wall", "artery", "bone", "location", "lymph node", "node"])
|
||||
if doc_has_specific_site and cand_unspec_site:
|
||||
score -= 0.25
|
||||
rationale_parts.append("unspecified site when specific anatomical location is documented")
|
||||
elif missing_core_tokens and "unspecified" in desc_lower:
|
||||
elif missing_core_tokens and is_unspec_code:
|
||||
score -= 0.15
|
||||
rationale_parts.append(f"unspecified code when specific detail ({', '.join(missing_core_tokens)}) is documented")
|
||||
elif not missing_core_tokens and not ((doc_left or doc_right) and cand_unspec_lat) and not (doc_has_specific_site and cand_unspec_site):
|
||||
score += 0.10
|
||||
rationale_parts.append("canonical base/unspecified code for general documentation")
|
||||
|
||||
has_matching_site = any(
|
||||
bool(re.search(rf"\b{re.escape(site_w)}\b", desc_lower)) and bool(re.search(rf"\b{re.escape(site_w)}\b", full_context))
|
||||
for site_w in [
|
||||
"anterior", "inferior", "lateral", "posterior", "apical", "subendocardial",
|
||||
"tarsal", "metatarsal", "malleolus", "femur", "tibia", "fibula", "radius", "ulna", "humerus",
|
||||
"intra-abdominal", "abdominal", "pelvis", "pelvic", "spine", "vertebra", "lumbar",
|
||||
]
|
||||
)
|
||||
if ("retroperitoneal" in full_context and ("intra-abdominal" in desc_lower or "intraabdominal" in desc_lower or "abdominal" in desc_lower)):
|
||||
has_matching_site = True
|
||||
elif ("spine" in full_context or "lumbar" in full_context or "pelvis" in full_context) and "bone" in desc_lower:
|
||||
has_matching_site = True
|
||||
|
||||
if has_matching_site:
|
||||
score += 0.25
|
||||
rationale_parts.append("documented anatomical site match")
|
||||
@@ -651,6 +690,22 @@ class CandidateRankingAgent(BaseAgent):
|
||||
(cand, round(score, 4), ", ".join(rationale_parts) or "evidence overlap")
|
||||
)
|
||||
|
||||
if not scored_candidates:
|
||||
return RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
ranking_reason=f"No valid diagnosis candidates supported for '{raw_term}'.",
|
||||
supporting_evidence=[evidence_quote],
|
||||
confidence=0.0,
|
||||
ranking_score=0.0,
|
||||
abstention_reason="NO_MATCHING_ICD_CANDIDATE",
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
# Sort descending by raw ranking score to maintain discrimination among top candidates
|
||||
scored_candidates.sort(key=lambda x: x[1], reverse=True)
|
||||
top_cand, top_score, top_rationale = scored_candidates[0]
|
||||
|
||||
@@ -572,6 +572,9 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
if not clean_query:
|
||||
clean_query = raw_query
|
||||
|
||||
norm_diag = getattr(cond, "normalized_diagnosis", None)
|
||||
search_query = norm_diag if (norm_diag and norm_diag.lower() != raw_query.lower()) else clean_query
|
||||
|
||||
# 2. Derive structured ClinicalConcept (Sections 5 & 6)
|
||||
concept = ClinicalConceptReasoner.reason_concept(
|
||||
cond,
|
||||
@@ -586,12 +589,19 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
existing_codes: set[str] = set()
|
||||
|
||||
# STAGE 1: Primary Hybrid Retrieval with Multi-Round Retry Checking
|
||||
primary_hits = retriever.retrieve_with_retry(clean_query, evidence=ev_quote, top_k=25, system="ICD-10-CM")
|
||||
primary_hits = retriever.retrieve_with_retry(search_query, evidence=ev_quote, top_k=25, system="ICD-10-CM")
|
||||
for h in primary_hits:
|
||||
if h.code not in existing_codes:
|
||||
hits.append(h)
|
||||
existing_codes.add(h.code)
|
||||
|
||||
if search_query != clean_query and (not primary_hits or primary_hits[0].retrieval_score < 0.70):
|
||||
fallback_primary = retriever.retrieve(clean_query, top_k=15, system="ICD-10-CM")
|
||||
for h in fallback_primary:
|
||||
if h.code not in existing_codes:
|
||||
hits.append(h)
|
||||
existing_codes.add(h.code)
|
||||
|
||||
# STAGE 2: Microsecond BM25 Inverted-Index Expansions (Bypasses redundant neural vector calls)
|
||||
from medical_coding.retrieval.tokenizer import (
|
||||
CLINICAL_ABBREVIATIONS,
|
||||
@@ -599,10 +609,12 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
get_expanded_query_tokens,
|
||||
)
|
||||
lexical_terms: list[str] = []
|
||||
if concept.canonical_name and concept.canonical_name.lower() != clean_query.lower():
|
||||
lexical_terms.append(concept.canonical_name)
|
||||
if raw_query.lower() != clean_query.lower():
|
||||
lexical_terms.append(raw_query)
|
||||
has_exact_match = bool(hits and hits[0].retrieval_score >= 0.90)
|
||||
if not has_exact_match:
|
||||
if concept.canonical_name and concept.canonical_name.lower() != clean_query.lower():
|
||||
lexical_terms.append(concept.canonical_name)
|
||||
if raw_query.lower() != clean_query.lower():
|
||||
lexical_terms.append(raw_query)
|
||||
|
||||
query_lower = clean_query.lower()
|
||||
for ab, full in CLINICAL_ABBREVIATIONS.items():
|
||||
@@ -721,13 +733,16 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
if not final_hits:
|
||||
final_hits = hits[:10]
|
||||
|
||||
# Handle ICD-O for neoplasms
|
||||
is_neoplasm = (
|
||||
concept.disease_family in ("breast_malignancy", "lymphoma", "pleural_metastasis", "kaposi_sarcoma", "liver_sarcoma", "neuroendocrine_tumor")
|
||||
or any(w in raw_query.lower() for w in ["cancer", "carcinoma", "neoplasm", "lymphoma", "tumor", "sarcoma", "melanoma", "malignancy", "dcis"])
|
||||
or bool(getattr(concept, "histology", None))
|
||||
# Handle ICD-O for neoplasms: only primary neoplasms require histology morphology coding
|
||||
is_primary_neoplasm = (
|
||||
getattr(cond, "role", None) in (DiagnosisRole.PRIMARY, "PRIMARY")
|
||||
and (
|
||||
concept.disease_family in ("breast_malignancy", "lymphoma", "pleural_metastasis", "kaposi_sarcoma", "liver_sarcoma", "neuroendocrine_tumor", "prostate_malignancy")
|
||||
or any(w in raw_query.lower() for w in ["cancer", "carcinoma", "neoplasm", "lymphoma", "tumor", "sarcoma", "melanoma", "malignancy", "dcis"])
|
||||
or bool(getattr(concept, "histology", None))
|
||||
)
|
||||
)
|
||||
if is_neoplasm:
|
||||
if is_primary_neoplasm:
|
||||
icdo_hits = retriever.retrieve(raw_query, top_k=5, system="ICD-O")
|
||||
for o_hit in icdo_hits:
|
||||
if o_hit.code not in existing_codes:
|
||||
@@ -742,15 +757,11 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"thoracentesis", "paracentesis", "endoscopy", "colonoscopy", "arthroplasty", "mastectomy"
|
||||
]
|
||||
has_proc = (
|
||||
getattr(cond, "procedure_relevance", 0.0) > 0
|
||||
or any(pw in raw_query.lower() or pw in ev_quote.lower() for pw in proc_keywords)
|
||||
getattr(cond, "procedure_relevance", 0.0) > 0.5
|
||||
or any(re.search(rf"\b{re.escape(pw)}\b", raw_query, re.IGNORECASE) for pw in proc_keywords)
|
||||
)
|
||||
if has_proc:
|
||||
proc_query = raw_query
|
||||
for pw in proc_keywords:
|
||||
if pw in ev_quote.lower() and pw not in raw_query.lower():
|
||||
proc_query = f"{raw_query} {pw}"
|
||||
break
|
||||
cpt_hits = retriever.retrieve(proc_query, top_k=5, system="CPT")
|
||||
for c_hit in cpt_hits:
|
||||
if c_hit.code not in existing_codes:
|
||||
@@ -759,16 +770,12 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
|
||||
return cond.diagnosis_id, concept, match_spec, final_hits
|
||||
|
||||
# Parallelize retrieval across diagnoses within document
|
||||
with concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=min(len(billable_conditions), 4)
|
||||
) as executor:
|
||||
futures = [executor.submit(_retrieve_for_condition, c) for c in billable_conditions]
|
||||
for f in concurrent.futures.as_completed(futures):
|
||||
diag_id, concept, match_spec, hits = f.result()
|
||||
clinical_concepts[diag_id] = concept
|
||||
match_specs[diag_id] = match_spec
|
||||
candidate_pool[diag_id] = hits
|
||||
# Sequential condition retrieval (eliminates thread contention on dense vector dot products)
|
||||
for c in billable_conditions:
|
||||
diag_id, concept, match_spec, hits = _retrieve_for_condition(c)
|
||||
clinical_concepts[diag_id] = concept
|
||||
match_specs[diag_id] = match_spec
|
||||
candidate_pool[diag_id] = hits
|
||||
|
||||
return {
|
||||
"clinical_concepts": clinical_concepts,
|
||||
@@ -813,12 +820,11 @@ def rank_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
|
||||
from medical_coding.retrieval.tokenizer import CLINICAL_MORPHOLOGY
|
||||
|
||||
for cond in classified:
|
||||
def _rank_for_condition(cond: ClassifiedDiagnosis) -> tuple[RankedSelection, list[ICDCandidate]]:
|
||||
candidates = candidate_pool.get(cond.diagnosis_id, [])
|
||||
ev_quote = getattr(cond.context.evidence, "quote", "") if hasattr(cond, "context") and hasattr(cond.context, "evidence") and cond.context.evidence else ""
|
||||
|
||||
# Corroborate evidence across document narrative (Master Prompt Sections 4, 10, 11)
|
||||
# Merge evidence spans discussing this specific condition from hospital course, exam, etc.
|
||||
ev_snippets: list[str] = [s.strip() for s in ev_quote.split(" | ") if s.strip()] if ev_quote else []
|
||||
cond_tokens = [
|
||||
w for w in re.findall(r"\b[a-z0-9]{3,}\b", cond.raw_term.lower())
|
||||
@@ -842,6 +848,7 @@ def rank_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
clean_evidence_quote = " | ".join(ev_snippets).strip() if ev_snippets else ev_quote
|
||||
selection = agent.rank_candidates(cond, candidates, evidence_override=clean_evidence_quote.strip() or None)
|
||||
|
||||
pool_res = candidates
|
||||
# Multi-round re-checking for conditions with positive evidence that were not identified on initial pass
|
||||
if (
|
||||
selection.selected_code is None
|
||||
@@ -861,9 +868,18 @@ def rank_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
re_selection = agent.rank_candidates(cond, retry_candidates, evidence_override=clean_evidence_quote.strip() or None)
|
||||
if re_selection.selected_code is not None:
|
||||
selection = re_selection
|
||||
candidate_pool[cond.diagnosis_id] = retry_candidates
|
||||
pool_res = retry_candidates
|
||||
|
||||
ranked_selections.append(selection)
|
||||
return selection, pool_res
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=min(len(classified), 4) if classified else 1
|
||||
) as executor:
|
||||
futures = [executor.submit(_rank_for_condition, c) for c in classified]
|
||||
for f in concurrent.futures.as_completed(futures):
|
||||
selection, pool = f.result()
|
||||
ranked_selections.append(selection)
|
||||
candidate_pool[selection.diagnosis_id] = pool
|
||||
|
||||
return {
|
||||
"ranked_selections": ranked_selections,
|
||||
@@ -1214,23 +1230,47 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
continue
|
||||
|
||||
# Per requirement: for [no_local_code] type diagnosis, nearest relatable code should get displayed, because they also have evidence
|
||||
from medical_coding.validation.reverse_attributes import ReverseAttributeChecker
|
||||
|
||||
def _is_clinically_relatable(cand: ICDCandidate) -> bool:
|
||||
if not catalog.is_valid_code(cand.code) or not catalog.is_billable_code(cand.code):
|
||||
return False
|
||||
anat_ok, _ = ReverseAttributeChecker.validate_anatomical_site(
|
||||
code_description=cand.description,
|
||||
evidence_text=c_quote,
|
||||
diagnosis_term=c_term,
|
||||
)
|
||||
if not anat_ok:
|
||||
return False
|
||||
lat_ok, _ = ReverseAttributeChecker.validate_laterality(
|
||||
code_description=cand.description,
|
||||
evidence_text=c_quote,
|
||||
diagnosis_term=c_term,
|
||||
)
|
||||
if not lat_ok:
|
||||
return False
|
||||
attr_ok, _ = ReverseAttributeChecker.validate_code_attributes(
|
||||
code_description=cand.description,
|
||||
evidence_text=c_quote,
|
||||
diagnosis_term=c_term,
|
||||
)
|
||||
if not attr_ok:
|
||||
return False
|
||||
return True
|
||||
|
||||
nearest_cand = None
|
||||
cand_pool_item = state.get("candidate_pool", {}).get(getattr(c, "diagnosis_id", ""), [])
|
||||
if cand_pool_item:
|
||||
for cand in cand_pool_item:
|
||||
if catalog.is_valid_code(cand.code) and catalog.is_billable_code(cand.code):
|
||||
if _is_clinically_relatable(cand):
|
||||
nearest_cand = cand
|
||||
break
|
||||
if not nearest_cand and cand_pool_item:
|
||||
nearest_cand = cand_pool_item[0]
|
||||
if not nearest_cand and c_term:
|
||||
retrieved = retriever.retrieve(c_term, top_k=5)
|
||||
for cand in retrieved:
|
||||
if catalog.is_valid_code(cand.code) and catalog.is_billable_code(cand.code):
|
||||
if _is_clinically_relatable(cand):
|
||||
nearest_cand = cand
|
||||
break
|
||||
if not nearest_cand and retrieved:
|
||||
nearest_cand = retrieved[0]
|
||||
|
||||
if nearest_cand and c_quote:
|
||||
is_icdo = bool(getattr(nearest_cand, "coding_system", None) == "ICD-O" or nearest_cand.code.startswith("M"))
|
||||
|
||||
@@ -18,6 +18,9 @@ logger = get_logger(__name__)
|
||||
|
||||
# Canonical Disease Families mapped to key entity detection cues
|
||||
DISEASE_FAMILY_PATTERNS: list[tuple[str, list[str], str]] = [
|
||||
("prostate_malignancy", ["prostate cancer", "prostate carcinoma", "carcinoma of prostate", "malignant neoplasm of prostate", "adenocarcinoma of prostate", "prostate adenocarcinoma", "prostate"], "prostate"),
|
||||
("bone_metastasis", ["bone metastasis", "bone metastases", "metastasis to bone", "metastases to bone", "secondary malignant neoplasm of bone", "osteoblastic metastasis", "osteoblastic metastases", "skeletal metastasis", "skeletal metastases", "osseous metastasis", "osseous metastases", "spine metastasis", "spine metastases"], "bone"),
|
||||
("lymph_node_metastasis", ["intra-abdominal lymph node metastases", "retroperitoneal lymph node metastases", "retroperitoneal lymphadenopathy", "retroperitoneal lymph nodes", "intrapelvic lymph nodes", "pelvic lymph node metastases", "intra-abdominal lymph nodes", "lymph node metastasis", "lymph node metastases", "distant lymphadenopathy", "secondary and unspecified malignant neoplasm of intra-abdominal lymph nodes", "secondary and unspecified malignant neoplasm of intrapelvic lymph nodes", "secondary and unspecified malignant neoplasm of lymph nodes"], "lymph nodes"),
|
||||
("breast_malignancy", ["breast cancer", "breast carcinoma", "carcinoma of breast", "malignant neoplasm of breast", "ductal carcinoma", "lobular carcinoma", "breast"], "breast"),
|
||||
("lymphoma", ["dlbcl", "diffuse large b-cell lymphoma", "b-cell lymphoma", "hodgkin", "non-hodgkin", "lymphoma"], "lymph nodes"),
|
||||
("renal_calculus", ["renal calculus", "kidney stone", "renal stone", "nephrolithiasis", "calculus of kidney"], "kidney"),
|
||||
@@ -167,19 +170,42 @@ class ClinicalConceptReasoner:
|
||||
# 3. Metastatic Status and Direction (Master Prompt Section 7 & 38)
|
||||
# Distinguish primary cancer with distant metastasis from metastatic lesions to an organ
|
||||
is_metastatic = bool(
|
||||
re.search(r"\b(?:metastatic|metastasis|metastasized|stage\s+iv)\b", local_context)
|
||||
and not re.search(r"\bwithout\s+metastasis\b", local_context)
|
||||
matched_family in ("bone_metastasis", "lymph_node_metastasis", "pleural_metastasis", "liver_metastasis")
|
||||
or (
|
||||
re.search(r"\b(?:metastatic|metastasis|metastases|metastasized|stage\s+iv)\b", local_context)
|
||||
and not re.search(r"\bwithout\s+metastasis\b", local_context)
|
||||
)
|
||||
)
|
||||
metastatic_sites: list[str] = []
|
||||
if is_metastatic:
|
||||
for site_cand in ["pleura", "pleural", "lung", "liver", "bone", "brain"]:
|
||||
if re.search(rf"\b{site_cand}\s+metastasis\b", local_context) or re.search(rf"\bmetastasis\s+to\s+{site_cand}\b", local_context):
|
||||
metastatic_sites.append(site_cand)
|
||||
site_checks = [
|
||||
("pleura", [r"\bpleura\w*\b"]),
|
||||
("lung", [r"\blung\w*\b", r"\bpulmonary\b"]),
|
||||
("liver", [r"\bliver\b", r"\bhepatic\b"]),
|
||||
("bone", [r"\bbone\w*\b", r"\bosseous\b", r"\bskeletal\b", r"\bosteoblastic\b", r"\bspine\b", r"\bpelvis\b"]),
|
||||
("brain", [r"\bbrain\b", r"\bcerebral\b"]),
|
||||
("lymph nodes", [r"\blymph\s+nodes?\b", r"\bretroperitoneal\b", r"\bintra-abdominal\b", r"\bintrapelvic\b", r"\blymphadenopathy\b"]),
|
||||
]
|
||||
for canonical_site, patterns in site_checks:
|
||||
if any(
|
||||
re.search(rf"{pat}.*?\b(?:metasta\w+|secondary)\b", local_context)
|
||||
or re.search(rf"\b(?:metasta\w+|secondary).*?{pat}", local_context)
|
||||
for pat in patterns
|
||||
):
|
||||
if canonical_site not in metastatic_sites:
|
||||
metastatic_sites.append(canonical_site)
|
||||
|
||||
if matched_family == "bone_metastasis" and "bone" not in metastatic_sites:
|
||||
metastatic_sites.append("bone")
|
||||
elif matched_family == "lymph_node_metastasis" and "lymph nodes" not in metastatic_sites:
|
||||
metastatic_sites.append("lymph nodes")
|
||||
|
||||
# 4. Histology & Etiology
|
||||
histology = None
|
||||
if "dlbcl" in local_context or "diffuse large b-cell" in local_context:
|
||||
histology = "diffuse large b-cell"
|
||||
elif "adenocarcinoma" in local_context:
|
||||
histology = "adenocarcinoma"
|
||||
elif "carcinoma" in local_context:
|
||||
histology = "carcinoma"
|
||||
elif "sarcoma" in local_context:
|
||||
|
||||
@@ -16,6 +16,9 @@ logger = get_logger(__name__)
|
||||
|
||||
# Mapping from canonical disease family to authoritative ICD-10-CM code category prefixes
|
||||
FAMILY_TO_CODE_PREFIXES: dict[str, list[str]] = {
|
||||
"prostate_malignancy": ["C61"],
|
||||
"bone_metastasis": ["C79.51", "C79.52", "C79.5"],
|
||||
"lymph_node_metastasis": ["C77.2", "C77.5", "C77.0", "C77.1", "C77.3", "C77.4", "C77.8", "C77.9", "C77"],
|
||||
"breast_malignancy": ["C50"],
|
||||
"lymphoma": ["C83", "C81", "C82", "C85"],
|
||||
"pyelonephritis": ["N10"],
|
||||
@@ -145,6 +148,38 @@ class MatchSpecBuilder:
|
||||
required_attrs["site"] = "liver"
|
||||
required_attrs["metastatic"] = True
|
||||
|
||||
elif concept.disease_family == "prostate_malignancy":
|
||||
forbidden_attrs.extend([
|
||||
"secondary malignant neoplasm of prostate",
|
||||
"c79.82",
|
||||
"n40",
|
||||
"benign prostatic hyperplasia",
|
||||
])
|
||||
required_attrs["primary_site"] = "prostate"
|
||||
|
||||
elif concept.disease_family == "bone_metastasis":
|
||||
forbidden_attrs.extend([
|
||||
"c40", "c41",
|
||||
"primary malignant neoplasm of bone",
|
||||
"osteosarcoma",
|
||||
"chondrosarcoma",
|
||||
"k68.2", "retroperitoneal fibrosis",
|
||||
"d16",
|
||||
"m47", "m51", "m54",
|
||||
])
|
||||
required_attrs["site"] = "bone"
|
||||
required_attrs["metastatic"] = True
|
||||
|
||||
elif concept.disease_family == "lymph_node_metastasis":
|
||||
forbidden_attrs.extend([
|
||||
"k68.2", "retroperitoneal fibrosis",
|
||||
"c81", "c82", "c83", "c84", "c85",
|
||||
"hodgkin", "non-hodgkin", "lymphoma",
|
||||
"i88", "lymphadenitis",
|
||||
])
|
||||
required_attrs["site"] = "lymph_node"
|
||||
required_attrs["metastatic"] = True
|
||||
|
||||
# 3. Symptom Firewall (Section 20 & CMS Guideline I.B.4)
|
||||
if concept.disease_family in ("renal_calculus", "ureteric_calculus"):
|
||||
# Calculus must not become symptom renal colic (N23)
|
||||
|
||||
@@ -339,6 +339,10 @@ class CancerConcept(BaseModel):
|
||||
molecular_attributes: list[str] = Field(default_factory=list, description="e.g. ['BRCA pathogenic', 'BRCA1 positive'].")
|
||||
ki67: str | None = Field(default=None, description="Ki-67 proliferation index (e.g. '> 80%', 'low', 'high').")
|
||||
treatment_response: str | None = Field(default=None, description="Pathologic or clinical response to neoadjuvant/adjuvant therapy.")
|
||||
gleason_score: str | None = Field(default=None, description="Gleason score (e.g. '9 (4+5)', '4+5=9').")
|
||||
grade_group: str | None = Field(default=None, description="WHO Grade Group (e.g. 'Grade Group 5', '5').")
|
||||
psa_level: str | None = Field(default=None, description="Prostate Specific Antigen level (e.g. '45 ng/mL').")
|
||||
castration_status: str | None = Field(default=None, description="Castration status (e.g. 'Castration-resistant', 'mCRPC', 'Castration-sensitive').")
|
||||
prior_treatments: list[str] = Field(default_factory=list, description="Prior treatments (e.g. neoadjuvant chemotherapy, endocrine therapy).")
|
||||
treatment_history: list[str] = Field(default_factory=list, description="Past chemotherapy/radiotherapy/surgery.")
|
||||
current_treatment: list[str] = Field(default_factory=list, description="Current inpatient chemotherapy or management.")
|
||||
|
||||
@@ -433,19 +433,52 @@ def render_oncology_context(oncology_context: dict[str, Any] | None) -> None:
|
||||
metastatic_sites = oncology_context.get("metastatic_sites", [])
|
||||
prior_treatments = oncology_context.get("prior_treatments", [])
|
||||
treatment_response = oncology_context.get("treatment_response") or "Not documented"
|
||||
gleason_score = oncology_context.get("gleason_score")
|
||||
grade_group = oncology_context.get("grade_group")
|
||||
psa_level = oncology_context.get("psa_level")
|
||||
castration_status = oncology_context.get("castration_status")
|
||||
|
||||
display_grade = grade
|
||||
if display_grade == "Not documented" and (gleason_score or grade_group):
|
||||
parts = [p for p in (f"Gleason {gleason_score}" if gleason_score else None, grade_group) if p]
|
||||
display_grade = ", ".join(parts)
|
||||
|
||||
c1, c2, c3, c4 = st.columns(4)
|
||||
with c1:
|
||||
st.metric("Primary Site", f"{primary_site} ({laterality})")
|
||||
st.metric("Primary Site", f"{primary_site} ({laterality})" if laterality != "Unspecified" else primary_site)
|
||||
with c2:
|
||||
st.metric("Histology", histology)
|
||||
with c3:
|
||||
st.metric("Histologic Grade", grade)
|
||||
st.metric("Histologic Grade", display_grade)
|
||||
with c4:
|
||||
st.metric("Ki-67 Index", ki67)
|
||||
st.metric("Biomarker Index", f"PSA: {psa_level}" if psa_level else (f"Ki-67: {ki67}" if ki67 != "Not documented" else "Not documented"))
|
||||
|
||||
# Receptor panel
|
||||
# Receptor and Biomarker panel
|
||||
rec_pills = []
|
||||
if psa_level:
|
||||
rec_pills.append(
|
||||
f'<span style="background: rgba(15, 23, 42, 0.8); border: 1px solid #334155; border-radius: 6px; padding: 4px 10px; margin-right: 8px; font-size: 13px;">'
|
||||
f'<strong style="color: #94a3b8;">PSA:</strong> <span style="color: #38bdf8; font-weight: 600;">{html.escape(str(psa_level))}</span>'
|
||||
f'</span>'
|
||||
)
|
||||
if gleason_score:
|
||||
rec_pills.append(
|
||||
f'<span style="background: rgba(15, 23, 42, 0.8); border: 1px solid #334155; border-radius: 6px; padding: 4px 10px; margin-right: 8px; font-size: 13px;">'
|
||||
f'<strong style="color: #94a3b8;">GLEASON:</strong> <span style="color: #f59e0b; font-weight: 600;">{html.escape(str(gleason_score))}</span>'
|
||||
f'</span>'
|
||||
)
|
||||
if grade_group:
|
||||
rec_pills.append(
|
||||
f'<span style="background: rgba(15, 23, 42, 0.8); border: 1px solid #334155; border-radius: 6px; padding: 4px 10px; margin-right: 8px; font-size: 13px;">'
|
||||
f'<strong style="color: #94a3b8;">GRADE GROUP:</strong> <span style="color: #f59e0b; font-weight: 600;">{html.escape(str(grade_group))}</span>'
|
||||
f'</span>'
|
||||
)
|
||||
if castration_status:
|
||||
rec_pills.append(
|
||||
f'<span style="background: rgba(15, 23, 42, 0.8); border: 1px solid #334155; border-radius: 6px; padding: 4px 10px; margin-right: 8px; font-size: 13px;">'
|
||||
f'<strong style="color: #94a3b8;">CASTRATION STATUS:</strong> <span style="color: #ec4899; font-weight: 600;">{html.escape(str(castration_status))}</span>'
|
||||
f'</span>'
|
||||
)
|
||||
if receptors:
|
||||
for r_name, r_val in receptors.items():
|
||||
r_color = "#34d399" if "pos" in str(r_val).lower() or "+" in str(r_val) else "#f87171"
|
||||
|
||||
@@ -108,6 +108,10 @@ METADATA_PATTERNS = [
|
||||
r"^\s*[\d\.\,\/]+\s*(?:mg/dl|mmol/l|g/dl|mmhg|bpm|%|cells/cumm)?\s*$",
|
||||
r"^\s*(?:ecg|ekg|cxr|chest\s+x[\s\-]?ray|ct\s+scan|mri|ultrasound|usg|2d\s+echo|cbc|bmp|cmp|lft|kft|rft|urinalysis|blood\s+culture|troponin|hba1c)\s*(?:normal|clear|pending|done|negative|reviewed)?\s*$",
|
||||
r"^\s*(?:patient\s+name|mrn|admission\s+date|discharge\s+date|admit\s+date|date\s+of\s+admission|date\s+of\s+discharge|dob|age|sex|gender)\s*[:\-–—]",
|
||||
r"^\s*metastatic\s+sites?\s*(?::\s*)?$",
|
||||
r"^\s*(?:oncology\s+attributes?(?:\s*(?:&|and)?\s*biomarkers?)?|biomarkers?\s*(?:&|and)?\s*receptor\s+status)\s*(?::\s*)?$",
|
||||
r"^\s*castration[- ]resistant\s+status(?:\s+on.*)?$",
|
||||
r"^\s*(?:androgen\s+deprivation\s+therapy|adt|palliative\s+radiotherapy)\s*$",
|
||||
]
|
||||
|
||||
# 5. Tumor attributes / Staging markers (attributes of a neoplasm, not standalone diagnoses)
|
||||
@@ -117,6 +121,12 @@ STANDALONE_ATTRIBUTE_PATTERNS = [
|
||||
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*grade\s+group\s*[1-5]\s*$",
|
||||
r"^\s*gleason(?:\s+score)?\s*(?::|=|\b)\s*\d+(?:\s*(?:\+|\/|\=|\(.*?\))\s*\d+)?\s*$",
|
||||
r"^\s*psa(?:\s+level)?\s*(?::|=|\b)\s*[\d\.\,]+(?:\s*ng\s*/\s*m[lL])?\s*$",
|
||||
r"^\s*(?:metastatic\s+)?castrat(?:ion|e)[- ]resistant(?:\s+(?:status|state|prostate\s+cancer))?\s*$",
|
||||
r"^\s*(?:mcrpc|crpc|nmcrpc|mhspc)\s*$",
|
||||
r"^\s*metastatic\s+sites?\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*$",
|
||||
@@ -126,7 +136,8 @@ STANDALONE_ATTRIBUTE_PATTERNS = [
|
||||
|
||||
# 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*$",
|
||||
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|retroperitoneal|intra-abdominal|pelvic|axial|skeletal|osseous)\s*$",
|
||||
r"^\s*(?:intra-abdominal|retroperitoneal|pelvic|axial|skeletal|osseous)\s*$",
|
||||
]
|
||||
|
||||
# Pathological condition words that validate an anatomical mention into a true disease entity
|
||||
@@ -417,6 +428,14 @@ class HardClinicalCandidateGate:
|
||||
# If the phrase has no clinical terms at all, reject it as a non-diagnostic statement
|
||||
return False, f"Phrase does not describe a clinical disease, disorder, pathology, or symptom: '{clean_term}'"
|
||||
|
||||
# Check: Incomplete adjectival phrases lacking a clinical condition noun
|
||||
if re.search(r"^\s*(?:metastatic\s+)?castrat(?:ion|e)[- ]resistant(?:\s+(?:status|state))?\s*$", term_lower) or term_lower in (
|
||||
"metastatic castration-resistant", "castration-resistant", "metastatic sites",
|
||||
"metastatic disease sites", "sites of metastasis", "metastatic status",
|
||||
"intra-abdominal", "retroperitoneal", "pelvic", "axial", "skeletal", "osseous",
|
||||
):
|
||||
return False, f"Adjectival modifier or attribute phrase without clinical entity: '{clean_term}'"
|
||||
|
||||
return True, "Valid clinical diagnosis entity"
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -277,10 +277,17 @@ class ReverseAttributeChecker:
|
||||
"stomach": [r"\bstomach\b", r"\bgastric\b"],
|
||||
"liver": [r"\bliver\b", r"\bhepatic\b"],
|
||||
"pancreas": [r"\bpancreas\b", r"\bpancreatic\b"],
|
||||
"bone": [r"\bbone\b", r"\bfemur\b", r"\btibia\b", r"\bhumerus\b", r"\bfibula\b", r"\bradius\b", r"\bulna\b"],
|
||||
"bone": [r"\bbones?\b", r"\bfemur\b", r"\btibia\b", r"\bhumerus\b", r"\bfibula\b", r"\bradius\b", r"\bulna\b", r"\bspines?\b", r"\blumbar\b", r"\bpelvis\b", r"\bpelvic\s+bone\b", r"\bsacrum\b", r"\bvertebra\w*\b", r"\bribs?\b", r"\bskeletal\b", r"\bosseous\b", r"\bosteoblastic\b"],
|
||||
"lymph_node": [r"\blymph\s*nodes?\b", r"\blymphadenopathy\b", r"\bretroperitoneal\b", r"\bintra-abdominal\b", r"\bintrapelvic\b", r"\bmesenteric\b", r"\baxillary\b", r"\bmediastinal\b", r"\binguinal\b"],
|
||||
"brain": [r"\bbrain\b", r"\bcerebral\b", r"\bcerebellum\b"],
|
||||
"adrenal": [r"\badrenal\b"],
|
||||
}
|
||||
|
||||
# Determine documented organs in diagnosis term + evidence
|
||||
# Determine documented organs in diagnosis term (primary) and combined text
|
||||
doc_term_organs = {
|
||||
organ for organ, pats in organ_patterns.items()
|
||||
if any(re.search(pat, diagnosis_term.lower()) for pat in pats)
|
||||
}
|
||||
doc_organs = {
|
||||
organ for organ, pats in organ_patterns.items()
|
||||
if any(re.search(pat, combined) for pat in pats)
|
||||
@@ -292,6 +299,16 @@ class ReverseAttributeChecker:
|
||||
if any(re.search(pat, desc_lower) for pat in pats)
|
||||
}
|
||||
|
||||
# If diagnosis term itself specifies an organ, candidate code MUST match that organ if code specifies an organ
|
||||
if doc_term_organs and code_organs and not doc_term_organs.intersection(code_organs):
|
||||
gyn_organs = {"ovary", "fallopian_tube", "uterus", "cervix"}
|
||||
if not (doc_term_organs.issubset(gyn_organs) and code_organs.issubset(gyn_organs)):
|
||||
return (
|
||||
False,
|
||||
f"anatomical site mismatch: code is for {', '.join(sorted(code_organs))} "
|
||||
f"but condition is for {', '.join(sorted(doc_term_organs))}",
|
||||
)
|
||||
|
||||
# If documented organ is specific and code organ is entirely disjoint
|
||||
if doc_organs and code_organs and not doc_organs.intersection(code_organs):
|
||||
gyn_organs = {"ovary", "fallopian_tube", "uterus", "cervix"}
|
||||
@@ -425,14 +442,31 @@ class ReverseAttributeChecker:
|
||||
bracketed_synonyms = [b.strip() for b in re.findall(r"\[(.*?)\]", desc_lower) if b.strip()]
|
||||
bracket_supported = any(has_positive_mention(b, combined_evidence) for b in bracketed_synonyms)
|
||||
|
||||
# Identify constituent tokens of qualifiers that were already verified as supported
|
||||
already_supported_qualifier_tokens: set[str] = set()
|
||||
for attr, is_positive in implied_attributes.items():
|
||||
if is_positive and attr not in unsupported:
|
||||
for tok in re.findall(r"[a-z0-9]+", attr):
|
||||
if len(tok) > 2:
|
||||
already_supported_qualifier_tokens.add(tok)
|
||||
|
||||
ANATOMICAL_MODIFIER_EQUIVALENCES: dict[str, list[str]] = {
|
||||
"intra": ["retroperitoneal", "intra-abdominal", "intraabdominal", "abdominal"],
|
||||
"abdominal": ["retroperitoneal", "intra-abdominal", "intraabdominal", "abdomen", "abdominal", "pelvic", "pelvis"],
|
||||
"bone": ["spine", "lumbar", "pelvis", "vertebra", "vertebral", "sacrum", "rib", "femur", "tibia", "skeletal", "osseous"],
|
||||
"osseous": ["bone", "spine", "lumbar", "pelvis", "vertebra", "vertebral"],
|
||||
}
|
||||
|
||||
for mod in code_modifiers:
|
||||
if mod in unsupported:
|
||||
if mod in unsupported or mod in already_supported_qualifier_tokens:
|
||||
continue
|
||||
variants = [mod] + CLINICAL_MORPHOLOGY.get(mod, [])
|
||||
if mod in CLINICAL_ABBREVIATIONS:
|
||||
variants.extend(CLINICAL_ABBREVIATIONS[mod].split())
|
||||
if mod in ORGANISM_EQUIVALENCES:
|
||||
variants.extend(ORGANISM_EQUIVALENCES[mod])
|
||||
if mod in ANATOMICAL_MODIFIER_EQUIVALENCES:
|
||||
variants.extend(ANATOMICAL_MODIFIER_EQUIVALENCES[mod])
|
||||
if mod.endswith("s") and len(mod) > 4:
|
||||
variants.append(mod[:-1])
|
||||
if mod.endswith("ic") and len(mod) > 4:
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"""End-to-End Test for Metastatic Prostate Oncology Case.
|
||||
|
||||
Validates:
|
||||
1. Normalization and capture of primary prostate cancer (C61).
|
||||
2. Normalization and capture of metastatic disease sites:
|
||||
- Bone metastases (lumbar spine, pelvis) -> C79.51
|
||||
- Retroperitoneal lymph node metastases -> C77.2
|
||||
3. Complete preservation of structured oncology attributes:
|
||||
- Gleason score: 9 (or 4+5)
|
||||
- WHO Grade Group: 5
|
||||
- PSA level: 45 ng/mL
|
||||
- Castration status: Castration-resistant / mCRPC
|
||||
- Metastatic sites list: bone, lymph nodes
|
||||
- Systemic therapies: ADT, leuprolide, enzalutamide, denosumab, radiotherapy
|
||||
4. Rejection of all five incorrect secondary mappings:
|
||||
- No C79.89 for "Metastatic sites"
|
||||
- No K68.2 for "retroperitoneal lymphadenopathy"
|
||||
- No CPT codes (e.g. 11057) for clinical diagnoses
|
||||
- No fragmented adjectival modifiers ("metastatic castration-resistant", "pelvis", "Gleason 9 (4")
|
||||
5. Latency profiling:
|
||||
- Measures retrieval and ranking latency separately.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
import pytest
|
||||
|
||||
from medical_coding.agents.clinical_extractor import EvidenceFirstFactExtractor
|
||||
from medical_coding.graph.pipeline import process_clinical_document
|
||||
|
||||
|
||||
PROSTATE_MCRPC_NOTE = """CLINICAL DOCUMENTATION / DISCHARGE SUMMARY:
|
||||
Patient is a 72-year-old male with metastatic castration-resistant prostate cancer (mCRPC), adenocarcinoma of the prostate, Gleason score 9 (4+5), Grade Group 5, PSA 45 ng/mL.
|
||||
Metastatic sites: bone (lumbar spine, pelvis), retroperitoneal lymphadenopathy.
|
||||
Patient on androgen deprivation therapy (ADT) with leuprolide and enzalutamide.
|
||||
Admitted for evaluation and management of secondary bone pain and osteoblastic spine lesions.
|
||||
Past Medical History: Essential hypertension, Type 2 diabetes mellitus without complications.
|
||||
Active Medications: Leuprolide, Enzalutamide, Denosumab, Amlodipine 10mg daily, Metformin 500mg BID.
|
||||
Hospital Course: Evaluated by Medical Oncology. Palliative radiotherapy recommended for painful lumbar spine osseous metastases. Hypertension managed with amlodipine; blood pressure stable. Blood glucose monitored; metformin continued.
|
||||
Discharge Diagnoses:
|
||||
1. Metastatic castration-resistant adenocarcinoma of prostate
|
||||
2. Metastatic sites: bone metastases (lumbar spine, pelvis)
|
||||
3. Retroperitoneal lymph node metastases
|
||||
4. Essential hypertension
|
||||
5. Type 2 diabetes mellitus
|
||||
"""
|
||||
|
||||
|
||||
def test_oncology_context_and_normalization_extraction():
|
||||
"""Verify evidence-to-concept normalization and oncology attribute extraction."""
|
||||
extractor = EvidenceFirstFactExtractor()
|
||||
state = extractor.extract_clinical_state(PROSTATE_MCRPC_NOTE, "doc-test-prostate")
|
||||
|
||||
# 1. Primary cancer concept verification
|
||||
assert state.primary_diagnosis is not None
|
||||
assert "prostate" in state.primary_diagnosis.raw_term.lower()
|
||||
|
||||
# 2. Oncology context attributes verification
|
||||
onc_ctx = state.oncology_context
|
||||
assert onc_ctx is not None
|
||||
assert onc_ctx.primary_site == "prostate"
|
||||
assert onc_ctx.gleason_score in ("9", "9 (4+5)", "4+5=9")
|
||||
assert "5" in str(onc_ctx.grade_group)
|
||||
assert "45" in str(onc_ctx.psa_level)
|
||||
assert "castrat" in str(onc_ctx.castration_status).lower()
|
||||
assert "bone" in onc_ctx.metastatic_sites
|
||||
assert any("lymph" in s.lower() for s in onc_ctx.metastatic_sites)
|
||||
|
||||
# 3. Check extracted candidate terms: no junk fragments
|
||||
all_raw_terms = [c.raw_term.lower() for c in state.all_candidates]
|
||||
for junk in ("metastatic sites", "pelvis", "metastatic castration-resistant", "gleason score 9 (4"):
|
||||
assert junk not in all_raw_terms, f"Junk candidate '{junk}' should not be in extracted candidates!"
|
||||
|
||||
# 4. Bone metastases and retroperitoneal lymph nodes must be present
|
||||
has_bone_met = any(
|
||||
"bone" in c.raw_term.lower() or "bone" in c.normalized_diagnosis.lower()
|
||||
for c in state.all_candidates
|
||||
)
|
||||
assert has_bone_met, "Bone metastases must be extracted!"
|
||||
|
||||
has_lymph_met = any(
|
||||
"retroperitoneal" in c.raw_term.lower() or "intra-abdominal" in c.normalized_diagnosis.lower() or "lymph" in c.raw_term.lower()
|
||||
for c in state.all_candidates
|
||||
)
|
||||
assert has_lymph_met, "Retroperitoneal lymph node metastases must be extracted!"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_prostate_pipeline_end_to_end_and_latency():
|
||||
"""Verify end-to-end coding, absence of incorrect mappings, and profiled latency."""
|
||||
node_timings = {}
|
||||
|
||||
def progress_callback(step, total, node, msg, duration_ms):
|
||||
node_timings[node] = duration_ms
|
||||
|
||||
from medical_coding.graph.nodes import get_or_initialize_retrieval_system
|
||||
# Pre-warm catalog/indices from disk so recorded latency measures steady-state inference
|
||||
get_or_initialize_retrieval_system()
|
||||
|
||||
t0 = time.perf_counter()
|
||||
result = await process_clinical_document(
|
||||
source=PROSTATE_MCRPC_NOTE,
|
||||
document_id="doc-prostate-mcrpc-e2e",
|
||||
progress_callback=progress_callback,
|
||||
persist_thread=False,
|
||||
)
|
||||
total_time = time.perf_counter() - t0
|
||||
|
||||
print(f"\n[E2E Latency Profile] Total: {total_time:.3f}s")
|
||||
for node, dur in node_timings.items():
|
||||
print(f" - {node}: {dur:.1f}ms")
|
||||
|
||||
# 1. Primary code must be C61 (Malignant neoplasm of prostate)
|
||||
assert result.primary_diagnosis is not None
|
||||
assert result.primary_diagnosis.database_code == "C61"
|
||||
|
||||
# 2. Secondary codes must include C79.51 (bone metastasis) and C77.2 (intra-abdominal / retroperitoneal lymph nodes)
|
||||
# 2. Secondary codes must include C79.51 (bone metastasis) and C77.2 (intra-abdominal / retroperitoneal lymph nodes)
|
||||
sec_codes = {s.database_code for s in result.secondary_diagnoses}
|
||||
print(f"Assigned secondary codes: {sec_codes}")
|
||||
for sec in result.secondary_diagnoses:
|
||||
print(f" {sec.database_code} - {sec.database_description} (term: '{sec.raw_term}')")
|
||||
|
||||
assert "C79.51" in sec_codes, f"Expected C79.51 (Secondary malignant neoplasm of bone) in {sec_codes}"
|
||||
assert "C77.2" in sec_codes, f"Expected C77.2 (Secondary and unspecified malignant neoplasm of intra-abdominal lymph nodes) in {sec_codes}"
|
||||
|
||||
# 3. Must include chronic co-morbidities
|
||||
assert "I10" in sec_codes, f"Expected I10 (Essential hypertension) in {sec_codes}"
|
||||
assert "E11.9" in sec_codes, f"Expected E11.9 (Type 2 diabetes mellitus) in {sec_codes}"
|
||||
|
||||
# 4. Zero incorrect mappings:
|
||||
# No C79.89, no K68.2, no CPT codes (e.g. 11057)
|
||||
assert "C79.89" not in sec_codes, "C79.89 must NOT be assigned!"
|
||||
assert "K68.2" not in sec_codes, "K68.2 (Retroperitoneal fibrosis) must NOT be assigned!"
|
||||
for c in sec_codes:
|
||||
assert not (c.isdigit() and len(c) in (4, 5)), f"CPT code '{c}' must not be assigned to a diagnosis!"
|
||||
|
||||
# 5. Check retrieval and ranking timings
|
||||
retrieval_ms = node_timings.get("retrieve_candidates", 0.0)
|
||||
ranking_ms = node_timings.get("rank_candidates", 0.0)
|
||||
print(f"Candidate Retrieval: {retrieval_ms:.1f}ms | Candidate Ranking: {ranking_ms:.1f}ms")
|
||||
# Candidate ranking should be under 500ms (achieving the ~1.0s to ~0.15s reduction)
|
||||
assert ranking_ms < 500.0, f"Ranking latency {ranking_ms:.1f}ms should be under 500ms"
|
||||
Reference in New Issue
Block a user