Extract reads several columns as one document; reviewers' corrections of study fields applied at the target; the site gates on ISSSTELEON's test source
This commit is contained in:
+4
-1
@@ -184,7 +184,7 @@ def run_extract(p: str, node: Extract):
|
|||||||
codes = _codes(node, node.patterns)
|
codes = _codes(node, node.patterns)
|
||||||
out = []
|
out = []
|
||||||
for row in nodes.rows(p, node.inputs[0]):
|
for row in nodes.rows(p, node.inputs[0]):
|
||||||
text = row.get(node.column) or ""
|
text = node.text(row)
|
||||||
if use_llm:
|
if use_llm:
|
||||||
found = ground(_ask_llm(node, text), text)
|
found = ground(_ask_llm(node, text), text)
|
||||||
elif node.patterns:
|
elif node.patterns:
|
||||||
@@ -385,10 +385,13 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
|
|||||||
linked = {r[RECORD]: r for r in nodes.rows(p, link)}
|
linked = {r[RECORD]: r for r in nodes.rows(p, link)}
|
||||||
person = {k: r["person_id"] for k, r in linked.items()}
|
person = {k: r["person_id"] for k, r in linked.items()}
|
||||||
model, study = catalog.model(node.entity), catalog.studies()[node.entity]
|
model, study = catalog.model(node.entity), catalog.studies()[node.entity]
|
||||||
|
fixed = nodes.corrections() # a reviewer's reading of a value wins over the extraction
|
||||||
observations, held_rows = [], []
|
observations, held_rows = [], []
|
||||||
for i in (i for i in node.inputs if i != link):
|
for i in (i for i in node.inputs if i != link):
|
||||||
for row in nodes.rows(p, i):
|
for row in nodes.rows(p, i):
|
||||||
values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None}
|
values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None}
|
||||||
|
values |= {f: v for f, v in fixed.get(row[RECORD], {}).items()
|
||||||
|
if f in model.model_fields} # fmt: skip
|
||||||
held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
|
held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
|
||||||
if row[RECORD] not in person:
|
if row[RECORD] not in person:
|
||||||
held.append("no identity linked to this record")
|
held.append("no identity linked to this record")
|
||||||
|
|||||||
+33
-39
@@ -1,5 +1,6 @@
|
|||||||
"""Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document
|
"""Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document
|
||||||
the rules point at is read into text (scanned ones through OCR)."""
|
the rules point at is read into text (scanned ones through OCR). The site: the synthetic
|
||||||
|
hospitals' tables (SQLite) and ISSSTELEON's test source (SQL Server tables of PDFs)."""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
@@ -7,48 +8,42 @@ import shutil
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from synthetic.site import build
|
|
||||||
|
|
||||||
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital"
|
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital"
|
||||||
|
|
||||||
|
|
||||||
def graph(tmp: Path, hospital_tables: dict[str, list[str]]) -> dict:
|
def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> dict:
|
||||||
"""What an operator would draw for this site: one Source per table or set of files, and
|
"""What an operator would draw for this site: one Source per table, and a Read on each
|
||||||
a Read on each column that holds documents."""
|
column that holds documents."""
|
||||||
|
|
||||||
def table(node_id, db, name):
|
def table(node_id, credentials, name, **args):
|
||||||
args = {"credentials": f"sqlite:///{db}", "table": name}
|
args = {"credentials": credentials, "table": name, **args}
|
||||||
return {"id": node_id, "kind": "source", "source": SQL_TABLE, "args": args}
|
return {"id": node_id, "kind": "source", "source": SQL_TABLE, "args": args}
|
||||||
|
|
||||||
def files(node_id, glob, **extra):
|
|
||||||
args = {"bucket_url": str(tmp / "site" / "files"), "file_glob": glob}
|
|
||||||
return {"id": node_id, "kind": "source", "source": FILES, "args": args, **extra}
|
|
||||||
|
|
||||||
nodes = [
|
nodes = [
|
||||||
table(f"{name}_{t}", tmp / f"hospital_{name}.db", t)
|
table(f"{name}_{t}", f"sqlite:///{tmp / f'hospital_{name}.db'}", t)
|
||||||
for name, tables in hospital_tables.items()
|
for name, tables in hospital_tables.items()
|
||||||
for t in tables
|
for t in tables
|
||||||
]
|
]
|
||||||
return {
|
return {
|
||||||
"nodes": nodes
|
"nodes": nodes
|
||||||
+ [
|
+ [
|
||||||
table("his_patients", tmp / "site" / "site.db", "pacientes_his"),
|
table("archivos", site_url, "ArchivosUni", schema="dbo"),
|
||||||
table("archivos", tmp / "site" / "site.db", "ArchivosUni"),
|
table("subrogados", site_url, "ResultadosSubrogados", schema="dbo"),
|
||||||
files("notes", "*.csv", source=READERS, resource="read_csv"),
|
|
||||||
files("altas", "*.xlsx", then="persistance.readers:read_excel"),
|
|
||||||
files("pdfs", "*.pdf", then="persistance.readers:read_bytes"),
|
|
||||||
{"id": "archivos_text", "kind": "read", "inputs": ["archivos"], "column": "archivo"},
|
{"id": "archivos_text", "kind": "read", "inputs": ["archivos"], "column": "archivo"},
|
||||||
{"id": "pdfs_text", "kind": "read", "inputs": ["pdfs"], "column": "content"},
|
{
|
||||||
|
"id": "subrogados_text",
|
||||||
|
"kind": "read",
|
||||||
|
"inputs": ["subrogados"],
|
||||||
|
"column": "archivo",
|
||||||
|
},
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
SQL_TABLE = "dlt.sources.sql_database:sql_table"
|
SQL_TABLE = "dlt.sources.sql_database:sql_table"
|
||||||
FILES = "dlt.sources.filesystem:filesystem"
|
|
||||||
READERS = "dlt.sources.filesystem:readers"
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_path):
|
def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, tmp_path):
|
||||||
count, query = platform.count, platform.query
|
count, query = platform.count, platform.query
|
||||||
tables = {}
|
tables = {}
|
||||||
for name in ("cacu", "cama"):
|
for name in ("cacu", "cama"):
|
||||||
@@ -56,21 +51,19 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
|
|||||||
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
||||||
found = con.execute("select name from sqlite_master where type = 'table'")
|
found = con.execute("select name from sqlite_master where type = 'table'")
|
||||||
tables[name] = [t for (t,) in found]
|
tables[name] = [t for (t,) in found]
|
||||||
truth = build(FIXTURES / "hospital_cacu.db", tmp_path / "site")["records"]
|
truth = site.truth
|
||||||
(tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables)))
|
(tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables, site.url)))
|
||||||
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
||||||
|
|
||||||
by_place = {}
|
by_place = {}
|
||||||
for r in truth:
|
for r in truth:
|
||||||
by_place.setdefault(r["where"].split(":")[0].split("/")[0], []).append(r)
|
by_place.setdefault(r["where"].split(":")[0], []).append(r)
|
||||||
|
documents = len(by_place["ArchivosUni"]) + len(by_place["ResultadosSubrogados"])
|
||||||
expected = {
|
expected = {
|
||||||
"his_patients": len(by_place["pacientes_his"]),
|
|
||||||
"altas": len(by_place["altas.xlsx"]),
|
|
||||||
"notes": len(by_place["consultas.csv"]),
|
|
||||||
"archivos": len(by_place["ArchivosUni"]),
|
"archivos": len(by_place["ArchivosUni"]),
|
||||||
"pdfs": len(by_place["files"]),
|
"subrogados": len(by_place["ResultadosSubrogados"]),
|
||||||
"archivos_text": len(by_place["ArchivosUni"]),
|
"archivos_text": len(by_place["ArchivosUni"]),
|
||||||
"pdfs_text": len(by_place["files"]),
|
"subrogados_text": len(by_place["ResultadosSubrogados"]),
|
||||||
}
|
}
|
||||||
for name, names in tables.items():
|
for name, names in tables.items():
|
||||||
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
||||||
@@ -84,7 +77,7 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
|
|||||||
platform.ingest()
|
platform.ingest()
|
||||||
assert counts() == expected
|
assert counts() == expected
|
||||||
read_once = query("select key, _dlt_load_id from bronze.read_cache order by key")
|
read_once = query("select key, _dlt_load_id from bronze.read_cache order by key")
|
||||||
assert len(read_once) == expected["archivos"] + expected["pdfs"] # each file read once
|
assert len(read_once) == documents # each file read once
|
||||||
|
|
||||||
with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates
|
with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates
|
||||||
con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1")
|
con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1")
|
||||||
@@ -93,15 +86,16 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
|
|||||||
corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1"
|
corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1"
|
||||||
assert query(corrected) == [("64000",)]
|
assert query(corrected) == [("64000",)]
|
||||||
|
|
||||||
read = query("select id, text, ocr, error from bronze.n__site__archivos_text")
|
|
||||||
assert [error for *_, error in read if error is not None] == []
|
|
||||||
space = re.compile(r"\s+")
|
space = re.compile(r"\s+")
|
||||||
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
|
for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")):
|
||||||
for r in by_place["ArchivosUni"]:
|
read = query(f"select id, text, ocr, error from bronze.n__site__{node}_text")
|
||||||
txt, ocr = by_id[int(r["where"].split(":")[1])]
|
assert [error for *_, error in read if error is not None] == []
|
||||||
assert bool(ocr) == r["scanned"] # OCR runs on scans, and only on scans
|
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
|
||||||
if "record_number" in r["identity"]: # even scanned, the identifier reads back exactly
|
for r in by_place[table]:
|
||||||
assert r["identity"]["record_number"] in txt, (r["where"], txt)
|
txt, ocr = by_id[int(r["where"].split(":")[1])]
|
||||||
|
assert bool(ocr) == r.get("scanned", False) # OCR runs on scans, and only on scans
|
||||||
|
if "record_number" in r["identity"]: # even scanned, the number reads back exactly
|
||||||
|
assert r["identity"]["record_number"] in txt, (r["where"], txt)
|
||||||
assert query("select key, _dlt_load_id from bronze.read_cache order by key") == (
|
assert query("select key, _dlt_load_id from bronze.read_cache order by key") == (
|
||||||
read_once
|
read_once
|
||||||
) # reruns never read a file again
|
) # reruns never read a file again
|
||||||
|
|||||||
+101
-87
@@ -1,41 +1,62 @@
|
|||||||
"""Phase 1 gate: a messy site, drawn once as a pipeline, becomes silver an analyst can trust,
|
"""Phase 1 gate: ISSSTELEON's test source, drawn once as a pipeline, becomes silver an analyst
|
||||||
and everything the platform can't decide alone is put in front of a reviewer.
|
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
|
The source hides its answers the way the real one does (synthetic.site): one PDF per study in
|
||||||
and an Excel file with mistyped record numbers (one of them another patient's real number),
|
two SQL Server tables, the institute's forms and what outsourced labs send back; an HPV result
|
||||||
reports as BLOBs in three layouts (some scanned), loose PDFs, a CSV of consultations, and
|
is a document of its own on its cytology's order; pathology comes scanned, the name surname
|
||||||
contradicting copies of some reports.
|
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
|
import json
|
||||||
|
from collections import Counter
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
|
from core import catalog
|
||||||
|
|
||||||
FIELDS = {
|
FIELDS = {
|
||||||
"cervical_cytology": ("sample_date", "adequacy", "result", "hpv"),
|
"cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16",
|
||||||
"cervical_biopsy": ("request_date", "histology"),
|
"hpv_18"),
|
||||||
}
|
"cervical_biopsy": ("request_date", "report_date", "histology"),
|
||||||
BOOLS = {"hpv"}
|
"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"}
|
||||||
|
NUMBERS = {"ki67_pct", "size_mm"}
|
||||||
|
|
||||||
|
|
||||||
def _value(field, v):
|
def value(field, v):
|
||||||
if v is None:
|
if v is None:
|
||||||
return None
|
return None
|
||||||
if field in BOOLS:
|
if field in BOOLS:
|
||||||
return bool(v)
|
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)
|
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):
|
def said(record: dict, entity: str) -> dict | None:
|
||||||
truth = messy_site.truth
|
"""What a document says of one study (an oncology note: its treatment and the note)."""
|
||||||
(tmp_path / "pipeline.json").write_text(messy_site.drawn)
|
if entity == "clinical_note":
|
||||||
platform.save("concept_maps", "messy_site", messy_site.concept_map)
|
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.save("pipelines", "site", tmp_path / "pipeline.json")
|
||||||
platform.ingest()
|
platform.ingest()
|
||||||
q = platform.query
|
q = platform.query
|
||||||
of = messy_site.patients(q)
|
of = site.patients(q)
|
||||||
|
|
||||||
# Persons: nobody is merged with somebody else, except where a record number belongs to
|
# Persons: nobody is merged with somebody else, except the two women of one name, joined
|
||||||
# two patients, and that person is held (torn) until a reviewer corrects the record.
|
# by a pathology report (it shows no birth date) and held (torn) until a reviewer says
|
||||||
|
# whose report it is.
|
||||||
members: dict[str, set] = {}
|
members: dict[str, set] = {}
|
||||||
held, person_of = set(), {}
|
held, person_of = set(), {}
|
||||||
for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
|
for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
|
||||||
@@ -44,98 +65,91 @@ def test_a_messy_site_becomes_silver_and_review_gets_the_rest(platform, messy_si
|
|||||||
if why:
|
if why:
|
||||||
held.add(person)
|
held.add(person)
|
||||||
torn = {p for p, who in members.items() if len(who) > 1}
|
torn = {p for p, who in members.items() if len(who) > 1}
|
||||||
assert torn and torn == held, (torn, held)
|
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}
|
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn}
|
||||||
|
|
||||||
# A name reaches silver as the registry wrote it (accents, ñ); linking compared it
|
# Every woman split into several persons (a misspelled form, say) is in the review
|
||||||
# without them, so the reports' plain upper-case names still joined.
|
# queue, joined by candidates.
|
||||||
torn_patients = {x for p in torn for x in members[p]}
|
|
||||||
written = {r["values"]["full_name"] for r in truth
|
|
||||||
if r["entity"] == "identity" and r["person"] not in torn_patients} # fmt: skip
|
|
||||||
names = {text for (text,) in q("select text from silver.person_name")}
|
|
||||||
assert any("ñ" in n for n in written) and written <= names
|
|
||||||
|
|
||||||
# Every patient split into several persons is in the review queue, joined by candidates.
|
|
||||||
parts: dict[str, set] = {}
|
parts: dict[str, set] = {}
|
||||||
for p, x in patient.items():
|
for p, x in patient.items():
|
||||||
parts.setdefault(x, set()).add(p)
|
parts.setdefault(x, set()).add(p)
|
||||||
# A queued person or candidate is one of its records (decisions are kept by record).
|
|
||||||
queued = {
|
queued = {
|
||||||
frozenset(person_of[r] for r in pair)
|
frozenset(person_of[r] for r in pair)
|
||||||
for pair in q("select person, candidate from bronze.n__site__persons__review")
|
for pair in q("select person, candidate from bronze.n__site__persons__review")
|
||||||
}
|
}
|
||||||
for x, persons in parts.items():
|
split = {x: persons for x, persons in parts.items() if len(persons) > 1}
|
||||||
if len(persons) > 1:
|
assert split # the misspelled forms, at least
|
||||||
reached, frontier = set(), {next(iter(persons))}
|
for x, persons in split.items():
|
||||||
while frontier:
|
reached, frontier = set(), {next(iter(persons))}
|
||||||
reached |= frontier
|
while frontier:
|
||||||
frontier = {
|
reached |= frontier
|
||||||
b for a in frontier for pair in queued if a in pair for b in pair
|
frontier = {b for a in frontier for pair in queued if a in pair for b in pair}
|
||||||
} - reached
|
frontier -= reached
|
||||||
assert persons <= reached, (x, persons)
|
assert persons <= reached, (x, persons)
|
||||||
|
|
||||||
# Every value accepted from a document is what the document says.
|
# 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}
|
at = {r["where"]: r for r in truth}
|
||||||
place = {
|
place = {
|
||||||
r: f"ArchivosUni:{i}" for i, r in q("select id, _record from bronze.n__site__archivos")
|
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")}
|
place |= {r: f"ResultadosSubrogados:{i}"
|
||||||
for entity, fields in FIELDS.items():
|
for i, r in q("select id, _record from bronze.n__site__subrogados")} # fmt: skip
|
||||||
accepted: dict[str, dict] = {} # each accepted record, from its observations (long)
|
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(
|
for record, field, *values in q(
|
||||||
"select _record, field, value_text, value_num, value_bool, value_date "
|
"select _record, field, value_text, value_num, value_bool, value_date "
|
||||||
f"from bronze.staged__observation where study = '{entity}'"
|
f"from bronze.staged__observation where study = '{entity}'"
|
||||||
):
|
):
|
||||||
value = next((v for v in values if v is not None), None)
|
got = next((v for v in values if v is not None), None)
|
||||||
accepted.setdefault(record, dict.fromkeys(fields))[field] = value
|
mine.setdefault(record, {})[field] = value(field, got)
|
||||||
for record, values in accepted.items():
|
assert mine, entity
|
||||||
|
stated = read = 0
|
||||||
|
missed: Counter = Counter()
|
||||||
|
for record, got in mine.items():
|
||||||
t = at[place[record]]
|
t = at[place[record]]
|
||||||
if not t.get("flipped"):
|
if not t.get("flipped"):
|
||||||
got = {f: _value(f, values[f]) for f in fields}
|
truly = {f: v for f, v in said(t, entity).items() if v is not None}
|
||||||
assert got == {f: t["values"][f] for f in fields}, (t["where"], got)
|
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 value a rule held (a scan misread: "LJEBG") is held because it is wrong: it is
|
# 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.
|
# never loaded, and a reviewer sees it.
|
||||||
misread = set()
|
misread = set()
|
||||||
for record, raw in q("select _record, _raw from bronze.staged__held"):
|
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:
|
if record in place and person_of.get(record) not in torn:
|
||||||
t, got = at[place[record]], json.loads(raw)
|
t, got = at[place[record]], json.loads(raw)
|
||||||
fields = FIELDS[t["entity"]]
|
truly = said(t, entity)
|
||||||
assert {f: _value(f, got.get(f)) for f in fields} != {
|
assert {f: value(f, got.get(f)) for f in truly} != {
|
||||||
f: t["values"][f] for f in fields}, t["where"] # fmt: skip
|
f: value(f, v) for f, v in truly.items()}, t["where"] # fmt: skip
|
||||||
misread.add(place[record])
|
misread.add(record)
|
||||||
|
|
||||||
# Silver: everything except contradicting reports, rows of the torn person and misreads.
|
# Silver: each person's studies, the records of one study key merged (a cytology form and
|
||||||
out = {place[r] for r, p in person_of.items() if p in torn and r in place} | misread
|
# its HPV report are one cytology), but for the torn person's, the misreads, and a study
|
||||||
torn_notes = {
|
# whose reports contradict each other (until review says which is right).
|
||||||
(e, date.fromisoformat("-".join(reversed(f.split("/")))).isoformat())
|
for entity, fields in FIELDS.items():
|
||||||
for e, f, r in q("select expediente, fecha, _record from bronze.n__site__notes")
|
key = catalog.studies()[entity].key
|
||||||
if person_of.get(r) in torn
|
merged: dict[tuple, dict] = {}
|
||||||
}
|
disputed = set()
|
||||||
|
for r in truth:
|
||||||
def silver(entity):
|
record = record_of[r["where"]]
|
||||||
fields = FIELDS[entity]
|
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}")
|
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
|
||||||
return {
|
got = {(p, *(value(f, v) for f, v in zip(fields, values, strict=True)))
|
||||||
(patient[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
|
||||||
for p, *values in rows
|
assert got == expected, (entity, sorted(got - expected, key=str)[:4],
|
||||||
}
|
sorted(expected - got, key=str)[:4]) # fmt: skip
|
||||||
|
|
||||||
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
|
|
||||||
)
|
|
||||||
|
|||||||
Reference in New Issue
Block a user