Files
tea/tests/export/test_edf_export_synthetic.py
T
AlbertoPMDM 2b4bea0c7f export: optional KTLX -> EDF+ exporter vendored from eeg@92bc2a0
Step 2 of the plan. src/eeg/utils copied into tea_modulo.export with only the
imports changed; outside the EDF pipeline (extra `export`, script ktlx2edf).
Synthetic tests (ktlx_synth, edf export, patient) carried over: 43 pass.
2026-11-18 19:54:48 -06:00

238 lines
9.3 KiB
Python

"""
Edge cases on synthetic KTLX studies (tests/ktlx_synth.py): internal gap, edge padding, photic train, accented annotations, headbox
constants, schema 8, clamping and 8-character header fields.
"""
import logging
import struct
import warnings
from datetime import datetime
from types import SimpleNamespace
import edfio
import mne
import numpy as np
import pytest
import ktlx_synth as tr
from edfio import EdfSignal
from tea_modulo.export import edf_export as ex
from tea_modulo.export import ktlx
from tea_modulo.export.edf_annotations import BAD_ACQ_SKIP, clamped
from tea_modulo.export.edf_header import EDF_RECORDING_LEN, recording_header
from tea_modulo.export.edf_signals import DIGITAL_RANGE, build_signals, half_range
ACCENTED = "Fotoestimulación ñandú"
ACCENTED_STAMP = 200
def _append_note(folder, text, stamp):
"""Add an annotation to the synthetic .ent (before its terminator)."""
ent = next(folder.glob("*.ent"))
blob = ent.read_bytes()[:-16]
payload = f'(."Annotation" (.Stamp {stamp}) (.Text "{text}"))'.encode(
"cp1252") + b"\x00\x00"
blob += struct.pack("<4i", 1, 16 + len(payload), 0, 0) + payload
ent.write_bytes(blob + struct.pack("<4i", 0, 0, 0, 0))
def _set_headbox(folder, headbox):
for erd in folder.glob("*.erd"):
b = bytearray(erd.read_bytes())
struct.pack_into("<i", b, ktlx.HEADBOX_OFFSET, headbox)
erd.write_bytes(bytes(b))
def _read(path):
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
raw = mne.io.read_raw_edf(path, preload=True, verbose="warning")
assert [str(w.message) for w in caught] == []
return raw
@pytest.fixture
def study(tmp_path):
folder = tmp_path / "study"
data, events, stamps, spans, n_tot = tr.build_study(folder)
_append_note(folder, ACCENTED, ACCENTED_STAMP)
return SimpleNamespace(folder=folder, data=data, stamps=stamps,
spans=spans, n_tot=n_tot)
def test_synthetic_roundtrip(study, tmp_path):
out = ex.ktlx_to_edf(study.folder, tmp_path / "s.edf")
raw = _read(out)
fs = tr.FS
k_v, _ = ktlx.scale_v_per_lsb(ktlx.KtlxStudy(study.folder).hdr)
# values: every packet lands at its global stamp, in volts
got = raw.get_data()
sigs = edfio.read_edf(out).signals
step = np.array([(s.physical_range.max - s.physical_range.min)
/ (s.digital_range.max - s.digital_range.min)
for s in sigs]) * 1e-6 # uV -> V
assert len({tuple(s.physical_range) for s in sigs}) == 1
assert all(s.physical_range.min == -s.physical_range.max for s in sigs)
full_v = sigs[0].physical_range.max * 1e-6
a = 0
for stamp, n in zip(study.stamps, study.spans):
exp = np.clip(study.data[a:a + n].T.astype(np.float64) * k_v,
-full_v, full_v)
assert np.all(np.abs(got[:, stamp:stamp + n] - exp)
<= step[:, None] / 2 + 1e-12)
a += n
# internal gap (zero-filled) and edge padding, both BAD_ACQ_SKIP
gap_a = int(study.stamps[1] + study.spans[1])
gap_b = int(study.stamps[2])
assert all(np.all(sig.digital[gap_a:gap_b] == 0) for sig in sigs)
assert np.allclose(got[:, gap_a:gap_b], 0, rtol=0, atol=1e-15)
n_data = study.n_tot
n_pad = raw.n_times - n_data
assert n_pad == (-n_data) % int(fs) and n_pad > 0
assert np.all(got[:, n_data:] == got[:, [n_data - 1]])
bad = sorted((round(o * fs), round(d * fs)) for o, d, t in zip(
raw.annotations.onset, raw.annotations.duration,
raw.annotations.description) if t == BAD_ACQ_SKIP)
assert bad == [(gap_a, gap_b - gap_a), (n_data, n_pad)]
# events: .ent notes (incl. UTF-8 text), photic train, IDS
desc = dict(zip(raw.annotations.description, raw.annotations.onset))
assert desc["Fotica 10 Hz"] == pytest.approx(100 / fs)
assert desc["Ojos abiertos"] == pytest.approx(620 / fs)
assert desc[ACCENTED] == pytest.approx(ACCENTED_STAMP / fs)
photic = [d for d in desc if d.startswith("Photic ")]
assert len(photic) == 1 and photic[0].endswith(" Hz (20 flashes)")
assert desc[photic[0]] == pytest.approx(100 / fs)
assert any(d.startswith("IDS guid=abc123 ") for d in desc)
# header: name anonymized, synthetic ID kept, stem name not leaked
si = raw.info["subject_info"]
assert si["his_id"] == "ID-0001" and si.get("last_name") == "X"
assert b"PEREZ" not in out.read_bytes()
def test_unknown_headbox_uses_classic_constant(study, tmp_path, caplog):
_set_headbox(study.folder, 15)
with caplog.at_level(logging.WARNING):
ex.ktlx_to_edf(study.folder, tmp_path / "hb15.edf")
assert "headbox_type=15" in caplog.text
k15, aviso = ktlx.scale_v_per_lsb({"headbox_type": [15], "discardbits": 0})
k26, ok = ktlx.scale_v_per_lsb({"headbox_type": [26], "discardbits": 0})
assert aviso and ok is None
assert k15 / k26 == pytest.approx(8711 / 5000)
assert k26 == pytest.approx(5000 / (2 ** 21 - 0.5) * 1e-6)
def test_schema_8(tmp_path, monkeypatch):
monkeypatch.setattr(tr, "SCHEMA", 8)
folder = tmp_path / "s8"
tr.build_study(folder)
raw = _read(ex.ktlx_to_edf(folder, tmp_path / "s8.edf"))
assert len(raw.ch_names) == tr.N_CHAN
@pytest.mark.parametrize("onset, dur, text, expected", [
(-30, 40, "early", (0.0, 10, "early [pre-start -0.1 s]")),
(-30, 10, "early", (0.0, None, "early [pre-start -0.1 s]")),
(300, None, "late", (299 / 256, None, "late [post-end +0.0 s]")),
(250, 100, "long", (250 / 256, 50, "long")),
])
def test_clamped(onset, dur, text, expected):
a = clamped(onset, dur, 300, 256.0, text)
exp_onset, exp_dur, exp_text = expected
assert a.onset == pytest.approx(exp_onset)
assert a.text == exp_text
if exp_dur is None:
assert a.duration is None
else:
assert a.duration == pytest.approx(exp_dur / 256)
HB3 = {"headbox_type": [26], "discardbits": 6}
HB3_V_PER_LSB = ktlx.scale_v_per_lsb(HB3)[0]
def test_hb3_resolution():
"""Datasheet: ±5 mV over 16 bits, 0.153 uV/bit (rounded)."""
assert HB3_V_PER_LSB * 1e6 == pytest.approx(10_000 / 65536, rel=1e-6)
for db in (0, 6):
assert ktlx.full_scale_v({**HB3, "discardbits": db}) == pytest.approx(
32767 * HB3_V_PER_LSB)
def test_fixed_range_lossless_and_clipped(caplog):
counts = np.array([[0, 131070], [32767, 131070], [-32768, 131070],
[-5, 131070], [12345, 131070]], np.int32)
with caplog.at_level(logging.WARNING):
sigs = build_signals(counts, HB3_V_PER_LSB, ktlx.full_scale_v(HB3),
256.0, ["Cz", "DC"],
["Xltek phys=7 erd=0", "Xltek phys=32 erd=1"])
assert "Cz=1, DC=5" in caplog.text
for s in sigs:
assert (s.physical_range.min, s.physical_range.max) == (-4999.9,
4999.9)
assert tuple(s.digital_range) == DIGITAL_RANGE
assert s.physical_dimension == "uV" and s.prefiltering == ""
assert sigs[0].transducer_type == "Xltek phys=7 erd=0"
assert list(sigs[0].digital) == [0, 32767, -32767, -5, 12345]
assert list(sigs[1].digital) == [32767] * 5
@pytest.mark.parametrize("x", [0.000873456, 0.0123456789, 0.7629394,
0.15304122616866642, 12.3456789, 1e-4,
4999.847])
def test_half_range_fits_8_chars(x):
h = half_range(x)
assert x <= h <= 1.5 * x
assert len(str(-h)) <= 8 and "e" not in str(h)
sig = EdfSignal(np.array([0.0, x, -x]), 1.0, physical_range=(-h, h),
digital_range=DIGITAL_RANGE)
assert (sig.physical_range.min, sig.physical_range.max) == (-h, h)
assert sig.digital[0] == 0
assert abs(sig.data[0]) < 1e-15 * max(h, 1)
def test_recording_field_fits(study):
st = ktlx.KtlxStudy(study.folder)
st.hdr["headbox_sw_version"] = ["9" * 10] * 4
rec = recording_header(datetime(2020, 1, 1).date(), st.guid,
ex._equipment(st))
field = (f"Startdate 01-JAN-2020 {rec.hospital_administration_code} "
f"X {rec.equipment_code}")
assert len(field) <= EDF_RECORDING_LEN
assert rec.equipment_code.startswith("Xltek_HB26")
def test_start_time_without_snc_is_utc(study, tmp_path, monkeypatch):
"""Without .snc the .stc creation time (Unix, UTC) is used, whatever
the time zone of the converting machine."""
import time
monkeypatch.setenv("TZ", "America/Mexico_City")
time.tzset()
try:
next(study.folder.glob("*.snc")).unlink()
raw = _read(ex.ktlx_to_edf(study.folder, tmp_path / "nosnc.edf"))
finally:
monkeypatch.undo()
time.tzset()
expected = datetime.fromtimestamp(1_600_000_000, ktlx.timezone.utc)
assert raw.info["meas_date"] == expected
def test_cli_reports_errors_without_traceback(tmp_path, caplog, capsys):
from tea_modulo.export import cli
with caplog.at_level(logging.ERROR):
assert cli.main([str(tmp_path / "missing")]) == 1
assert "La carpeta no existe" in caplog.text
assert "Traceback" not in capsys.readouterr().err
def test_cli_converts(study, tmp_path, capsys):
from tea_modulo.export import cli
out = tmp_path / "cli.edf"
assert cli.main([str(study.folder), "-o", str(out)]) == 0
assert out.exists() and str(out) in capsys.readouterr().out