From 3950b3c1f561f2ce7b1eb2ce90db2a3e49c64aea Mon Sep 17 00:00:00 2001 From: alberto Date: Sat, 28 Nov 2026 13:37:27 -0600 Subject: [PATCH] tea_preview job: one file previewed, result as run output: preview analyses one staged EDF (and an ADOS-2 PDF) against the champions, writes nothing --- models/definitions.py | 38 ++++++- models/tea/preview.py | 216 ++++++++++++++++++++++++++++++++++++ tests/test_tea_preview.py | 227 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 479 insertions(+), 2 deletions(-) create mode 100644 models/tea/preview.py create mode 100644 tests/test_tea_preview.py diff --git a/models/definitions.py b/models/definitions.py index 9e2327b..ec7fb56 100644 --- a/models/definitions.py +++ b/models/definitions.py @@ -14,7 +14,8 @@ from core.domains import Domain from models import execution, graph from models.jobs import EmptyCohort from models.tea import jobs as tea_jobs -from persistance import bundle, cluster, config_log, eeg, silver +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) @@ -178,6 +179,38 @@ def tea_build_gold(context: dg.OpExecutionContext, related: dict) -> dict: 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.""" @@ -251,5 +284,6 @@ def import_bundle(): defs = dg.Definitions( - jobs=[ingest, train, score, analyze, tea_eeg, import_bundle], sensors=[tea_eeg_after_ingest] + jobs=[ingest, train, score, analyze, tea_eeg, tea_preview, import_bundle], + sensors=[tea_eeg_after_ingest], ) diff --git a/models/tea/preview.py b/models/tea/preview.py new file mode 100644 index 0000000..afe6fe8 --- /dev/null +++ b/models/tea/preview.py @@ -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) diff --git a/tests/test_tea_preview.py b/tests/test_tea_preview.py new file mode 100644 index 0000000..1f6b662 --- /dev/null +++ b/tests/test_tea_preview.py @@ -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())