Long silver from targets, stable person ids, ConceptMap translation, the fhir node
This commit is contained in:
+71
-26
@@ -5,6 +5,7 @@ import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import unicodedata
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from functools import cache
|
||||
@@ -19,12 +20,14 @@ from splink import Linker, SettingsCreator, block_on
|
||||
from splink.backends.duckdb import DuckDBAPI
|
||||
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||
|
||||
from core import catalog, concept_map, fhir_in
|
||||
from core.pipeline import (
|
||||
HELD,
|
||||
IDENTIFIERS,
|
||||
QUOTES,
|
||||
RECORD,
|
||||
Extract,
|
||||
Fhir,
|
||||
Join,
|
||||
Link,
|
||||
Map,
|
||||
@@ -40,8 +43,7 @@ from core.pipeline import (
|
||||
matches,
|
||||
validate,
|
||||
)
|
||||
from core.schema import ENTITIES
|
||||
from persistance import nodes, silver
|
||||
from persistance import config_log, nodes, silver
|
||||
|
||||
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer
|
||||
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
|
||||
@@ -112,8 +114,29 @@ def run_route(p: str, node: Route):
|
||||
return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)])
|
||||
|
||||
|
||||
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
|
||||
"""The node's ConceptMap as a translation table per field (none without one)."""
|
||||
if node.concept_map is None:
|
||||
return {}
|
||||
found = config_log.concept_map(node.concept_map)
|
||||
return {f: concept_map.table([found], f) for f in fields}
|
||||
|
||||
|
||||
def run_map(p: str, node: Map):
|
||||
return nodes.write(p, node.id, [map_row(node, r) for r in nodes.rows(p, node.inputs[0])])
|
||||
codes = _codes(node, node.fields)
|
||||
rows = [map_row(node, r, codes) for r in nodes.rows(p, node.inputs[0])]
|
||||
return nodes.write(p, node.id, rows)
|
||||
|
||||
|
||||
def run_fhir(p: str, node: Fhir):
|
||||
"""Each Bundle's rows of the node's entity; a resource sent again is its latest."""
|
||||
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
|
||||
found: dict[str, dict] = {}
|
||||
for row in nodes.rows(p, node.inputs[0]):
|
||||
bundle = json.loads(row[node.column])
|
||||
for r in fhir_in.rows(bundle, node.entity, p, maps):
|
||||
found[r[RECORD]] = r
|
||||
return nodes.write(p, node.id, list(found.values()))
|
||||
|
||||
|
||||
def run_join(p: str, node: Join):
|
||||
@@ -160,13 +183,14 @@ def _ask_llm(node: Extract, text: str) -> dict:
|
||||
|
||||
def run_extract(p: str, node: Extract):
|
||||
use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None)
|
||||
codes = _codes(node, node.patterns)
|
||||
out = []
|
||||
for row in nodes.rows(p, node.inputs[0]):
|
||||
text = row.get(node.column) or ""
|
||||
if use_llm:
|
||||
found = ground(_ask_llm(node, text), text)
|
||||
elif node.patterns:
|
||||
found = apply_patterns(node, text)
|
||||
found = apply_patterns(node, text, codes)
|
||||
else:
|
||||
found = [({}, {}, ["no LLM answering and no patterns set"])]
|
||||
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
|
||||
@@ -191,6 +215,12 @@ def _plain(identifier: str) -> str:
|
||||
return "".join(ch for ch in identifier if ch.isalnum()).upper()
|
||||
|
||||
|
||||
def _name(name: str) -> str:
|
||||
"""A name as compared: upper case, without accents, single spaces."""
|
||||
plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
|
||||
return " ".join(plain.upper().split())
|
||||
|
||||
|
||||
def _near(identifier: str) -> list[str]:
|
||||
"""The identifier and every version of it with one character left out: two identifiers
|
||||
one typo apart (a wrong, missing, extra or swapped character) share one of these."""
|
||||
@@ -199,23 +229,30 @@ def _near(identifier: str) -> list[str]:
|
||||
)
|
||||
|
||||
|
||||
def _identities(p: str, node: Link) -> pd.DataFrame:
|
||||
def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str]]:
|
||||
"""One row per record: its identity fields (first value found, reviewers' corrections
|
||||
applied, identifiers plain); records rejected for identity are left out."""
|
||||
applied, identifiers plain); records rejected for identity are left out. And the input
|
||||
each record came through (its record number's system)."""
|
||||
skip, fixed = nodes.rejected("identity"), nodes.corrections()
|
||||
records: dict[str, dict] = {}
|
||||
sources: dict[str, str] = {}
|
||||
for i in node.inputs:
|
||||
for row in nodes.rows(p, i):
|
||||
if row.get(HELD) or row[RECORD] in skip:
|
||||
continue
|
||||
row = {**row, **fixed.get(row[RECORD], {})} # a reviewer's correction wins
|
||||
mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]})
|
||||
sources.setdefault(row[RECORD], i)
|
||||
for f in node.fields:
|
||||
if row.get(f) is not None and mine.get(f) is None:
|
||||
value = str(row[f])
|
||||
mine[f] = _plain(value) if f in IDENTIFIERS else value
|
||||
mine[f] = (
|
||||
_plain(value) if f in IDENTIFIERS
|
||||
else _name(value) if f == "full_name" else value
|
||||
) # fmt: skip
|
||||
frame = pd.DataFrame(list(records.values()))
|
||||
return frame[["unique_id", *(f for f in node.fields if f in frame and frame[f].notna().any())]]
|
||||
present = [f for f in node.fields if f in frame and frame[f].notna().any()]
|
||||
return frame[["unique_id", *present]], sources
|
||||
|
||||
|
||||
def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame:
|
||||
@@ -230,7 +267,7 @@ def run_link(p: str, node: Link):
|
||||
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."""
|
||||
records = _identities(p, node)
|
||||
records, sources = _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()
|
||||
if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
|
||||
@@ -256,15 +293,16 @@ def run_link(p: str, node: Link):
|
||||
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"])
|
||||
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, *fields)}
|
||||
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": r.cluster_id,
|
||||
{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,
|
||||
**{f: getattr(r, f) for f in fields}}
|
||||
for r in persons.itertuples()
|
||||
] # fmt: skip
|
||||
nodes.write(p, node.id, linked, columns)
|
||||
nodes.stage("identity", p, node.id, linked, silver.columns("identity")) # silver.person
|
||||
nodes.stage("identity", p, node.id, linked, silver.identity_columns()) # silver.person
|
||||
|
||||
# One row per person, so random pairs are different people and Splink's u is honest.
|
||||
ids = [f for f in IDENTIFIERS if f in fields]
|
||||
@@ -293,7 +331,7 @@ def run_link(p: str, node: Link):
|
||||
model.training.estimate_u_using_random_sampling(max_pairs=1e6)
|
||||
found = model.inference.predict(warning_mode="never").as_pandas_dataframe()
|
||||
|
||||
known = [f for f in ("birth_date", "sex", "postal_code") if f in fields]
|
||||
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()
|
||||
lone = set() # persons whose identifier is carried by one record only
|
||||
for f in ids:
|
||||
@@ -338,11 +376,14 @@ def run_link(p: str, node: Link):
|
||||
|
||||
|
||||
def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
"""Rows of one study into silver's staging, each given its person by the link node:
|
||||
a clean row becomes one observation per field it has (long), keyed by its study
|
||||
instance (the study's key values); a row a rule held waits for review, whole."""
|
||||
link = next(i for i in node.inputs if kinds[i] == "link")
|
||||
linked = {r[RECORD]: r for r in nodes.rows(p, link)}
|
||||
person = {k: r["person_id"] for k, r in linked.items()}
|
||||
model = ENTITIES[node.entity]
|
||||
out = []
|
||||
model, study = catalog.model(node.entity), catalog.studies()[node.entity]
|
||||
observations, held_rows = [], []
|
||||
for i in (i for i in node.inputs if i != link):
|
||||
for row in nodes.rows(p, i):
|
||||
values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None}
|
||||
@@ -351,21 +392,25 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
held.append("no identity linked to this record")
|
||||
else:
|
||||
held += json.loads(linked[row[RECORD]].get(HELD) or "[]")
|
||||
staged = {
|
||||
"person_id": person.get(row[RECORD]), RECORD: row[RECORD],
|
||||
"_index": row.get("_index", 0), QUOTES: row.get(QUOTES),
|
||||
HELD: json.dumps(held) if held else None,
|
||||
"_raw": json.dumps(values, default=str, ensure_ascii=False) if held else None,
|
||||
} # fmt: skip
|
||||
if not held:
|
||||
staged |= model.model_validate(values).model_dump()
|
||||
out.append(staged)
|
||||
return nodes.stage(node.entity, p, node.id, out, silver.columns(node.entity))
|
||||
base = {"study": node.entity, "person_id": person.get(row[RECORD]), RECORD: row[RECORD],
|
||||
"_index": row.get("_index", 0), QUOTES: row.get(QUOTES)} # fmt: skip
|
||||
if held:
|
||||
raw = json.dumps(values, default=str, ensure_ascii=False)
|
||||
held_rows.append({**base, HELD: json.dumps(held), "_raw": raw})
|
||||
continue
|
||||
clean = model.model_validate(values)
|
||||
instance = json.dumps([str(getattr(clean, k)) for k in model.key])
|
||||
for name, field in study.fields.items():
|
||||
if (value := getattr(clean, name)) is not None:
|
||||
observations.append({**base, "instance": instance, "field": name,
|
||||
catalog.value_column(field): value}) # fmt: skip
|
||||
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
|
||||
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
|
||||
|
||||
|
||||
RUNNERS: dict[str, Callable] = {
|
||||
"source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map,
|
||||
"join": run_join, "extract": run_extract, "link": run_link,
|
||||
"join": run_join, "extract": run_extract, "link": run_link, "fhir": run_fhir,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
|
||||
tables[name] = [t for (t,) in found]
|
||||
truth = build(FIXTURES / "hospital_cacu.db", tmp_path / "site")["records"]
|
||||
(tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables)))
|
||||
platform.run("python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json"))
|
||||
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
||||
|
||||
by_place = {}
|
||||
for r in truth:
|
||||
|
||||
+28
-8
@@ -7,6 +7,7 @@ reports as BLOBs in three layouts (some scanned), loose PDFs, a CSV of consultat
|
||||
contradicting copies of some reports.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
FIELDS = {
|
||||
@@ -27,7 +28,8 @@ def _value(field, v):
|
||||
def test_a_messy_site_becomes_silver_and_review_gets_the_rest(platform, messy_site, tmp_path):
|
||||
truth = messy_site.truth
|
||||
(tmp_path / "pipeline.json").write_text(messy_site.drawn)
|
||||
platform.run("python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json"))
|
||||
platform.save("concept_maps", "messy_site", messy_site.concept_map)
|
||||
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
||||
platform.ingest()
|
||||
q = platform.query
|
||||
of = messy_site.patients(q)
|
||||
@@ -49,8 +51,9 @@ def test_a_messy_site_becomes_silver_and_review_gets_the_rest(platform, messy_si
|
||||
parts: dict[str, set] = {}
|
||||
for p, x in patient.items():
|
||||
parts.setdefault(x, set()).add(p)
|
||||
# A queued person or candidate is one of its records (decisions are kept by record).
|
||||
queued = {
|
||||
frozenset(pair)
|
||||
frozenset(person_of[r] for r in pair)
|
||||
for pair in q("select person, candidate from bronze.n__site__persons__review")
|
||||
}
|
||||
for x, persons in parts.items():
|
||||
@@ -70,15 +73,32 @@ def test_a_messy_site_becomes_silver_and_review_gets_the_rest(platform, messy_si
|
||||
}
|
||||
place |= {r: f"files/{n}" for n, r in q("select file_name, _record from bronze.n__site__pdfs")}
|
||||
for entity, fields in FIELDS.items():
|
||||
rows = q(f"select _record, _held, {', '.join(fields)} from bronze.staged__{entity}")
|
||||
for record, why, *values in rows:
|
||||
accepted: dict[str, dict] = {} # each accepted record, from its observations (long)
|
||||
for record, field, *values in q(
|
||||
"select _record, field, value_text, value_num, value_bool, value_date "
|
||||
f"from bronze.staged__observation where study = '{entity}'"
|
||||
):
|
||||
value = next((v for v in values if v is not None), None)
|
||||
accepted.setdefault(record, dict.fromkeys(fields))[field] = value
|
||||
for record, values in accepted.items():
|
||||
t = at[place[record]]
|
||||
if why is None and not t.get("flipped"):
|
||||
got = {f: _value(f, v) for f, v in zip(fields, values, strict=True)}
|
||||
if not t.get("flipped"):
|
||||
got = {f: _value(f, values[f]) for f in fields}
|
||||
assert got == {f: t["values"][f] for f in fields}, (t["where"], got)
|
||||
|
||||
# Silver: everything except contradicting reports and rows of the torn person.
|
||||
out = {place[r] for r, p in person_of.items() if p in torn and r in place}
|
||||
# A value a rule held (a scan misread: "LJEBG") is held because it is wrong: it is
|
||||
# never loaded, and a reviewer sees it.
|
||||
misread = set()
|
||||
for record, raw in q("select _record, _raw from bronze.staged__held"):
|
||||
if record in place and person_of.get(record) not in torn:
|
||||
t, got = at[place[record]], json.loads(raw)
|
||||
fields = FIELDS[t["entity"]]
|
||||
assert {f: _value(f, got.get(f)) for f in fields} != {
|
||||
f: t["values"][f] for f in fields}, t["where"] # fmt: skip
|
||||
misread.add(place[record])
|
||||
|
||||
# Silver: everything except contradicting reports, rows of the torn person and misreads.
|
||||
out = {place[r] for r, p in person_of.items() if p in torn and r in place} | misread
|
||||
torn_notes = {
|
||||
(e, date.fromisoformat("-".join(reversed(f.split("/")))).isoformat())
|
||||
for e, f, r in q("select expediente, fecha, _record from bronze.n__site__notes")
|
||||
|
||||
Reference in New Issue
Block a user