228 lines
8.4 KiB
Python
228 lines
8.4 KiB
Python
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())
|