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
+39 -1
View File
@@ -26,6 +26,7 @@ from core.pipeline import (
IDENTIFIERS, IDENTIFIERS,
QUOTES, QUOTES,
RECORD, RECORD,
Edf,
Extract, Extract,
Fhir, Fhir,
Join, Join,
@@ -43,6 +44,7 @@ from core.pipeline import (
matches, matches,
validate, validate,
) )
from models.tea.eeg import read
from persistance import config_log, files, nodes, silver from persistance import config_log, files, nodes, silver
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer 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 @cache
def _reader() -> MarkItDown: def _reader() -> MarkItDown:
return MarkItDown() return MarkItDown()
@@ -108,6 +116,36 @@ def run_read(p: str, node: Read):
return nodes.write(p, node.id, rows, READ_COLUMNS) 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): 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)]) return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)])
@@ -430,7 +468,7 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
RUNNERS: dict[str, Callable] = { RUNNERS: dict[str, Callable] = {
"source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map, "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 } # fmt: skip
+82 -4
View File
@@ -13,6 +13,7 @@ import io
import re import re
from dataclasses import dataclass from dataclasses import dataclass
from datetime import date, datetime from datetime import date, datetime
from struct import Struct
import edfio import edfio
import mne import mne
@@ -75,14 +76,91 @@ class Recording:
return [name for name in self.names if kind(name) in kinds] return [name for name in self.names if kind(name) in kinds]
def _kept(edf: bytes) -> list[tuple[str, str]]: @dataclass(frozen=True)
"""(label, name) of the channels to read: recognised, at the majority rate, first of each.""" class Header:
if len(edf) < 256: 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)") raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
def _fixed_header(data: bytes) -> dict:
_check_length(data)
try: 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 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 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: if not signals:
raise FileNotValid("the EDF declares zero signals") raise FileNotValid("the EDF declares zero signals")
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals] named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
+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"]]