114 lines
4.8 KiB
Python
114 lines
4.8 KiB
Python
"""Phase 1 gate: a messy site, 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 site hides its answers the way real ones do: demographics split between a database
|
|
and an Excel file with mistyped record numbers (one of them another patient's real number),
|
|
reports as BLOBs in three layouts (some scanned), loose PDFs, a CSV of consultations, and
|
|
contradicting copies of some reports.
|
|
"""
|
|
|
|
from datetime import date
|
|
|
|
FIELDS = {
|
|
"cervical_cytology": ("sample_date", "adequacy", "result", "hpv"),
|
|
"cervical_biopsy": ("request_date", "histology"),
|
|
}
|
|
BOOLS = {"hpv"}
|
|
|
|
|
|
def _value(field, v):
|
|
if v is None:
|
|
return None
|
|
if field in BOOLS:
|
|
return bool(v)
|
|
return v.isoformat() if isinstance(v, date) else str(v)
|
|
|
|
|
|
def test_a_messy_site_becomes_silver_and_review_gets_the_rest(platform, messy_site, tmp_path):
|
|
truth = messy_site.truth
|
|
(tmp_path / "pipeline.json").write_text(messy_site.drawn)
|
|
platform.run("python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json"))
|
|
platform.ingest()
|
|
q = platform.query
|
|
of = messy_site.patients(q)
|
|
|
|
# Persons: nobody is merged with somebody else, except where a record number belongs to
|
|
# two patients, and that person is held (torn) until a reviewer corrects the record.
|
|
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 torn and torn == held, (torn, held)
|
|
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn}
|
|
|
|
# Every patient split into several persons 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(pair)
|
|
for pair in q("select person, candidate from bronze.n__site__persons__review")
|
|
}
|
|
for x, persons in parts.items():
|
|
if len(persons) > 1:
|
|
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
|
|
} - reached
|
|
assert persons <= reached, (x, persons)
|
|
|
|
# Every value accepted from a document is what the document says.
|
|
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"files/{n}" for n, r in q("select file_name, _record from bronze.n__site__pdfs")}
|
|
for entity, fields in FIELDS.items():
|
|
rows = q(f"select _record, _held, {', '.join(fields)} from bronze.staged__{entity}")
|
|
for record, why, *values in rows:
|
|
t = at[place[record]]
|
|
if why is None and not t.get("flipped"):
|
|
got = {f: _value(f, v) for f, v in zip(fields, values, strict=True)}
|
|
assert got == {f: t["values"][f] for f in fields}, (t["where"], got)
|
|
|
|
# Silver: everything except contradicting reports and rows of the torn person.
|
|
out = {place[r] for r, p in person_of.items() if p in torn and r in place}
|
|
torn_notes = {
|
|
(e, date.fromisoformat("-".join(reversed(f.split("/")))).isoformat())
|
|
for e, f, r in q("select expediente, fecha, _record from bronze.n__site__notes")
|
|
if person_of.get(r) in torn
|
|
}
|
|
|
|
def silver(entity):
|
|
fields = FIELDS[entity]
|
|
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
|
|
return {
|
|
(patient[p], *(_value(f, v) for f, v in zip(fields, values, strict=True)))
|
|
for p, *values in rows
|
|
}
|
|
|
|
def expected(entity, keep):
|
|
return {
|
|
(r["person"], *(r["values"][f] for f in FIELDS[entity]))
|
|
for r in truth
|
|
if r["entity"] == entity and r["where"] not in out and keep(r)
|
|
}
|
|
|
|
assert silver("cervical_cytology") == expected(
|
|
"cervical_cytology", lambda r: not r.get("conflict")
|
|
)
|
|
assert silver("cervical_biopsy") == expected("cervical_biopsy", lambda r: True)
|
|
notes = q("select person_id, note_date, specialty, icd10 from silver.clinical_note")
|
|
assert sorted((patient[p], *map(str, n)) for p, *n in notes) == sorted(
|
|
(r["person"], r["values"]["note_date"], r["values"]["specialty"], r["values"]["icd10"])
|
|
for r in truth
|
|
if r["entity"] == "clinical_note"
|
|
and (r["person"], r["values"]["note_date"]) not in torn_notes
|
|
)
|