Link each distinct identity once, not every pair of a patient's records
This commit is contained in:
+30
-4
@@ -10,6 +10,7 @@ from collections.abc import Callable
|
|||||||
from concurrent.futures import ProcessPoolExecutor
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
from functools import cache
|
from functools import cache
|
||||||
|
|
||||||
|
import duckdb
|
||||||
import ocrmypdf
|
import ocrmypdf
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pdfplumber
|
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
|
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:
|
def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame:
|
||||||
clusters = cluster_pairwise_predictions_at_threshold(
|
clusters = cluster_pairwise_predictions_at_threshold(
|
||||||
records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r"
|
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()
|
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
|
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]
|
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()
|
db = DuckDBAPI()
|
||||||
linker = Linker(
|
linker = Linker(
|
||||||
db.register(records),
|
db.register(distinct),
|
||||||
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
|
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
|
||||||
blocking_rules_to_generate_predictions=rules),
|
blocking_rules_to_generate_predictions=rules),
|
||||||
log_level=None,
|
log_level=None,
|
||||||
) # fmt: skip
|
) # fmt: skip
|
||||||
decided = nodes.person_decisions()
|
|
||||||
sure = linker.inference.deterministic_link().as_pandas_dataframe()
|
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 = {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}
|
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(
|
edges = pd.DataFrame(
|
||||||
[sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"]
|
[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]
|
facts = [f for f in ("birth_date", "sex") if f in fields]
|
||||||
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
|
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ dependencies = [
|
|||||||
"mlflow-skinny",
|
"mlflow-skinny",
|
||||||
"openai>=3.59.0",
|
"openai>=3.59.0",
|
||||||
"splink>=5.0.0",
|
"splink>=5.0.0",
|
||||||
|
"duckdb>=2.0.1",
|
||||||
"markitdown[docx,xlsx]>=0.1.9",
|
"markitdown[docx,xlsx]>=0.1.9",
|
||||||
"ocrmypdf>=17.14.2",
|
"ocrmypdf>=17.14.2",
|
||||||
"pikepdf>=10.0",
|
"pikepdf>=10.0",
|
||||||
|
|||||||
Reference in New Issue
Block a user