diff --git a/models/graph.py b/models/graph.py index 00b5b2b..1977634 100644 --- a/models/graph.py +++ b/models/graph.py @@ -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() diff --git a/tests/test_silver.py b/tests/test_silver.py index eec1325..24e9dbc 100644 --- a/tests/test_silver.py +++ b/tests/test_silver.py @@ -6,6 +6,7 @@ two SQL Server tables, the institute's forms and what outsourced labs send back; 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,9 +100,11 @@ 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") @@ -108,22 +122,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 +160,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 +170,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