Compare commits

..

6 Commits

Author SHA1 Message Date
edgar a93292f3dd Silver gate: findings as the cytologist confirmed them
No inflammation grade field; one endometrial-cells field (40 or more).
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
2026-11-27 16:03:20 -06:00
edgar 0fcbe95c90 Silver gate checks the cytologist's additional findings
The synthetic cytology form now has a free-text findings section; its text,
the inflammation grade and each stated finding are expected, the rest unknown.
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
2026-11-27 15:42:46 -06:00
edgar 8908184093 Silver gate checks the cytology's cervix_exam
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
2026-11-27 15:38:33 -06:00
edgar 1dc681fb5a Silver gate checks the cytology's presents_ answers
The synthetic cytology form records one "actualmente presenta" answer; only
that field is expected true, the others stay unknown.
Not run yet: tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:50:23 -06:00
edgar 7b6ffe17f5 Silver gate checks the cytology's gyn_ conditions
The synthetic cytology form records one gynaecological/obstetric condition;
only that field is expected true, the others stay unknown.
Not run yet: tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:36:07 -06:00
edgar 1f0d38de3c Silver gate checks the cytology's screening_history
The synthetic cytology form now says one of the four detection answers, and
the gate compares screening_history with the rest of the cytology's fields.
Not run yet: tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:33:32 -06:00
4 changed files with 64 additions and 69 deletions
-5
View File
@@ -80,9 +80,6 @@ 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_),
}
@@ -142,8 +139,6 @@ 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()),
+5 -20
View File
@@ -267,8 +267,7 @@ 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. A person
with nothing that names her (no name, birth date or record number read) is held too."""
don't contradict each other are queued for review, with Splink's probability."""
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()
@@ -294,16 +293,12 @@ 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()
# 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}
held = json.dumps(["records of this person disagree on birth date or sex"])
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: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
HELD: held if r.cluster_id in torn 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()
@@ -340,8 +335,6 @@ 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()
@@ -351,23 +344,15 @@ 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. 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)."""
demographics and the other's identifier stands on a single record."""
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
reason = reasons[int(r.match_key)]
if not reason.endswith("typo apart"):
if not reasons[int(r.match_key)].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:
+18 -6
View File
@@ -27,8 +27,15 @@ def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> di
return {
"nodes": nodes
+ [
table("resultados", site_url, "ResultadoSubrogado", schema="dbo"),
{"id": "text", "kind": "read", "inputs": ["resultados"], "column": "archivo"},
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",
},
]
}
@@ -51,8 +58,13 @@ 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(truth)
expected = {"resultados": documents, "text": documents}
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"]),
}
for name, names in tables.items():
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
for t in names:
@@ -75,8 +87,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 in ("ResultadoSubrogado",):
read = query("select id, text, ocr, error from bronze.n__site__text")
for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")):
read = query(f"select id, text, ocr, error from bronze.n__site__{node}_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]:
+41 -38
View File
@@ -2,11 +2,10 @@
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
one SQL Server table, the institute's forms beside what outsourced labs send back; an HPV result
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.
Medical notes (the colposcopy clinic's, oncology's) and death notes are the institute's forms.
"""
import json
@@ -15,18 +14,37 @@ 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")
CYTO = ("cyto_inflammation", "cyto_reactive_changes",
"cyto_bacterial_vaginosis_flora", "cyto_candida",
"cyto_bacillary_flora_cytolysis", "cyto_intermediate_cytolysis",
"cyto_trichomonas", "cyto_leptothrix",
"cyto_actinomyces_organisms", "cyto_actinomyces_changes",
"cyto_herpes_simplex_changes", "cyto_squamous_tubular_metaplasia",
"cyto_keratotic_changes", "cyto_pregnancy_changes",
"cyto_atrophy", "cyto_hypoestrogenism",
"cyto_radiotherapy_effect", "cyto_iud_changes",
"cyto_post_hysterectomy_glandular_cells",
"cyto_bacteria", "cyto_herpes_image",
"cyto_fungi", "cyto_radiation",
"cyto_repair", "cyto_iud_effect",
"cyto_endometrial_cells_40_plus", "cyto_findings_none")
FIELDS = {
"cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16",
"hpv_18"),
"cervical_cytology": ("sample_date", "screening_history", *GYN, *PRESENTS,
"cervix_exam", "report_date", "adequacy", "result", "hpv", "hpv_16",
"hpv_18", "cyto_findings_text", *CYTO),
"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"),
"death": ("death_date",),
} # fmt: skip
BOOLS = {"hpv", "hpv_16", "hpv_18"}
BOOLS = {"hpv", "hpv_16", "hpv_18", *GYN, *PRESENTS, *CYTO}
NUMBERS = {"ki67_pct", "size_mm"}
@@ -59,27 +77,17 @@ 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, 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"
):
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 any(identifiers):
named.add(person)
if why and "no name" in why:
nameless.add(person)
elif why:
if 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 | nameless}
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.
@@ -100,14 +108,15 @@ 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 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.
# 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"ResultadoSubrogado:{i}"
for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip
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:
@@ -119,28 +128,22 @@ 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 = scanned = 0
stated = read = 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}
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
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)
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 | nameless:
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} != {
@@ -157,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 | nameless or record in misread:
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)
@@ -167,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 | nameless} # fmt: skip
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