8908184093
The synthetic cytology form now records one of the three exploration answers. Not run yet: tests are deferred until all the new fields are in. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
162 lines
7.7 KiB
Python
162 lines
7.7 KiB
Python
"""Phase 1 gate: ISSSTELEON's test source, drawn once as a pipeline, becomes silver an analyst
|
|
can trust, and everything the platform can't decide alone is put in front of a reviewer.
|
|
|
|
The source hides its answers the way the real one does (synthetic.site): one PDF per study in
|
|
two SQL Server tables, the institute's forms and what outsourced labs send back; an HPV result
|
|
is a document of its own on its cytology's order; pathology comes scanned, the name surname
|
|
first and no birth date; some forms say "MA." for María or misspell the name and leave the
|
|
employee number out; some HPV reports were re-issued the other way; two women share a name.
|
|
"""
|
|
|
|
import json
|
|
from collections import Counter
|
|
from datetime import date
|
|
|
|
from core import catalog
|
|
|
|
GYN = ("gyn_puerperium", "gyn_pregnancy", "gyn_iud",
|
|
"gyn_hormonal_treatment", "gyn_other_treatment",
|
|
"gyn_postmenopause", "gyn_hysterectomy", "gyn_not_applicable")
|
|
PRESENTS = ("presents_discharge", "presents_vulvar_pruritus",
|
|
"presents_abnormal_bleeding", "presents_none")
|
|
FIELDS = {
|
|
"cervical_cytology": ("sample_date", "screening_history", *GYN, *PRESENTS,
|
|
"cervix_exam", "report_date", "adequacy", "result", "hpv", "hpv_16",
|
|
"hpv_18"),
|
|
"cervical_biopsy": ("request_date", "report_date", "histology"),
|
|
"mammography": ("exam_date", "report_date", "adequacy", "birads"),
|
|
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
|
|
"er", "pr", "her2", "ki67_pct", "size_mm", "stage"),
|
|
"breast_treatment": ("start_date", "kind"),
|
|
"clinical_note": ("note_date", "specialty", "icd10"),
|
|
} # fmt: skip
|
|
BOOLS = {"hpv", "hpv_16", "hpv_18", *GYN, *PRESENTS}
|
|
NUMBERS = {"ki67_pct", "size_mm"}
|
|
|
|
|
|
def value(field, v):
|
|
if v is None:
|
|
return None
|
|
if field in BOOLS:
|
|
return bool(v) if not isinstance(v, str) else v == "true"
|
|
if field in NUMBERS:
|
|
return float(v)
|
|
return v.isoformat() if isinstance(v, date) else str(v)
|
|
|
|
|
|
def said(record: dict, entity: str) -> dict | None:
|
|
"""What a document says of one study (an oncology note: its treatment and the note)."""
|
|
if entity == "clinical_note":
|
|
return record.get("clinical_note")
|
|
return record["values"] if record["entity"] == entity else None
|
|
|
|
|
|
def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path):
|
|
truth = site.truth
|
|
(tmp_path / "pipeline.json").write_text(site.drawn)
|
|
platform.save("concept_maps", "erick_site", site.concept_map)
|
|
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
|
platform.ingest()
|
|
q = platform.query
|
|
of = site.patients(q)
|
|
|
|
# Persons: nobody is merged with somebody else, except the two women of one name, joined
|
|
# by a pathology report (it shows no birth date) and held (torn) until a reviewer says
|
|
# whose report it is.
|
|
members: dict[str, set] = {}
|
|
held, person_of = set(), {}
|
|
for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
|
|
members.setdefault(person, set()).add(of[record])
|
|
person_of[record] = person
|
|
if why:
|
|
held.add(person)
|
|
torn = {p for p, who in members.items() if len(who) > 1}
|
|
assert len(torn) == 1 and torn == held, (torn, held)
|
|
assert members[next(iter(torn))] == set(site.meta["namesakes"])
|
|
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn}
|
|
|
|
# Every woman split into several persons (a misspelled form, say) is in the review
|
|
# queue, joined by candidates.
|
|
parts: dict[str, set] = {}
|
|
for p, x in patient.items():
|
|
parts.setdefault(x, set()).add(p)
|
|
queued = {
|
|
frozenset(person_of[r] for r in pair)
|
|
for pair in q("select person, candidate from bronze.n__site__persons__review")
|
|
}
|
|
split = {x: persons for x, persons in parts.items() if len(persons) > 1}
|
|
assert split # the misspelled forms, at least
|
|
for x, persons in split.items():
|
|
reached, frontier = set(), {next(iter(persons))}
|
|
while frontier:
|
|
reached |= frontier
|
|
frontier = {b for a in frontier for pair in queued if a in pair for b in pair}
|
|
frontier -= reached
|
|
assert persons <= reached, (x, persons)
|
|
|
|
# Every value accepted from a document is what the document says; and most of what the
|
|
# documents say is read (a scan's columns can come back out of order, and a value its
|
|
# pattern doesn't find is left out, never guessed).
|
|
at = {r["where"]: r for r in truth}
|
|
place = {
|
|
r: f"ArchivosUni:{i}" for i, r in q("select id, _record from bronze.n__site__archivos")
|
|
}
|
|
place |= {r: f"ResultadosSubrogados:{i}"
|
|
for i, r in q("select id, _record from bronze.n__site__subrogados")} # fmt: skip
|
|
record_of = {w: r for r, w in place.items()}
|
|
accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows)
|
|
for entity in FIELDS:
|
|
mine = accepted[entity] = {}
|
|
for record, field, *values in q(
|
|
"select _record, field, value_text, value_num, value_bool, value_date "
|
|
f"from bronze.staged__observation where study = '{entity}'"
|
|
):
|
|
got = next((v for v in values if v is not None), None)
|
|
mine.setdefault(record, {})[field] = value(field, got)
|
|
assert mine, entity
|
|
stated = read = 0
|
|
missed: Counter = Counter()
|
|
for record, got in mine.items():
|
|
t = at[place[record]]
|
|
if not t.get("flipped"):
|
|
truly = {f: v for f, v in said(t, entity).items() if v is not None}
|
|
assert got == {f: value(f, truly.get(f)) for f in got}, (t["where"], got)
|
|
stated, read = stated + len(truly), read + len(got)
|
|
missed.update(set(truly) - set(got))
|
|
assert read >= 0.95 * stated, (entity, read, stated, missed)
|
|
|
|
# A row a rule held because of a value (a scan misread) is held because it is wrong:
|
|
# never loaded, and a reviewer sees it.
|
|
misread = set()
|
|
for record, entity, raw in q("select _record, study, _raw from bronze.staged__held"):
|
|
if record in place and person_of.get(record) not in torn:
|
|
t, got = at[place[record]], json.loads(raw)
|
|
truly = said(t, entity)
|
|
assert {f: value(f, got.get(f)) for f in truly} != {
|
|
f: value(f, v) for f, v in truly.items()}, t["where"] # fmt: skip
|
|
misread.add(record)
|
|
|
|
# Silver: each person's studies, the records of one study key merged (a cytology form and
|
|
# its HPV report are one cytology), but for the torn person's, the misreads, and a study
|
|
# whose reports contradict each other (until review says which is right).
|
|
for entity, fields in FIELDS.items():
|
|
key = catalog.studies()[entity].key
|
|
merged: dict[tuple, dict] = {}
|
|
disputed = set()
|
|
for r in truth:
|
|
record = record_of[r["where"]]
|
|
got = accepted[entity].get(record)
|
|
if got is None or person_of[record] in torn or record in misread:
|
|
continue
|
|
at_key = (person_of[record], *(got.get(k) for k in key))
|
|
merged.setdefault(at_key, {}).update(got)
|
|
if r.get("conflict"):
|
|
disputed.add(at_key)
|
|
expected = {(k[0], *(row.get(f) for f in fields))
|
|
for k, row in merged.items() if k not in disputed} # fmt: skip
|
|
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
|
|
got = {(p, *(value(f, v) for f, v in zip(fields, values, strict=True)))
|
|
for p, *values in rows if p not in torn} # fmt: skip
|
|
assert got == expected, (entity, sorted(got - expected, key=str)[:4],
|
|
sorted(expected - got, key=str)[:4]) # fmt: skip
|