diff --git a/models/definitions.py b/models/definitions.py index abdfba3..43d7120 100644 --- a/models/definitions.py +++ b/models/definitions.py @@ -1,17 +1,40 @@ """Dagster code location: every heavy step of the platform is a job defined here.""" import importlib +from collections.abc import Callable from datetime import date import dagster as dg -from models import graph +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 persistance import cluster, config_log, eeg, 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 @@ -43,6 +66,7 @@ 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() @dg.op @@ -51,14 +75,15 @@ def train_models(context: dg.OpExecutionContext, config: Training) -> dict: jobs = _jobs(config.domain) as_of = date.fromisoformat(config.as_of) if config.as_of else None 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) + 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 +115,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 +132,78 @@ 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} + + +@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) + + +defs = dg.Definitions(jobs=[ingest, train, score, analyze, tea_eeg], sensors=[tea_eeg_after_ingest]) diff --git a/models/tea/eeg/reference.py b/models/tea/eeg/reference.py index 67d92b6..450adfa 100644 --- a/models/tea/eeg/reference.py +++ b/models/tea/eeg/reference.py @@ -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]: diff --git a/models/tea/jobs.py b/models/tea/jobs.py index e306dc5..f9f7d1c 100644 --- a/models/tea/jobs.py +++ b/models/tea/jobs.py @@ -15,14 +15,15 @@ from pathlib import Path import mlflow.pyfunc import pandas as pd -from joblib import Parallel, delayed -from joblib.externals.loky import get_reusable_executor +from models import execution from models.tea.eeg import analysis, curves, reference from persistance import eeg, registry, silver 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: _risk) +GOLD_SELECT = ["tea_eeg_analyses+", "tea_eeg_metrics+"] # what a rebuild of TEA's gold selects class Baseline(mlflow.pyfunc.PythonModel): @@ -40,18 +41,21 @@ 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) @@ -65,7 +69,7 @@ def _reference() -> tuple[str, list[dict]]: path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None if path and path.exists(): return digest, json.loads(path.read_text()) - measured = reference.measure(studies, workers=os.cpu_count() or 4) + measured = reference.measure(studies) measured = [{**m, "key": str(m["key"])} for m in measured] if path: path.parent.mkdir(parents=True, exist_ok=True) @@ -109,6 +113,19 @@ def train(name: str, as_of: date | None = None) -> int: 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 relate() -> int | None: + """The ADOS-2 association: scores every analysed EEG with the `ados2_association` + champion (Phase 2). Returns the version that scored, None when the model has no champion. + It writes bronze only (ASSOCIATION_SCORES); the gold rebuild is the job's last step, not + this one's. Until Phase 2 exists it does nothing.""" + return None + + 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.""" diff --git a/tests/test_tea_job.py b/tests/test_tea_job.py new file mode 100644 index 0000000..9dddf6b --- /dev/null +++ b/tests/test_tea_job.py @@ -0,0 +1,139 @@ +"""The tea_eeg job's graph, its sensor and the config classes, in process (no EEG data).""" + +import dagster as dg +import pytest +from pydantic import ValidationError + +from models import definitions +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, eeg + + +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