From 1a46a5ba736c23577e3caf194b8c26eb15d9cf3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?= Date: Sat, 28 Nov 2026 01:17:40 -0600 Subject: [PATCH] Link each distinct identity once, not every pair of a patient's records --- models/graph.py | 34 ++++++++++++++++++++++++++++++---- pyproject.toml | 1 + 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/models/graph.py b/models/graph.py index baaeec6..0c569dc 100644 --- a/models/graph.py +++ b/models/graph.py @@ -10,6 +10,7 @@ from collections.abc import Callable from concurrent.futures import ProcessPoolExecutor from functools import cache +import duckdb import ocrmypdf import pandas as pd import pdfplumber @@ -313,6 +314,28 @@ def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[ return frame[["unique_id", *present]], sources, written +def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series: + """Each record's stand-in: one record per identity that the rules join to itself (a + patient's 24 reports carrying one record number are one row to compare, not 24² pairs). + A record a reviewer judged stands for itself, and so does one the rules would not join + to an identical record (nothing compared was read, say).""" + fields = [c for c in records.columns if c != "unique_id"] + key = records[fields].astype(object).where(records[fields].notna(), None) + same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index) + stand_in = records.groupby(same, sort=False)["unique_id"].transform("first") + stand_in = stand_in.where(~records["unique_id"].isin(judged), records["unique_id"]) + joined = set() + if rules: + con = duckdb.connect() + con.register("candidates", records[records["unique_id"].isin(set(stand_in))]) + joins = " or ".join(f"({r})" for r in rules) + joined = set(con.sql( + f"select l.unique_id from candidates l join candidates r" + f" on l.unique_id = r.unique_id where {joins}" + ).df()["unique_id"]) # fmt: skip + return stand_in.where(stand_in.isin(joined), records["unique_id"]) + + def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame: clusters = cluster_pairwise_predictions_at_threshold( records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r" @@ -331,22 +354,25 @@ def run_link(p: str, node: Link): rules = [r for r in node.rules or node.default_rules() if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip comparisons = [_comparison(f) for f in fields] + decided = nodes.person_decisions() + stand_in = _distinct(records, rules, set().union(*decided)) + distinct = records[records["unique_id"].isin(set(stand_in))] db = DuckDBAPI() linker = Linker( - db.register(records), + db.register(distinct), SettingsCreator(link_type="dedupe_only", comparisons=comparisons, blocking_rules_to_generate_predictions=rules), log_level=None, ) # fmt: skip - decided = nodes.person_decisions() sure = linker.inference.deterministic_link().as_pandas_dataframe() pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)} pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same} - known = set(records.unique_id) + known = set(distinct.unique_id) edges = pd.DataFrame( [sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"] ) - persons = _persons(records, edges, db) + cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"] + persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy()) facts = [f for f in ("birth_date", "sex") if f in fields] spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame() diff --git a/pyproject.toml b/pyproject.toml index 79369aa..e05c1fe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,6 +11,7 @@ dependencies = [ "mlflow-skinny", "openai>=3.59.0", "splink>=5.0.0", + "duckdb>=2.0.1", "markitdown[docx,xlsx]>=0.1.9", "ocrmypdf>=17.14.2", "pikepdf>=10.0",