diff --git a/models/cluster.py b/models/cluster.py new file mode 100644 index 0000000..b9055cc --- /dev/null +++ b/models/cluster.py @@ -0,0 +1,39 @@ +"""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, through joblib's own +Dask backend. Without it (the product) joblib runs them on local processes. BATCH_JOBS caps +how many run at once (each task carries its recording: a cap paces a slow link).""" + +import os +from collections.abc import Iterator +from contextlib import contextmanager +from importlib.util import find_spec + +from joblib import parallel_config +from joblib.externals.loky import get_reusable_executor + + +def jobs() -> int: + """How many tasks run at once: BATCH_JOBS, or every core (or worker).""" + return int(os.environ.get("BATCH_JOBS", "-1")) + + +@contextmanager +def batch() -> Iterator[None]: + if find_spec("distributed") is None: + try: + yield + finally: # the local workers go when the batch is done + get_reusable_executor().shutdown(wait=True) + return + from distributed import Client, LocalCluster + + 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), parallel_config(backend="dask"): + yield + finally: + if not address: + where.close() diff --git a/models/graph.py b/models/graph.py index 1d88c31..ba27b9a 100644 --- a/models/graph.py +++ b/models/graph.py @@ -50,9 +50,22 @@ READ_COLUMNS = { # declared, so a load where every file read cleanly still has "text": {"data_type": "text", "nullable": True}, "ocr": {"data_type": "bool"}, "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 def _reader() -> MarkItDown: return MarkItDown() @@ -73,7 +86,15 @@ def _text(content: bytes) -> str: def read_file(content: bytes) -> dict: - """Text of one file, and whether OCR was needed. An unreadable file keeps its error.""" + """Text of one file, its format, and whether OCR was needed. An unreadable file keeps + 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: try: found = _text(content) ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS @@ -91,12 +112,19 @@ def read_file(content: bytes) -> dict: def run_read(p: str, node: Read): - """The input's rows with the file column replaced by its text; each file read once.""" + """The input's rows with their file's text and format beside the file column (which + 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])) for row in rows: # the source kept the file; the row carries its hash - row["key"] = row.pop(node.column) or None + row["key"] = row.get(node.column) or None keys = {r["key"] for r in rows} - {None} found = nodes.cached("read_cache", keys) + legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats + for k in legacy: + found[k]["format"] = file_format(files.content(k) or b"") + nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}} + for k in legacy], READ_COLUMNS) # fmt: skip new = {k: files.content(k) for k in keys - set(found)} with ProcessPoolExecutor() as pool: read = dict(zip(new, pool.map(read_file, new.values()), strict=True)) @@ -191,8 +219,9 @@ def run_extract(p: str, node: Extract): found = apply_patterns(node, text, codes) else: 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"])]): - out.append({**values, RECORD: row[RECORD], "_index": index, + out.append({**values, **taken, RECORD: row[RECORD], "_index": index, QUOTES: json.dumps(quotes, ensure_ascii=False), HELD: json.dumps(held) if held else None}) # fmt: skip return nodes.write(p, node.id, out) diff --git a/models/tea/eeg/reference.py b/models/tea/eeg/reference.py index 67d92b6..738c06f 100644 --- a/models/tea/eeg/reference.py +++ b/models/tea/eeg/reference.py @@ -8,12 +8,12 @@ mains, with the table's age) in worker processes; `tables` gives each scenario's from the valid studies. """ -import multiprocessing -from concurrent.futures import ProcessPoolExecutor from pathlib import Path import pandas as pd +from joblib import Parallel, delayed +from models import cluster from models.tea.eeg.analysis import analyze from models.tea.eeg.curves import SCENARIOS @@ -34,9 +34,8 @@ 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)] -def _one(study: tuple[str, Path, float]) -> dict: - key, path, age = study - a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=MAINS_HZ) +def _one(key: str, edf: bytes, age: float) -> dict: + a = analyze(edf, age_months=age, mains_hz=MAINS_HZ) return { "key": key, "age_months": age, @@ -46,11 +45,12 @@ def _one(study: tuple[str, Path, float]) -> dict: } -def measure(studies, workers: int = 4) -> list[dict]: - """Each study's verdict and features, in listing order.""" - context = multiprocessing.get_context("spawn") - with ProcessPoolExecutor(workers, mp_context=context) as pool: - return list(pool.map(_one, studies)) +def measure(studies) -> list[dict]: + """Each study's verdict and features, in listing order, each a task on the cluster + (models.cluster).""" + with cluster.batch(): # each task carries its recording: workers see no local folder + return Parallel(n_jobs=cluster.jobs())(delayed(_one)(key, Path(path).read_bytes(), age) + for key, path, age in studies) # fmt: skip def tables(measured: list[dict]) -> dict[str, pd.DataFrame]: diff --git a/models/tea/jobs.py b/models/tea/jobs.py index e306dc5..f886240 100644 --- a/models/tea/jobs.py +++ b/models/tea/jobs.py @@ -16,8 +16,8 @@ from pathlib import Path import mlflow.pyfunc 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 persistance import eeg, registry, silver @@ -40,16 +40,14 @@ class Baseline(mlflow.pyfunc.PythonModel): 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: """Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt.""" pending = eeg.pending() - found = dict(Parallel(n_jobs=-1)(delayed(_analyze)(r["edf"], r["birth_date"]) - for r in pending)) # fmt: skip - get_reusable_executor().shutdown(wait=True) + with cluster.batch(): # one task per EEG, carrying its recording (models.cluster) + tasks = (delayed(analysis.analyze)(eeg.signal(r["edf"]), r["birth_date"]) + for r in pending) # fmt: skip + done = Parallel(n_jobs=cluster.jobs())(tasks) + found = dict(zip((r["edf"] for r in pending), done, strict=True)) eeg.save_analyses(found) silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"]) return len(found) @@ -65,7 +63,7 @@ def _reference() -> tuple[str, list[dict]]: path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None if path and path.exists(): return digest, json.loads(path.read_text()) - measured = reference.measure(studies, workers=os.cpu_count() or 4) + measured = reference.measure(studies) measured = [{**m, "key": str(m["key"])} for m in measured] if path: path.parent.mkdir(parents=True, exist_ok=True) diff --git a/pyproject.toml b/pyproject.toml index 744a4ea..4bab10c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,10 @@ dependencies = [ "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] requires = ["uv_build>=0.12,<0.13"] build-backend = "uv_build" diff --git a/tests/test_eeg.py b/tests/test_eeg.py index c94fc0a..ddabc6e 100644 --- a/tests/test_eeg.py +++ b/tests/test_eeg.py @@ -263,7 +263,7 @@ def test_metric_values(analyses): def _measure_reference(): studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv") - measured = reference.measure(studies, WORKERS) + measured = reference.measure(studies) CACHE.parent.mkdir(parents=True, exist_ok=True) CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured})) return measured diff --git a/tests/test_silver.py b/tests/test_silver.py index 33d1cb1..0017b39 100644 --- a/tests/test_silver.py +++ b/tests/test_silver.py @@ -6,7 +6,8 @@ one SQL Server table, the institute's forms beside what outsourced labs send bac 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. +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 @@ -15,6 +16,7 @@ from datetime import date from core import catalog +ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number") FIELDS = { "cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16", "hpv_18"), @@ -25,9 +27,12 @@ FIELDS = { "breast_treatment": ("start_date", "kind"), "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 BOOLS = {"hpv", "hpv_16", "hpv_18"} -NUMBERS = {"ki67_pct", "size_mm"} +NUMBERS = {"ki67_pct", "size_mm", "score", *ADOS2_SCORES} def value(field, v): @@ -104,7 +109,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path # 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. + # values (one, on a site too small for a rate), each listed. 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 @@ -134,7 +139,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path 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) + 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: # never loaded, and a reviewer sees it.