Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e71a7baac5 | |||
| 8c910e7500 | |||
| 0b4f7593e5 | |||
| c6c55e0ffe | |||
| 3950b3c1f5 | |||
| b7eaf7055d | |||
| 9ed686e87a | |||
| dce0e0c690 | |||
| d954faa28e | |||
| cc95054a96 | |||
| 9220b8c52c | |||
| 3546269eaf | |||
| 7b9ae69de2 | |||
| 4ff4a3a7d8 |
@@ -80,6 +80,9 @@ class Pim:
|
||||
found = {
|
||||
"n_train": len(train),
|
||||
"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_,
|
||||
"converged": float(mixture.converged_),
|
||||
}
|
||||
@@ -139,6 +142,8 @@ class Logistic:
|
||||
metrics = {
|
||||
"n_train": len(train),
|
||||
"n_test": len(test),
|
||||
"events_train": float(train["y"].sum()),
|
||||
"events_test": float(test["y"].sum()),
|
||||
"auc": float(roc_auc_score(test["y"], p)),
|
||||
"brier": float(brier_score_loss(test["y"], p)),
|
||||
"positive_rate_train": float(train["y"].mean()),
|
||||
|
||||
+208
-12
@@ -1,17 +1,47 @@
|
||||
"""Dagster code location: every heavy step of the platform is a job defined here."""
|
||||
|
||||
import hashlib
|
||||
import importlib
|
||||
import inspect
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
|
||||
import dagster as dg
|
||||
|
||||
from models import graph
|
||||
from core.domains import Domain
|
||||
from models import execution, graph
|
||||
from models.jobs import EmptyCohort
|
||||
from persistance import config_log, silver
|
||||
from models.tea import jobs as tea_jobs
|
||||
from models.tea import preview as tea_preview_analysis
|
||||
from persistance import bundle, cluster, config_log, eeg, previews, silver
|
||||
|
||||
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
|
||||
|
||||
|
||||
class ExecutionConfig(dg.Config):
|
||||
"""Where a heavy op's work runs: the fields of `persistance.cluster.Execution`."""
|
||||
|
||||
mode: str | None = None # Dagster's config has no Literal: `model()` checks it
|
||||
scheduler: str | None = None
|
||||
|
||||
def model(self) -> cluster.Execution:
|
||||
return cluster.Execution(**self.model_dump())
|
||||
|
||||
|
||||
class ScopeConfig(dg.Config):
|
||||
"""Which EEGs an analysis takes: the fields of `persistance.eeg.Scope`."""
|
||||
|
||||
mode: str = "pending" # Dagster's config has no Literal: `model()` checks it
|
||||
n: int | None = None
|
||||
ids: list[str] = []
|
||||
|
||||
def model(self) -> eeg.Scope:
|
||||
return eeg.Scope(**self.model_dump()) # validates
|
||||
|
||||
|
||||
class PipelineRun(dg.Config):
|
||||
pipeline: str
|
||||
version: int | None = None # default: the latest saved
|
||||
@@ -39,10 +69,20 @@ def _jobs(domain: str):
|
||||
raise ValueError(f"{domain} has no models") from e
|
||||
|
||||
|
||||
class ReferenceConfig(dg.Config):
|
||||
name: str
|
||||
line_hz: int = 50
|
||||
|
||||
def model(self) -> cluster.Reference:
|
||||
return cluster.Reference(**self.model_dump())
|
||||
|
||||
|
||||
class Training(dg.Config):
|
||||
domain: str
|
||||
models: list[str] = [] # default: every model of the domain but the slow ones
|
||||
as_of: str | None = None # the date the data are taken up to (default: today)
|
||||
execution: ExecutionConfig = ExecutionConfig()
|
||||
reference: ReferenceConfig | None = None
|
||||
|
||||
|
||||
@dg.op
|
||||
@@ -50,15 +90,21 @@ def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
|
||||
"""A new registered version of each model (MLflow), with its reports."""
|
||||
jobs = _jobs(config.domain)
|
||||
as_of = date.fromisoformat(config.as_of) if config.as_of else None
|
||||
options = {}
|
||||
if config.reference is not None:
|
||||
if "reference" not in inspect.signature(jobs.train).parameters:
|
||||
raise ValueError(f"{config.domain} models take no reference cohort")
|
||||
options["reference"] = config.reference.model()
|
||||
found = {}
|
||||
for name in config.models or jobs.JOBS.routine():
|
||||
try:
|
||||
found[name] = jobs.train(name, as_of)
|
||||
except EmptyCohort as e: # the site has no such patients; the others still train
|
||||
found[name] = None
|
||||
context.log.warning(f"{e}: not trained")
|
||||
continue
|
||||
context.log.info(f"{config.domain}.{name}: version {found[name]}")
|
||||
with execution.running(context, config.execution.model()):
|
||||
for name in config.models or jobs.JOBS.routine():
|
||||
try:
|
||||
found[name] = jobs.train(name, as_of, **options)
|
||||
except EmptyCohort as e: # the site has no such patients; the others still train
|
||||
found[name] = None
|
||||
context.log.warning(f"{e}: not trained")
|
||||
continue
|
||||
context.log.info(f"{config.domain}.{name}: version {found[name]}")
|
||||
return found
|
||||
|
||||
|
||||
@@ -90,12 +136,14 @@ def score():
|
||||
|
||||
class Analysis(dg.Config):
|
||||
domain: str
|
||||
execution: ExecutionConfig = ExecutionConfig()
|
||||
|
||||
|
||||
@dg.op
|
||||
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
|
||||
"""The domain's studies a model reads whole (TEA: each EEG not analysed yet)."""
|
||||
found = _jobs(config.domain).analyze()
|
||||
with execution.running(context, config.execution.model()):
|
||||
found = _jobs(config.domain).analyze()
|
||||
context.log.info(f"{config.domain}: {found} analysed")
|
||||
return found
|
||||
|
||||
@@ -105,4 +153,152 @@ def analyze():
|
||||
analyze_studies()
|
||||
|
||||
|
||||
defs = dg.Definitions(jobs=[ingest, train, score, analyze])
|
||||
class TeaAnalysis(dg.Config):
|
||||
scope: ScopeConfig = ScopeConfig()
|
||||
execution: ExecutionConfig = ExecutionConfig()
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_analyze_studies(context: dg.OpExecutionContext, config: TeaAnalysis) -> dict:
|
||||
"""The EEGs in scope, analysed in the chosen execution. Bronze is written after the last
|
||||
study, so a cancel during the analysis leaves it as it was."""
|
||||
with execution.running(context, config.execution.model()):
|
||||
found = tea_jobs.analyze(config.scope.model(), rebuild_gold=False)
|
||||
context.log.info(f"{found} EEGs analysed (scope {config.scope.mode})")
|
||||
return {"analysed": found}
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_score_curves(context: dg.OpExecutionContext, analysed: dict) -> dict:
|
||||
"""Each age curve's champion scores every analysed EEG."""
|
||||
found = tea_jobs.score_curves()
|
||||
for name, version in found.items():
|
||||
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
|
||||
return {"scored": found}
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_relate_ados2(context: dg.OpExecutionContext, scored: dict) -> dict:
|
||||
"""The ADOS-2 association champion scores the EEGs (a seam: nothing until Phase 2)."""
|
||||
version = tea_jobs.relate()
|
||||
context.log.info("ados2_association: " + (f"version {version}" if version else "no champion"))
|
||||
return {"ados2_association": version}
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_build_gold(context: dg.OpExecutionContext, related: dict) -> dict:
|
||||
"""Gold's TEA tables rebuilt from bronze. A cancel here stops dbt between models, so gold
|
||||
may be partly rebuilt until the next successful run (dbt replaces each model whole)."""
|
||||
silver.build(tea_jobs.GOLD_SELECT)
|
||||
context.log.info("gold rebuilt")
|
||||
return {"built": tea_jobs.GOLD_SELECT}
|
||||
|
||||
|
||||
class Preview(dg.Config):
|
||||
edf: str
|
||||
ados2: str | None = None
|
||||
birth_date: str | None = None
|
||||
pipeline: str = "tea"
|
||||
|
||||
|
||||
@dg.op
|
||||
def preview_study(context: dg.OpExecutionContext, config: Preview) -> dict:
|
||||
try:
|
||||
previews.sweep()
|
||||
result = tea_preview_analysis.preview(
|
||||
previews.get(config.edf),
|
||||
previews.get(config.ados2) if config.ados2 else None,
|
||||
date.fromisoformat(config.birth_date) if config.birth_date else None,
|
||||
config.pipeline,
|
||||
)
|
||||
context.add_output_metadata(
|
||||
{"result": dg.MetadataValue.json(json.loads(result.model_dump_json()))}
|
||||
)
|
||||
for warning in result.warnings:
|
||||
context.log.warning(warning)
|
||||
return {"valid": result.eeg.valid, "warnings": len(result.warnings)}
|
||||
finally:
|
||||
previews.discard([config.edf, config.ados2])
|
||||
|
||||
|
||||
@dg.job(tags={"domain": "tea"})
|
||||
def tea_preview():
|
||||
preview_study()
|
||||
|
||||
|
||||
@dg.job(tags={**WRITES, "domain": "tea"})
|
||||
def tea_eeg():
|
||||
"""Analyse the EEGs in scope, score the age curves, relate ADOS-2, rebuild gold."""
|
||||
tea_build_gold(tea_relate_ados2(tea_score_curves(tea_analyze_studies())))
|
||||
|
||||
|
||||
def pending_eegs() -> bool:
|
||||
return bool(eeg.pending())
|
||||
|
||||
|
||||
def after_ingest(run_id: str, has_pending: Callable[[], bool]) -> dg.RunRequest | dg.SkipReason:
|
||||
"""A `tea_eeg` run for an ingest that left EEGs to analyse; otherwise a skip."""
|
||||
if not has_pending():
|
||||
return dg.SkipReason("the ingest brought no EEG to analyse")
|
||||
return dg.RunRequest(
|
||||
run_key=f"after-ingest-{run_id}",
|
||||
run_config={"ops": {"tea_analyze_studies": {"config": {"scope": {"mode": "pending"}}}}},
|
||||
tags={"domain": "tea", "triggered_by": run_id},
|
||||
)
|
||||
|
||||
|
||||
@dg.run_status_sensor(
|
||||
name="tea_eeg_after_ingest",
|
||||
run_status=dg.DagsterRunStatus.SUCCESS,
|
||||
monitored_jobs=[ingest],
|
||||
request_job=tea_eeg,
|
||||
minimum_interval_seconds=10,
|
||||
default_status=dg.DefaultSensorStatus.RUNNING,
|
||||
)
|
||||
def tea_eeg_after_ingest(context: dg.RunStatusSensorContext):
|
||||
return after_ingest(context.dagster_run.run_id, pending_eegs)
|
||||
|
||||
|
||||
class BundleImport(dg.Config):
|
||||
domain: str
|
||||
sha256: str
|
||||
|
||||
|
||||
@dg.op
|
||||
def import_bundle_files(context: dg.OpExecutionContext, config: BundleImport) -> dict:
|
||||
path = bundle.staged(config.sha256)
|
||||
try:
|
||||
data = path.read_bytes()
|
||||
if hashlib.sha256(data).hexdigest() != config.sha256:
|
||||
raise bundle.BundleError("the staged file's SHA-256 does not match the run config")
|
||||
result = bundle.import_(Domain(config.domain), data)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
||||
manifest = json.loads(archive.read(bundle.MANIFEST))
|
||||
skipped = set(result.skipped)
|
||||
sources = sorted(
|
||||
(item["name"], item["version"])
|
||||
for item in manifest["versions"]
|
||||
if (item["name"], item["version"]) not in skipped
|
||||
)
|
||||
for (_, source), (name, version) in zip(sources, result.imported, strict=True):
|
||||
context.log.info(f"{name}: source v{source} -> version {version}")
|
||||
for name, version in result.skipped:
|
||||
context.log.warning(f"{name} v{version}: already registered, skipped")
|
||||
return {
|
||||
"imported": [list(item) for item in result.imported],
|
||||
"skipped": [list(item) for item in result.skipped],
|
||||
}
|
||||
|
||||
|
||||
@dg.job
|
||||
def import_bundle():
|
||||
import_bundle_files()
|
||||
|
||||
|
||||
defs = dg.Definitions(
|
||||
jobs=[ingest, train, score, analyze, tea_eeg, tea_preview, import_bundle],
|
||||
sensors=[tea_eeg_after_ingest],
|
||||
)
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
"""The one way a heavy op spreads work over cores or machines: `map(fn, items)` returns the
|
||||
results in input order whatever the mode (in this process, on local worker processes, on a
|
||||
remote Dask scheduler). While it runs, a monitor thread reports progress: a JSON run tag the
|
||||
API reads at once (Dagster shows op metadata only when the op returns, so the tag is the live
|
||||
channel) and one throttled log line per tenth of the work. Ops never touch Dask themselves.
|
||||
|
||||
`with running(context, execution):` makes a Dagster op's context the ambient one, so that
|
||||
`map` calls inside the block report on that run, share one cluster, and leave a summary in the
|
||||
op's output metadata."""
|
||||
|
||||
import contextvars
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable, Iterable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from datetime import UTC, datetime
|
||||
from itertools import islice
|
||||
|
||||
import dagster as dg
|
||||
import psutil
|
||||
|
||||
from persistance import cluster
|
||||
from persistance.cluster import (
|
||||
PROGRESS_TAG,
|
||||
ClusterVersionError,
|
||||
Execution,
|
||||
ExecutionError,
|
||||
Health,
|
||||
Options,
|
||||
Progress,
|
||||
Resolved,
|
||||
Tasks,
|
||||
Worker,
|
||||
health,
|
||||
options,
|
||||
resolve,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ClusterVersionError",
|
||||
"Execution",
|
||||
"ExecutionError",
|
||||
"Health",
|
||||
"Options",
|
||||
"Progress",
|
||||
"Resolved",
|
||||
"health",
|
||||
"map",
|
||||
"options",
|
||||
"resolve",
|
||||
"running",
|
||||
]
|
||||
|
||||
SAMPLE_S = 2.0
|
||||
_SINGLE_THREAD = {
|
||||
"OMP_NUM_THREADS": "1",
|
||||
"OPENBLAS_NUM_THREADS": "1",
|
||||
"MKL_NUM_THREADS": "1",
|
||||
}
|
||||
|
||||
|
||||
class Eta:
|
||||
"""Seconds left, from an exponentially smoothed rate of items per second."""
|
||||
|
||||
def __init__(self, alpha: float = 0.3, min_done: int = 3):
|
||||
self.alpha, self.min_done = alpha, min_done
|
||||
self.rate: float | None = None
|
||||
self._last: tuple[float, int] | None = None
|
||||
|
||||
def update(self, elapsed_s: float, done: int) -> None:
|
||||
last, self._last = self._last, (elapsed_s, done)
|
||||
if last is None or elapsed_s <= last[0]:
|
||||
return
|
||||
rate = (done - last[1]) / (elapsed_s - last[0])
|
||||
self.rate = rate if self.rate is None else self.alpha * rate + (1 - self.alpha) * self.rate
|
||||
|
||||
def eta_s(self, total: int) -> float | None:
|
||||
done = self._last[1] if self._last else 0
|
||||
if done < self.min_done or not self.rate or self.rate <= 0:
|
||||
return None
|
||||
return max(0, total - done) / self.rate
|
||||
|
||||
|
||||
class _Ambient:
|
||||
"""What `running` shares with the `map` calls in its block."""
|
||||
|
||||
def __init__(self, context, execution: Execution | None):
|
||||
self.context, self.execution = context, execution
|
||||
self.client = None
|
||||
self.cluster = None
|
||||
self.phases: list[dict] = []
|
||||
self.peak_cpu_pct = 0.0
|
||||
self.peak_memory_bytes = 0
|
||||
|
||||
def close(self) -> None:
|
||||
_close(self.client, self.cluster)
|
||||
self.client = self.cluster = None
|
||||
|
||||
|
||||
_ambient: contextvars.ContextVar[_Ambient | None] = contextvars.ContextVar(
|
||||
"execution_ambient", default=None
|
||||
)
|
||||
|
||||
|
||||
def _close(client, local_cluster) -> None:
|
||||
"""Close what this module opened; a remote scheduler is only disconnected from."""
|
||||
for closable in (client, local_cluster):
|
||||
if closable is not None:
|
||||
try:
|
||||
closable.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _counts(dask_scheduler) -> dict:
|
||||
"""Run on the scheduler: how many tasks are in each state."""
|
||||
counts: dict = {}
|
||||
for task in dask_scheduler.tasks.values():
|
||||
counts[task.state] = counts.get(task.state, 0) + 1
|
||||
return counts
|
||||
|
||||
|
||||
def _connect(resolved: Resolved, workers: int | None):
|
||||
"""A client on the chosen Dask cluster and the local cluster it started, if any."""
|
||||
from distributed import Client, LocalCluster
|
||||
|
||||
if resolved.mode == "local":
|
||||
local = LocalCluster(
|
||||
n_workers=cluster.local_workers(workers),
|
||||
threads_per_worker=1,
|
||||
processes=True,
|
||||
memory_limit=cluster.memory_per_worker(),
|
||||
dashboard_address=None,
|
||||
env=_SINGLE_THREAD,
|
||||
)
|
||||
try:
|
||||
return Client(local), local
|
||||
except BaseException:
|
||||
_close(None, local)
|
||||
raise
|
||||
try:
|
||||
client = Client(resolved.scheduler, timeout=10)
|
||||
except Exception as e:
|
||||
raise ExecutionError(f"cannot reach the Dask scheduler {resolved.scheduler}: {e}") from e
|
||||
detail = cluster.versions_error(client)
|
||||
if detail is not None:
|
||||
_close(client, None)
|
||||
raise ClusterVersionError(
|
||||
f"Dask workers differ from this server: {detail}. "
|
||||
"Rebuild the worker image from the same commit."
|
||||
)
|
||||
return client, None
|
||||
|
||||
|
||||
class _Monitor:
|
||||
"""Samples one `map` every `SAMPLE_S` seconds and reports it."""
|
||||
|
||||
def __init__(self, ambient, resolved, phase, total, log, client):
|
||||
self.ambient, self.resolved, self.phase = ambient, resolved, phase
|
||||
self.total, self.log, self.client = total, log, client
|
||||
self.done = 0
|
||||
self.started = time.monotonic()
|
||||
self.eta = Eta()
|
||||
self.tasks: Tasks | None = None
|
||||
self.last_tenth = 0
|
||||
self.peak_cpu = 0.0
|
||||
self.peak_memory = 0
|
||||
self._lock = threading.Lock()
|
||||
self._stop = threading.Event()
|
||||
self._thread = threading.Thread(target=self._loop, daemon=True)
|
||||
self._process = psutil.Process()
|
||||
|
||||
def item_done(self) -> None:
|
||||
with self._lock:
|
||||
self.done += 1
|
||||
|
||||
def start(self) -> None:
|
||||
self.report(force_log=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self, *, final: bool) -> None:
|
||||
self._stop.set()
|
||||
self._thread.join()
|
||||
if final:
|
||||
self.report(force_log=True)
|
||||
|
||||
def _loop(self) -> None:
|
||||
while not self._stop.wait(SAMPLE_S):
|
||||
self.report()
|
||||
|
||||
def _cluster_state(self) -> list[Worker]:
|
||||
if self.client is None:
|
||||
cpu = self._process.cpu_percent()
|
||||
self.peak_cpu = max(self.peak_cpu, cpu)
|
||||
self.peak_memory = max(self.peak_memory, self._process.memory_info().rss)
|
||||
return []
|
||||
workers = []
|
||||
try:
|
||||
info = self.client.scheduler_info()["workers"]
|
||||
for w in info.values():
|
||||
m = w.get("metrics", {})
|
||||
workers.append(
|
||||
Worker(
|
||||
name=str(w.get("name", "")),
|
||||
cpu_pct=float(m.get("cpu", 0.0)),
|
||||
memory_bytes=int(m.get("memory", 0)),
|
||||
memory_limit=w.get("memory_limit"),
|
||||
executing=int(m.get("executing", 0)),
|
||||
threads=int(w.get("nthreads", 1)),
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
return []
|
||||
try:
|
||||
counts = self.client.run_on_scheduler(_counts)
|
||||
self.tasks = Tasks(**{k: counts.get(k, 0) for k in Tasks.model_fields})
|
||||
except Exception:
|
||||
pass # a failed sample keeps the previous one
|
||||
self.peak_cpu = max(self.peak_cpu, sum(w.cpu_pct for w in workers))
|
||||
self.peak_memory = max(self.peak_memory, sum(w.memory_bytes for w in workers))
|
||||
return workers
|
||||
|
||||
def report(self, *, force_log: bool = False) -> None:
|
||||
workers = self._cluster_state()
|
||||
with self._lock:
|
||||
done = self.done
|
||||
elapsed = time.monotonic() - self.started
|
||||
self.eta.update(elapsed, done)
|
||||
progress = Progress(
|
||||
phase=self.phase,
|
||||
done=done,
|
||||
total=self.total,
|
||||
elapsed_s=round(elapsed, 1),
|
||||
eta_s=self.eta.eta_s(self.total),
|
||||
mode=self.resolved.mode,
|
||||
scheduler=self.resolved.scheduler,
|
||||
workers=workers,
|
||||
tasks=self.tasks,
|
||||
updated_at=datetime.now(UTC).isoformat(timespec="seconds"),
|
||||
)
|
||||
tenth = done * 10 // self.total
|
||||
if force_log or tenth > self.last_tenth:
|
||||
self.last_tenth = tenth
|
||||
self.log(f"{self.phase}: {done}/{self.total}")
|
||||
context = self.ambient.context if self.ambient else None
|
||||
if context is not None:
|
||||
context.instance.add_run_tags(
|
||||
context.run_id, {PROGRESS_TAG: progress.model_dump_json()}
|
||||
)
|
||||
|
||||
|
||||
def _default_log(ambient) -> Callable[[str], None]:
|
||||
return ambient.context.log.info if ambient and ambient.context else print
|
||||
|
||||
|
||||
def _run_sync(fn, iterator, monitor, on_error):
|
||||
results = []
|
||||
for item in iterator:
|
||||
try:
|
||||
results.append(fn(item))
|
||||
except Exception as e:
|
||||
if on_error is None:
|
||||
raise
|
||||
results.append(on_error(item, e))
|
||||
monitor.item_done()
|
||||
return results
|
||||
|
||||
|
||||
def _run_dask(fn, iterator, client, monitor, on_error):
|
||||
from distributed import as_completed
|
||||
|
||||
threads = sum(w["nthreads"] for w in client.scheduler_info()["workers"].values()) or 1
|
||||
limit = max(4, 2 * threads)
|
||||
results: dict[int, object] = {}
|
||||
pending: dict = {} # future -> (index, item)
|
||||
completed = as_completed([])
|
||||
numbered = enumerate(iterator)
|
||||
try:
|
||||
while True:
|
||||
for index, item in islice(numbered, max(0, limit - len(pending))):
|
||||
future = client.submit(fn, item, pure=False, retries=1)
|
||||
pending[future] = (index, item)
|
||||
completed.add(future)
|
||||
if not pending:
|
||||
break
|
||||
future = next(completed)
|
||||
index, item = pending.pop(future)
|
||||
try:
|
||||
results[index] = future.result()
|
||||
except Exception as e:
|
||||
if on_error is None:
|
||||
raise
|
||||
results[index] = on_error(item, e)
|
||||
monitor.item_done()
|
||||
except BaseException:
|
||||
try:
|
||||
client.cancel(list(pending), force=True)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return [results[i] for i in range(len(results))]
|
||||
|
||||
|
||||
def map[T, R]( # noqa: A001 - the module's public name, as in `execution.map`
|
||||
fn: Callable[[T], R],
|
||||
items: Iterable[T],
|
||||
*,
|
||||
execution: Execution | None = None,
|
||||
log: Callable[[str], None] | None = None,
|
||||
phase: str = "working",
|
||||
total: int | None = None,
|
||||
workers: int | None = None,
|
||||
on_error: Callable[[T, Exception], R] | None = None,
|
||||
) -> list[R]:
|
||||
"""Apply `fn` to every item and return the results in input order.
|
||||
|
||||
`fn` is a module-level function of one item returning something picklable, and must give
|
||||
the same result for the same item: then every mode returns equal lists. `items` may be a
|
||||
lazy generator; at most `max(4, 2 * threads)` items are loaded and unfinished at once.
|
||||
`total` is needed only when `items` has no length. `phase` is the lowercase code the
|
||||
WebApp shows. `workers` overrides the local worker count (a cluster shared inside
|
||||
`running` keeps the count it started with). A failed item takes `on_error(item, error)`
|
||||
as its result, or, without it, the error propagates after the rest is cancelled."""
|
||||
ambient = _ambient.get()
|
||||
if execution is None and ambient is not None:
|
||||
execution = ambient.execution
|
||||
resolved = resolve(execution)
|
||||
log = log or _default_log(ambient)
|
||||
if total is None:
|
||||
try:
|
||||
total = len(items) # type: ignore[arg-type]
|
||||
except TypeError:
|
||||
raise ValueError("total is needed when items has no length") from None
|
||||
iterator = iter(items)
|
||||
if total == 0:
|
||||
return []
|
||||
monitor = None
|
||||
client, local = (ambient.client, None) if ambient else (None, None)
|
||||
opened_here = False
|
||||
ok = False
|
||||
try:
|
||||
if resolved.mode != "sync" and client is None:
|
||||
client, local = _connect(resolved, workers)
|
||||
if ambient is not None:
|
||||
ambient.client, ambient.cluster = client, local
|
||||
else:
|
||||
opened_here = True
|
||||
monitor = _Monitor(ambient, resolved, phase, total, log, client)
|
||||
monitor.start()
|
||||
if resolved.mode == "sync":
|
||||
results = _run_sync(fn, iterator, monitor, on_error)
|
||||
else:
|
||||
results = _run_dask(fn, iterator, client, monitor, on_error)
|
||||
ok = True
|
||||
return results
|
||||
finally:
|
||||
if monitor is not None:
|
||||
monitor.stop(final=ok)
|
||||
if ambient is not None:
|
||||
ambient.phases.append(
|
||||
{
|
||||
"phase": phase,
|
||||
"done": monitor.done,
|
||||
"total": total,
|
||||
"elapsed_s": round(time.monotonic() - monitor.started, 1),
|
||||
}
|
||||
)
|
||||
ambient.peak_cpu_pct = max(ambient.peak_cpu_pct, monitor.peak_cpu)
|
||||
ambient.peak_memory_bytes = max(ambient.peak_memory_bytes, monitor.peak_memory)
|
||||
if opened_here:
|
||||
_close(client, local)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def running(context: dg.OpExecutionContext, execution: Execution | None = None) -> Iterator[None]:
|
||||
"""Make `context` and `execution` the ambient ones for the `map` calls in the block; on
|
||||
exit close the shared cluster and leave the run's figures in the op's output metadata."""
|
||||
ambient = _Ambient(context, execution)
|
||||
token = _ambient.set(ambient)
|
||||
failed = True
|
||||
try:
|
||||
yield
|
||||
failed = False
|
||||
finally:
|
||||
_ambient.reset(token)
|
||||
ambient.close()
|
||||
try:
|
||||
resolved = resolve(execution)
|
||||
context.add_output_metadata(
|
||||
{
|
||||
"mode": dg.MetadataValue.text(resolved.mode),
|
||||
"scheduler": (
|
||||
dg.MetadataValue.text(resolved.scheduler)
|
||||
if resolved.scheduler
|
||||
else dg.MetadataValue.null()
|
||||
),
|
||||
"phases": dg.MetadataValue.json(ambient.phases),
|
||||
"peak_cpu_pct": dg.MetadataValue.float(ambient.peak_cpu_pct),
|
||||
"peak_memory_bytes": dg.MetadataValue.int(ambient.peak_memory_bytes),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
if not failed:
|
||||
raise
|
||||
+59
-6
@@ -26,6 +26,7 @@ from core.pipeline import (
|
||||
IDENTIFIERS,
|
||||
QUOTES,
|
||||
RECORD,
|
||||
Edf,
|
||||
Extract,
|
||||
Fhir,
|
||||
Join,
|
||||
@@ -43,6 +44,7 @@ from core.pipeline import (
|
||||
matches,
|
||||
validate,
|
||||
)
|
||||
from models.tea.eeg import read
|
||||
from persistance import config_log, files, nodes, silver
|
||||
|
||||
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer
|
||||
@@ -53,6 +55,12 @@ READ_COLUMNS = { # declared, so a load where every file read cleanly still has
|
||||
}
|
||||
|
||||
|
||||
EDF_COLUMNS = {f"edf_{name}": {"data_type": kind, "nullable": True} for name, kind in (
|
||||
("patient_code", "text"), ("sex", "text"), ("birth_date", "text"), ("study_date", "text"),
|
||||
("record_code", "text"), ("duration_s", "double"), ("channels", "bigint"), ("error", "text"),
|
||||
)} # fmt: skip
|
||||
|
||||
|
||||
@cache
|
||||
def _reader() -> MarkItDown:
|
||||
return MarkItDown()
|
||||
@@ -108,6 +116,36 @@ def run_read(p: str, node: Read):
|
||||
return nodes.write(p, node.id, rows, READ_COLUMNS)
|
||||
|
||||
|
||||
def run_edf(p: str, node: Edf):
|
||||
"""Keep every input row and add the header facts or the file's error."""
|
||||
rows = list(nodes.rows(p, node.inputs[0]))
|
||||
empty = dict.fromkeys(EDF_COLUMNS)
|
||||
found = {None: {**empty, "edf_error": "empty"}}
|
||||
for key in {row.get(node.column) for row in rows} - {None}:
|
||||
content = files.content(key)
|
||||
if content is None:
|
||||
found[key] = {**empty, "edf_error": "no file"}
|
||||
continue
|
||||
try:
|
||||
h = read.header(content)
|
||||
except read.FileNotValid as exc:
|
||||
found[key] = {**empty, "edf_error": str(exc)}
|
||||
continue
|
||||
found[key] = {
|
||||
"edf_patient_code": h.patient_code,
|
||||
"edf_sex": h.sex,
|
||||
"edf_birth_date": h.birthdate.isoformat() if h.birthdate else None,
|
||||
"edf_study_date": h.start_date.isoformat() if h.start_date else None,
|
||||
"edf_record_code": h.record_code,
|
||||
"edf_duration_s": h.duration_s,
|
||||
"edf_channels": h.channels,
|
||||
"edf_error": None,
|
||||
}
|
||||
for row in rows:
|
||||
row.update(found[row.get(node.column)])
|
||||
return nodes.write(p, node.id, rows, EDF_COLUMNS)
|
||||
|
||||
|
||||
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)])
|
||||
|
||||
@@ -267,7 +305,8 @@ def run_link(p: str, node: Link):
|
||||
"""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
|
||||
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."""
|
||||
don't contradict each other are queued for review, with Splink's probability. A person
|
||||
with nothing that names her (no name, birth date or record number read) is held too."""
|
||||
records, sources, written = _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()
|
||||
@@ -293,12 +332,16 @@ def run_link(p: str, node: Link):
|
||||
facts = [f for f in ("birth_date", "sex") if f in fields]
|
||||
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"])
|
||||
# Nothing that names her was read (a scan's name line misread, say): nobody to join.
|
||||
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)}
|
||||
stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
|
||||
linked = [
|
||||
{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,
|
||||
HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
|
||||
**{f: getattr(r, f) for f in fields},
|
||||
**({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
|
||||
for r in persons.itertuples()
|
||||
@@ -335,6 +378,8 @@ def run_link(p: str, node: Link):
|
||||
|
||||
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()
|
||||
# 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
|
||||
for f in ids:
|
||||
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
|
||||
@@ -344,15 +389,23 @@ def run_link(p: str, node: Link):
|
||||
"""(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
|
||||
record numbers every patient has such neighbours) unless one side has no
|
||||
demographics and the other's identifier stands on a single record."""
|
||||
demographics and the other's identifier stands on a single record. Names one typo
|
||||
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
|
||||
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
||||
if frozenset((a, b)) in decided or any(
|
||||
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
|
||||
):
|
||||
return None
|
||||
if not reasons[int(r.match_key)].endswith("typo apart"):
|
||||
reason = reasons[int(r.match_key)]
|
||||
if not reason.endswith("typo apart"):
|
||||
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:
|
||||
return a, b
|
||||
if b in orphan and a in lone:
|
||||
@@ -415,7 +468,7 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
|
||||
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, "fhir": run_fhir,
|
||||
"join": run_join, "extract": run_extract, "link": run_link, "edf": run_edf, "fhir": run_fhir,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,657 @@
|
||||
"""ADOS-2 associations with age-standardized EEG biomarkers, adjusted for age and module."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow.pyfunc
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import optimize, stats
|
||||
from scipy.special import expit
|
||||
|
||||
from core.tea import ADOS2_ITEMS
|
||||
from models.tea.eeg.spindles import ZONES
|
||||
|
||||
BIOMARKERS = {
|
||||
"spikes": "paroxysmal_spikes",
|
||||
"spindles": "spindles_n2",
|
||||
"posterior_rhythm": "posterior_rhythm",
|
||||
"gradient": "anteroposterior_gradient",
|
||||
}
|
||||
ASSOCIATION_COLUMNS = (
|
||||
"biomarker",
|
||||
"zone",
|
||||
"kind",
|
||||
"outcome",
|
||||
"outcome_code",
|
||||
"event",
|
||||
"model",
|
||||
"n",
|
||||
"odds_ratio",
|
||||
"ci_low",
|
||||
"ci_high",
|
||||
"p",
|
||||
"q",
|
||||
"sens_model",
|
||||
"sens_odds_ratio",
|
||||
"same_direction",
|
||||
"reason",
|
||||
)
|
||||
SCORE_COLUMNS = (
|
||||
"key",
|
||||
"biomarker",
|
||||
"zone",
|
||||
"outcome_code",
|
||||
"z",
|
||||
"probability",
|
||||
"reference_probability",
|
||||
)
|
||||
ADJUST = ("age_months", "ados_module")
|
||||
|
||||
# Item number: (label, algorithm domain, supported modules).
|
||||
ITEMS = {
|
||||
1: ("Vocalización espontánea dirigida a otros", "SA", {"toddler", "module_1"}),
|
||||
2: ("Señalar", "SA", {"toddler", "module_1", "module_2"}),
|
||||
3: ("Gestos", "SA", {"toddler", "module_1", "module_2"}),
|
||||
4: ("Contacto visual inusual", "SA", {"toddler", "module_1", "module_2"}),
|
||||
5: ("Expresiones faciales dirigidas a otros", "SA", {"toddler", "module_1", "module_2"}),
|
||||
6: ("Integración de la mirada con otras conductas", "SA", {"toddler", "module_1"}),
|
||||
7: ("Disfrute compartido en la interacción", "SA", {"toddler", "module_1", "module_2"}),
|
||||
8: ("Respuesta al nombre", "SA", {"toddler"}),
|
||||
9: ("Búsqueda de atención cuando se le ignora", "SA", {"toddler"}),
|
||||
10: ("Pedir", "SA", {"toddler"}),
|
||||
11: ("Mostrar", "SA", {"toddler", "module_1", "module_2"}),
|
||||
12: (
|
||||
"Iniciación espontánea de la atención conjunta",
|
||||
"SA",
|
||||
{"toddler", "module_1", "module_2"},
|
||||
),
|
||||
13: ("Respuesta a la atención conjunta", "SA", {"toddler", "module_1"}),
|
||||
14: ("Calidad de los acercamientos sociales", "SA", {"toddler", "module_1", "module_2"}),
|
||||
15: ("Cantidad de acercamientos sociales al cuidador", "SA", {"toddler"}),
|
||||
16: ("Cantidad de comunicación social recíproca", "SA", {"module_2"}),
|
||||
17: ("Calidad general de la relación", "SA", {"toddler", "module_2"}),
|
||||
18: ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"toddler", "module_1"}),
|
||||
19: ("Uso estereotipado o idiosincrático de palabras", "RRB", {"module_1", "module_2"}),
|
||||
20: ("Interés sensorial inusual", "RRB", {"toddler", "module_1", "module_2"}),
|
||||
21: ("Manierismos de manos y dedos", "RRB", {"toddler", "module_1", "module_2"}),
|
||||
22: (
|
||||
"Intereses repetitivos o conductas estereotipadas",
|
||||
"RRB",
|
||||
{"toddler", "module_1", "module_2"},
|
||||
),
|
||||
}
|
||||
|
||||
# Items each zone's spike density is paired with.
|
||||
ZONE_ITEMS = {
|
||||
"frontal_left": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16),
|
||||
"frontal_right": (4, 5, 7, 14, 22),
|
||||
"frontal_midline": (6, 11, 12, 13, 14),
|
||||
"central": (21,),
|
||||
"parietal": (6, 13, 20),
|
||||
"temporal_left": (1, 16, 18, 19),
|
||||
"temporal_right": (4, 5, 8),
|
||||
"occipital": (4, 20),
|
||||
}
|
||||
SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal")
|
||||
RHYTHM_ITEMS = (20, 22)
|
||||
|
||||
# The calibrated severity score runs from 1 to 10 and is high from 8 (Gotham 2009; Hus 2014).
|
||||
CSS = "CSS"
|
||||
CSS_HIGH = 8
|
||||
ALTERED = 1 # An item is altered from algorithm score 1.
|
||||
|
||||
|
||||
def item_code(n: int) -> str:
|
||||
"""The module-independent outcome code of item `n`."""
|
||||
return f"ados2_item_{n:02d}"
|
||||
|
||||
|
||||
def pairs(level: str) -> list[dict]:
|
||||
"""The pairs tested. `level` "item": spike zones and the posterior rhythm against items,
|
||||
spindles and gradient against the CSS; "domain": everything against the CSS. Each pair:
|
||||
biomarker, zone, predictor column, outcome kind ("item" or "domain") and outcome (item number or
|
||||
`CSS`)."""
|
||||
out = []
|
||||
for zone in ZONES:
|
||||
outcomes = [("item", n) for n in ZONE_ITEMS[zone]] if level == "item" else [("domain", CSS)]
|
||||
out += [
|
||||
{
|
||||
"biomarker": "spikes",
|
||||
"zone": zone,
|
||||
"predictor": f"z_spikes_{zone}",
|
||||
"kind": k,
|
||||
"outcome": o,
|
||||
}
|
||||
for k, o in outcomes
|
||||
]
|
||||
out += [
|
||||
{
|
||||
"biomarker": "spindles",
|
||||
"zone": zone,
|
||||
"predictor": f"z_spindles_{zone}",
|
||||
"kind": "domain",
|
||||
"outcome": CSS,
|
||||
}
|
||||
for zone in SPINDLE_ZONES
|
||||
]
|
||||
rhythm = [("item", n) for n in RHYTHM_ITEMS] if level == "item" else [("domain", CSS)]
|
||||
out += [
|
||||
{
|
||||
"biomarker": "posterior_rhythm",
|
||||
"zone": "posterior",
|
||||
"predictor": "z_posterior_rhythm",
|
||||
"kind": k,
|
||||
"outcome": o,
|
||||
}
|
||||
for k, o in rhythm
|
||||
]
|
||||
out.append(
|
||||
{
|
||||
"biomarker": "gradient",
|
||||
"zone": "global",
|
||||
"predictor": "z_gradient",
|
||||
"kind": "domain",
|
||||
"outcome": CSS,
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def algorithm_score(v) -> pd.Series:
|
||||
"""Protocol code to algorithm score: 3 is 2; 7, 8 and 9 are 0; 0, 1 and 2 stay."""
|
||||
v = pd.to_numeric(pd.Series(v), errors="coerce")
|
||||
return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2)
|
||||
|
||||
|
||||
def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series:
|
||||
"""Item `n`'s algorithm score (0 to 2) for each child, read from the column of the child's
|
||||
module. NaN when the item is not in that module's algorithm or has no value."""
|
||||
column = ADOS2_ITEMS[n - 1]
|
||||
if "ados_module" not in cohort or column not in cohort:
|
||||
return pd.Series(np.nan, index=cohort.index)
|
||||
return algorithm_score(cohort[column]).where(cohort["ados_module"].isin(ITEMS[n][2]))
|
||||
|
||||
|
||||
def has_items(cohort: pd.DataFrame, minimum: int = 10) -> bool:
|
||||
"""Whether at least `minimum` children have some item score."""
|
||||
scores = pd.concat([item_scores(cohort, n) for n in ITEMS], axis=1)
|
||||
return int(scores.notna().any(axis=1).sum()) >= minimum
|
||||
|
||||
|
||||
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
|
||||
MIN_ROWS = 8
|
||||
|
||||
|
||||
@dataclass
|
||||
class Design:
|
||||
"""How a table becomes the design matrix: intercept, predictor (uncentred, z = 0 is the
|
||||
reference median), numeric adjustments centred on their mean, categorical ones as indicators
|
||||
against the most frequent level. Adjustments that do not vary are left out."""
|
||||
|
||||
predictor: str
|
||||
numeric: dict[str, float] = field(default_factory=dict)
|
||||
categorical: dict[str, list[str]] = field(
|
||||
default_factory=dict
|
||||
) # the indicator levels, by adjustment
|
||||
reference: dict[str, str] = field(default_factory=dict) # the reference level, by adjustment
|
||||
|
||||
@classmethod
|
||||
def of(cls, t: pd.DataFrame, predictor: str, adjust) -> Design:
|
||||
d = cls(predictor)
|
||||
for a in adjust:
|
||||
if a not in t:
|
||||
continue
|
||||
v = t[a]
|
||||
if pd.api.types.is_numeric_dtype(v):
|
||||
v = v.astype(float)
|
||||
if v.std() > 0:
|
||||
d.numeric[a] = float(v.mean())
|
||||
else:
|
||||
ref = v.value_counts().index[0]
|
||||
levels = [lv for lv in sorted(set(v) - {ref}) if 0 < (v == lv).sum() < len(v)]
|
||||
if levels:
|
||||
d.categorical[a] = [str(lv) for lv in levels]
|
||||
d.reference[a] = str(ref)
|
||||
return d
|
||||
|
||||
@property
|
||||
def names(self) -> list[str]:
|
||||
return ["intercept", self.predictor, *self.numeric] + [
|
||||
f"{a}={lv}" for a, levels in self.categorical.items() for lv in levels
|
||||
]
|
||||
|
||||
def matrix(self, t: pd.DataFrame) -> np.ndarray:
|
||||
"""X for `t`. A row missing a covariate, or with a level the fit never saw, is NaN."""
|
||||
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
|
||||
for a, mean in self.numeric.items():
|
||||
cols.append(t[a].to_numpy(float) - mean if a in t else np.full(len(t), np.nan))
|
||||
for a, levels in self.categorical.items():
|
||||
v = t[a].astype(str) if a in t else pd.Series([None] * len(t))
|
||||
for lv in levels:
|
||||
cols.append((v == lv).to_numpy(float))
|
||||
X = np.column_stack(cols)
|
||||
known = np.ones(len(t), bool)
|
||||
for a, levels in self.categorical.items():
|
||||
seen = {self.reference[a], *levels}
|
||||
known &= (
|
||||
t[a].astype(str).isin(seen).to_numpy() & t[a].notna().to_numpy()
|
||||
if a in t
|
||||
else False
|
||||
)
|
||||
X[~known] = np.nan
|
||||
return X
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"predictor": self.predictor,
|
||||
"numeric": self.numeric,
|
||||
"categorical": self.categorical,
|
||||
"reference": self.reference,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d: dict) -> Design:
|
||||
return cls(
|
||||
d["predictor"],
|
||||
dict(d["numeric"]),
|
||||
{k: list(v) for k, v in d["categorical"].items()},
|
||||
dict(d["reference"]),
|
||||
)
|
||||
|
||||
|
||||
# Firth
|
||||
def _pl(b, X, y):
|
||||
"""Firth's penalised log-likelihood: l(b) + log|X'WX| / 2."""
|
||||
eta = X @ b
|
||||
p = expit(eta)
|
||||
w = p * (1 - p)
|
||||
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
|
||||
if sign <= 0:
|
||||
return -np.inf
|
||||
return float(np.sum(y * eta - np.logaddexp(0, eta)) + 0.5 * logdet)
|
||||
|
||||
|
||||
def _score(b, X, y):
|
||||
"""Firth's modified score X'(y - p + h(1/2 - p)), h the hat matrix diagonal, and the
|
||||
information."""
|
||||
p = expit(X @ b)
|
||||
w = p * (1 - p)
|
||||
info = X.T @ (X * w[:, None])
|
||||
h = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
|
||||
return X.T @ (y - p + h * (0.5 - p)), info
|
||||
|
||||
|
||||
def _fit_firth(X, y, max_iter=200, tol=1e-10):
|
||||
b = np.zeros(X.shape[1])
|
||||
pl = _pl(b, X, y)
|
||||
for _ in range(max_iter):
|
||||
U, info = _score(b, X, y)
|
||||
step = np.linalg.solve(info, U)
|
||||
t = 1.0
|
||||
while t > 1e-8:
|
||||
nb = b + t * step
|
||||
npl = _pl(nb, X, y)
|
||||
if npl >= pl - 1e-12:
|
||||
break
|
||||
t /= 2
|
||||
b, pl = nb, npl
|
||||
if np.max(np.abs(t * step)) < tol:
|
||||
break
|
||||
return b, pl
|
||||
|
||||
|
||||
def _profile_firth(value, j, X, y, b0):
|
||||
free = [k for k in range(X.shape[1]) if k != j]
|
||||
|
||||
def f(bf):
|
||||
b = np.empty(X.shape[1])
|
||||
b[free], b[j] = bf, value
|
||||
v = _pl(b, X, y)
|
||||
if not np.isfinite(v):
|
||||
return 1e10, np.zeros(len(free))
|
||||
U, _ = _score(b, X, y)
|
||||
return -v, -U[free]
|
||||
|
||||
return -float(optimize.minimize(f, b0[free], jac=True, method="BFGS").fun)
|
||||
|
||||
|
||||
def _interval(profile, centre, maximum, scale):
|
||||
"""Profile likelihood interval: where 2 (max - profile) reaches the 95 % chi-square with one
|
||||
degree."""
|
||||
g = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
|
||||
limits = []
|
||||
for sign in (-1, 1):
|
||||
previous, limit = centre, sign * np.inf
|
||||
for k in range(1, 80):
|
||||
v = centre + sign * scale * k
|
||||
if g(v) > 0:
|
||||
limit = optimize.brentq(g, min(previous, v), max(previous, v))
|
||||
break
|
||||
previous = v
|
||||
limits.append(limit)
|
||||
return limits[0], limits[1]
|
||||
|
||||
|
||||
def _summary(model, n, coef, lo, hi, p, design, state, **extra) -> dict:
|
||||
return {
|
||||
"model": model,
|
||||
"n": n,
|
||||
"coef": round(float(coef), 4),
|
||||
"odds_ratio": round(float(np.exp(coef)), 4),
|
||||
"ci_low": round(float(np.exp(lo)), 4),
|
||||
"ci_high": round(float(np.exp(hi)), 4),
|
||||
"p": round(p, 5),
|
||||
"adjusted_for": ", ".join(design.names[2:]),
|
||||
"reason": "",
|
||||
**extra,
|
||||
"state": {"design": design.to_dict(), **state},
|
||||
}
|
||||
|
||||
|
||||
def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict:
|
||||
"""Firth logistic regression of `outcome` (0/1) on `predictor`, adjusted: n, events, odds ratio
|
||||
per unit of z, profiled 95 % interval, penalised likelihood-ratio p, and the state
|
||||
`firth_probability` scores with."""
|
||||
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
|
||||
y = d[outcome].to_numpy(float)
|
||||
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
|
||||
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
|
||||
return {**out, "reason": "too few data or no variation"}
|
||||
design = Design.of(d, predictor, adjust)
|
||||
X = design.matrix(d)
|
||||
b, pl = _fit_firth(X, y)
|
||||
_, info = _score(b, X, y)
|
||||
se = float(np.sqrt(np.linalg.inv(info)[1, 1]))
|
||||
profile = lambda v: _profile_firth(v, 1, X, y, b) # noqa: E731
|
||||
lo, hi = _interval(profile, b[1], pl, max(se, 0.05))
|
||||
p = float(stats.chi2.sf(max(2 * (pl - profile(0.0)), 0.0), 1))
|
||||
eta = X[:, 1:] @ b[1:]
|
||||
flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
||||
return _summary(
|
||||
"firth",
|
||||
len(d),
|
||||
b[1],
|
||||
lo,
|
||||
hi,
|
||||
p,
|
||||
design,
|
||||
{"beta": [float(v) for v in b[1:]], "intercept": float(flic)},
|
||||
events=int(y.sum()),
|
||||
)
|
||||
|
||||
|
||||
def firth_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
|
||||
X = Design.from_dict(state["design"]).matrix(t)
|
||||
return expit(state["intercept"] + X[:, 1:] @ np.asarray(state["beta"]))
|
||||
|
||||
|
||||
def firth_reference(state: dict) -> float:
|
||||
"""The probability at z = 0 with the covariates at their reference: mean age, most frequent
|
||||
level."""
|
||||
return float(expit(state["intercept"]))
|
||||
|
||||
|
||||
# Ordinal (proportional odds)
|
||||
def _nll_ordinal(par, X, yk, K):
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
eta = X @ par[K - 1 :]
|
||||
n = len(yk)
|
||||
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)]
|
||||
pr = cdf[np.arange(n), yk + 1] - cdf[np.arange(n), yk]
|
||||
return -float(np.sum(np.log(np.clip(pr, 1e-300, None))))
|
||||
|
||||
|
||||
def _fit_ordinal(X, yk, K, fixed=None):
|
||||
"""Minimum of the negative log-likelihood; `fixed` = (j, value) holds coefficient j of X (the
|
||||
profile)."""
|
||||
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
|
||||
if fixed is None:
|
||||
r = optimize.minimize(lambda q: _nll_ordinal(q, X, yk, K), start, method="BFGS")
|
||||
return r.x, float(r.fun)
|
||||
j, value = fixed
|
||||
idx = [k for k in range(len(start)) if k != K - 1 + j]
|
||||
|
||||
def f(q):
|
||||
par = np.empty(len(start))
|
||||
par[idx], par[K - 1 + j] = q, value
|
||||
return _nll_ordinal(par, X, yk, K)
|
||||
|
||||
return None, float(optimize.minimize(f, start[idx], method="BFGS").fun)
|
||||
|
||||
|
||||
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict:
|
||||
"""Ordinal logistic regression of `outcome` (ordered levels): odds ratio of a higher level per
|
||||
unit of z, profiled interval, likelihood-ratio p, and the state `ordinal_probability` scores
|
||||
P(outcome >= high) with."""
|
||||
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
|
||||
levels = np.sort(d[outcome].unique())
|
||||
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
|
||||
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
|
||||
return {**out, "reason": "too few data or no variation"}
|
||||
design = Design.of(d, predictor, adjust)
|
||||
X = design.matrix(d)[:, 1:] # the thresholds are the intercept
|
||||
K = len(levels)
|
||||
yk = np.searchsorted(levels, d[outcome].to_numpy())
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
par, nll = _fit_ordinal(X, yk, K)
|
||||
beta = par[K - 1 :]
|
||||
if abs(beta[0]) > 20:
|
||||
return {**out, "reason": "does not converge (separation)"}
|
||||
profile = lambda v: -_fit_ordinal(X, yk, K, fixed=(0, v))[1] # noqa: E731
|
||||
lo, hi = _interval(profile, beta[0], -nll, 0.1)
|
||||
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
k = int(np.searchsorted(levels, high)) # first level at or above `high`
|
||||
return _summary(
|
||||
"ordinal",
|
||||
len(d),
|
||||
beta[0],
|
||||
lo,
|
||||
hi,
|
||||
p,
|
||||
design,
|
||||
{
|
||||
"beta": [float(v) for v in beta],
|
||||
"threshold": float(theta[k - 1]) if 0 < k < K else None,
|
||||
"always": None if 0 < k < K else float(k == 0),
|
||||
},
|
||||
levels=K,
|
||||
)
|
||||
|
||||
|
||||
def ordinal_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
|
||||
X = Design.from_dict(state["design"]).matrix(t)[:, 1:]
|
||||
if state["threshold"] is None:
|
||||
return np.where(np.isnan(X).any(axis=1), np.nan, state["always"])
|
||||
return 1 - expit(state["threshold"] - X @ np.asarray(state["beta"]))
|
||||
|
||||
|
||||
def ordinal_reference(state: dict) -> float:
|
||||
"""P(outcome >= high) at z = 0 with the covariates at their reference."""
|
||||
return state["always"] if state["threshold"] is None else float(1 - expit(state["threshold"]))
|
||||
|
||||
|
||||
def bh(p) -> np.ndarray:
|
||||
"""Benjamini-Hochberg q values; NaN stays NaN."""
|
||||
p = np.asarray(p, dtype=float)
|
||||
q = np.full(len(p), np.nan)
|
||||
ok = np.isfinite(p)
|
||||
if ok.any():
|
||||
v = p[ok]
|
||||
o = np.argsort(v)
|
||||
r = v[o] * len(v) / np.arange(1, len(v) + 1)
|
||||
r = np.minimum.accumulate(r[::-1])[::-1]
|
||||
q[np.flatnonzero(ok)[o]] = np.minimum(r, 1)
|
||||
return q
|
||||
|
||||
|
||||
def _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
|
||||
"""The pair's principal outcome and the ordinal one: item altered and item score, or CSS high
|
||||
and CSS."""
|
||||
if pair["kind"] == "item":
|
||||
score = item_scores(cohort, pair["outcome"])
|
||||
return (score >= ALTERED).astype(float).where(score.notna()), score
|
||||
css = pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce")
|
||||
return (css >= CSS_HIGH).astype(float).where(css.notna()), css
|
||||
|
||||
|
||||
def _guarded(fit, model: str, *args, **kwargs) -> dict:
|
||||
"""One fit, or a row with its reason when the design is singular: one pair never stops the
|
||||
others."""
|
||||
try:
|
||||
return fit(*args, **kwargs)
|
||||
except (np.linalg.LinAlgError, ValueError) as error:
|
||||
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
|
||||
|
||||
|
||||
def _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]:
|
||||
"""Principal and sensitivity fits: Firth then ordinal for an item, ordinal then Firth for the
|
||||
CSS."""
|
||||
p = pair["predictor"]
|
||||
fit_firth = lambda: _guarded(firth, "firth", d, "_yes", p, ADJUST) # noqa: E731
|
||||
if pair["kind"] == "item":
|
||||
return fit_firth(), _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=ALTERED)
|
||||
return _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=CSS_HIGH), fit_firth()
|
||||
|
||||
|
||||
def _probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
|
||||
"""Each row's probability of the event, and the reference probability (z = 0, covariates at
|
||||
reference)."""
|
||||
if fit["model"] == "firth":
|
||||
return firth_probability(fit["state"], t), firth_reference(fit["state"])
|
||||
return ordinal_probability(fit["state"], t), ordinal_reference(fit["state"])
|
||||
|
||||
|
||||
class Ados2Association:
|
||||
name = "ados2_association"
|
||||
version = "0.1.0"
|
||||
impl = "modern"
|
||||
|
||||
def __init__(self, level: str = "auto", fitted: dict | None = None):
|
||||
if level not in ("auto", "item", "domain"):
|
||||
raise ValueError(f"level must be auto, item or domain, not {level!r}")
|
||||
self.level = level
|
||||
self.fitted = fitted
|
||||
|
||||
def fit(self, cohort: pd.DataFrame) -> Ados2Association:
|
||||
level = self.level if self.level != "auto" else ("item" if has_items(cohort) else "domain")
|
||||
rows = []
|
||||
for pair in pairs(level):
|
||||
if pair["predictor"] not in cohort:
|
||||
continue
|
||||
d = cohort.copy()
|
||||
d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan)
|
||||
d["_yes"], d["_level"] = _outcome(cohort, pair)
|
||||
principal, sensitivity = _models(d, pair)
|
||||
rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
|
||||
q = np.full(len(rows), np.nan)
|
||||
biomarkers = np.array([r["biomarker"] for r in rows])
|
||||
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
|
||||
for b in dict.fromkeys(biomarkers):
|
||||
q[biomarkers == b] = bh(p[biomarkers == b]).round(5)
|
||||
for r, v in zip(rows, q, strict=True):
|
||||
r["q"] = None if np.isnan(v) else float(v)
|
||||
self.fitted = {"level": level, "n": len(cohort), "rows": rows}
|
||||
return self
|
||||
|
||||
def _rows(self) -> list[dict]:
|
||||
if self.fitted is None:
|
||||
raise ValueError(f"{self.name}: fit() before associations() or score()")
|
||||
return self.fitted["rows"]
|
||||
|
||||
def associations(self) -> pd.DataFrame:
|
||||
"""One row per pair tested: the cohort's odds ratio per unit of z, interval, p and q, and
|
||||
the sensitivity model's odds ratio and whether it points the same way."""
|
||||
out = []
|
||||
for r in self._rows():
|
||||
f, s = r["principal"], r["sensitivity"]
|
||||
kind = r["kind"]
|
||||
ors, sens = f.get("odds_ratio"), s.get("odds_ratio")
|
||||
out.append(
|
||||
{
|
||||
"biomarker": r["biomarker"],
|
||||
"zone": r["zone"],
|
||||
"kind": kind,
|
||||
"outcome": r["outcome"],
|
||||
"outcome_code": item_code(r["outcome"]) if kind == "item" else CSS,
|
||||
"event": f">={ALTERED if kind == 'item' else CSS_HIGH}",
|
||||
"model": f["model"],
|
||||
"n": f["n"],
|
||||
"odds_ratio": ors,
|
||||
"ci_low": f.get("ci_low"),
|
||||
"ci_high": f.get("ci_high"),
|
||||
"p": f.get("p"),
|
||||
"q": r["q"],
|
||||
"sens_model": s["model"],
|
||||
"sens_odds_ratio": sens,
|
||||
"same_direction": (
|
||||
None
|
||||
if ors is None or sens is None
|
||||
else bool(np.sign(ors - 1) == np.sign(sens - 1))
|
||||
),
|
||||
"reason": f.get("reason", ""),
|
||||
}
|
||||
)
|
||||
return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS))
|
||||
|
||||
def score(self, cohort: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Each child's z and probability of the event, with the pair's reference probability (z =
|
||||
0, mean age, most frequent module), for every estimated pair whose outcome exists in the
|
||||
child's module."""
|
||||
parts = []
|
||||
for r in self._rows():
|
||||
f = r["principal"]
|
||||
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
|
||||
continue
|
||||
t = cohort
|
||||
if r["kind"] == "item":
|
||||
modules = set(ITEMS[r["outcome"]][2])
|
||||
t = cohort[cohort["ados_module"].isin(modules)]
|
||||
t = t[t[r["predictor"]].notna()]
|
||||
if not len(t):
|
||||
continue
|
||||
prob, ref = _probability(f, t)
|
||||
kept = np.isfinite(prob)
|
||||
parts.append(
|
||||
pd.DataFrame(
|
||||
{
|
||||
"key": t["key"].to_numpy()[kept],
|
||||
"biomarker": r["biomarker"],
|
||||
"zone": r["zone"],
|
||||
"outcome_code": item_code(r["outcome"]) if r["kind"] == "item" else CSS,
|
||||
"z": t[r["predictor"]].to_numpy(float)[kept],
|
||||
"probability": prob[kept].round(4),
|
||||
"reference_probability": round(ref, 4),
|
||||
}
|
||||
)
|
||||
)
|
||||
if not parts:
|
||||
return pd.DataFrame(columns=list(SCORE_COLUMNS))
|
||||
return pd.concat(parts, ignore_index=True)[list(SCORE_COLUMNS)]
|
||||
|
||||
def save(self, path) -> None:
|
||||
Path(path, "association.json").write_text(
|
||||
json.dumps({"level": self.level, "fitted": self.fitted}, default=float)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def load(cls, path) -> Ados2Association:
|
||||
d = json.loads(Path(path, "association.json").read_text())
|
||||
return cls(d["level"], d["fitted"])
|
||||
|
||||
|
||||
MODULE = Ados2Association()
|
||||
|
||||
|
||||
class Model(mlflow.pyfunc.PythonModel):
|
||||
def __init__(self, fitted: dict):
|
||||
self.fitted = json.loads(json.dumps(fitted, default=float))
|
||||
|
||||
def predict(self, context, cohort_df):
|
||||
return Ados2Association(fitted=self.fitted).score(cohort_df)
|
||||
+82
-4
@@ -13,6 +13,7 @@ import io
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from struct import Struct
|
||||
|
||||
import edfio
|
||||
import mne
|
||||
@@ -75,14 +76,91 @@ class Recording:
|
||||
return [name for name in self.names if kind(name) in kinds]
|
||||
|
||||
|
||||
def _kept(edf: bytes) -> list[tuple[str, str]]:
|
||||
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
|
||||
if len(edf) < 256:
|
||||
@dataclass(frozen=True)
|
||||
class Header:
|
||||
patient_code: str | None
|
||||
sex: str | None
|
||||
birthdate: date | None
|
||||
start_date: date | None
|
||||
record_code: str | None
|
||||
duration_s: float | None
|
||||
channels: int
|
||||
|
||||
|
||||
_FIXED = Struct("8s80s80s8s8s8s44s8s8s4s")
|
||||
|
||||
|
||||
def _check_length(data: bytes) -> None:
|
||||
if len(data) < _FIXED.size:
|
||||
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
|
||||
|
||||
|
||||
def _fixed_header(data: bytes) -> dict:
|
||||
_check_length(data)
|
||||
try:
|
||||
signals = edfio.read_edf(edf, lazy_load_data=True).signals
|
||||
(
|
||||
version,
|
||||
patient,
|
||||
recording,
|
||||
startdate,
|
||||
starttime,
|
||||
size,
|
||||
reserved,
|
||||
records,
|
||||
duration,
|
||||
signals,
|
||||
) = (field.decode("ascii").strip() for field in _FIXED.unpack_from(data))
|
||||
size, records, duration, signals = int(size), int(records), float(duration), int(signals)
|
||||
if version != "0" or size != 256 * (1 + signals) or signals < 0:
|
||||
raise ValueError
|
||||
except ValueError as exc:
|
||||
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
|
||||
return dict(
|
||||
version=version, patient=patient, recording=recording, startdate=startdate,
|
||||
starttime=starttime, size=size, reserved=reserved, records=records,
|
||||
duration=duration, signals=signals,
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def _date(value: str, fmt: str) -> date | None:
|
||||
try:
|
||||
return datetime.strptime(value, fmt).date()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def header(edf: bytes) -> Header:
|
||||
"""Read the declared facts from the fixed header without opening any signals."""
|
||||
fixed = _fixed_header(edf)
|
||||
patient = fixed["patient"].split(maxsplit=3) + [""] * 3
|
||||
recording = fixed["recording"].split(maxsplit=3) + [""] * 3
|
||||
start = _date(recording[1], "%d-%b-%Y") if recording[0] == "Startdate" else None
|
||||
return Header(
|
||||
patient_code=None if patient[0] in ("", "X") else patient[0],
|
||||
sex=patient[1] if patient[1] in ("F", "M") else None,
|
||||
birthdate=_date(patient[2], "%d-%b-%Y"),
|
||||
start_date=None if start == UNKNOWN_START else start,
|
||||
record_code=None if recording[2] in ("", "X") else recording[2],
|
||||
duration_s=None if fixed["records"] == -1 else fixed["records"] * fixed["duration"],
|
||||
channels=fixed["signals"],
|
||||
)
|
||||
|
||||
|
||||
def _open(edf: bytes) -> edfio.Edf:
|
||||
_check_length(edf)
|
||||
try:
|
||||
opened = edfio.read_edf(edf, lazy_load_data=True)
|
||||
except Exception as exc: # noqa: BLE001 -- any parse failure means the same
|
||||
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
|
||||
declared_records = int(edf[236:244])
|
||||
if declared_records > opened.num_data_records:
|
||||
raise FileNotValid("the EDF signal data is truncated")
|
||||
return opened
|
||||
|
||||
|
||||
def _kept(edf: bytes) -> list[tuple[str, str]]:
|
||||
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
|
||||
signals = _open(edf).signals
|
||||
if not signals:
|
||||
raise FileNotValid("the EDF declares zero signals")
|
||||
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
|
||||
|
||||
@@ -4,16 +4,15 @@ children of 16 to 36 months, recorded on 50 Hz mains.
|
||||
`listing` pairs each EDF under a folder with its age from the cohort's table (first column the
|
||||
file name, second the age in years; months = years x 12 to one decimal); keys are positions in
|
||||
path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's
|
||||
mains, with the table's age) in worker processes; `tables` gives each scenario's training table
|
||||
mains, with the table's age) in the cluster's workers; `tables` gives each scenario's training table
|
||||
from the valid studies.
|
||||
"""
|
||||
|
||||
import multiprocessing
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models import execution
|
||||
from models.tea.eeg.analysis import analyze
|
||||
from models.tea.eeg.curves import SCENARIOS
|
||||
|
||||
@@ -34,9 +33,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)]
|
||||
|
||||
|
||||
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(study: tuple[str, Path, float, float]) -> dict:
|
||||
key, path, age, mains_hz = study
|
||||
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=mains_hz)
|
||||
return {
|
||||
"key": key,
|
||||
"age_months": age,
|
||||
@@ -46,11 +45,10 @@ def _one(study: tuple[str, Path, float]) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def measure(studies, workers: int = 4) -> list[dict]:
|
||||
def measure(studies, workers: int | None = None, mains_hz: float = MAINS_HZ) -> 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))
|
||||
items = [(k, p, a, mains_hz) for k, p, a in studies]
|
||||
return execution.map(_one, items, phase="measuring_reference", workers=workers)
|
||||
|
||||
|
||||
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
|
||||
|
||||
+234
-33
@@ -1,10 +1,10 @@
|
||||
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves
|
||||
(models.tea.eeg.curves), trained on the reference cohort of TEA_REFERENCE_DIR (its EDFs and
|
||||
its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age.
|
||||
"""TEA jobs analyse the hospital's EEGs and score them against seven age curves
|
||||
(models.tea.eeg.curves). Training uses a named reference cohort or the legacy
|
||||
TEA_REFERENCE_DIR and TEA_REFERENCE_AGES settings.
|
||||
|
||||
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its
|
||||
features are kept in TEA_REFERENCE_CACHE, a JSON file named by the cohort's hash: a file set
|
||||
or ages table that changes is measured again."""
|
||||
features are kept in TEA_REFERENCE_CACHE in a JSON file named by the cohort and its hash.
|
||||
Changes to the study list, ages or mains frequency require measuring the cohort again."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
@@ -15,14 +15,27 @@ 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 sqlalchemy import bindparam, inspect, text
|
||||
|
||||
from models.tea.eeg import analysis, curves, reference
|
||||
from persistance import eeg, registry, silver
|
||||
from core.tea import ADOS2_ITEMS, ados2
|
||||
from models import execution
|
||||
from models.jobs import EmptyCohort
|
||||
from models.tea import association
|
||||
from models.tea.eeg import analysis, curves
|
||||
from models.tea.eeg import reference as cohort_reference
|
||||
from persistance import cluster, eeg, registry, silver
|
||||
from persistance.destination import engine
|
||||
|
||||
ASSOCIATION = "ados2_association"
|
||||
MODELS = curves.SCENARIOS
|
||||
CURVES = curves.SCENARIOS # what the tea_eeg job scores; MODELS may grow in Phase 2
|
||||
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
|
||||
GOLD_SELECT = [
|
||||
"tea_eeg_analyses+",
|
||||
"tea_eeg_metrics+",
|
||||
"tea_associations",
|
||||
"tea_association_scores",
|
||||
]
|
||||
|
||||
|
||||
class Baseline(mlflow.pyfunc.PythonModel):
|
||||
@@ -40,37 +53,54 @@ 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(item: tuple[str, date | None, bytes]) -> tuple[str, analysis.Analysis]:
|
||||
edf, birth, signal = item
|
||||
return edf, analysis.analyze(signal, 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)
|
||||
def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int:
|
||||
"""The EEGs in scope (default: those not analysed yet), analysed in the ambient
|
||||
execution; then, unless told not to, gold's TEA tables are rebuilt. Bronze is written
|
||||
once, after the last study, so a cancelled run leaves it as it was."""
|
||||
rows = eeg.select(scope or eeg.Scope())
|
||||
items = ((r["edf"], r["birth_date"], eeg.signal(r["edf"])) for r in rows) # lazy: bytes travel
|
||||
found = dict(execution.map(_analyze, items, phase="analyzing", total=len(rows)))
|
||||
eeg.save_analyses(found)
|
||||
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
|
||||
if rebuild_gold:
|
||||
silver.build(GOLD_SELECT)
|
||||
return len(found)
|
||||
|
||||
|
||||
def _reference() -> tuple[str, list[dict]]:
|
||||
"""The reference cohort's hash and each study's verdict and features, cached."""
|
||||
folder = Path(os.environ["TEA_REFERENCE_DIR"])
|
||||
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
|
||||
studies = reference.listing(folder, ages)
|
||||
digest = hashlib.sha256("\n".join(f"{p.name}|{a}" for _, p, a in studies).encode()).hexdigest()
|
||||
def _reference(reference: cluster.Reference | None) -> tuple[str, list[dict], str, int]:
|
||||
"""The reference cohort's hash, cached measurements, name and mains frequency."""
|
||||
if reference is None:
|
||||
folder = Path(os.environ["TEA_REFERENCE_DIR"])
|
||||
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
|
||||
name, line_hz = cohort_reference.NAME, 50
|
||||
else:
|
||||
folder = cluster.reference_dir(reference.name)
|
||||
ages = folder / "edades.csv"
|
||||
if not ages.is_file():
|
||||
raise ValueError(f"reference cohort {reference.name!r} has no edades.csv")
|
||||
name, line_hz = reference.name, reference.line_hz
|
||||
|
||||
studies = cohort_reference.listing(folder, ages)
|
||||
if reference is not None and not studies:
|
||||
raise ValueError(f"reference cohort {name!r} has no EDF with an age from 16 to 36 months")
|
||||
content = "\n".join(f"{p.name}|{a}" for _, p, a in studies)
|
||||
if line_hz != 50:
|
||||
content += f"|line_hz={line_hz}"
|
||||
digest = hashlib.sha256(content.encode()).hexdigest()
|
||||
cache = os.environ.get("TEA_REFERENCE_CACHE")
|
||||
path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None
|
||||
path = Path(cache) / f"{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)
|
||||
return digest, json.loads(path.read_text()), name, line_hz
|
||||
measured = cohort_reference.measure(studies, mains_hz=float(line_hz))
|
||||
measured = [{**m, "key": str(m["key"])} for m in measured]
|
||||
if path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(measured))
|
||||
return digest, measured
|
||||
return digest, measured, name, line_hz
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -88,27 +118,198 @@ def registered(name: str) -> str:
|
||||
return f"tea.{name}"
|
||||
|
||||
|
||||
def train(name: str, as_of: date | None = None) -> int:
|
||||
def train(
|
||||
name: str, as_of: date | None = None, reference: cluster.Reference | None = None
|
||||
) -> int | None:
|
||||
"""A new version of one age curve, trained on the reference cohort's valid studies,
|
||||
with its two reports: the cohort it learned from, and its centile curves."""
|
||||
digest, measured = _reference()
|
||||
table = reference.tables(measured)[name]
|
||||
if name == ASSOCIATION:
|
||||
return train_association(as_of)
|
||||
digest, measured, cohort, hz = _reference(reference)
|
||||
table = cohort_reference.tables(measured)[name]
|
||||
baseline = curves.train(table, name)
|
||||
valid = [m for m in measured if m["valid"] and m["error"] is None]
|
||||
technical = {
|
||||
"model": name, "method": "age curves (weighted centiles on log age)",
|
||||
"cohort": reference.NAME, "cohort_sha256": digest, "studies": len(measured),
|
||||
"cohort": cohort, "cohort_sha256": digest, "line_hz": hz, "studies": len(measured),
|
||||
"valid_studies": len(valid),
|
||||
"ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)],
|
||||
"features": sorted(baseline),
|
||||
} # fmt: skip
|
||||
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
|
||||
metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))}
|
||||
params = {"cohort": reference.NAME, "cohort_sha256": digest}
|
||||
params = {"cohort": cohort, "cohort_sha256": digest, "line_hz": str(hz)}
|
||||
reports = {"technical_validation": technical, "interpretability": interpretability}
|
||||
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
|
||||
|
||||
|
||||
def score_curves() -> dict[str, int | None]:
|
||||
"""The version of each age curve's champion that scored, None without a champion."""
|
||||
return {name: score(name) for name in CURVES}
|
||||
|
||||
|
||||
def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""The first EEG with a predictor per child for fitting, and all eligible EEGs for scoring."""
|
||||
columns = [
|
||||
"key",
|
||||
"person_id",
|
||||
"study_date",
|
||||
"edf",
|
||||
"age_months",
|
||||
"ados_module",
|
||||
"css",
|
||||
*ADOS2_ITEMS,
|
||||
]
|
||||
records, values = [], {}
|
||||
with engine().connect() as con:
|
||||
tables = inspect(con)
|
||||
if tables.has_table("eeg_analysis", schema="bronze"):
|
||||
items = ", ".join(ADOS2_ITEMS)
|
||||
selected_items = ", ".join(f"t.{i}" for i in ADOS2_ITEMS)
|
||||
query = text(f"""
|
||||
with first_ados as (
|
||||
select person_id, module, evaluation_date, {items},
|
||||
row_number() over (
|
||||
partition by person_id order by evaluation_date nulls last, known_at
|
||||
) as rn
|
||||
from silver.ados2
|
||||
)
|
||||
select e.person_id, e.study_date, e.edf, a.age_months,
|
||||
t.module, t.evaluation_date, p.birth_date, {selected_items}
|
||||
from silver.eeg as e
|
||||
join bronze.eeg_analysis as a on a.edf = e.edf
|
||||
join first_ados as t on t.person_id = e.person_id and t.rn = 1
|
||||
left join silver.person as p on p.person_id = e.person_id
|
||||
where a.valid and a.age_months is not null
|
||||
""")
|
||||
for raw in con.execute(query).mappings():
|
||||
row = dict(raw)
|
||||
for field in ("birth_date", "evaluation_date"):
|
||||
row[field] = date.fromisoformat(str(row[field])[:10]) if row[field] else None
|
||||
records.append(
|
||||
{
|
||||
**row,
|
||||
"key": f"{row['person_id']}|{str(row['study_date'])[:10]}",
|
||||
"ados_module": row["module"],
|
||||
"css": ados2.score(
|
||||
row, row["birth_date"] if row["evaluation_date"] else None
|
||||
)[0],
|
||||
}
|
||||
)
|
||||
if records and tables.has_table("eeg_scores", schema="bronze"):
|
||||
biomarker = {metric: name for name, metric in association.BIOMARKERS.items()}
|
||||
query = text("""
|
||||
select edf, metric, part, site, z from bronze.eeg_scores
|
||||
where metric in :metrics and z is not null
|
||||
""").bindparams(bindparam("metrics", expanding=True))
|
||||
edfs = {row["edf"] for row in records}
|
||||
for edf, metric, part, site, z in con.execute(query, {"metrics": list(biomarker)}):
|
||||
if edf not in edfs:
|
||||
continue
|
||||
name = biomarker[metric]
|
||||
if name in ("spikes", "spindles"):
|
||||
if part != "zones":
|
||||
continue
|
||||
predictor = f"z_{name}_{site}"
|
||||
else:
|
||||
if part != "value":
|
||||
continue
|
||||
predictor = f"z_{name}"
|
||||
values.setdefault(edf, {})[predictor] = z
|
||||
scored = pd.DataFrame(records, columns=columns)
|
||||
if values:
|
||||
scored = scored.join(pd.DataFrame.from_dict(values, orient="index"), on="edf")
|
||||
scored = scored.sort_values(["person_id", "study_date", "key"], na_position="last").reset_index(
|
||||
drop=True
|
||||
)
|
||||
predictors = [c for c in scored.columns if c.startswith("z_")]
|
||||
fit = (
|
||||
scored[scored[predictors].notna().any(axis=1)]
|
||||
.drop_duplicates("person_id")
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
drop = ["person_id", "study_date", "edf"]
|
||||
return fit.drop(columns=drop), scored.drop(columns=drop)
|
||||
|
||||
|
||||
def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str:
|
||||
"""Hash the scored EEGs, fit membership, and module identifier in canonical order."""
|
||||
t = scored.assign(_fit=scored["key"].isin(fit["key"]))
|
||||
t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True)
|
||||
text = module + "\n" + t.to_csv(index=False, float_format="%.6g")
|
||||
return hashlib.sha256(text.encode()).hexdigest()[:8]
|
||||
|
||||
|
||||
def _records(frame: pd.DataFrame) -> list[dict]:
|
||||
"""Coerce missing estimates and open interval limits to JSON/SQL nulls."""
|
||||
clean = frame.replace([float("inf"), -float("inf")], None).astype(object)
|
||||
return clean.where(clean.notna(), None).to_dict("records")
|
||||
|
||||
|
||||
def train_association(as_of: date | None = None) -> int | None:
|
||||
fit, scored = cohort()
|
||||
if fit.empty:
|
||||
raise EmptyCohort(ASSOCIATION)
|
||||
estimator = association.Ados2Association(level="auto")
|
||||
mark = fingerprint(
|
||||
fit, scored, f"{estimator.name}/{estimator.version}/{estimator.impl}/{estimator.level}"
|
||||
)
|
||||
name = registered(ASSOCIATION)
|
||||
versions = registry.versions(name)
|
||||
if versions and versions[-1]["params"].get("fingerprint") == mark:
|
||||
return versions[-1]["version"]
|
||||
|
||||
estimator.fit(fit)
|
||||
pairs = estimator.associations()
|
||||
level = estimator.fitted["level"]
|
||||
forest = ["biomarker", "zone", "outcome_code", "odds_ratio", "ci_low", "ci_high", "q"]
|
||||
reports = {
|
||||
"technical_validation": {
|
||||
"model": ASSOCIATION,
|
||||
"method": "Firth / ordinal logistic, profile CI, BH within biomarker",
|
||||
"level": level,
|
||||
"cohort": len(fit),
|
||||
"scored": len(scored),
|
||||
"fingerprint": mark,
|
||||
"pairs": _records(pairs),
|
||||
},
|
||||
"interpretability": {"kind": "forest", "rows": _records(pairs[forest])},
|
||||
}
|
||||
params = {"fingerprint": mark, "level": level}
|
||||
metrics = {"n_reference": len(fit), "pairs": int(pairs["odds_ratio"].notna().sum())}
|
||||
return registry.register(name, association.Model(estimator.fitted), params, metrics, reports)
|
||||
|
||||
|
||||
def relate() -> int | None:
|
||||
found = registry.champion(registered(ASSOCIATION))
|
||||
if found is None:
|
||||
return None
|
||||
version, model = found
|
||||
estimator = association.Ados2Association(fitted=model.unwrap_python_model().fitted)
|
||||
_, scored = cohort()
|
||||
rows = []
|
||||
for row in _records(estimator.associations()):
|
||||
if row["odds_ratio"] is None or row["odds_ratio"] <= 0:
|
||||
continue
|
||||
row["key"] = f"{row['biomarker']}|{row['zone']}|{row['outcome_code']}"
|
||||
row["method"] = row.pop("model")
|
||||
row.pop("outcome")
|
||||
row["level"] = estimator.fitted["level"]
|
||||
row["n_cohort"] = estimator.fitted["n"]
|
||||
row["reason"] = row["reason"] or None
|
||||
rows.append(row)
|
||||
keys = {row["key"] for row in rows}
|
||||
scores = []
|
||||
for row in model.predict(scored).to_dict("records"):
|
||||
pair = "|".join(row.pop(field) for field in ("biomarker", "zone", "outcome_code"))
|
||||
if pair in keys:
|
||||
eeg_id = row["key"]
|
||||
scores.append({**row, "eeg_id": eeg_id, "pair": pair, "key": f"{eeg_id}|{pair}"})
|
||||
eeg.save_associations(version, rows)
|
||||
eeg.save_association_scores(version, scores)
|
||||
return version
|
||||
|
||||
|
||||
def score(name: str) -> int | None:
|
||||
"""The champion curve's scores of every analysed EEG: the metric's value, and each
|
||||
electrode and zone it measures; None without a champion."""
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Analyse a single study and its optional report without persisting the results."""
|
||||
|
||||
import math
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
|
||||
from core import concept_map, tea
|
||||
from core.pipeline import apply_patterns
|
||||
from core.tea import ados2 as scoring
|
||||
from models import graph
|
||||
from models.tea.eeg import analysis, curves, read
|
||||
from models.tea.jobs import MODELS
|
||||
from persistance import config_log, registry
|
||||
from persistance.previews import PreviewAdos2, PreviewEeg, PreviewMetric, PreviewResult, Site
|
||||
|
||||
|
||||
def _deviations(models: dict, study: analysis.Analysis) -> dict:
|
||||
metrics = {metric.code: metric for metric in study.metrics}
|
||||
missing_values = set()
|
||||
for name, baseline in models.items():
|
||||
scenario = curves.SCENARIOS[name]
|
||||
if scenario.metric not in metrics:
|
||||
continue
|
||||
metric = metrics[scenario.metric]
|
||||
changes = {
|
||||
part: {
|
||||
site: value
|
||||
for site, value in getattr(metric, part).items()
|
||||
if curves.PREFIX[part] + site in baseline
|
||||
}
|
||||
for part in scenario.parts
|
||||
if part != "value"
|
||||
}
|
||||
if "value" in scenario.parts and "value" not in baseline:
|
||||
# A missing value short-circuits curves.score, while the sites still get scored.
|
||||
models[name] = baseline | {"value": {}}
|
||||
changes["value"] = None
|
||||
missing_values.add(metric.code)
|
||||
metrics[metric.code] = replace(metric, **changes)
|
||||
|
||||
features = {name: study.features.get(name, {}) for name in models}
|
||||
found = curves.deviations(
|
||||
models, replace(study, metrics=list(metrics.values()), features=features)
|
||||
)
|
||||
for code in missing_values:
|
||||
found.get(code, {}).pop("value", None)
|
||||
return found
|
||||
|
||||
|
||||
def _sites(values: dict, scores: dict) -> dict[str, Site]:
|
||||
return {key: Site(value=value, score=scores.get(key)) for key, value in values.items()}
|
||||
|
||||
|
||||
def _metrics(study: analysis.Analysis, warnings: list[str]) -> list[PreviewMetric]:
|
||||
models, versions = {}, {}
|
||||
found = {}
|
||||
if study.valid:
|
||||
for name in curves.SCENARIOS:
|
||||
champion = registry.champion(f"tea.{name}")
|
||||
if champion is not None:
|
||||
versions[name], model = champion
|
||||
models[name] = model.unwrap_python_model().baseline
|
||||
if not models:
|
||||
warnings.append("there are no champion age curves: no z is shown")
|
||||
else:
|
||||
codes = {metric.code for metric in study.metrics}
|
||||
warnings.extend(
|
||||
f"no champion for {name}: its z is not shown"
|
||||
for name, scenario in curves.SCENARIOS.items()
|
||||
if name not in models and scenario.metric in codes
|
||||
)
|
||||
found = _deviations(models, study)
|
||||
|
||||
labels = {
|
||||
MODELS[name].metric: f"tea.{name}/{version}"
|
||||
for name, version in versions.items()
|
||||
if "value" in MODELS[name].parts
|
||||
}
|
||||
metrics = []
|
||||
for metric in study.metrics:
|
||||
parts = found.get(metric.code, {})
|
||||
metrics.append(
|
||||
PreviewMetric(
|
||||
code=metric.code,
|
||||
value=metric.value,
|
||||
score=parts.get("value"),
|
||||
model=labels.get(metric.code) if "value" in parts else None,
|
||||
electrodes=_sites(metric.electrodes, parts.get("electrodes", {})),
|
||||
zones=_sites(metric.zones, parts.get("zones", {})),
|
||||
)
|
||||
)
|
||||
return metrics
|
||||
|
||||
|
||||
def _parse(field, value, kind, warnings):
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if kind == "date":
|
||||
return value if isinstance(value, date) else date.fromisoformat(value)
|
||||
number = float(value)
|
||||
if math.isfinite(number):
|
||||
return number
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
warnings.append(f"{field}: could not read {value!r} as a {kind}")
|
||||
return None
|
||||
|
||||
|
||||
def _report(
|
||||
content: bytes,
|
||||
pipeline: str,
|
||||
recorded_on: date | None,
|
||||
birth: date | None,
|
||||
warnings: list[str],
|
||||
) -> PreviewAdos2 | None:
|
||||
if not content.startswith(b"%PDF"):
|
||||
warnings.append("the ADOS-2 file is not a PDF")
|
||||
return None
|
||||
text = graph.read_file(content)
|
||||
if error := text["error"]:
|
||||
warnings.append(f"the ADOS-2 report could not be read: {error}")
|
||||
return None
|
||||
|
||||
try:
|
||||
saved = config_log.get(pipeline)
|
||||
except Exception: # noqa: BLE001 -- an unavailable saved pipeline is reported in the result
|
||||
saved = None
|
||||
if saved is None:
|
||||
warnings.append(f"no saved pipeline {pipeline}: the ADOS-2 report is not read")
|
||||
return None
|
||||
_, definition = saved
|
||||
node = next((n for n in definition.nodes if n.kind == "extract" and n.entity == "ados2"), None)
|
||||
if node is None:
|
||||
warnings.append(f"pipeline {pipeline} has no ados2 extract node")
|
||||
return None
|
||||
|
||||
codes = {}
|
||||
if node.concept_map:
|
||||
mapping = config_log.concept_map(node.concept_map)
|
||||
codes = {field: concept_map.table([mapping], field) for field in node.patterns}
|
||||
found = apply_patterns(node, text["text"], codes)
|
||||
if not found:
|
||||
warnings.append("no ADOS-2 field was found in the report")
|
||||
return None
|
||||
|
||||
row = dict(found[0][0])
|
||||
fields = sorted(row)
|
||||
evaluation_date = _parse("evaluation_date", row.get("evaluation_date"), "date", warnings)
|
||||
if "evaluation_date" not in row:
|
||||
evaluation_date = recorded_on
|
||||
items = {
|
||||
item: _parse(item, row.get(item), "number", warnings)
|
||||
for item in tea.SOCIAL_AFFECT_ITEMS + tea.RESTRICTED_REPETITIVE_ITEMS
|
||||
}
|
||||
css, classification = None, None
|
||||
if evaluation_date is None:
|
||||
warnings.append("ADOS-2 not scored: no evaluation date")
|
||||
else:
|
||||
try:
|
||||
css, classification = scoring.score(
|
||||
row | items | {"evaluation_date": evaluation_date}, birth
|
||||
)
|
||||
except (ValueError, TypeError) as exc:
|
||||
warnings.append(f"ADOS-2 not scored: {exc}")
|
||||
else:
|
||||
if css is None and classification is None:
|
||||
warnings.append(
|
||||
"the ADOS-2 score could not be calculated: "
|
||||
"the report lacks the module or the item scores"
|
||||
)
|
||||
return PreviewAdos2(
|
||||
module=row.get("module"),
|
||||
evaluation_date=evaluation_date,
|
||||
items=items,
|
||||
css=css,
|
||||
classification=classification,
|
||||
read=fields,
|
||||
)
|
||||
|
||||
|
||||
def preview(
|
||||
edf: bytes,
|
||||
ados2: bytes | None = None,
|
||||
birth_date: date | None = None,
|
||||
pipeline: str = "tea",
|
||||
) -> PreviewResult:
|
||||
study = analysis.analyze(edf, birth_date)
|
||||
try:
|
||||
header = read.header(edf)
|
||||
except read.FileNotValid:
|
||||
header = None
|
||||
recorded_on = header.start_date if header else None
|
||||
warnings = []
|
||||
if study.error:
|
||||
warnings.append(f"the EEG analysis ended with an error: {study.error}")
|
||||
eeg = PreviewEeg(
|
||||
valid=study.valid,
|
||||
level=study.level,
|
||||
recorded_on=recorded_on,
|
||||
age_months=study.age_months,
|
||||
clean_fraction=study.clean_fraction,
|
||||
bad_channels=study.bad_channels,
|
||||
channels=study.channels,
|
||||
duration_min=study.duration_min,
|
||||
line_noise_db=study.line_noise_db,
|
||||
sleep=study.sleep,
|
||||
checks=study.checks,
|
||||
metrics=_metrics(study, warnings),
|
||||
error=study.error,
|
||||
)
|
||||
report = None
|
||||
if ados2 is not None:
|
||||
birth = birth_date or (header.birthdate if header else None)
|
||||
report = _report(ados2, pipeline, recorded_on, birth, warnings)
|
||||
return PreviewResult(eeg=eeg, ados2=report, warnings=warnings)
|
||||
@@ -0,0 +1,78 @@
|
||||
import sqlite3
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import edfio
|
||||
import numpy as np
|
||||
|
||||
SEX_MAP = {
|
||||
"resourceType": "ConceptMap",
|
||||
"status": "active",
|
||||
"group": [
|
||||
{
|
||||
"source": "urn:edf",
|
||||
"target": "http://hl7.org/fhir/administrative-gender",
|
||||
"element": [
|
||||
{"code": "F", "target": [{"code": "female", "equivalence": "equivalent"}]},
|
||||
{"code": "M", "target": [{"code": "male", "equivalence": "equivalent"}]},
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def small_edf(
|
||||
path: Path,
|
||||
*,
|
||||
patient_code="N1001",
|
||||
sex="F",
|
||||
birthdate=date(2025, 1, 5),
|
||||
startdate=date(2026, 3, 2),
|
||||
record_code="LAB-1",
|
||||
seconds=20,
|
||||
channels=("Fp1", "Fp2", "Cz"),
|
||||
) -> bytes:
|
||||
edf = edfio.Edf(
|
||||
[
|
||||
edfio.EdfSignal(
|
||||
np.random.default_rng(1).normal(0, 20, 100 * seconds),
|
||||
sampling_frequency=100,
|
||||
label=name,
|
||||
)
|
||||
for name in channels
|
||||
],
|
||||
patient=edfio.Patient(code=patient_code, sex=sex, birthdate=birthdate),
|
||||
recording=edfio.Recording(startdate=startdate, hospital_administration_code=record_code),
|
||||
)
|
||||
edf.write(path)
|
||||
return path.read_bytes()
|
||||
|
||||
|
||||
def hospital(path: Path) -> str:
|
||||
with sqlite3.connect(path) as con:
|
||||
con.execute("create table pacientes (record_number text primary key, birth_date text)")
|
||||
con.executemany("insert into pacientes values (?, ?)",
|
||||
[("N1001", "2025-01-05"), ("N1002", "2025-02-05")]) # fmt: skip
|
||||
return f"sqlite:///{path}"
|
||||
|
||||
|
||||
def pipeline(hospital_url: str, bucket_url: str) -> dict:
|
||||
return {"nodes": [
|
||||
{"id": "patients", "kind": "source", "source": "dlt.sources.sql_database:sql_table",
|
||||
"args": {"credentials": hospital_url, "table": "pacientes"}},
|
||||
{"id": "patients_identity", "kind": "map", "inputs": ["patients"],
|
||||
"fields": {"record_number": "record_number", "birth_date": "birth_date"},
|
||||
"formats": {"birth_date": "%Y-%m-%d"}},
|
||||
{"id": "uploads", "kind": "source", "source": "dlt.sources.filesystem:filesystem",
|
||||
"args": {"bucket_url": bucket_url, "file_glob": "*.edf"},
|
||||
"then": "persistance.readers:read_bytes"},
|
||||
{"id": "header", "kind": "edf", "inputs": ["uploads"], "column": "content"},
|
||||
{"id": "uploads_identity", "kind": "map", "inputs": ["header"], "concept_map": "edf_sex",
|
||||
"fields": {"record_number": "edf_patient_code", "birth_date": "edf_birth_date",
|
||||
"sex": "edf_sex"}, "formats": {"birth_date": "%Y-%m-%d"}},
|
||||
{"id": "eegs", "kind": "map", "inputs": ["header"],
|
||||
"fields": {"study_date": "edf_study_date", "lab_record_id": "edf_record_code",
|
||||
"edf": "content"}, "formats": {"study_date": "%Y-%m-%d"}},
|
||||
{"id": "people", "kind": "link", "inputs": ["patients_identity", "uploads_identity"]},
|
||||
{"id": "target", "kind": "target", "inputs": ["eegs", "people"], "entity": "eeg"},
|
||||
]} # fmt: skip
|
||||
@@ -0,0 +1,215 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from core.domains import Domain, part
|
||||
from persistance import bundle, config, registry
|
||||
|
||||
DOMAIN = Domain.TEA
|
||||
NAME = "tea.curve_x"
|
||||
|
||||
|
||||
class Model(mlflow.pyfunc.PythonModel):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None):
|
||||
return model_input.assign(score=self.value)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def stores(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
||||
|
||||
def use(name):
|
||||
path = tmp_path / name
|
||||
path.mkdir(exist_ok=True)
|
||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", f"sqlite:///{path}/a.db")
|
||||
monkeypatch.chdir(path)
|
||||
|
||||
use("a")
|
||||
return use
|
||||
|
||||
|
||||
def _register(value=1, clinical=True):
|
||||
version = registry.register(
|
||||
NAME,
|
||||
Model(value),
|
||||
{"scenario": "curve"},
|
||||
{"n_reference": 10},
|
||||
{"technical_validation": {"a": 1}, "interpretability": {"b": 2}},
|
||||
tags={"source": "test", "bundle.source_version": "stale"},
|
||||
)
|
||||
if clinical:
|
||||
registry.add_report(NAME, version, "clinical_validation", "review.txt", b"approved")
|
||||
return version
|
||||
|
||||
|
||||
def _trust(data):
|
||||
sha = hashlib.sha256(data).hexdigest()
|
||||
with bundle.trusted_file().open("a") as file:
|
||||
file.write(f"\n# approved\n {sha.upper()} \n")
|
||||
return sha
|
||||
|
||||
|
||||
def _entries(data):
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
||||
return {name: archive.read(name) for name in archive.namelist()}
|
||||
|
||||
|
||||
def _zip(entries):
|
||||
stream = io.BytesIO()
|
||||
with zipfile.ZipFile(stream, "w") as archive:
|
||||
for name, data in entries.items():
|
||||
archive.writestr(name, data)
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
def test_export_is_deterministic(stores):
|
||||
registry.promote(NAME, _register())
|
||||
first, second = bundle.export(DOMAIN), bundle.export(DOMAIN)
|
||||
assert first.data == second.data
|
||||
assert first.sha256 == second.sha256 == hashlib.sha256(first.data).hexdigest()
|
||||
with zipfile.ZipFile(io.BytesIO(first.data)) as archive:
|
||||
assert archive.namelist() == sorted(archive.namelist())
|
||||
for info in archive.infolist():
|
||||
assert info.date_time == bundle.EPOCH
|
||||
assert info.compress_type == zipfile.ZIP_DEFLATED
|
||||
assert info.external_attr == 0o644 << 16
|
||||
assert info.create_system == 3
|
||||
|
||||
|
||||
def test_layout_and_manifest_hold_every_file_hash(stores):
|
||||
_register()
|
||||
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
|
||||
manifest = json.loads(entries.pop("manifest.json"))
|
||||
assert (manifest["format"], manifest["domain"]) == (1, "tea")
|
||||
(item,) = manifest["versions"]
|
||||
assert (item["name"], item["version"]) == (NAME, 1)
|
||||
prefix = "models/tea.curve_x/v1/"
|
||||
assert prefix + "meta.json" in entries
|
||||
assert prefix + "model/MLmodel" in entries
|
||||
assert prefix + "reports/clinical_validation.txt" in entries
|
||||
assert item["files"] == {key: hashlib.sha256(data).hexdigest() for key, data in entries.items()}
|
||||
meta = json.loads(entries.pop(prefix + "meta.json"))
|
||||
content = {key.removeprefix(prefix): data for key, data in entries.items()}
|
||||
assert meta["content_sha256"] == item["content_sha256"] == bundle.content_sha256(content)
|
||||
|
||||
|
||||
def test_selection_champion_latest_all(stores):
|
||||
for value in (1, 2, 3):
|
||||
_register(value)
|
||||
with pytest.raises(bundle.Empty, match="nothing to export"):
|
||||
bundle.export(DOMAIN)
|
||||
registry.promote(NAME, 2)
|
||||
assert bundle.export(DOMAIN).versions == [(NAME, 2)]
|
||||
assert bundle.export(DOMAIN, ["curve_x"], "latest").versions == [(NAME, 3)]
|
||||
assert bundle.export(DOMAIN, versions="all").versions == [(NAME, 1), (NAME, 2), (NAME, 3)]
|
||||
with pytest.raises(bundle.BundleError, match="no tea model missing"):
|
||||
bundle.export(DOMAIN, ["missing"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("clinical", [True, False])
|
||||
def test_roundtrip_registers_candidates_with_lineage(stores, clinical):
|
||||
_register()
|
||||
source_version = _register(2, clinical=clinical)
|
||||
source = registry.snapshot(NAME, source_version)
|
||||
inputs = pd.DataFrame({"value": [0]})
|
||||
prediction = mlflow.pyfunc.load_model(f"models:/{NAME}/{source_version}").predict(inputs)
|
||||
exported = bundle.export(DOMAIN, versions="latest")
|
||||
stores("b")
|
||||
_trust(exported.data)
|
||||
assert bundle.import_(DOMAIN, exported.data) == bundle.Imported(
|
||||
exported.sha256, [(NAME, 1)], []
|
||||
)
|
||||
target = registry.snapshot(NAME, 1)
|
||||
pd.testing.assert_frame_equal(
|
||||
mlflow.pyfunc.load_model(f"models:/{NAME}/1").predict(inputs),
|
||||
prediction,
|
||||
)
|
||||
assert target.params == source.params
|
||||
assert target.metrics == source.metrics
|
||||
assert target.reports == source.reports
|
||||
assert target.tags == {
|
||||
"source": "test",
|
||||
"bundle.sha256": exported.sha256,
|
||||
"bundle.source_name": NAME,
|
||||
"bundle.source_version": "2",
|
||||
"bundle.content_sha256": json.loads(_entries(exported.data)["manifest.json"])["versions"][
|
||||
0
|
||||
]["content_sha256"],
|
||||
}
|
||||
assert registry.champion_version(NAME) is None
|
||||
if clinical:
|
||||
registry.promote(NAME, 1)
|
||||
assert registry.champion_version(NAME) == 1
|
||||
else:
|
||||
with pytest.raises(registry.MissingReports, match="clinical_validation"):
|
||||
registry.promote(NAME, 1)
|
||||
|
||||
|
||||
def test_importing_twice_is_a_conflict_and_partial_imports_skip(stores):
|
||||
_register()
|
||||
single = bundle.export(DOMAIN, versions="latest")
|
||||
_register(2)
|
||||
both = bundle.export(DOMAIN, versions="all")
|
||||
stores("b")
|
||||
_trust(single.data)
|
||||
_trust(both.data)
|
||||
assert bundle.import_(DOMAIN, single.data).imported == [(NAME, 1)]
|
||||
with pytest.raises(bundle.Conflict, match="every version is already registered"):
|
||||
bundle.import_(DOMAIN, single.data)
|
||||
result = bundle.import_(DOMAIN, both.data)
|
||||
assert result.imported == [(NAME, 2)]
|
||||
assert result.skipped == [(NAME, 1)]
|
||||
|
||||
|
||||
def test_tampered_bundles_are_refused(stores):
|
||||
_register()
|
||||
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
|
||||
path = "models/tea.curve_x/v1/model/MLmodel"
|
||||
manifest = json.loads(entries["manifest.json"])
|
||||
|
||||
def with_manifest(**fields):
|
||||
return entries | {"manifest.json": json.dumps(manifest | fields).encode()}
|
||||
|
||||
cases = [
|
||||
(_zip(entries | {path: entries[path][:-1] + b"!"}), "content does not match the manifest"),
|
||||
(_zip(entries | {"extra": b""}), "files in the bundle do not match the manifest"),
|
||||
(_zip({k: v for k, v in entries.items() if k != path}), "files in the bundle do not match"),
|
||||
(_zip(entries | {"../x": b""}), r"unsafe bundle path: \.\./x"),
|
||||
(_zip(with_manifest(format=2)), "bundle format 2, this platform reads 1"),
|
||||
(_zip(with_manifest(domain="cacu")), "bundle is for cacu, not tea"),
|
||||
(b"hello", "not a bundle"),
|
||||
]
|
||||
for data, message in cases:
|
||||
_trust(data)
|
||||
with pytest.raises(bundle.BundleError, match=message):
|
||||
bundle.import_(DOMAIN, data)
|
||||
|
||||
|
||||
def test_guard_runs_on_export_and_on_import(stores, monkeypatch):
|
||||
_register()
|
||||
hook = part(DOMAIN, "bundle")
|
||||
monkeypatch.setattr(hook, "guard", lambda version: [])
|
||||
exported = bundle.export(DOMAIN, versions="latest")
|
||||
_trust(exported.data)
|
||||
monkeypatch.setattr(hook, "guard", lambda version: ["problem"])
|
||||
for operation in (
|
||||
lambda: bundle.export(DOMAIN, versions="latest"),
|
||||
lambda: bundle.import_(DOMAIN, exported.data),
|
||||
):
|
||||
with pytest.raises(bundle.BundleError, match=r"tea\.curve_x v1: problem"):
|
||||
operation()
|
||||
|
||||
|
||||
def test_import_refuses_an_untrusted_digest(stores):
|
||||
_register()
|
||||
exported = bundle.export(DOMAIN, versions="latest")
|
||||
with pytest.raises(bundle.BundleError, match=f"bundle {exported.sha256} is not trusted"):
|
||||
bundle.import_(DOMAIN, exported.data)
|
||||
@@ -0,0 +1,50 @@
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from edf_files import small_edf
|
||||
|
||||
from models.tea.eeg.read import FileNotValid, Header, _kept, header
|
||||
|
||||
|
||||
def test_header_reads_the_facts(tmp_path):
|
||||
data = small_edf(tmp_path / "a.edf")
|
||||
assert header(data) == Header(
|
||||
"N1001", "F", date(2025, 1, 5), date(2026, 3, 2), "LAB-1", 20.0, 3
|
||||
)
|
||||
|
||||
|
||||
def test_placeholders_are_none(tmp_path):
|
||||
data = small_edf(
|
||||
tmp_path / "a.edf", patient_code="X", sex="X", birthdate=None,
|
||||
startdate=date(1985, 1, 1), record_code="X",
|
||||
) # fmt: skip
|
||||
assert header(data) == Header(None, None, None, None, None, 20.0, 3)
|
||||
|
||||
|
||||
def test_header_does_not_read_the_signal(tmp_path):
|
||||
data = small_edf(tmp_path / "a.edf")
|
||||
truncated = data[: int(data[184:192])]
|
||||
assert header(truncated) == header(data)
|
||||
assert header(truncated).duration_s == 20.0
|
||||
with pytest.warns(UserWarning, match="Updating header"):
|
||||
with pytest.raises(FileNotValid, match="truncated"):
|
||||
_kept(truncated)
|
||||
|
||||
|
||||
def test_zero_signal_header_is_valid(tmp_path):
|
||||
data = small_edf(tmp_path / "a.edf")
|
||||
zero = data[:184] + b"256 " + data[192:252] + b"0 "
|
||||
assert header(zero).channels == 0
|
||||
with pytest.raises(FileNotValid, match="ZeroDivisionError"):
|
||||
_kept(zero)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", [b"", b"x" * 100, b"x" * 300])
|
||||
def test_not_an_edf_is_not_valid(data):
|
||||
with pytest.raises(FileNotValid):
|
||||
header(data)
|
||||
|
||||
|
||||
def test_kept_channels_are_unchanged(tmp_path):
|
||||
data = small_edf(tmp_path / "a.edf")
|
||||
assert _kept(data) == [("Fp1", "Fp1"), ("Fp2", "Fp2"), ("Cz", "Cz")]
|
||||
@@ -0,0 +1,54 @@
|
||||
import json
|
||||
from datetime import date
|
||||
from hashlib import sha256
|
||||
|
||||
from edf_files import SEX_MAP, hospital, pipeline, small_edf
|
||||
|
||||
|
||||
def test_edf_pipeline_keeps_and_links_the_files(platform, tmp_path):
|
||||
hospital_url = hospital(tmp_path / "hospital.db")
|
||||
uploads = tmp_path / "uploads"
|
||||
uploads.mkdir()
|
||||
a = small_edf(uploads / "a.edf")
|
||||
b = small_edf(uploads / "b.edf", patient_code="N1002", birthdate=date(2025, 2, 5))
|
||||
bad = b"junk"
|
||||
(uploads / "bad.edf").write_bytes(bad)
|
||||
clean = {sha256(a).hexdigest(): a, sha256(b).hexdigest(): b}
|
||||
bad_hash = sha256(bad).hexdigest()
|
||||
|
||||
drawing = tmp_path / "edf.json"
|
||||
drawing.write_text(json.dumps(pipeline(hospital_url, str(uploads))))
|
||||
concepts = tmp_path / "sex.json"
|
||||
concepts.write_text(json.dumps(SEX_MAP))
|
||||
platform.save("concept_maps", "edf_sex", concepts)
|
||||
platform.save("pipelines", "edf", drawing)
|
||||
|
||||
for _ in range(2):
|
||||
platform.ingest("edf")
|
||||
people = dict(
|
||||
platform.query(
|
||||
"select i.value, p.person_id from silver.person p "
|
||||
"join silver.person_identifier i on i.person_id = p.person_id"
|
||||
)
|
||||
)
|
||||
assert set(people) == {"N1001", "N1002"}
|
||||
studies = platform.query("select person_id, study_date, lab_record_id, edf from silver.eeg")
|
||||
assert {(p, str(d), lab, key) for p, d, lab, key in studies} == {
|
||||
(people["N1001"], "2026-03-02", "LAB-1", sha256(a).hexdigest()),
|
||||
(people["N1002"], "2026-03-02", "LAB-1", sha256(b).hexdigest()),
|
||||
}
|
||||
assert len(studies) == 2
|
||||
assert {
|
||||
key: bytes(value)
|
||||
for key, value in platform.query("select key, content from bronze.files")
|
||||
} == {**clean, bad_hash: bad}
|
||||
assert platform.count("bronze.n__edf__header") == 3
|
||||
((error, *fields),) = platform.query(
|
||||
"select edf_error, edf_patient_code, edf_sex, edf_birth_date, edf_study_date, "
|
||||
"edf_record_code, edf_duration_s, edf_channels from bronze.n__edf__header "
|
||||
f"where content = '{bad_hash}'"
|
||||
)
|
||||
assert error and fields == [None] * 7
|
||||
((study, reasons),) = platform.query("select study, _held from bronze.staged__held")
|
||||
assert study == "eeg"
|
||||
assert any(reason.startswith("study_date:") for reason in json.loads(reasons))
|
||||
@@ -0,0 +1,60 @@
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from edf_files import SEX_MAP, hospital, pipeline, small_edf
|
||||
|
||||
|
||||
def _ok(response):
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def wait_for(api, run_id: str, seconds: int = 900) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while (state := _ok(api.get(f"/runs/{run_id}"))["state"]) in ("queued", "running"):
|
||||
assert time.monotonic() < deadline, f"run {run_id} still {state}"
|
||||
time.sleep(2)
|
||||
assert state == "succeeded"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
|
||||
def test_an_uploaded_edf_is_analysed_by_itself(api, tmp_path):
|
||||
hospital_url = hospital(tmp_path / "hospital.db")
|
||||
data = small_edf(tmp_path / "a.edf")
|
||||
|
||||
def upload():
|
||||
result = _ok(api.post("/ingest/uploads", files={"file": ("a.edf", data)}))
|
||||
assert set(result) == {"bucket_url", "file_name"}
|
||||
assert result["file_name"] == "a.edf"
|
||||
return result["bucket_url"]
|
||||
|
||||
def run():
|
||||
wait_for(api, _ok(api.post("/ingest/pipelines/edf/runs", json={}))["run_id"])
|
||||
|
||||
def runs():
|
||||
return _ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))
|
||||
|
||||
bucket_url = upload()
|
||||
_ok(api.put("/ingest/concept-maps/edf_sex", json=SEX_MAP))
|
||||
_ok(api.put("/ingest/pipelines/edf", json=pipeline(hospital_url, bucket_url)))
|
||||
run()
|
||||
|
||||
deadline = time.monotonic() + 600
|
||||
found = runs()
|
||||
while not any(item["state"] == "succeeded" for item in found):
|
||||
assert time.monotonic() < deadline, found
|
||||
time.sleep(2)
|
||||
found = runs()
|
||||
(first,) = found
|
||||
(study,) = _ok(api.get("/tea/eegs"))
|
||||
assert study["study_date"] == "2026-03-02"
|
||||
assert study["lab_record_id"] == "LAB-1"
|
||||
assert study["analysed"] is True
|
||||
|
||||
assert upload() == bucket_url
|
||||
run()
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
assert [item["id"] for item in runs()] == [first["id"]]
|
||||
time.sleep(2)
|
||||
assert [item["id"] for item in runs()] == [first["id"]]
|
||||
@@ -0,0 +1,380 @@
|
||||
"""`execution.map` returns the same list in every mode, spreads lazy input without loading it
|
||||
all, fails fast when the cluster is wrong, cleans up after a cancel, and reports progress on
|
||||
the Dagster run. Remote tests need a scheduler: set `DASK_TEST_SCHEDULER` and
|
||||
`DASK_EXPECTED_WORKERS` (the compose `test` profile does)."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import cloudpickle
|
||||
import dagster as dg
|
||||
import numpy as np
|
||||
import psutil
|
||||
import pytest
|
||||
|
||||
from models import execution
|
||||
from models.execution import Execution, ExecutionError, Progress
|
||||
from persistance import cluster
|
||||
|
||||
cloudpickle.register_pickle_by_value(sys.modules[__name__])
|
||||
|
||||
|
||||
def by_value(fn):
|
||||
"""Mark a worker function so that Dask ships its code, not its name: the scheduler
|
||||
unpickles task graphs too, and has no test module (Dask wraps `fn` in a task, which
|
||||
hides the by-value registration above from it)."""
|
||||
fn.__module__ = "__main__"
|
||||
return fn
|
||||
|
||||
|
||||
@by_value
|
||||
def square(x):
|
||||
return int(x) ** 2
|
||||
|
||||
|
||||
@by_value
|
||||
def numeric(x):
|
||||
rng = np.random.default_rng(x)
|
||||
return float(np.linalg.norm(rng.normal(size=(20, 20)) @ rng.normal(size=(20, 20))))
|
||||
|
||||
|
||||
@by_value
|
||||
def slow(x):
|
||||
time.sleep(0.2)
|
||||
return x
|
||||
|
||||
|
||||
@by_value
|
||||
def sleep_forever(x):
|
||||
time.sleep(60)
|
||||
|
||||
|
||||
@by_value
|
||||
def fail_on_three(x):
|
||||
if x == 3:
|
||||
raise RuntimeError("three")
|
||||
return x
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def env(monkeypatch):
|
||||
for name in ("EXECUTION_MODE", "DASK_SCHEDULERS"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
monkeypatch.setenv("DASK_LOCAL_WORKERS", "2")
|
||||
|
||||
|
||||
def fake_context():
|
||||
context = SimpleNamespace(run_id="r1", logs=[], tags=[], metadata=[])
|
||||
context.log = SimpleNamespace(info=context.logs.append)
|
||||
context.instance = SimpleNamespace(add_run_tags=lambda run, tags: context.tags.append(tags))
|
||||
context.add_output_metadata = context.metadata.append
|
||||
return context
|
||||
|
||||
|
||||
def test_resolve_defaults_and_allow_list(monkeypatch):
|
||||
assert execution.resolve().mode == "local"
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
assert execution.resolve().mode == "sync"
|
||||
with pytest.raises(ExecutionError):
|
||||
execution.resolve(Execution(mode="remote"))
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786,tcp://b:8786")
|
||||
assert execution.resolve(Execution(mode="remote")).scheduler == "tcp://a:8786"
|
||||
assert execution.resolve(Execution(mode="remote", scheduler="b:8786")).scheduler == (
|
||||
"tcp://b:8786"
|
||||
)
|
||||
assert execution.options().schedulers == ["tcp://a:8786", "tcp://b:8786"]
|
||||
|
||||
|
||||
def test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode(monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786")
|
||||
with pytest.raises(ExecutionError, match="not in DASK_SCHEDULERS"):
|
||||
execution.resolve(Execution(mode="remote", scheduler="c:8786"))
|
||||
with pytest.raises(ExecutionError, match="only goes with remote"):
|
||||
execution.resolve(Execution(mode="local", scheduler="a:8786"))
|
||||
with pytest.raises(ExecutionError, match="not host:port"):
|
||||
cluster.normalize("http://a:1")
|
||||
|
||||
|
||||
def test_map_sync_keeps_input_order_and_reports_each_item(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
lines = []
|
||||
assert execution.map(square, range(5), log=lines.append) == [0, 1, 4, 9, 16]
|
||||
assert lines[0] == "working: 0/5" and lines[-1] == "working: 5/5"
|
||||
|
||||
|
||||
def test_map_empty_items_starts_nothing(monkeypatch):
|
||||
import distributed
|
||||
|
||||
def boom(*a, **k):
|
||||
raise AssertionError("a cluster was started")
|
||||
|
||||
monkeypatch.setattr(distributed, "LocalCluster", boom)
|
||||
assert execution.map(square, []) == []
|
||||
assert execution.map(square, iter([]), total=0) == []
|
||||
|
||||
|
||||
def test_map_local_equals_sync(monkeypatch):
|
||||
items = list(range(12))
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
expected = execution.map(numeric, items, log=lambda s: None)
|
||||
monkeypatch.setenv("EXECUTION_MODE", "local")
|
||||
assert execution.map(numeric, items, log=lambda s: None) == expected
|
||||
|
||||
|
||||
def test_map_lazy_items_are_not_all_loaded_at_once():
|
||||
state = {"loaded": 0, "finished": 0, "peak": 0}
|
||||
lock = threading.Lock()
|
||||
|
||||
def generate():
|
||||
for i in range(30):
|
||||
with lock:
|
||||
state["loaded"] += 1
|
||||
state["peak"] = max(state["peak"], state["loaded"] - state["finished"])
|
||||
yield i
|
||||
|
||||
class Counting:
|
||||
def __init__(self):
|
||||
self.n = 0
|
||||
|
||||
out = []
|
||||
real = execution._Monitor.item_done
|
||||
|
||||
def item_done(self):
|
||||
with lock:
|
||||
state["finished"] += 1
|
||||
real(self)
|
||||
|
||||
execution._Monitor.item_done = item_done
|
||||
try:
|
||||
out = execution.map(slow, generate(), total=30, log=lambda s: None)
|
||||
finally:
|
||||
execution._Monitor.item_done = real
|
||||
assert out == list(range(30))
|
||||
assert state["peak"] <= max(4, 2 * 2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["sync", "local"])
|
||||
def test_map_on_error_converts_a_failed_item(monkeypatch, mode):
|
||||
monkeypatch.setenv("EXECUTION_MODE", mode)
|
||||
out = execution.map(fail_on_three, range(6), on_error=lambda item, e: -item, log=lambda s: None)
|
||||
assert out == [0, 1, 2, -3, 4, 5]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["sync", "local"])
|
||||
def test_map_raises_without_on_error(monkeypatch, mode):
|
||||
monkeypatch.setenv("EXECUTION_MODE", mode)
|
||||
with pytest.raises(RuntimeError, match="three"):
|
||||
execution.map(fail_on_three, range(6), log=lambda s: None)
|
||||
|
||||
|
||||
def test_eta_smoothing_and_threshold():
|
||||
eta = execution.Eta(alpha=0.3, min_done=3)
|
||||
eta.update(0.0, 0)
|
||||
eta.update(1.0, 2)
|
||||
assert eta.eta_s(10) is None # fewer than 3 done
|
||||
eta.update(2.0, 4)
|
||||
assert eta.eta_s(10) == pytest.approx((10 - 4) / 2.0)
|
||||
eta.update(3.0, 8) # a faster burst: 4 items/s
|
||||
assert eta.rate == pytest.approx(0.3 * 4 + 0.7 * 2.0)
|
||||
assert eta.eta_s(10) == pytest.approx(2 / eta.rate)
|
||||
|
||||
|
||||
def test_progress_tag_and_log_lines_inside_running(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
context = fake_context()
|
||||
with execution.running(context):
|
||||
execution.map(square, range(6), phase="analyzing")
|
||||
first, last = (Progress.model_validate_json(t[execution.PROGRESS_TAG]) for t in
|
||||
(context.tags[0], context.tags[-1])) # fmt: skip
|
||||
assert first.done == 0 and last.done == last.total == 6 and last.phase == "analyzing"
|
||||
assert context.logs[0] == "analyzing: 0/6" and context.logs[-1] == "analyzing: 6/6"
|
||||
summary = context.metadata[-1]
|
||||
assert set(summary) == {"mode", "scheduler", "phases", "peak_cpu_pct", "peak_memory_bytes"}
|
||||
|
||||
|
||||
def test_no_tag_outside_running(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
context = fake_context()
|
||||
execution.map(square, range(3), log=context.logs.append)
|
||||
assert context.tags == [] and context.logs
|
||||
|
||||
|
||||
def test_version_mismatch_fails_before_any_task(monkeypatch):
|
||||
import distributed
|
||||
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "x:8786")
|
||||
submitted = []
|
||||
|
||||
class SpyClient:
|
||||
def __init__(self, *a, **k):
|
||||
self.closed = False
|
||||
|
||||
def submit(self, *a, **k):
|
||||
submitted.append(a)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
monkeypatch.setattr(distributed, "Client", SpyClient)
|
||||
monkeypatch.setattr(cluster, "versions_error", lambda client: "numpy 1.0 vs 2.0")
|
||||
with pytest.raises(execution.ClusterVersionError, match="numpy 1.0 vs 2.0"):
|
||||
execution.map(square, range(3), execution=Execution(mode="remote"))
|
||||
assert submitted == []
|
||||
|
||||
|
||||
CANCEL_SCRIPT = textwrap.dedent(
|
||||
"""
|
||||
import signal, sys
|
||||
from models import execution
|
||||
from models.execution import Execution
|
||||
|
||||
def stop(*a):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
def sleep_forever(x):
|
||||
import time
|
||||
time.sleep(60)
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
import cloudpickle
|
||||
cloudpickle.register_pickle_by_value(sys.modules["__main__"])
|
||||
execution.map(sleep_forever, range({n}), log=lambda s: print(s, flush=True),
|
||||
execution=Execution(mode="{mode}"))
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def run_cancelled(mode, n):
|
||||
"""Start a `map` of sleepers in a subprocess, send SIGTERM after its first line."""
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-c", CANCEL_SCRIPT.format(n=n, mode=mode)],
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
env={**os.environ, "DASK_LOCAL_WORKERS": "2"},
|
||||
)
|
||||
assert proc.stdout.readline().startswith("working: 0/")
|
||||
time.sleep(3) # the cluster is up and the tasks are submitted
|
||||
return proc
|
||||
|
||||
|
||||
def test_local_cancel_leaves_no_worker_processes():
|
||||
proc = run_cancelled("local", 4)
|
||||
children = psutil.Process(proc.pid).children(recursive=True)
|
||||
assert children
|
||||
proc.send_signal(signal.SIGTERM)
|
||||
proc.wait(timeout=30)
|
||||
deadline = time.time() + 20
|
||||
while time.time() < deadline and any(c.is_running() and c.status() != "zombie"
|
||||
for c in children): # fmt: skip
|
||||
time.sleep(0.5)
|
||||
assert not [c for c in children if c.is_running() and c.status() != "zombie"]
|
||||
|
||||
|
||||
def test_health_sync_and_local(monkeypatch):
|
||||
sync = execution.health(Execution(mode="sync"))
|
||||
assert sync.reachable and sync.workers == 1 and sync.threads == 1
|
||||
local = execution.health(Execution(mode="local"))
|
||||
assert local.reachable and local.workers == 2 and local.versions_ok is None
|
||||
|
||||
|
||||
def test_health_unreachable_remote(monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1")
|
||||
started = time.time()
|
||||
h = execution.health(Execution(mode="remote"))
|
||||
assert not h.reachable and h.error and time.time() - started < 15
|
||||
|
||||
|
||||
def test_health_rejects_unlisted_scheduler(monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1")
|
||||
with pytest.raises(ExecutionError):
|
||||
execution.health(Execution(mode="remote", scheduler="tcp://127.0.0.1:2"))
|
||||
with pytest.raises(ExecutionError):
|
||||
execution.health(Execution(mode="sync"), reference="../x")
|
||||
|
||||
|
||||
def test_progress_reaches_the_dagster_run():
|
||||
@dg.op
|
||||
def analyze(context) -> dg.Nothing:
|
||||
with execution.running(context, Execution(mode="sync")):
|
||||
execution.map(square, range(6), phase="analyzing")
|
||||
|
||||
@dg.op(ins={"start": dg.In(dg.Nothing)})
|
||||
def after(context):
|
||||
pass
|
||||
|
||||
@dg.job
|
||||
def two():
|
||||
after(analyze())
|
||||
|
||||
instance = dg.DagsterInstance.ephemeral()
|
||||
result = two.execute_in_process(instance=instance)
|
||||
assert result.success
|
||||
tags = instance.get_run_by_id(result.run_id).tags
|
||||
progress = Progress.model_validate_json(tags[execution.PROGRESS_TAG])
|
||||
assert (progress.done, progress.total, progress.phase) == (6, 6, "analyzing")
|
||||
event = next(e for e in result.events_for_node("analyze") if e.is_successful_output)
|
||||
assert "mode" in event.event_specific_data.metadata
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def scheduler():
|
||||
address = os.environ.get("DASK_TEST_SCHEDULER")
|
||||
if not address:
|
||||
pytest.skip("DASK_TEST_SCHEDULER is not set")
|
||||
expected = int(os.environ["DASK_EXPECTED_WORKERS"])
|
||||
os.environ["DASK_SCHEDULERS"] = address
|
||||
deadline = time.time() + 60
|
||||
while time.time() < deadline:
|
||||
if execution.health(Execution(mode="remote", scheduler=address)).workers == expected:
|
||||
return cluster.normalize(address)
|
||||
time.sleep(1)
|
||||
pytest.fail(f"the scheduler never showed {expected} workers")
|
||||
|
||||
|
||||
def test_map_remote_equals_sync(scheduler, monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
|
||||
items = list(range(12))
|
||||
expected = execution.map(numeric, items, execution=Execution(mode="sync"), log=print)
|
||||
remote = execution.map(numeric, items, execution=Execution(mode="remote"), log=print)
|
||||
assert remote == expected
|
||||
|
||||
|
||||
def test_health_remote(scheduler, monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
|
||||
h = execution.health(Execution(mode="remote"))
|
||||
assert h.reachable and h.workers == h.expected_workers == 2
|
||||
assert h.versions_ok and h.latency_ms > 0 and h.dashboard_ok
|
||||
|
||||
|
||||
def test_remote_cancel_cancels_futures(scheduler, monkeypatch):
|
||||
from distributed import Client
|
||||
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
|
||||
proc = run_cancelled("remote", 8)
|
||||
proc.send_signal(signal.SIGTERM)
|
||||
proc.wait(timeout=30)
|
||||
with Client(scheduler, timeout=10) as client:
|
||||
deadline = time.time() + 20
|
||||
processing = None
|
||||
while time.time() < deadline:
|
||||
processing = client.run_on_scheduler(execution._counts).get("processing", 0)
|
||||
if processing == 0:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
assert processing == 0
|
||||
assert client.scheduler_info()["workers"]
|
||||
|
||||
|
||||
def test_progress_json_is_stable(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
context = fake_context()
|
||||
with execution.running(context):
|
||||
execution.map(square, range(2))
|
||||
assert json.loads(context.tags[-1][execution.PROGRESS_TAG])["mode"] == "sync"
|
||||
+6
-18
@@ -27,15 +27,8 @@ def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> di
|
||||
return {
|
||||
"nodes": nodes
|
||||
+ [
|
||||
table("archivos", site_url, "ArchivosUni", schema="dbo"),
|
||||
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",
|
||||
},
|
||||
table("resultados", site_url, "ResultadoSubrogado", schema="dbo"),
|
||||
{"id": "text", "kind": "read", "inputs": ["resultados"], "column": "archivo"},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -58,13 +51,8 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, t
|
||||
by_place = {}
|
||||
for r in truth:
|
||||
by_place.setdefault(r["where"].split(":")[0], []).append(r)
|
||||
documents = len(by_place["ArchivosUni"]) + len(by_place["ResultadosSubrogados"])
|
||||
expected = {
|
||||
"archivos": len(by_place["ArchivosUni"]),
|
||||
"subrogados": len(by_place["ResultadosSubrogados"]),
|
||||
"archivos_text": len(by_place["ArchivosUni"]),
|
||||
"subrogados_text": len(by_place["ResultadosSubrogados"]),
|
||||
}
|
||||
documents = len(truth)
|
||||
expected = {"resultados": documents, "text": documents}
|
||||
for name, names in tables.items():
|
||||
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
||||
for t in names:
|
||||
@@ -87,8 +75,8 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, t
|
||||
assert query(corrected) == [("64000",)]
|
||||
|
||||
space = re.compile(r"\s+")
|
||||
for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")):
|
||||
read = query(f"select id, text, ocr, error from bronze.n__site__{node}_text")
|
||||
for table in ("ResultadoSubrogado",):
|
||||
read = query("select id, text, ocr, error from bronze.n__site__text")
|
||||
assert [error for *_, error in read if error is not None] == []
|
||||
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
|
||||
for r in by_place[table]:
|
||||
|
||||
+38
-41
@@ -2,10 +2,11 @@
|
||||
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
|
||||
two SQL Server tables, the institute's forms and what outsourced labs send back; an HPV result
|
||||
one SQL Server table, the institute's forms beside 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
|
||||
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.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -14,37 +15,18 @@ from datetime import date
|
||||
|
||||
from core import catalog
|
||||
|
||||
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 = {
|
||||
"cervical_cytology": ("sample_date", "screening_history", *GYN, *PRESENTS,
|
||||
"cervix_exam", "report_date", "adequacy", "result", "hpv", "hpv_16",
|
||||
"hpv_18", "cyto_findings_text", *CYTO),
|
||||
"cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16",
|
||||
"hpv_18"),
|
||||
"cervical_biopsy": ("request_date", "report_date", "histology"),
|
||||
"mammography": ("exam_date", "report_date", "adequacy", "birads"),
|
||||
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
|
||||
"er", "pr", "her2", "ki67_pct", "size_mm", "stage"),
|
||||
"breast_treatment": ("start_date", "kind"),
|
||||
"clinical_note": ("note_date", "specialty", "icd10"),
|
||||
"death": ("death_date",),
|
||||
} # fmt: skip
|
||||
BOOLS = {"hpv", "hpv_16", "hpv_18", *GYN, *PRESENTS, *CYTO}
|
||||
BOOLS = {"hpv", "hpv_16", "hpv_18"}
|
||||
NUMBERS = {"ki67_pct", "size_mm"}
|
||||
|
||||
|
||||
@@ -77,17 +59,27 @@ 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
|
||||
# by a pathology report (it shows no birth date) and held (torn) until a reviewer says
|
||||
# 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] = {}
|
||||
held, person_of = set(), {}
|
||||
for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
|
||||
held, nameless, named, person_of = set(), set(), set(), {}
|
||||
for record, person, why, *identifiers in q(
|
||||
"select _record, person_id, _held, full_name, birth_date, record_number "
|
||||
"from bronze.n__site__persons"
|
||||
):
|
||||
members.setdefault(person, set()).add(of[record])
|
||||
person_of[record] = person
|
||||
if why:
|
||||
if any(identifiers):
|
||||
named.add(person)
|
||||
if why and "no name" in why:
|
||||
nameless.add(person)
|
||||
elif why:
|
||||
held.add(person)
|
||||
assert nameless == set(members) - named, nameless
|
||||
torn = {p for p, who in members.items() if len(who) > 1}
|
||||
assert len(torn) == 1 and torn == held, (torn, held)
|
||||
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}
|
||||
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn | nameless}
|
||||
|
||||
# Every woman split into several persons (a misspelled form, say) is in the review
|
||||
# queue, joined by candidates.
|
||||
@@ -108,15 +100,14 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
|
||||
frontier -= reached
|
||||
assert persons <= reached, (x, persons)
|
||||
|
||||
# Every value accepted from a document is what the document says; and most of what 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).
|
||||
# Every value accepted from a typed document is what the document says; and most of what
|
||||
# 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.
|
||||
at = {r["where"]: r for r in truth}
|
||||
place = {
|
||||
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
|
||||
place = {r: f"ResultadoSubrogado:{i}"
|
||||
for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip
|
||||
record_of = {w: r for r, w in place.items()}
|
||||
accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows)
|
||||
for entity in FIELDS:
|
||||
@@ -128,22 +119,28 @@ 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)
|
||||
mine.setdefault(record, {})[field] = value(field, got)
|
||||
assert mine, entity
|
||||
stated = read = 0
|
||||
stated = read = scanned = 0
|
||||
missed: Counter = Counter()
|
||||
wrong = []
|
||||
for record, got in mine.items():
|
||||
t = at[place[record]]
|
||||
if not t.get("flipped"):
|
||||
truly = {f: v for f, v in said(t, entity).items() if v is not None}
|
||||
assert got == {f: value(f, truly.get(f)) for f in got}, (t["where"], got)
|
||||
differ = {f: (v, value(f, truly.get(f))) for f, v in got.items()
|
||||
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)
|
||||
missed.update(set(truly) - set(got))
|
||||
assert read >= 0.95 * stated, (entity, read, stated, missed)
|
||||
assert len(wrong) <= 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.
|
||||
misread = set()
|
||||
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:
|
||||
if record in place and person_of.get(record) not in torn | nameless:
|
||||
t, got = at[place[record]], json.loads(raw)
|
||||
truly = said(t, entity)
|
||||
assert {f: value(f, got.get(f)) for f in truly} != {
|
||||
@@ -160,7 +157,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
|
||||
for r in truth:
|
||||
record = record_of[r["where"]]
|
||||
got = accepted[entity].get(record)
|
||||
if got is None or person_of[record] in torn or record in misread:
|
||||
if got is None or person_of[record] in torn | nameless or record in misread:
|
||||
continue
|
||||
at_key = (person_of[record], *(got.get(k) for k in key))
|
||||
merged.setdefault(at_key, {}).update(got)
|
||||
@@ -170,6 +167,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
|
||||
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)))
|
||||
for p, *values in rows if p not in torn} # fmt: skip
|
||||
for p, *values in rows if p not in torn | nameless} # fmt: skip
|
||||
assert got == expected, (entity, sorted(got - expected, key=str)[:4],
|
||||
sorted(expected - got, key=str)[:4]) # fmt: skip
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""The association fit and its parity with the pinned tea-lib source."""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core.tea import ADOS2_ITEMS
|
||||
from models.tea import association as a
|
||||
|
||||
REFERENCE = Path("/home/milk/tea-parity/specs/P2-ref")
|
||||
MODULES = {"toddler": "TODDLER", "module_1": "MODULO_1", "module_2": "MODULO_2"}
|
||||
ZONES = dict(zip(
|
||||
a.ZONE_ITEMS,
|
||||
("frontal_izq", "frontal_der", "frontal_media", "central", "parietal",
|
||||
"temporal_izq", "temporal_der", "occipital"),
|
||||
strict=True,
|
||||
)) # fmt: skip
|
||||
|
||||
|
||||
def test_firth_on_separation():
|
||||
frame = pd.DataFrame({"z": np.arange(12), "event": [0] * 6 + [1] * 6})
|
||||
fit = a.firth(frame, "event", "z", ())
|
||||
assert np.isfinite(fit["odds_ratio"])
|
||||
assert fit["ci_low"] < fit["odds_ratio"] < fit["ci_high"]
|
||||
|
||||
|
||||
def test_bh():
|
||||
np.testing.assert_allclose(a.bh([0.04, 0.01, np.nan, 0.03]), [0.04, 0.03, np.nan, 0.04])
|
||||
|
||||
|
||||
def test_ordinal_on_monotone_trend():
|
||||
frame = pd.DataFrame({"z": np.arange(12), "level": [0, 0, 1, 0, 1, 1, 2, 0, 2, 1, 2, 2]})
|
||||
assert a.ordinal(frame, "level", "z", (), high=2)["odds_ratio"] > 1
|
||||
|
||||
|
||||
def test_pairs_and_item_availability():
|
||||
assert len(a.pairs("item")) == 41
|
||||
assert len(a.pairs("domain")) == 15
|
||||
# Item order in the source, translated by meaning into the platform catalog names.
|
||||
assert ADOS2_ITEMS == [
|
||||
"vocalization_directed", "pointing", "gestures", "unusual_eye_contact",
|
||||
"facial_expressions", "gaze_integration", "shared_enjoyment", "response_to_name",
|
||||
"ignoring", "requesting", "showing", "joint_attention_initiation",
|
||||
"joint_attention_response", "social_overtures_quality", "social_overtures_caregiver",
|
||||
"reciprocal_communication", "rapport_quality", "intonation", "stereotyped_language",
|
||||
"unusual_sensory_interest", "hand_finger_mannerisms", "repetitive_interests",
|
||||
] # fmt: skip
|
||||
frame = pd.DataFrame(
|
||||
{
|
||||
"ados_module": ["toddler", "module_1", "module_2", "module_3"],
|
||||
"vocalization_directed": [3, 7, 1, 1],
|
||||
}
|
||||
)
|
||||
np.testing.assert_allclose(a.item_scores(frame, 1), [2, 0, np.nan, np.nan])
|
||||
|
||||
|
||||
def _reference(monkeypatch):
|
||||
package = ModuleType("p2_reference")
|
||||
package.__path__ = [str(REFERENCE)]
|
||||
contracts = ModuleType("tea.contracts")
|
||||
contracts.ZONES = tuple(ZONES.values())
|
||||
contracts.ASSOCIATION_COLUMNS = a.ASSOCIATION_COLUMNS
|
||||
contracts.SCORE_COLUMNS = a.SCORE_COLUMNS
|
||||
contracts.CONTRACT_VERSION = None
|
||||
monkeypatch.setitem(sys.modules, "p2_reference", package)
|
||||
monkeypatch.setitem(sys.modules, "tea.contracts", contracts)
|
||||
for name in ("_items", "_models", "api"):
|
||||
qualified = f"p2_reference.{name}"
|
||||
spec = importlib.util.spec_from_file_location(qualified, REFERENCE / f"{name}.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, qualified, module)
|
||||
spec.loader.exec_module(module)
|
||||
return sys.modules["p2_reference.api"]
|
||||
|
||||
|
||||
def test_reference_parity(monkeypatch):
|
||||
ref = _reference(monkeypatch)
|
||||
rng = np.random.default_rng(0)
|
||||
cohort = pd.DataFrame(
|
||||
{
|
||||
"key": range(50),
|
||||
"age_months": rng.uniform(16, 48, 50),
|
||||
"ados_module": rng.choice(list(MODULES), 50),
|
||||
"css": rng.integers(1, 11, 50),
|
||||
**{item: rng.choice([0, 1, 2, 3, 7, 8], 50) for item in ADOS2_ITEMS},
|
||||
**{
|
||||
predictor: rng.normal(size=50)
|
||||
for predictor in dict.fromkeys(pair["predictor"] for pair in a.pairs("item"))
|
||||
},
|
||||
}
|
||||
)
|
||||
other = cohort.drop(columns=ADOS2_ITEMS).copy()
|
||||
other["ados_module"] = other["ados_module"].map(MODULES)
|
||||
for number, (_, _, modules) in ref.it.ITEMS.items():
|
||||
for module, code in modules.items():
|
||||
chosen = other["ados_module"] == module
|
||||
other.loc[chosen, code] = cohort.loc[chosen, ADOS2_ITEMS[number - 1]]
|
||||
other = other.rename(
|
||||
columns={
|
||||
f"z_{b}_{zone}": f"z_{b}_{old}"
|
||||
for zone, old in ZONES.items()
|
||||
for b in ("spikes", "spindles")
|
||||
}
|
||||
)
|
||||
ours = a.Ados2Association().fit(cohort)
|
||||
theirs = ref.Ados2Association().fit(other)
|
||||
for actual, expected in (
|
||||
(ours.associations(), theirs.associations()),
|
||||
(a.Model(ours.fitted).predict(None, cohort), theirs.score(other)),
|
||||
):
|
||||
actual["zone"] = actual["zone"].replace(ZONES)
|
||||
pd.testing.assert_frame_equal(actual, expected, check_exact=True)
|
||||
@@ -0,0 +1,224 @@
|
||||
"""The tea_eeg job's graph, sensor, config classes and synthetic EEG scope."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import dagster as dg
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from sqlalchemy import inspect
|
||||
|
||||
from models import definitions, execution
|
||||
from models.definitions import (
|
||||
ExecutionConfig,
|
||||
ScopeConfig,
|
||||
after_ingest,
|
||||
defs,
|
||||
tea_eeg,
|
||||
tea_eeg_after_ingest,
|
||||
)
|
||||
from models.tea import jobs as tea_jobs
|
||||
from persistance import cluster, destination, eeg
|
||||
from synthetic import tea
|
||||
|
||||
|
||||
def _config(scope: dict) -> dict:
|
||||
return {"ops": {"tea_analyze_studies": {"config": {
|
||||
"scope": scope, "execution": {"mode": "sync"}}}}} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def calls(monkeypatch):
|
||||
log = []
|
||||
|
||||
def analyze(scope=None, *, rebuild_gold=True):
|
||||
log.append(("analyze", scope, rebuild_gold))
|
||||
return 2
|
||||
|
||||
monkeypatch.setattr(tea_jobs, "analyze", analyze)
|
||||
monkeypatch.setattr(tea_jobs, "score_curves", lambda: log.append(("score",)) or {"c": 3})
|
||||
monkeypatch.setattr(tea_jobs, "relate", lambda: log.append(("relate",)))
|
||||
monkeypatch.setattr(definitions.silver, "build", lambda sel: log.append(("build", sel)))
|
||||
return log
|
||||
|
||||
|
||||
def test_tea_eeg_runs_the_four_steps_in_order(calls):
|
||||
result = tea_eeg.execute_in_process(
|
||||
instance=dg.DagsterInstance.ephemeral(), run_config=_config({"mode": "first_n", "n": 2})
|
||||
)
|
||||
assert result.success
|
||||
assert [c[0] for c in calls] == ["analyze", "score", "relate", "build"]
|
||||
assert calls[0][1].n == 2 and calls[0][2] is False
|
||||
assert calls[3][1] == tea_jobs.GOLD_SELECT
|
||||
assert result.output_for_node("tea_analyze_studies") == {"analysed": 2}
|
||||
assert result.output_for_node("tea_score_curves") == {"scored": {"c": 3}}
|
||||
assert result.output_for_node("tea_relate_ados2") == {"ados2_association": None}
|
||||
assert result.output_for_node("tea_build_gold") == {"built": tea_jobs.GOLD_SELECT}
|
||||
|
||||
|
||||
def test_a_failing_analysis_stops_the_graph(calls, monkeypatch):
|
||||
def boom(scope=None, *, rebuild_gold=True):
|
||||
raise RuntimeError("no signal")
|
||||
|
||||
monkeypatch.setattr(tea_jobs, "analyze", boom)
|
||||
result = tea_eeg.execute_in_process(
|
||||
instance=dg.DagsterInstance.ephemeral(),
|
||||
run_config=_config({"mode": "pending"}),
|
||||
raise_on_error=False,
|
||||
)
|
||||
assert not result.success
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_a_bad_scope_fails_before_any_work(calls):
|
||||
result = tea_eeg.execute_in_process(
|
||||
instance=dg.DagsterInstance.ephemeral(),
|
||||
run_config=_config({"mode": "first_n"}),
|
||||
raise_on_error=False,
|
||||
)
|
||||
assert not result.success
|
||||
assert calls == []
|
||||
failure = next(e for e in result.all_events if e.is_step_failure)
|
||||
assert "first_n needs n" in str(failure.event_specific_data.error)
|
||||
|
||||
|
||||
def test_scope_validation():
|
||||
assert eeg.Scope().mode == "pending"
|
||||
assert eeg.Scope(mode="first_n", n=3).n == 3
|
||||
good = "p1|2024-05-06"
|
||||
assert eeg.Scope(mode="ids", ids=[good]).ids == [good]
|
||||
bad = [
|
||||
{"mode": "first_n"},
|
||||
{"mode": "first_n", "n": 0},
|
||||
{"mode": "first_n", "n": 2, "ids": [good]},
|
||||
{"mode": "ids"},
|
||||
{"mode": "ids", "ids": [good], "n": 1},
|
||||
{"mode": "ids", "ids": ["nobar"]},
|
||||
{"mode": "ids", "ids": ["p|2024-5-6"]},
|
||||
{"mode": "ids", "ids": ["|2024-05-06"]},
|
||||
{"mode": "ids", "ids": [f"p{i}|2024-05-06" for i in range(501)]},
|
||||
{"mode": "pending", "n": 1},
|
||||
{"mode": "pending", "ids": [good]},
|
||||
{"mode": "other"},
|
||||
{"extra": 1},
|
||||
]
|
||||
for kwargs in bad:
|
||||
with pytest.raises(ValidationError):
|
||||
eeg.Scope(**kwargs)
|
||||
assert len(eeg.Scope(mode="ids", ids=[f"p{i}|2024-05-06" for i in range(500)]).ids) == 500
|
||||
with pytest.raises(ValidationError, match="first_n needs n"):
|
||||
ScopeConfig(mode="first_n").model()
|
||||
|
||||
|
||||
def test_config_mirrors_match_the_shared_models():
|
||||
for config, shared in ((ScopeConfig, eeg.Scope), (ExecutionConfig, cluster.Execution)):
|
||||
assert list(config.model_fields) == list(shared.model_fields)
|
||||
for name, field in shared.model_fields.items():
|
||||
assert config.model_fields[name].default == field.default, name
|
||||
# a wrong value still reaches the shared model's validation
|
||||
with pytest.raises(ValidationError):
|
||||
ExecutionConfig(mode="cloud").model()
|
||||
with pytest.raises(ValidationError):
|
||||
ScopeConfig(mode="all").model()
|
||||
|
||||
|
||||
def test_after_ingest_requests_a_run_only_with_pending_eegs():
|
||||
skip = after_ingest("r1", lambda: False)
|
||||
assert isinstance(skip, dg.SkipReason)
|
||||
request = after_ingest("r1", lambda: True)
|
||||
assert isinstance(request, dg.RunRequest)
|
||||
assert request.run_key == "after-ingest-r1"
|
||||
scope = request.run_config["ops"]["tea_analyze_studies"]["config"]["scope"]
|
||||
assert scope == {"mode": "pending"}
|
||||
assert request.tags["domain"] == "tea" and request.tags["triggered_by"] == "r1"
|
||||
|
||||
|
||||
def test_definitions_load_with_every_job_and_the_sensor():
|
||||
dg.Definitions.validate_loadable(defs)
|
||||
names = {j.name for j in defs.jobs}
|
||||
assert names >= {"ingest", "train", "score", "analyze", "tea_eeg"}
|
||||
assert tea_eeg_after_ingest.default_status == dg.DefaultSensorStatus.RUNNING
|
||||
|
||||
|
||||
def test_relate_is_a_no_op_until_phase_2():
|
||||
assert tea_jobs.relate() is None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def synthetic_tea(platform, tmp_path, monkeypatch):
|
||||
tea.build(tmp_path / "hospital_tea.db")
|
||||
fixtures = Path(__file__).parents[2] / "tests" / "fixtures"
|
||||
drawing = tmp_path / "pipeline.json"
|
||||
drawing.write_text(
|
||||
(fixtures / "pipelines" / "hospital_tea.json")
|
||||
.read_text()
|
||||
.replace("{hospital}", str(tmp_path))
|
||||
)
|
||||
platform.save("concept_maps", "hospital_tea", fixtures / "concept_maps" / "hospital_tea.json")
|
||||
platform.save("pipelines", "tea", drawing)
|
||||
platform.ingest("tea")
|
||||
|
||||
for name in ("PLATFORM_DATABASE_URL", "DLT_DATA_DIR", "EXECUTION_MODE"):
|
||||
monkeypatch.setenv(name, platform.env[name])
|
||||
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
|
||||
destination.engine.cache_clear()
|
||||
try:
|
||||
yield platform
|
||||
finally:
|
||||
destination.engine.cache_clear()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
|
||||
def test_tea_eeg_first_n_analyses_exactly_n(synthetic_tea):
|
||||
table = "bronze.eeg_analysis"
|
||||
with destination.engine().connect() as con:
|
||||
has_analysis = inspect(con).has_table("eeg_analysis", schema="bronze")
|
||||
before = synthetic_tea.count(table) if has_analysis else 0
|
||||
pending = len(eeg.pending())
|
||||
tea_jobs.analyze(eeg.Scope(mode="first_n", n=3), rebuild_gold=False)
|
||||
assert synthetic_tea.count(table) == before + 3
|
||||
assert len(eeg.pending()) == pending - 3
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not os.environ.get("DASK_TEST_SCHEDULER"), reason="DASK_TEST_SCHEDULER is not set"
|
||||
)
|
||||
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
|
||||
def test_tea_eeg_remote_mode_gives_the_same_analysis(synthetic_tea):
|
||||
def snapshot():
|
||||
analyses = synthetic_tea.query(
|
||||
"select edf, valid, level, age_months, clean_fraction, bad_channels "
|
||||
"from bronze.eeg_analysis order by edf"
|
||||
)
|
||||
metrics = synthetic_tea.query(
|
||||
"select edf, code, value from bronze.eeg_metrics order by edf, code"
|
||||
)
|
||||
return analyses, metrics
|
||||
|
||||
assert tea_jobs.analyze(eeg.Scope(mode="first_n", n=2), rebuild_gold=False) == 2
|
||||
before, metrics_before = snapshot()
|
||||
ids = [study["id"] for study in eeg.studies() if study["analysed"]]
|
||||
assert len(ids) == 2
|
||||
|
||||
@dg.op
|
||||
def remote_analysis(context):
|
||||
remote = cluster.Execution(mode="remote", scheduler=os.environ["DASK_TEST_SCHEDULER"])
|
||||
with execution.running(context, remote):
|
||||
return tea_jobs.analyze(eeg.Scope(mode="ids", ids=ids), rebuild_gold=False)
|
||||
|
||||
@dg.job
|
||||
def reanalyze():
|
||||
remote_analysis()
|
||||
|
||||
result = reanalyze.execute_in_process()
|
||||
assert result.success
|
||||
assert result.output_for_node("remote_analysis") == 2
|
||||
after, metrics_after = snapshot()
|
||||
|
||||
def close(value):
|
||||
return pytest.approx(value, rel=1e-12) if isinstance(value, float) else value
|
||||
|
||||
assert [tuple(row) for row in after] == [tuple(map(close, row)) for row in before]
|
||||
assert [tuple(row) for row in metrics_after] == [
|
||||
tuple(map(close, row)) for row in metrics_before
|
||||
]
|
||||
@@ -0,0 +1,227 @@
|
||||
import hashlib
|
||||
import os
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import dagster as dg
|
||||
import pytest
|
||||
|
||||
from core import tea
|
||||
from core.pipeline import Extract, Pipeline, Source
|
||||
from core.tea import ados2
|
||||
from models.definitions import tea_preview
|
||||
from models.tea import preview as study
|
||||
from models.tea.eeg import analysis, curves
|
||||
from persistance import config, previews
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def preview_area(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
||||
return previews.area()
|
||||
|
||||
|
||||
def test_previews_area(preview_area):
|
||||
key = previews.put(b"file")
|
||||
assert key == hashlib.sha256(b"file").hexdigest()
|
||||
os.utime(preview_area / key, (1, 1))
|
||||
assert previews.put(b"file") == key
|
||||
assert (preview_area / key).stat().st_mtime == 1
|
||||
assert previews.get(key) == b"file"
|
||||
for invalid in ("../x", "abc"):
|
||||
with pytest.raises(ValueError):
|
||||
previews.get(invalid)
|
||||
with pytest.raises(LookupError, match=f"no preview file {'0' * 64}"):
|
||||
previews.get("0" * 64)
|
||||
previews.discard([key, None, "0" * 64])
|
||||
assert not (preview_area / key).exists()
|
||||
|
||||
old = previews.put(b"old")
|
||||
recent = previews.put(b"recent")
|
||||
os.utime(preview_area / old, (1, 1))
|
||||
assert previews.sweep() == 1
|
||||
assert {path.name for path in preview_area.iterdir()} == {recent}
|
||||
|
||||
|
||||
def test_an_unreadable_file_is_a_result_not_a_crash():
|
||||
result = study.preview(b"nope")
|
||||
assert result.eeg.valid is False
|
||||
assert result.eeg.checks
|
||||
assert result.ados2 is None
|
||||
assert result.eeg.recorded_on is None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valid_study(monkeypatch):
|
||||
metric = analysis.Metric("paroxysmal_spikes", 3, {"F3": 3, "F4": 0}, {"frontal": 3})
|
||||
analysed = analysis.Analysis(
|
||||
valid=True,
|
||||
level="valid",
|
||||
age_months=42,
|
||||
clean_fraction=1,
|
||||
bad_channels=0,
|
||||
channels=19,
|
||||
duration_min=20,
|
||||
line_noise_db=None,
|
||||
sleep=True,
|
||||
checks=[],
|
||||
metrics=[metric],
|
||||
features={"eeg-spikes": {curves.EXPOSURE: 20}},
|
||||
error=None,
|
||||
)
|
||||
monkeypatch.setattr(analysis, "analyze", lambda *_: analysed)
|
||||
|
||||
|
||||
def test_scores_come_from_the_champions(monkeypatch, valid_study):
|
||||
baseline = dict.fromkeys(("value", "electrode_F3", "zone_frontal"))
|
||||
model = SimpleNamespace(unwrap_python_model=lambda: SimpleNamespace(baseline=baseline))
|
||||
monkeypatch.setattr(study.registry, "champion", lambda _: (3, model))
|
||||
score = {"z": 1, "outside": 0, "p5": 0, "median": 2, "p95": 4}
|
||||
|
||||
def deviations(models, analysed):
|
||||
assert set(models) == set(curves.SCENARIOS)
|
||||
assert analysed.metrics[0].electrodes == {"F3": 3}
|
||||
return {
|
||||
"paroxysmal_spikes": {
|
||||
"value": score,
|
||||
"electrodes": {"F3": score},
|
||||
"zones": {"frontal": score},
|
||||
}
|
||||
}
|
||||
|
||||
monkeypatch.setattr(curves, "deviations", deviations)
|
||||
result = study.preview(b"edf")
|
||||
metric = result.eeg.metrics[0]
|
||||
assert metric.score == previews.Score(**score)
|
||||
assert metric.electrodes == {
|
||||
"F3": previews.Site(value=3, score=previews.Score(**score)),
|
||||
"F4": previews.Site(value=0, score=None),
|
||||
}
|
||||
assert metric.zones == {"frontal": previews.Site(value=3, score=previews.Score(**score))}
|
||||
assert metric.model == "tea.eeg-spikes/3"
|
||||
assert not result.warnings
|
||||
|
||||
|
||||
def test_no_champions_warns_and_leaves_z_empty(monkeypatch, valid_study):
|
||||
monkeypatch.setattr(study.registry, "champion", lambda _: None)
|
||||
result = study.preview(b"edf")
|
||||
assert result.warnings == ["there are no champion age curves: no z is shown"]
|
||||
metric = result.eeg.metrics[0]
|
||||
assert metric.score is metric.model is None
|
||||
assert all(site.score is None for site in (metric.electrodes | metric.zones).values())
|
||||
|
||||
|
||||
def _pipeline(patterns):
|
||||
return Pipeline(
|
||||
nodes=[
|
||||
Source(id="source", source="dlt.sources.sql_database:sql_table"),
|
||||
Extract(
|
||||
id="x",
|
||||
inputs=["source"],
|
||||
column="text",
|
||||
entity="ados2",
|
||||
method="patterns",
|
||||
patterns=patterns,
|
||||
), # fmt: skip
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_ados2_read_with_the_pipeline_patterns(monkeypatch):
|
||||
text = "module module_1; date 2025-01-01; pointing 2; gestures 1; intonation 3"
|
||||
patterns = {
|
||||
"module": r"module (\w+)",
|
||||
"evaluation_date": r"date ([\d-]+)",
|
||||
"pointing": r"pointing (\d+)",
|
||||
"gestures": r"gestures (\d+)",
|
||||
"intonation": r"intonation (\d+)",
|
||||
}
|
||||
monkeypatch.setattr(study.graph, "read_file", lambda _: {"text": text, "error": None})
|
||||
monkeypatch.setattr(study.config_log, "get", lambda _: (1, _pipeline(patterns)))
|
||||
birth = date(2022, 1, 1)
|
||||
result = study.preview(b"edf", b"%PDF", birth)
|
||||
row = dict(module="module_1", evaluation_date=date(2025, 1, 1),
|
||||
pointing=2, gestures=1, intonation=3) # fmt: skip
|
||||
assert result.ados2 is not None
|
||||
assert result.ados2.items == {
|
||||
name: row.get(name) for name in tea.SOCIAL_AFFECT_ITEMS + tea.RESTRICTED_REPETITIVE_ITEMS
|
||||
}
|
||||
assert result.ados2.module == row["module"]
|
||||
assert result.ados2.evaluation_date == row["evaluation_date"]
|
||||
assert result.ados2.read == sorted(row)
|
||||
assert (result.ados2.css, result.ados2.classification) == ados2.score(row, birth)
|
||||
assert not result.warnings
|
||||
|
||||
|
||||
def test_ados2_problems_are_warnings_not_errors(monkeypatch):
|
||||
def check(report, *warnings):
|
||||
result = study.preview(b"edf", report)
|
||||
assert result.eeg == study.preview(b"edf").eeg
|
||||
assert result.warnings == list(warnings)
|
||||
return result.ados2
|
||||
|
||||
assert check(b"text", "the ADOS-2 file is not a PDF") is None
|
||||
monkeypatch.setattr(study.graph, "read_file", lambda _: {"error": "broken"})
|
||||
assert check(b"%PDF", "the ADOS-2 report could not be read: broken") is None
|
||||
|
||||
def missing(_):
|
||||
raise LookupError("tea")
|
||||
|
||||
text = "pointing bad; date 2025-01-01"
|
||||
monkeypatch.setattr(study.graph, "read_file", lambda _: {"text": text, "error": None})
|
||||
monkeypatch.setattr(study.config_log, "get", missing)
|
||||
assert check(b"%PDF", "no saved pipeline tea: the ADOS-2 report is not read") is None
|
||||
monkeypatch.setattr(study.config_log, "get", lambda _: (1, Pipeline(nodes=[])))
|
||||
assert check(b"%PDF", "pipeline tea has no ados2 extract node") is None
|
||||
monkeypatch.setattr(
|
||||
study.config_log, "get", lambda _: (1, _pipeline({"module": r"missing (.)"}))
|
||||
)
|
||||
assert check(b"%PDF", "no ADOS-2 field was found in the report") is None
|
||||
|
||||
patterns = {"pointing": r"pointing (\w+)"}
|
||||
monkeypatch.setattr(study.config_log, "get", lambda _: (1, _pipeline(patterns)))
|
||||
report = check(
|
||||
b"%PDF",
|
||||
"pointing: could not read 'bad' as a number",
|
||||
"ADOS-2 not scored: no evaluation date",
|
||||
)
|
||||
assert report is not None
|
||||
assert report.read == ["pointing"]
|
||||
assert report.items["pointing"] is report.css is report.classification is None
|
||||
|
||||
patterns = {"evaluation_date": r"date ([\d-]+)"}
|
||||
report = check(
|
||||
b"%PDF",
|
||||
"the ADOS-2 score could not be calculated: the report lacks the module or the item scores",
|
||||
)
|
||||
assert report is not None
|
||||
assert report.css is report.classification is None
|
||||
|
||||
|
||||
def _execute(key, ados_key, *, raise_on_error=True):
|
||||
with dg.DagsterInstance.ephemeral() as instance:
|
||||
return tea_preview.execute_in_process(
|
||||
run_config={"ops": {"preview_study": {"config": {"edf": key, "ados2": ados_key}}}},
|
||||
instance=instance,
|
||||
raise_on_error=raise_on_error,
|
||||
)
|
||||
|
||||
|
||||
def test_the_job_deletes_its_files_and_returns_the_result_as_output(preview_area):
|
||||
run = _execute(previews.put(b"edf"), previews.put(b"not a report"))
|
||||
assert run.success
|
||||
assert not list(preview_area.iterdir())
|
||||
assert run.output_for_node("preview_study") == {"valid": False, "warnings": 1}
|
||||
(event,) = run.filter_events(lambda event: event.event_type == dg.DagsterEventType.STEP_OUTPUT)
|
||||
result = previews.PreviewResult.model_validate(event.step_output_data.metadata["result"].value)
|
||||
assert result.eeg.valid is False
|
||||
|
||||
|
||||
def test_the_job_deletes_its_files_when_the_study_fails(monkeypatch, preview_area):
|
||||
def failed(*_):
|
||||
raise RuntimeError("study failed")
|
||||
|
||||
monkeypatch.setattr(study, "preview", failed)
|
||||
run = _execute(previews.put(b"edf"), previews.put(b"%PDF"), raise_on_error=False)
|
||||
assert not run.success
|
||||
assert not list(preview_area.iterdir())
|
||||
@@ -0,0 +1,144 @@
|
||||
import hashlib
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from edf_files import small_edf
|
||||
from pydantic import ValidationError
|
||||
|
||||
from models import definitions
|
||||
from models.tea import jobs
|
||||
from models.tea.eeg import curves, reference
|
||||
from persistance.cluster import Reference
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
|
||||
monkeypatch.delenv("TEA_REFERENCE_CACHE", raising=False)
|
||||
folder = tmp_path / "hel"
|
||||
folder.mkdir()
|
||||
for i in range(3):
|
||||
small_edf(folder / f"{i}.edf")
|
||||
ages = folder / "edades.csv"
|
||||
ages.write_text("name,age\n0.edf,1.5\n1.edf,2.0\n2.edf,2.5\n")
|
||||
return folder, ages
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def measurements(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def measure(studies, *, mains_hz):
|
||||
calls.append((studies, mains_hz))
|
||||
return [
|
||||
{"key": key, "age_months": age, "valid": True, "error": None, "features": {}}
|
||||
for key, _, age in studies
|
||||
]
|
||||
|
||||
monkeypatch.setattr(reference, "measure", measure)
|
||||
return calls
|
||||
|
||||
|
||||
def test_a_named_reference_resolves_under_the_root(cohort, measurements):
|
||||
_, measured, name, hz = jobs._reference(Reference(name="hel"))
|
||||
[(studies, mains_hz)] = measurements
|
||||
assert len(studies) == len(measured) == 3
|
||||
assert all(path.parent == cohort[0] for _, path, _ in studies)
|
||||
assert mains_hz == 50.0
|
||||
assert (name, hz) == ("hel", 50)
|
||||
|
||||
|
||||
def test_60_hz_changes_the_digest_and_is_passed_on(cohort, measurements):
|
||||
digest_50, *_ = jobs._reference(Reference(name="hel"))
|
||||
digest_60, _, _, hz = jobs._reference(Reference(name="hel", line_hz=60))
|
||||
assert digest_50 == hashlib.sha256(b"0.edf|18.0\n1.edf|24.0\n2.edf|30.0").hexdigest()
|
||||
assert digest_60 != digest_50
|
||||
assert hz == 60
|
||||
assert measurements[-1][1] == 60.0
|
||||
|
||||
|
||||
def test_the_cache_is_named_by_cohort_and_digest_and_reused(cohort, measurements, monkeypatch):
|
||||
cache = cohort[0].parent / "c"
|
||||
monkeypatch.setenv("TEA_REFERENCE_CACHE", str(cache))
|
||||
result = jobs._reference(Reference(name="hel"))
|
||||
assert [p.name for p in cache.iterdir()] == [f"hel-{result[0][:16]}.json"]
|
||||
assert jobs._reference(Reference(name="hel")) == result
|
||||
assert len(measurements) == 1
|
||||
|
||||
|
||||
def test_bad_references_fail_with_a_reason(cohort):
|
||||
folder, ages = cohort
|
||||
for name in ("..", ".", "nope"):
|
||||
with pytest.raises(ValueError) as exc:
|
||||
jobs._reference(Reference(name=name))
|
||||
assert str(exc.value) == f"no reference cohort {name!r}"
|
||||
|
||||
ages.write_text("name,age\n0.edf,1\n1.edf,4\n2.edf,5\n")
|
||||
with pytest.raises(
|
||||
ValueError, match="reference cohort 'hel' has no EDF with an age from 16 to 36 months"
|
||||
):
|
||||
jobs._reference(Reference(name="hel"))
|
||||
|
||||
ages.unlink()
|
||||
with pytest.raises(ValueError, match=r"reference cohort 'hel' has no edades\.csv"):
|
||||
jobs._reference(Reference(name="hel"))
|
||||
|
||||
with pytest.raises(ValidationError, match="name"):
|
||||
Reference(name="../x")
|
||||
with pytest.raises(ValidationError, match="line_hz"):
|
||||
Reference(name="hel", line_hz=55)
|
||||
|
||||
|
||||
def test_legacy_environment_still_works(cohort, measurements, monkeypatch):
|
||||
folder, ages = cohort
|
||||
monkeypatch.setenv("TEA_REFERENCE_DIR", str(folder))
|
||||
monkeypatch.setenv("TEA_REFERENCE_AGES", str(ages))
|
||||
_, measured, name, hz = jobs._reference(None)
|
||||
assert len(measured) == 3
|
||||
assert (name, hz) == ("hk1k", 50)
|
||||
assert measurements[0][1] == 50.0
|
||||
|
||||
|
||||
def test_train_records_cohort_and_line_hz(cohort, measurements, monkeypatch):
|
||||
monkeypatch.setattr(reference, "tables", lambda measured: {"curve": measured})
|
||||
monkeypatch.setattr(curves, "train", lambda table, name: {"value": {}})
|
||||
registrations = []
|
||||
|
||||
def register(*args):
|
||||
registrations.append(args)
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr(jobs.registry, "register", register)
|
||||
config = Reference(name="hel", line_hz=60)
|
||||
assert jobs.train("curve", reference=config) == 1
|
||||
[(_, _, params, _, reports)] = registrations
|
||||
digest, *_ = jobs._reference(config)
|
||||
assert params == {"cohort": "hel", "cohort_sha256": digest, "line_hz": "60"}
|
||||
technical = reports["technical_validation"]
|
||||
assert technical["cohort"] == "hel"
|
||||
assert technical["line_hz"] == 60
|
||||
|
||||
|
||||
def test_the_train_op_passes_the_reference_or_refuses_it(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def train(name, as_of, reference=None):
|
||||
calls.append((name, as_of, reference))
|
||||
return 1
|
||||
|
||||
fake = SimpleNamespace(train=train)
|
||||
monkeypatch.setattr(definitions, "_jobs", lambda domain: fake)
|
||||
config = {"ops": {"train_models": {"config": {
|
||||
"domain": "tea", "models": ["curve"], "execution": {"mode": "sync"},
|
||||
"reference": {"name": "a", "line_hz": 60},
|
||||
}}}} # fmt: skip
|
||||
assert definitions.train.execute_in_process(run_config=config).success
|
||||
assert calls == [("curve", None, Reference(name="a", line_hz=60))]
|
||||
|
||||
fake.train = lambda name, as_of: 1
|
||||
with pytest.raises(ValueError, match="tea models take no reference cohort"):
|
||||
definitions.train.execute_in_process(run_config=config)
|
||||
|
||||
|
||||
def test_reference_config_mirrors_the_shared_model():
|
||||
assert definitions.ReferenceConfig.model_fields.keys() == Reference.model_fields.keys()
|
||||
Reference in New Issue
Block a user