Compare commits

...

3 Commits

4 changed files with 66 additions and 41 deletions
+5
View File
@@ -80,6 +80,9 @@ class Pim:
found = {
"n_train": len(train),
"n_test": len(test),
# outcomes, prevalent or incident, each split learned from or was judged on
"events_train": float(((train["c"] == 1) | np.isfinite(train["r"])).sum()),
"events_test": float(((test["c"] == 1) | np.isfinite(test["r"])).sum()),
"neg_loglik": mixture.neg_loglik_,
"converged": float(mixture.converged_),
}
@@ -139,6 +142,8 @@ class Logistic:
metrics = {
"n_train": len(train),
"n_test": len(test),
"events_train": float(train["y"].sum()),
"events_test": float(test["y"].sum()),
"auc": float(roc_auc_score(test["y"], p)),
"brier": float(brier_score_loss(test["y"], p)),
"positive_rate_train": float(train["y"].mean()),
+20 -5
View File
@@ -267,7 +267,8 @@ def run_link(p: str, node: Link):
"""Persons: records the node's rules join (Splink deterministic linking), joined or kept
apart by reviewers' decisions. A person whose records disagree on birth date or sex is
held. Persons that may be one (identifiers one typo apart, or the same birth date) and
don't contradict each other are queued for review, with Splink's probability."""
don't contradict each other are queued for review, with Splink's probability. A person
with nothing that names her (no name, birth date or record number read) is held too."""
records, sources, written = _identities(p, node)
fields = [c for c in records.columns if c != "unique_id"]
rules = [r for r in node.rules or node.default_rules()
@@ -293,12 +294,16 @@ def run_link(p: str, node: Link):
facts = [f for f in ("birth_date", "sex") if f in fields]
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
held = json.dumps(["records of this person disagree on birth date or sex"])
# Nothing that names her was read (a scan's name line misread, say): nobody to join.
read = persons.groupby("cluster_id")[[f for f in fields if f != "sex"]].count().sum(axis=1)
nameless = set(read[read == 0].index)
why = {c: "records of this person disagree on birth date or sex" for c in torn}
why |= {c: "no name, birth date or record number was read" for c in nameless - torn}
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)}
stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
linked = [
{RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id],
HELD: held if r.cluster_id in torn else None,
HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
**{f: getattr(r, f) for f in fields},
**({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
for r in persons.itertuples()
@@ -335,6 +340,8 @@ def run_link(p: str, node: Link):
known = [f for f in ("birth_date", "sex") if f in fields]
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
lone = set() # persons whose identifier is carried by one record only
for f in ids:
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
@@ -344,15 +351,23 @@ def run_link(p: str, node: Link):
"""(the person to settle, a possible owner), or None when the pair is implausible:
they contradict each other, or one typo apart is all they share (with sequential
record numbers every patient has such neighbours) unless one side has no
demographics and the other's identifier stands on a single record."""
demographics and the other's identifier stands on a single record. Names one typo
apart are rare: an undated side (a misread pathology scan) is always queued; so is the
very same identifier on a record that says nothing else (a scan read only in part)."""
a, b = r.unique_id_l, r.unique_id_r
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
if frozenset((a, b)) in decided or any(
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
):
return None
if not reasons[int(r.match_key)].endswith("typo apart"):
reason = reasons[int(r.match_key)]
if not reason.endswith("typo apart"):
return a, b
field = reason.removesuffix(" one typo apart")
if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"): # the very same identifier
return (a, b) if a in undated or b not in undated else (b, a)
if field == "full_name" and (a in undated) != (b in undated):
return (a, b) if a in undated else (b, a) # names are rarely one typo apart
if a in orphan and b in lone:
return a, b
if b in orphan and a in lone:
+6 -18
View File
@@ -27,15 +27,8 @@ def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> di
return {
"nodes": nodes
+ [
table("archivos", site_url, "ArchivosUni", schema="dbo"),
table("subrogados", site_url, "ResultadosSubrogados", schema="dbo"),
{"id": "archivos_text", "kind": "read", "inputs": ["archivos"], "column": "archivo"},
{
"id": "subrogados_text",
"kind": "read",
"inputs": ["subrogados"],
"column": "archivo",
},
table("resultados", site_url, "ResultadoSubrogado", schema="dbo"),
{"id": "text", "kind": "read", "inputs": ["resultados"], "column": "archivo"},
]
}
@@ -58,13 +51,8 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, t
by_place = {}
for r in truth:
by_place.setdefault(r["where"].split(":")[0], []).append(r)
documents = len(by_place["ArchivosUni"]) + len(by_place["ResultadosSubrogados"])
expected = {
"archivos": len(by_place["ArchivosUni"]),
"subrogados": len(by_place["ResultadosSubrogados"]),
"archivos_text": len(by_place["ArchivosUni"]),
"subrogados_text": len(by_place["ResultadosSubrogados"]),
}
documents = len(truth)
expected = {"resultados": documents, "text": documents}
for name, names in tables.items():
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
for t in names:
@@ -87,8 +75,8 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, t
assert query(corrected) == [("64000",)]
space = re.compile(r"\s+")
for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")):
read = query(f"select id, text, ocr, error from bronze.n__site__{node}_text")
for table in ("ResultadoSubrogado",):
read = query("select id, text, ocr, error from bronze.n__site__text")
assert [error for *_, error in read if error is not None] == []
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
for r in by_place[table]:
+35 -18
View File
@@ -2,10 +2,11 @@
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
one SQL Server table, the institute's forms beside 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.
Medical notes (the colposcopy clinic's, oncology's) and death notes are the institute's forms.
"""
import json
@@ -23,6 +24,7 @@ FIELDS = {
"er", "pr", "her2", "ki67_pct", "size_mm", "stage"),
"breast_treatment": ("start_date", "kind"),
"clinical_note": ("note_date", "specialty", "icd10"),
"death": ("death_date",),
} # fmt: skip
BOOLS = {"hpv", "hpv_16", "hpv_18"}
NUMBERS = {"ki67_pct", "size_mm"}
@@ -57,17 +59,27 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
# 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.
# A person nothing names (a scan whose name line wasn't read) is held as well: there is
# nobody to join her to.
members: dict[str, set] = {}
held, person_of = set(), {}
for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
held, nameless, named, person_of = set(), set(), set(), {}
for record, person, why, *identifiers in q(
"select _record, person_id, _held, full_name, birth_date, record_number "
"from bronze.n__site__persons"
):
members.setdefault(person, set()).add(of[record])
person_of[record] = person
if why:
if any(identifiers):
named.add(person)
if why and "no name" in why:
nameless.add(person)
elif why:
held.add(person)
assert nameless == set(members) - named, nameless
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}
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn | nameless}
# Every woman split into several persons (a misspelled form, say) is in the review
# queue, joined by candidates.
@@ -88,15 +100,14 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
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).
# Every value accepted from a typed 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). A scan can misread one valid code as
# another ("IIA" as "IA"), which nothing in the text betrays: at most 1% of a scan's
# values, each listed.
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
place = {r: f"ResultadoSubrogado:{i}"
for i, r in q("select id, _record from bronze.n__site__resultados")} # 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:
@@ -108,22 +119,28 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
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
stated = read = scanned = 0
missed: Counter = Counter()
wrong = []
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)
differ = {f: (v, value(f, truly.get(f))) for f, v in got.items()
if v != value(f, truly.get(f))} # fmt: skip
assert t.get("scanned") or not differ, (t["where"], differ)
wrong += [(t["where"], differ)] if differ else []
scanned += len(got) if t.get("scanned") else 0
stated, read = stated + len(truly), read + len(got)
missed.update(set(truly) - set(got))
assert read >= 0.95 * stated, (entity, read, stated, missed)
assert len(wrong) <= 0.01 * scanned, (entity, wrong)
# 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:
if record in place and person_of.get(record) not in torn | nameless:
t, got = at[place[record]], json.loads(raw)
truly = said(t, entity)
assert {f: value(f, got.get(f)) for f in truly} != {
@@ -140,7 +157,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
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:
if got is None or person_of[record] in torn | nameless or record in misread:
continue
at_key = (person_of[record], *(got.get(k) for k in key))
merged.setdefault(at_key, {}).update(got)
@@ -150,6 +167,6 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
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
for p, *values in rows if p not in torn | nameless} # fmt: skip
assert got == expected, (entity, sorted(got - expected, key=str)[:4],
sorted(expected - got, key=str)[:4]) # fmt: skip