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
10 changed files with 120 additions and 276 deletions
-5
View File
@@ -80,9 +80,6 @@ class Pim:
found = { found = {
"n_train": len(train), "n_train": len(train),
"n_test": len(test), "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_, "neg_loglik": mixture.neg_loglik_,
"converged": float(mixture.converged_), "converged": float(mixture.converged_),
} }
@@ -142,8 +139,6 @@ class Logistic:
metrics = { metrics = {
"n_train": len(train), "n_train": len(train),
"n_test": len(test), "n_test": len(test),
"events_train": float(train["y"].sum()),
"events_test": float(test["y"].sum()),
"auc": float(roc_auc_score(test["y"], p)), "auc": float(roc_auc_score(test["y"], p)),
"brier": float(brier_score_loss(test["y"], p)), "brier": float(brier_score_loss(test["y"], p)),
"positive_rate_train": float(train["y"].mean()), "positive_rate_train": float(train["y"].mean()),
-52
View File
@@ -1,52 +0,0 @@
"""Where long batches run (the EEG analysis, measuring a reference cohort). Where Dask is
installed (the `dask` extra, for testing on a cluster) they run on the scheduler at
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores. Without it (the
product) joblib runs them on local processes. BATCH_JOBS caps how many run at once: each
task carries its data (a recording), so a cap paces a slow link."""
import os
from collections.abc import Callable, Iterable
from importlib.util import find_spec
from typing import Any
from joblib import Parallel, delayed
def jobs() -> int:
"""How many tasks run at once: BATCH_JOBS, or every core (or worker)."""
return int(os.environ.get("BATCH_JOBS", "-1"))
def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
"""`task(*a)` for each tuple of `arguments`, results in their order. The arguments are
drawn as tasks start, so at most `jobs()` of them are held at once."""
if find_spec("distributed") is None:
return Parallel(n_jobs=jobs())(delayed(task)(*a) for a in arguments)
from distributed import Client, LocalCluster, as_completed
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
# one process per core, no dashboard port to collide with (8787 is often taken)
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
try:
with Client(where) as client:
limit = jobs() if jobs() > 0 else sum(client.nthreads().values())
pending = iter(enumerate(arguments))
results: dict[int, Any] = {}
order: dict[Any, int] = {}
def submit() -> Any | None:
if (item := next(pending, None)) is None:
return None
future = client.submit(task, *item[1], pure=False)
order[future] = item[0]
return future
running = as_completed([f for f in (submit() for _ in range(limit)) if f])
for done in running:
results[order.pop(done)] = done.result()
if (future := submit()) is not None:
running.add(future)
return [results[i] for i in range(len(results))]
finally:
if not address:
where.close()
+37 -139
View File
@@ -10,11 +10,9 @@ 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
import pikepdf
import splink.comparison_library as cl import splink.comparison_library as cl
from markitdown import MarkItDown from markitdown import MarkItDown
from openai import OpenAI, OpenAIError from openai import OpenAI, OpenAIError
@@ -47,28 +45,14 @@ from core.pipeline import (
) )
from persistance import config_log, files, nodes, silver from persistance import config_log, files, nodes, silver
MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer
READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done)
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error` READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
"text": {"data_type": "text", "nullable": True}, "text": {"data_type": "text", "nullable": True},
"ocr": {"data_type": "bool"}, "ocr": {"data_type": "bool"},
"error": {"data_type": "text", "nullable": True}, "error": {"data_type": "text", "nullable": True},
"format": {"data_type": "text", "nullable": True},
} }
def file_format(content: bytes) -> str:
"""What kind of file this is, from its first bytes, so a route can tell a PDF from an
EEG recording in the same column: pdf, edf (EDF and EDF+: a fixed ASCII header whose
version is "0"), or other (whatever MarkItDown reads)."""
if content.startswith(b"%PDF"):
return "pdf"
head = content[:256]
if len(head) == 256 and head[:8] == b"0 " and head[184:192].strip().isdigit():
return "edf"
return "other"
@cache @cache
def _reader() -> MarkItDown: def _reader() -> MarkItDown:
return MarkItDown() return MarkItDown()
@@ -80,93 +64,52 @@ def _lines(text: str) -> str:
def _text(content: bytes) -> str: def _text(content: bytes) -> str:
"""Files other than PDFs, through MarkItDown.""" """PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each
(spacing within a line collapsed); every other format through MarkItDown."""
if content.startswith(b"%PDF"):
with pdfplumber.open(io.BytesIO(content)) as pdf:
return _lines("\n".join(page.extract_text(layout=True) or "" for page in pdf.pages))
return _reader().convert_stream(io.BytesIO(content)).text_content return _reader().convert_stream(io.BytesIO(content)).text_content
def _pdf_pages(content: bytes) -> list[str]:
"""Each page's text layer, through pdfplumber's layout mode, which keeps a table's rows
on one line each (spacing within a line collapsed)."""
with pdfplumber.open(io.BytesIO(content)) as pdf:
return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages]
def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
"""Tesseract's text (OCRmyPDF's sidecar, from the deskewed page) of these pages only,
copied into a PDF of their own: a typed page keeps its own text layer."""
source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new()
for n in numbers:
scans.pages.append(source.pages[n])
pages, sidecar = io.BytesIO(), io.BytesIO()
scans.save(pages)
pages.seek(0)
ocrmypdf.ocr(
pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0,
progress_bar=False, jobs=1, deskew=True, sidecar=sidecar,
) # fmt: skip
found = sidecar.getvalue().decode().split("\f")
return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))]
def read_file(content: bytes) -> dict: def read_file(content: bytes) -> dict:
"""Text of one file, its format, and whether OCR was needed. An unreadable file keeps """Text of one file, and whether OCR was needed. An unreadable file keeps its error."""
its error; a signal recording (EDF) has no text to read."""
kind = file_format(content)
if kind == "edf":
return {"text": None, "ocr": False, "error": None, "format": kind}
return {**_read_text(content), "format": kind}
def _read_text(content: bytes) -> dict:
"""The file's text; a PDF page by page, OCR only on the pages without a text layer (a
typed form whose second page is a scan, say)."""
try: try:
if not content.startswith(b"%PDF"): found = _text(content)
return {"text": _text(content), "ocr": False, "error": None} ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
pages = _pdf_pages(content) if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page
scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS] text = io.BytesIO()
if scanned: ocrmypdf.ocr(
for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True): io.BytesIO(content), io.BytesIO(), language="spa", skip_text=True,
pages[i] = page output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True,
return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None} sidecar=text,
) # fmt: skip
found = _lines(text.getvalue().decode())
return {"text": found, "ocr": ocr, "error": None}
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"} return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
def run_read(p: str, node: Read): def run_read(p: str, node: Read):
"""The input's rows with their file's text and format beside the file column (which """The input's rows with the file column replaced by its text; each file read once."""
keeps the file, for a study that takes the file itself: an EEG's recording); each file
read once."""
rows = list(nodes.rows(p, node.inputs[0])) rows = list(nodes.rows(p, node.inputs[0]))
for row in rows: # the source kept the file; the row carries its hash for row in rows: # the source kept the file; the row carries its hash
row["key"] = row.get(node.column) or None row["key"] = row.pop(node.column) or None
keys = {r["key"] for r in rows} - {None} keys = {r["key"] for r in rows} - {None}
found = nodes.cached("read_cache", keys) found = nodes.cached("read_cache", keys)
legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats new = {k: files.content(k) for k in keys - set(found)}
for k in legacy: with ProcessPoolExecutor() as pool:
found[k]["format"] = file_format(files.content(k) or b"") read = dict(zip(new, pool.map(read_file, new.values()), strict=True))
nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}} nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS)
for k in legacy], READ_COLUMNS) # fmt: skip found |= read
new = sorted(keys - set(found))
with ProcessPoolExecutor() as pool: # a batch of files in memory at a time, each kept
for start in range(0, len(new), READ_BATCH):
batch = new[start : start + READ_BATCH]
read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)),
strict=True)) # fmt: skip
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()],
READ_COLUMNS) # fmt: skip
found |= read
for row in rows: for row in rows:
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"}) result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
row |= {k: result[k] for k in READ_COLUMNS} row |= {k: result[k] for k in READ_COLUMNS}
return nodes.write(p, node.id, rows, READ_COLUMNS) return nodes.write(p, node.id, rows, READ_COLUMNS)
def run_route(p: str, node: Route, others: list[Route] = ()): def run_route(p: str, node: Route):
"""The input's rows the route takes; an `otherwise` route, those `others` don't.""" return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)])
rows = nodes.rows(p, node.inputs[0])
taken = [r for r in rows if matches(node, r) and not any(matches(o, r) for o in others)]
return nodes.write(p, node.id, taken)
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]: def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
@@ -248,9 +191,8 @@ def run_extract(p: str, node: Extract):
found = apply_patterns(node, text, codes) found = apply_patterns(node, text, codes)
else: else:
found = [({}, {}, ["no LLM answering and no patterns set"])] found = [({}, {}, ["no LLM answering and no patterns set"])]
taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None}
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]): for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
out.append({**values, **taken, RECORD: row[RECORD], "_index": index, out.append({**values, RECORD: row[RECORD], "_index": index,
QUOTES: json.dumps(quotes, ensure_ascii=False), QUOTES: json.dumps(quotes, ensure_ascii=False),
HELD: json.dumps(held) if held else None}) # fmt: skip HELD: json.dumps(held) if held else None}) # fmt: skip
return nodes.write(p, node.id, out) return nodes.write(p, node.id, out)
@@ -314,28 +256,6 @@ 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"
@@ -347,46 +267,38 @@ def run_link(p: str, node: Link):
"""Persons: records the node's rules join (Splink deterministic linking), joined or kept """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 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 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 don't contradict each other are queued for review, with Splink's probability."""
with nothing that names her (no name, birth date or record number read) is held too."""
records, sources, written = _identities(p, node) records, sources, written = _identities(p, node)
fields = [c for c in records.columns if c != "unique_id"] fields = [c for c in records.columns if c != "unique_id"]
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(distinct), db.register(records),
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(distinct.unique_id) known = set(records.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"]
) )
cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"] persons = _persons(records, edges, db)
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()
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set() 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. held = json.dumps(["records of this person disagree on birth date or sex"])
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)} 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()) stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
linked = [ linked = [
{RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id], {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}, **{f: getattr(r, f) for f in fields},
**({"full_name": written[r.unique_id]} if r.unique_id in written else {})} **({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
for r in persons.itertuples() for r in persons.itertuples()
@@ -423,8 +335,6 @@ def run_link(p: str, node: Link):
known = [f for f in ("birth_date", "sex") 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() 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 lone = set() # persons whose identifier is carried by one record only
for f in ids: for f in ids:
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size() carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
@@ -434,23 +344,15 @@ def run_link(p: str, node: Link):
"""(the person to settle, a possible owner), or None when the pair is implausible: """(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 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 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 demographics and the other's identifier stands on a single record."""
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)."""
a, b = r.unique_id_l, r.unique_id_r 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] sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
if frozenset((a, b)) in decided or any( if frozenset((a, b)) in decided or any(
pd.notna(x) and pd.notna(y) and x != y for x, y in sides pd.notna(x) and pd.notna(y) and x != y for x, y in sides
): ):
return None return None
reason = reasons[int(r.match_key)] if not reasons[int(r.match_key)].endswith("typo apart"):
if not reason.endswith("typo apart"):
return a, b 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: if a in orphan and b in lone:
return a, b return a, b
if b in orphan and a in lone: if b in orphan and a in lone:
@@ -522,10 +424,6 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
for node in pipeline.order(): for node in pipeline.order():
if node.kind == "target": if node.kind == "target":
run_target(pipeline_id, node, kinds) run_target(pipeline_id, node, kinds)
elif node.kind == "route" and node.otherwise:
others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id
and n.inputs == node.inputs and not n.otherwise] # fmt: skip
run_route(pipeline_id, node, others)
else: else:
RUNNERS[node.kind](pipeline_id, node) RUNNERS[node.kind](pipeline_id, node)
log(f"{node.id} ({node.kind}) done") log(f"{node.id} ({node.kind}) done")
+2 -9
View File
@@ -220,9 +220,7 @@ class IntervalSurvival(BaseEstimator):
# ---------------------------------------------------------------- a model over gold timelines # ---------------------------------------------------------------- a model over gold timelines
TRAIN_FRACTION = 0.7 TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high", OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
"scenarios"] # fmt: skip
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]: def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
@@ -326,17 +324,13 @@ class Spec:
return model, metrics, {"train": train, "test": test} return model, metrics, {"train": train, "test": test}
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame: def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member and horizon: her mortality by it, its interval when kept, and """One row per member and horizon: her mortality by it, and its interval when kept."""
the clinical scenarios of the report she falls in (the curves her record draws)."""
members = self.members(events) members = self.members(events)
mortality = 1.0 - model.survival(members) mortality = 1.0 - model.survival(members)
n, h = len(members), len(self.horizons) n, h = len(members), len(self.horizons)
empty = ([np.nan] * h, [np.nan] * h) empty = ([np.nan] * h, [np.nan] * h)
ends = [model.intervals_.get(tuple(c), empty) ends = [model.intervals_.get(tuple(c), empty)
for c in self._combinations(members).itertuples(index=False)] # fmt: skip for c in self._combinations(members).itertuples(index=False)] # fmt: skip
masks = scenario_masks(members, self.scenarios)
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
for i in range(n)] # fmt: skip
return pd.DataFrame({ return pd.DataFrame({
"person_id": np.repeat(members["person_id"].to_numpy(), h), "person_id": np.repeat(members["person_id"].to_numpy(), h),
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h), "index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
@@ -344,7 +338,6 @@ class Spec:
"probability": mortality.ravel(), "probability": mortality.ravel(),
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(), "ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(), "ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
})[OUTPUT] # fmt: skip })[OUTPUT] # fmt: skip
+10 -8
View File
@@ -8,11 +8,12 @@ mains, with the table's age) in worker processes; `tables` gives each scenario's
from the valid studies. from the valid studies.
""" """
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path from pathlib import Path
import pandas as pd import pandas as pd
from models import cluster
from models.tea.eeg.analysis import analyze from models.tea.eeg.analysis import analyze
from models.tea.eeg.curves import SCENARIOS from models.tea.eeg.curves import SCENARIOS
@@ -33,8 +34,9 @@ def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path,
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)] return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
def _one(key: str, edf: bytes, age: float) -> dict: def _one(study: tuple[str, Path, float]) -> dict:
a = analyze(edf, age_months=age, mains_hz=MAINS_HZ) key, path, age = study
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=MAINS_HZ)
return { return {
"key": key, "key": key,
"age_months": age, "age_months": age,
@@ -44,11 +46,11 @@ def _one(key: str, edf: bytes, age: float) -> dict:
} }
def measure(studies) -> list[dict]: def measure(studies, workers: int = 4) -> list[dict]:
"""Each study's verdict and features, in listing order, each a task on the cluster """Each study's verdict and features, in listing order."""
(models.cluster).""" context = multiprocessing.get_context("spawn")
# each task carries its recording: workers see no local folder with ProcessPoolExecutor(workers, mp_context=context) as pool:
return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies)) return list(pool.map(_one, studies))
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]: def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
+10 -6
View File
@@ -15,8 +15,9 @@ from pathlib import Path
import mlflow.pyfunc import mlflow.pyfunc
import pandas as pd import pandas as pd
from joblib import Parallel, delayed
from joblib.externals.loky import get_reusable_executor
from models import cluster
from models.tea.eeg import analysis, curves, reference from models.tea.eeg import analysis, curves, reference
from persistance import eeg, registry, silver from persistance import eeg, registry, silver
@@ -39,13 +40,16 @@ class Baseline(mlflow.pyfunc.PythonModel):
for r in rows]) # fmt: skip for r in rows]) # fmt: skip
def _analyze(edf: str, birth) -> tuple[str, analysis.Analysis]:
return edf, analysis.analyze(eeg.signal(edf), birth)
def analyze() -> int: def analyze() -> int:
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt.""" """Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
pending = eeg.pending() pending = eeg.pending()
done = cluster.run( found = dict(Parallel(n_jobs=-1)(delayed(_analyze)(r["edf"], r["birth_date"])
analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending) for r in pending)) # fmt: skip
) # one task per EEG get_reusable_executor().shutdown(wait=True)
found = dict(zip((r["edf"] for r in pending), done, strict=True))
eeg.save_analyses(found) eeg.save_analyses(found)
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"]) silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
return len(found) return len(found)
@@ -61,7 +65,7 @@ def _reference() -> tuple[str, list[dict]]:
path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None
if path and path.exists(): if path and path.exists():
return digest, json.loads(path.read_text()) return digest, json.loads(path.read_text())
measured = reference.measure(studies) measured = reference.measure(studies, workers=os.cpu_count() or 4)
measured = [{**m, "key": str(m["key"])} for m in measured] measured = [{**m, "key": str(m["key"])} for m in measured]
if path: if path:
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
-6
View File
@@ -11,10 +11,8 @@ 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",
"pdfplumber>=0.11.11", "pdfplumber>=0.11.11",
"scikit-learn>=1.9.1", "scikit-learn>=1.9.1",
"scipy>=1.18.1", "scipy>=1.18.1",
@@ -26,10 +24,6 @@ dependencies = [
"pgmpy>=1.1.2", "pgmpy>=1.1.2",
] ]
[project.optional-dependencies]
# Where a Dask cluster runs the long batches (testing here); the product runs without it.
dask = ["dask[distributed]>=2026.8.0,<2026.9"] # as the testing cluster runs
[build-system] [build-system]
requires = ["uv_build>=0.12,<0.13"] requires = ["uv_build>=0.12,<0.13"]
build-backend = "uv_build" build-backend = "uv_build"
+1 -1
View File
@@ -263,7 +263,7 @@ def test_metric_values(analyses):
def _measure_reference(): def _measure_reference():
studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv") studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv")
measured = reference.measure(studies) measured = reference.measure(studies, WORKERS)
CACHE.parent.mkdir(parents=True, exist_ok=True) CACHE.parent.mkdir(parents=True, exist_ok=True)
CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured})) CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured}))
return measured return measured
+18 -6
View File
@@ -27,8 +27,15 @@ def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> di
return { return {
"nodes": nodes "nodes": nodes
+ [ + [
table("resultados", site_url, "ResultadoSubrogado", schema="dbo"), table("archivos", site_url, "ArchivosUni", schema="dbo"),
{"id": "text", "kind": "read", "inputs": ["resultados"], "column": "archivo"}, 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 = {} by_place = {}
for r in truth: for r in truth:
by_place.setdefault(r["where"].split(":")[0], []).append(r) by_place.setdefault(r["where"].split(":")[0], []).append(r)
documents = len(truth) documents = len(by_place["ArchivosUni"]) + len(by_place["ResultadosSubrogados"])
expected = {"resultados": documents, "text": documents} 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(): for name, names in tables.items():
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con: with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
for t in names: 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",)] assert query(corrected) == [("64000",)]
space = re.compile(r"\s+") space = re.compile(r"\s+")
for table in ("ResultadoSubrogado",): for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")):
read = query("select id, text, ocr, error from bronze.n__site__text") 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] == [] assert [error for *_, error in read if error is not None] == []
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read} by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
for r in by_place[table]: for r in by_place[table]:
+42 -44
View File
@@ -2,12 +2,10 @@
can trust, and everything the platform can't decide alone is put in front of a reviewer. 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 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 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 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. 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, neurology's), death notes and TEA's
M-CHAT, ADOS-2 and EEG reports are the institute's forms.
""" """
import json import json
@@ -16,23 +14,38 @@ from datetime import date
from core import catalog from core import catalog
ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number") 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 = { FIELDS = {
"cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16", "cervical_cytology": ("sample_date", "screening_history", *GYN, *PRESENTS,
"hpv_18"), "cervix_exam", "report_date", "adequacy", "result", "hpv", "hpv_16",
"hpv_18", "cyto_findings_text", *CYTO),
"cervical_biopsy": ("request_date", "report_date", "histology"), "cervical_biopsy": ("request_date", "report_date", "histology"),
"mammography": ("exam_date", "report_date", "adequacy", "birads"), "mammography": ("exam_date", "report_date", "adequacy", "birads"),
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade", "breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
"er", "pr", "her2", "ki67_pct", "size_mm", "stage"), "er", "pr", "her2", "ki67_pct", "size_mm", "stage"),
"breast_treatment": ("start_date", "kind"), "breast_treatment": ("start_date", "kind"),
"clinical_note": ("note_date", "specialty", "icd10"), "clinical_note": ("note_date", "specialty", "icd10"),
"death": ("death_date",),
"mchat": ("screening_date", "score"),
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
"eeg": ("study_date", "lab_record_id", "edf"),
} # fmt: skip } # fmt: skip
BOOLS = {"hpv", "hpv_16", "hpv_18"} BOOLS = {"hpv", "hpv_16", "hpv_18", *GYN, *PRESENTS, *CYTO}
NUMBERS = {"ki67_pct", "size_mm", "score", *ADOS2_SCORES} NUMBERS = {"ki67_pct", "size_mm"}
def value(field, v): def value(field, v):
@@ -64,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 # 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 # by a pathology report (it shows no birth date) and held (torn) until a reviewer says
# whose report it is. # 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] = {} members: dict[str, set] = {}
held, nameless, named, person_of = set(), set(), set(), {} held, person_of = set(), {}
for record, person, why, *identifiers in q( for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
"select _record, person_id, _held, full_name, birth_date, record_number "
"from bronze.n__site__persons"
):
members.setdefault(person, set()).add(of[record]) members.setdefault(person, set()).add(of[record])
person_of[record] = person person_of[record] = person
if any(identifiers): if why:
named.add(person)
if why and "no name" in why:
nameless.add(person)
elif why:
held.add(person) held.add(person)
assert nameless == set(members) - named, nameless
torn = {p for p, who in members.items() if len(who) > 1} torn = {p for p, who in members.items() if len(who) > 1}
assert len(torn) == 1 and torn == held, (torn, held) assert len(torn) == 1 and torn == held, (torn, held)
assert members[next(iter(torn))] == set(site.meta["namesakes"]) 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 # Every woman split into several persons (a misspelled form, say) is in the review
# queue, joined by candidates. # queue, joined by candidates.
@@ -105,14 +108,15 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
frontier -= reached frontier -= reached
assert persons <= reached, (x, persons) assert persons <= reached, (x, persons)
# Every value accepted from a typed document is what the document says; and most of what # Every value accepted from a document is what the document says; and most of what the
# the documents say is read (a scan's columns can come back out of order, and a value its # 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 # pattern doesn't find is left out, never guessed).
# another ("IIA" as "IA"), which nothing in the text betrays: at most 1% of a scan's
# values (one, on a site too small for a rate), each listed.
at = {r["where"]: r for r in truth} at = {r["where"]: r for r in truth}
place = {r: f"ResultadoSubrogado:{i}" place = {
for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip 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()} record_of = {w: r for r, w in place.items()}
accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows) accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows)
for entity in FIELDS: for entity in FIELDS:
@@ -124,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) got = next((v for v in values if v is not None), None)
mine.setdefault(record, {})[field] = value(field, got) mine.setdefault(record, {})[field] = value(field, got)
assert mine, entity assert mine, entity
stated = read = scanned = 0 stated = read = 0
missed: Counter = Counter() missed: Counter = Counter()
wrong = []
for record, got in mine.items(): for record, got in mine.items():
t = at[place[record]] t = at[place[record]]
if not t.get("flipped"): if not t.get("flipped"):
truly = {f: v for f, v in said(t, entity).items() if v is not None} 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() assert got == {f: value(f, truly.get(f)) for f in got}, (t["where"], got)
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) stated, read = stated + len(truly), read + len(got)
missed.update(set(truly) - set(got)) missed.update(set(truly) - set(got))
assert read >= 0.95 * stated, (entity, read, stated, missed) assert read >= 0.95 * stated, (entity, read, stated, missed)
assert len(wrong) <= max(1, 0.01 * scanned), (entity, wrong)
# A row a rule held because of a value (a scan misread) is held because it is 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. # never loaded, and a reviewer sees it.
misread = set() misread = set()
for record, entity, raw in q("select _record, study, _raw from bronze.staged__held"): 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) t, got = at[place[record]], json.loads(raw)
truly = said(t, entity) truly = said(t, entity)
assert {f: value(f, got.get(f)) for f in truly} != { assert {f: value(f, got.get(f)) for f in truly} != {
@@ -162,7 +160,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
for r in truth: for r in truth:
record = record_of[r["where"]] record = record_of[r["where"]]
got = accepted[entity].get(record) 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 continue
at_key = (person_of[record], *(got.get(k) for k in key)) at_key = (person_of[record], *(got.get(k) for k in key))
merged.setdefault(at_key, {}).update(got) merged.setdefault(at_key, {}).update(got)
@@ -172,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 for k, row in merged.items() if k not in disputed} # fmt: skip
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}") 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))) 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], assert got == expected, (entity, sorted(got - expected, key=str)[:4],
sorted(expected - got, key=str)[:4]) # fmt: skip sorted(expected - got, key=str)[:4]) # fmt: skip