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.
This commit is contained in:
AlbertoPMDM
2026-11-18 19:54:48 -06:00
parent 449acf8b44
commit 2b4bea0c7f
14 changed files with 1972 additions and 0 deletions
+237
View File
@@ -0,0 +1,237 @@
"""
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
+71
View File
@@ -0,0 +1,71 @@
"""Unit tests for the sex / birthdate extraction (tea_modulo.export.patient)."""
import struct
from datetime import date, datetime, timedelta
import pytest
from tea_modulo.export import patient
@pytest.mark.parametrize("raw, expected", [
("F", "F"), ("Female", "F"), ("Mujer", "F"), ("madre", "F"), ("2", "F"),
("M", "M"), ("Male", "M"), ("Masculino", "M"), ("Hombre", "M"), ("1", "M"),
("", None), ("X", None), ("unknown", None),
])
def test_normalizar_sexo(raw, expected):
assert patient.normalizar_sexo(raw) == expected
@pytest.mark.parametrize("ident, orden, expected", [
("11012022", "dmy", date(2022, 1, 11)),
("11012022", "mdy", date(2022, 11, 1)),
("25122019", "mdy", date(2019, 12, 25)), # month 25 impossible: swapped
(" 01022020 ", "dmy", date(2020, 2, 1)),
("ID-0001", "dmy", None),
("99992020", "dmy", None),
])
def test_fecha_del_identificador(ident, orden, expected):
d, motivo = patient.fecha_del_identificador(ident, orden)
assert (d.date() if d else None) == expected
assert motivo
def _ole(d: datetime) -> bytes:
return struct.pack("<d", (d - datetime(1899, 12, 30)) / timedelta(days=1))
def test_fields_skip_label_and_read_value():
blob = (b"GenderLabel\x00Sexo\x00" # display label: skipped
b"Gender\x00\x00Female\x00"
b"BirthDateLabel\x00Fecha\x00"
b"BirthDate\x00\x00" + _ole(datetime(2021, 3, 4)))
bloques = [blob]
assert patient.sexo_del_eeg(bloques)[0] == "F"
d, _ = patient.fecha_tras_campo(bloques, referencia=datetime(2025, 1, 1))
assert d.date() == date(2021, 3, 4)
def test_fields_inside_hex_block():
inner = b"Gender\x00M\x00"
blob = b'(."Bin", 0x' + inner.hex().encode() + b"00" * 12 + b")"
assert patient.sexo_del_eeg(patient.desde_hex(blob))[0] == "M"
def test_birthdate_rejects_implausible_age():
blob = b"BirthDate\x00" + _ole(datetime(1850, 1, 1))
d, _ = patient.fecha_tras_campo([blob], referencia=datetime(2025, 1, 1))
assert d is None
def test_patient_info_sources(tmp_path):
eeg = tmp_path / "x.eeg"
eeg.write_bytes(b"Gender\x00F\x00BirthDate\x00"
+ _ole(datetime(2018, 6, 7)))
rec = datetime(2025, 1, 1)
# identifier is a date: it wins over the OLE double
assert patient.patient_info(eeg, "11012022", rec) == ("F", date(2022, 1, 11))
# identifier is not a date: OLE double after BirthDate
assert patient.patient_info(eeg, "ID-0001", rec) == ("F", date(2018, 6, 7))
# no .eeg at all
assert patient.patient_info(None, "ID-0001", rec) == (None, None)
+188
View File
@@ -0,0 +1,188 @@
"""
Synthetic KTLX studies for tests.
Writes a complete schema 8/9 study (.erd/.etc/.stc/.snc/.ent) with two
segments, a 500-sample gap, a 10 Hz photic train and two annotations. The
builder and the reference encoder come from examples/test_roundtrip.py and
examples/xltek_convert.py (encode_packet); they live here so the tests do not
depend on examples/.
"""
import struct
from pathlib import Path
import numpy as np
from tea_modulo.export import ktlx
FS = 256.0
N_CHAN = 20
CHAN_NAMES = ["Fp1", "Fp2", "F3", "F4", "C3", "C4", "P3", "P4", "O1", "O2",
"F7", "F8", "T3", "T4", "T5", "T6", "Fz", "Cz", "Pz", "EKG"]
DISCARDBITS = 0
SCHEMA = 9
DATA_OFFSET = 8656 # 352 + campos + headbox + shorted/frequency_factor
def encode_packet(data: np.ndarray, events: np.ndarray, n_chan: int,
sentinel: int = -1) -> bytes:
"""
Codificador de referencia (solo se usa en las pruebas de ida y vuelta).
Fuerza valores absolutos en la primera muestra del paquete.
"""
out = bytearray()
l_mask = (n_chan + 7) // 8
prev = np.zeros(n_chan, dtype=np.int64)
for t in range(data.shape[0]):
cur = data[t].astype(np.int64)
delta = cur - prev
fits8 = (delta >= -128) & (delta <= 127)
fits16 = (delta >= -32768) & (delta <= 32767) & (delta != sentinel)
if t == 0: # la primera muestra del paquete va siempre absoluta
small = np.zeros(n_chan, dtype=bool)
big_ok = np.zeros(n_chan, dtype=bool)
else:
small = fits8
big_ok = fits16 & ~fits8
absolute = ~(small | big_ok)
bits = np.zeros(n_chan, dtype=np.uint8)
bits[big_ok | absolute] = 1
out.append(int(events[t]) & 0x01)
out += np.packbits(
np.concatenate([bits, np.zeros(l_mask * 8 - n_chan, np.uint8)]),
bitorder="little").tobytes()
vals = np.where(absolute, sentinel, delta).astype(np.int64)
fmt = "<" + "".join("h" if b else "b" for b in bits)
out += struct.pack(fmt, *[int(v) for v in vals])
if absolute.any():
out += cur[absolute].astype("<i4").tobytes()
prev = cur
return bytes(out)
def generic_header(schema: int) -> bytes:
b = bytearray(352)
b[0:16] = bytes(range(16))
struct.pack_into("<H", b, 16, schema)
struct.pack_into("<H", b, 18, 1)
struct.pack_into("<i", b, 20, 1_600_000_000)
struct.pack_into("<i", b, 24, 111)
struct.pack_into("<i", b, 28, 222)
b[32:32 + 6] = b"PEREZ\x00"
b[112:112 + 4] = b"ANA\x00"
b[272:272 + 7] = b"ID-0001"
return bytes(b)
def erd_header() -> bytes:
b = bytearray(DATA_OFFSET)
b[0:352] = generic_header(SCHEMA)
struct.pack_into("<d", b, 352, FS)
struct.pack_into("<i", b, 360, N_CHAN)
struct.pack_into("<i", b, 364, 8) # deltabits
struct.pack_into(f"<{N_CHAN}i", b, 368, *range(N_CHAN)) # phys_chan
off = 4464
struct.pack_into("<4i", b, off, 26, 0, 0, 0) # headbox_type = 26
struct.pack_into("<4i", b, off + 16, 987654, 0, 0, 0) # headbox_sn
b[off + 32:off + 42] = b"1.2.3\x00\x00\x00\x00\x00"
b[off + 72:off + 82] = b"HW-A\x00\x00\x00\x00\x00\x00"
b[off + 82:off + 92] = b"SW-B\x00\x00\x00\x00\x00\x00"
struct.pack_into("<i", b, off + 92, DISCARDBITS) # 4556
# shorted[1024] en 4560 y frequency_factor[1024] en 6608: todo cero/uno
struct.pack_into("<1024h", b, 4560, *([0] * 1024))
struct.pack_into("<1024h", b, 6608, *([1] * 1024))
assert len(b) == DATA_OFFSET
return bytes(b)
def make_signal(n_smp: int, seed: int = 0) -> np.ndarray:
"""Senal con deltas pequenos, saltos grandes y saturaciones ocasionales."""
rng = np.random.default_rng(seed)
t = np.arange(n_smp)
x = np.zeros((n_smp, N_CHAN), dtype=np.int64)
for c in range(N_CHAN):
base = (12000 * np.sin(2 * np.pi * (8 + c * 0.3) * t / FS)
+ 3000 * np.sin(2 * np.pi * 0.7 * t / FS + c))
ruido = rng.integers(-40, 41, size=n_smp)
x[:, c] = base.astype(np.int64) + ruido + c * 1000
# saltos que fuerzan deltas de 16 bit y valores absolutos
for c in range(0, N_CHAN, 5):
x[n_smp // 3:, c] += 900 # -> delta de 16 bit
x[2 * n_smp // 3:, c] += 5_000_000 # -> valor absoluto int32
return x.astype(np.int32)
def build_study(folder: Path, packets_smp=(300, 300, 257), gap_after=1):
"""Crea un estudio con dos segmentos .erd y un hueco intencional."""
folder.mkdir(parents=True, exist_ok=True)
stem = "PEREZ, ANA_abc123"
total = sum(packets_smp)
data = make_signal(total)
events = np.zeros(total, dtype=np.uint8)
# tren fotico: 10 Hz durante 2 s a partir de la muestra 100
for k in range(20):
events[100 + int(k * FS / 10)] = 1
# dos segmentos: paquetes 0-1 en el primer .erd, paquete 2 en el segundo
reparto = [(0, [0, 1]), (1, [2])]
stamps_ini = np.concatenate([[0], np.cumsum(packets_smp)[:-1]])
# hueco de 500 muestras antes del ultimo paquete
hueco = 500
stamps_glob = stamps_ini.copy()
stamps_glob[gap_after + 1:] += hueco
stc_entries = []
for seg_i, pks in reparto:
name = stem if seg_i == 0 else f"{stem}_{seg_i:03d}"
erd = folder / f"{name}.erd"
etc = folder / f"{name}.etc"
blob = bytearray(erd_header())
etc_rows = []
for k in pks:
a = int(stamps_ini[k])
n = packets_smp[k]
off = len(blob)
blob += encode_packet(data[a:a + n], events[a:a + n], N_CHAN)
etc_rows.append((off, int(stamps_glob[k]), n, n, 0))
erd.write_bytes(bytes(blob))
eb = bytearray(generic_header(SCHEMA))
for row in etc_rows:
eb += struct.pack("<iiihh", *row)
etc.write_bytes(bytes(eb))
a0 = int(stamps_glob[pks[0]])
a1 = int(stamps_glob[pks[-1]] + packets_smp[pks[-1]])
stc_entries.append((name.encode(), a0, a1, a1 - a0, a1 - a0))
sb = bytearray(generic_header(SCHEMA))
sb += struct.pack("<ii", len(stc_entries), 1) + b"\x00" * 48
for name, a0, a1, num, span in stc_entries:
sb += name.ljust(256, b"\x00") + struct.pack("<iiii", a0, a1, num, span)
(folder / f"{stem}.stc").write_bytes(bytes(sb))
# .snc: dos anclas
nb = bytearray(generic_header(SCHEMA))
ft0 = ktlx.EPOCH_AS_FILETIME + 1_600_000_000 * ktlx.HUNDREDS_OF_NS
n_tot = int(stamps_glob[-1] + packets_smp[-1])
nb += struct.pack("<iq", 0, ft0)
nb += struct.pack("<iq", n_tot,
int(ft0 + n_tot / FS * ktlx.HUNDREDS_OF_NS))
(folder / f"{stem}.snc").write_bytes(bytes(nb))
# .ent: nota de montaje con ChanNames + dos anotaciones
eb = bytearray(generic_header(SCHEMA))
notas = [
'(."Montage" (.ChanNames (' + ", ".join(f'"{c}"' for c in CHAN_NAMES)
+ ')) (.Stamp 0))',
'(."Annotation" (.Stamp 100) (.Text "Fotica 10 Hz") '
'(.Data (.User "tecnico1")))',
'(."Annotation" (.Stamp 620) (.Text "Ojos abiertos") '
'(.Data (.User "tecnico1")))',
]
for nota in notas:
payload = nota.encode() + b"\x00\x00"
eb += struct.pack("<4i", 1, 16 + len(payload), 0, 0) + payload
eb += struct.pack("<4i", 0, 0, 0, 0)
(folder / f"{stem}.ent").write_bytes(bytes(eb))
return data, events, stamps_glob, packets_smp, n_tot