EDF reader node in the ingestion DSL: run_edf keeps each row and adds the header facts or the file's error; read.header parses the fixed EDF header without edfio

This commit is contained in:
2026-11-28 10:30:48 -06:00
parent cc95054a96
commit dce0e0c690
6 changed files with 363 additions and 5 deletions
+78
View File
@@ -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
+50
View File
@@ -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")]
+54
View File
@@ -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))
+60
View File
@@ -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"]]