From 2b4bea0c7fe710263532a426306fe4e60ba069c1 Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Wed, 18 Nov 2026 19:54:48 -0600 Subject: [PATCH] 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. --- pyproject.toml | 7 + src/tea_modulo/export/__init__.py | 14 + src/tea_modulo/export/cli.py | 49 ++ src/tea_modulo/export/edf_annotations.py | 67 ++ src/tea_modulo/export/edf_export.py | 144 +++++ src/tea_modulo/export/edf_header.py | 54 ++ src/tea_modulo/export/edf_signals.py | 72 +++ src/tea_modulo/export/ktlx.py | 720 ++++++++++++++++++++++ src/tea_modulo/export/patient.py | 225 +++++++ src/tea_modulo/export/text.py | 49 ++ tests/export/test_edf_export_synthetic.py | 237 +++++++ tests/export/test_patient.py | 71 +++ tests/ktlx_synth.py | 188 ++++++ uv.lock | 75 +++ 14 files changed, 1972 insertions(+) create mode 100644 src/tea_modulo/export/__init__.py create mode 100644 src/tea_modulo/export/cli.py create mode 100644 src/tea_modulo/export/edf_annotations.py create mode 100644 src/tea_modulo/export/edf_export.py create mode 100644 src/tea_modulo/export/edf_header.py create mode 100644 src/tea_modulo/export/edf_signals.py create mode 100644 src/tea_modulo/export/ktlx.py create mode 100644 src/tea_modulo/export/patient.py create mode 100644 src/tea_modulo/export/text.py create mode 100644 tests/export/test_edf_export_synthetic.py create mode 100644 tests/export/test_patient.py create mode 100644 tests/ktlx_synth.py diff --git a/pyproject.toml b/pyproject.toml index 3ffcb27..70b5a04 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,13 @@ dependencies = [ "yasa>=0.8.1", ] +[project.optional-dependencies] +export = ["edfio>=0.4.18"] +s3 = ["s3fs"] + +[project.scripts] +ktlx2edf = "tea_modulo.export.cli:main" + [build-system] requires = ["uv_build>=0.13.1,<0.14.0"] build-backend = "uv_build" diff --git a/src/tea_modulo/export/__init__.py b/src/tea_modulo/export/__init__.py new file mode 100644 index 0000000..ac93169 --- /dev/null +++ b/src/tea_modulo/export/__init__.py @@ -0,0 +1,14 @@ +""" +Optional KTLX (Natus/Xltek) -> EDF+ exporter, vendored from the `eeg` library +(Gitea alberto/eeg @ 92bc2a0, src/eeg/utils). Only the imports were changed. + +Outside the pipeline: everything else in tea_modulo takes EDF. Install with +the `export` extra (needs edfio). + + from tea_modulo.export import ktlx_to_edf + ktlx_to_edf("natus/STUDY_FOLDER", "study.edf") +""" + +from tea_modulo.export.edf_export import ktlx_to_edf + +__all__ = ["ktlx_to_edf"] diff --git a/src/tea_modulo/export/cli.py b/src/tea_modulo/export/cli.py new file mode 100644 index 0000000..509a70f --- /dev/null +++ b/src/tea_modulo/export/cli.py @@ -0,0 +1,49 @@ +""" +Command line entry point. + + ktlx2edf [-o out.edf] [--id-order dmy|mdy] [-v] +""" + +from __future__ import annotations + +import argparse +import logging + +from tea_modulo.export.edf_export import ktlx_to_edf + +LOG = logging.getLogger(__name__) + + +def build_parser() -> argparse.ArgumentParser: + """The `ktlx2edf` argument parser (also read by the documentation).""" + p = argparse.ArgumentParser( + description="Convert a Natus/Xltek (KTLX) study folder to EDF+ (V)") + p.add_argument("folder", help="folder with the .stc, .erd, .etc, .ent ...") + p.add_argument("-o", "--out", default=None, + help="output .edf (default: .edf)") + p.add_argument("--id-order", choices=("dmy", "mdy"), default="dmy", + help="date order of the patient identifier (birthdate)") + p.add_argument("--record-s", type=float, default=None, + help="EDF data record duration in seconds") + p.add_argument("-v", "--verbose", action="store_true") + return p + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, + format="%(levelname)s %(message)s") + try: + out = ktlx_to_edf(args.folder, args.out, id_order=args.id_order, + record_s=args.record_s) + except (OSError, ValueError, NotImplementedError) as e: + # the reader's messages are written for people: show them, keep the + # traceback for -v + LOG.error("%s", e, exc_info=args.verbose) + return 1 + print(out) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/tea_modulo/export/edf_annotations.py b/src/tea_modulo/export/edf_annotations.py new file mode 100644 index 0000000..da52ae3 --- /dev/null +++ b/src/tea_modulo/export/edf_annotations.py @@ -0,0 +1,67 @@ +""" +EDF+ annotations (the file's events) from sample-indexed events. + +All onsets are relative to the first sample written to the file. MNE drops +annotations outside the data when it loads a file, so events before the start +or after the end are moved to the edge and the shift is written in the text. +""" + +from __future__ import annotations + +from collections.abc import Iterable + +import numpy as np +from edfio import EdfAnnotation + +# MNE's label for skipped acquisition; excluded by reject_by_annotation. +BAD_ACQ_SKIP = "BAD_ACQ_SKIP" + + +def runs(mask: np.ndarray) -> list[tuple[int, int]]: + """[start, end) runs where mask is True.""" + d = np.diff(mask.astype(np.int8), prepend=0, append=0) + return list(zip(np.flatnonzero(d == 1).tolist(), + np.flatnonzero(d == -1).tolist())) + + +def gap_annotations(valid: np.ndarray, n_pad: int, + fs: float) -> list[EdfAnnotation]: + """BAD_ACQ_SKIP for each run of invalid samples and for the padded tail.""" + out = [EdfAnnotation(a / fs, (b - a) / fs, BAD_ACQ_SKIP) + for a, b in runs(~valid)] + if n_pad: + out.append(EdfAnnotation(len(valid) / fs, n_pad / fs, BAD_ACQ_SKIP)) + return out + + +def clamped(onset_smp: int, dur_smp: int | None, n_data: int, fs: float, + text: str) -> EdfAnnotation: + """Annotation kept inside [0, n_data), with any shift noted in the text.""" + if onset_smp < 0: + text = f"{text} [pre-start {onset_smp / fs:.1f} s]" + dur_smp = None if dur_smp is None else max(dur_smp + onset_smp, 0) + onset_smp = 0 + elif onset_smp >= n_data: + text = f"{text} [post-end +{(onset_smp - n_data + 1) / fs:.1f} s]" + onset_smp, dur_smp = n_data - 1, None + if dur_smp is not None: + dur_smp = min(dur_smp, n_data - onset_smp) + return EdfAnnotation(onset_smp / fs, + dur_smp / fs if dur_smp else None, text) + + +def event_annotations(events: Iterable[tuple[int | None, int | None, str]], + first: int, n_data: int, + fs: float) -> list[EdfAnnotation]: + """ + (stamp, end stamp, text) events in global samples. Events without a + stamp go at 0, flagged in the text. + """ + out = [] + for stamp, fin, text in events: + if stamp is None: + out.append(EdfAnnotation(0.0, None, f"{text} [no timestamp]")) + continue + dur = fin - stamp if fin is not None and fin > stamp else None + out.append(clamped(stamp - first, dur, n_data, fs, text)) + return out diff --git a/src/tea_modulo/export/edf_export.py b/src/tea_modulo/export/edf_export.py new file mode 100644 index 0000000..9b620aa --- /dev/null +++ b/src/tea_modulo/export/edf_export.py @@ -0,0 +1,144 @@ +""" +Convert a Natus/Xltek (KTLX) study folder into a single EDF+ file in +microvolts. + +What goes into the file: + * every channel, in microvolts with one fixed range for all channels + (V/LSB from the headbox constant, see ktlx.scale_v_per_lsb and + edf_signals); + * the .ent events, the photic trigger trains and the acquisition gaps as + EDF+ annotations; + * patient code, sex and birthdate (the name is anonymized as "X"), the study + GUID as admin code and a short hardware summary as equipment. + +Gaps follow the MNE convention: missing samples are zero-filled and marked +with a BAD_ACQ_SKIP annotation, and the last data record is padded with edge +values (as mne.export does). The file starts at the first valid sample. + +This module only maps a KTLX study onto the EDF+ pieces (edf_signals, +edf_annotations, edf_header); it does not parse files or format fields. +""" + +from __future__ import annotations + +import logging +import math +from fractions import Fraction +from pathlib import Path + +import numpy as np +from edfio import Edf, EdfAnnotation + +from tea_modulo.export import ktlx, patient +from tea_modulo.export.edf_annotations import event_annotations, gap_annotations, runs +from tea_modulo.export.edf_header import patient_header, recording_header +from tea_modulo.export.edf_signals import build_signals + +LOG = logging.getLogger(__name__) + + +def ktlx_to_edf(folder, out_path=None, *, id_order: str = "dmy", + record_s: float | None = None) -> Path: + """Convert one KTLX study folder into an EDF+ file. Returns its path.""" + study = ktlx.KtlxStudy(Path(folder)) + out_path = Path(out_path) if out_path else Path(f"{study.guid}.edf") + fs = float(study.fs) + v_per_lsb, warning = ktlx.scale_v_per_lsb(study.hdr) + if warning: + LOG.warning(warning) + LOG.info("Scale: %.6g V/LSB (headbox %d, discardbits %d)", v_per_lsb, + study.hdr["headbox_type"][0], study.hdr["discardbits"]) + + counts, valid, trig = study.read_all() + if not valid.any(): + raise ValueError(f"{study.folder}: no valid samples to convert") + first = int(np.argmax(valid)) + last = len(valid) - int(np.argmax(valid[::-1])) # exclusive + counts, valid = counts[first:last], valid[first:last] + n_data = last - first + + record_s, spr = record_layout(fs, record_s) + n_pad = (-n_data) % spr + if n_pad: + LOG.warning("EDF needs whole data records: %d samples (%.3f s) of edge " + "values appended at the end", n_pad, n_pad / fs) + counts = np.pad(counts, ((0, n_pad), (0, 0)), mode="edge") + + annotations = gap_annotations(valid, n_pad, fs) + annotations.append(EdfAnnotation(0.0, None, _ids_text(study))) + annotations += event_annotations(_ent_events(study), first, n_data, fs) + annotations += event_annotations(_photic_events(study, trig), first, + n_data, fs) + gaps = runs(~valid) + LOG.info("Recorded span %.1f s from sample %d (initial offset %.1f s), " + "%d internal gaps, %.1f s lost, coverage %.4f%%", + n_data / fs, first, first / fs, len(gaps), + sum(b - a for a, b in gaps) / fs, 100 * valid.mean()) + + t0 = study.stamp_to_datetime(first) + if t0 is None: + raise ValueError(f"{study.folder}: recording start time is unknown") + sex, birthdate = patient.patient_info(study.eeg_path, study.hdr["pat_id"], + t0, id_order) + edf = Edf( + build_signals(counts, v_per_lsb, ktlx.full_scale_v(study.hdr), fs, + study.chan_names, _transducers(study)), + patient=patient_header(study.hdr["pat_id"], sex, birthdate), + recording=recording_header(t0.date(), study.guid, _equipment(study)), + starttime=t0.time(), + data_record_duration=record_s, + annotations=annotations, + ) + out_path.parent.mkdir(parents=True, exist_ok=True) + edf.write(out_path) + LOG.info("Written %s (%d channels, %d annotations)", out_path, + study.n_chan, len(annotations)) + return out_path + + +def record_layout(fs: float, record_s: float | None) -> tuple[float, int]: + """(record duration in s, samples per record) with an integer count.""" + if record_s is None: + record_s = float(Fraction(fs).limit_denominator(1000).denominator) + spr = fs * record_s + if not math.isclose(spr, round(spr)) or round(spr) < 1: + raise ValueError(f"fs={fs} Hz x record={record_s} s is not a whole " + f"number of samples per data record") + return record_s, int(round(spr)) + + +# ------------------------------------------------- KTLX -> EDF+ mapping + + +def _transducers(study: ktlx.KtlxStudy) -> list[str]: + return [f"Xltek phys={study.hdr['phys_chan'][c]} erd={c}" + for c in range(study.n_chan)] + + +def _equipment(study: ktlx.KtlxStudy) -> list[str]: + """Hardware summary, most important first (the field is short).""" + h = study.hdr + return [f"Xltek_HB{h['headbox_type'][0]}", f"db{h['discardbits']}", + f"SN{h['headbox_sn'][0]}", f"sw{h['headbox_sw_version'][0]}", + f"dsp{h['dsp_hw_version']}/{h['dsp_sw_version']}"] + + +def _ids_text(study: ktlx.KtlxStudy) -> str: + h = study.hdr + return (f"IDS guid={study.guid} file_guid={h['file_guid']} " + f"patient_id_num={h['patient_id_num']} " + f"study_id_num={h['study_id_num']}") + + +def _ent_events(study: ktlx.KtlxStudy): + return [(e["stamp"], e["stamp_fin"], e["texto"]) + for e in study.events_from_ent()] + + +def _photic_events(study: ktlx.KtlxStudy, trig: np.ndarray): + out = [] + for t in study.trains_from_trigger(trig): + freq = f" {t['frecuencia_hz']:g} Hz" if t["frecuencia_hz"] else "" + out.append((t["stamp"], t["stamp_fin"], + f"Photic{freq} ({t['n_flancos']} flashes)")) + return out diff --git a/src/tea_modulo/export/edf_header.py b/src/tea_modulo/export/edf_header.py new file mode 100644 index 0000000..bcfa712 --- /dev/null +++ b/src/tea_modulo/export/edf_header.py @@ -0,0 +1,54 @@ +""" +EDF+ patient and recording header fields. + +EDF+ subfields are printable ASCII without spaces, 'X' when unknown, and the +whole recording field is limited to 80 characters. +""" + +from __future__ import annotations + +import logging +from collections.abc import Sequence +from datetime import date + +from edfio import Patient, Recording + +from tea_modulo.export.text import to_ascii + +LOG = logging.getLogger(__name__) + +EDF_RECORDING_LEN = 80 + + +def field(s) -> str: + """EDF+ header subfield: printable ASCII without spaces, or 'X'.""" + s = to_ascii(s).strip().replace(" ", "_") + return s or "X" + + +def patient_header(code: str, sex: str | None, + birthdate: date | None) -> Patient: + """Patient field with the name anonymized as 'X'.""" + return Patient(code=field(code), sex=sex or "X", birthdate=birthdate, + name="X") + + +def recording_header(startdate: date, admin_code: str, + equipment: Sequence[str]) -> Recording: + """ + Recording field. `equipment` pieces are joined with '_' in order of + importance and dropped whole once the 80 characters of + "Startdate dd-MMM-yyyy X " are used up. + """ + admin = field(admin_code) + room = EDF_RECORDING_LEN - len(f"Startdate 01-JAN-2000 {admin} X ") + pieces = [field(p) for p in equipment] + equip = pieces[0][:room] if pieces else "X" + for i, piece in enumerate(pieces[1:], 1): + if len(equip) + 1 + len(piece) > room: + LOG.info("Equipment field limited to %d characters, dropped: %s", + room, " ".join(pieces[i:])) + break + equip += "_" + piece + return Recording(startdate=startdate, hospital_administration_code=admin, + investigator_technician_code="X", equipment_code=equip) diff --git a/src/tea_modulo/export/edf_signals.py b/src/tea_modulo/export/edf_signals.py new file mode 100644 index 0000000..85a6451 --- /dev/null +++ b/src/tea_modulo/export/edf_signals.py @@ -0,0 +1,72 @@ +""" +EDF+ signals in microvolts from integer ADC counts. + +All channels share one fixed range: the 16-bit ADC input range of the +headbox (±5 mV for the HB-3, see ADR-010), digital -32767..32767. Thus each +digital value is the ADC count itself (lossless), all channels have the same +resolution (EDFbrowser derivations need it), and 0 V maps exactly to digital +0, so zero-filled gaps read back as exactly 0 V. (With -32768 the zero falls +between two levels and reads back as half a step.) Values outside the range +are clipped with a warning. +""" + +from __future__ import annotations + +import logging +import math +from collections.abc import Sequence + +import numpy as np +from edfio import EdfSignal +from edfio.edf_signal import _round_float_to_8_characters + +from tea_modulo.export.text import to_ascii + +LOG = logging.getLogger(__name__) + +DIGITAL_RANGE = (-32767, 32767) +LABEL_LEN = 16 + + +def half_range(x: float) -> float: + """ + Smallest h >= x such that +h and -h fit the 8-character header fields + and survive edfio's own outward rounding unchanged (otherwise the range + stops being symmetric and 0 V no longer lands on a digital level). + """ + for dec in range(7, -1, -1): + h = math.ceil(x * 10 ** dec) / 10 ** dec + if (len(str(-h)) <= 8 + and _round_float_to_8_characters(h, math.ceil) == h + and _round_float_to_8_characters(-h, math.floor) == -h): + return h + raise ValueError(f"{x} does not fit an 8-character EDF field") + + +def build_signals(counts: np.ndarray, v_per_lsb: float, full_scale_v: float, + fs: float, labels: Sequence[str], + transducers: Sequence[str]) -> list[EdfSignal]: + """ + One EdfSignal per column of `counts`, scaled to microvolts, all with the + range ±`full_scale_v`. When full_scale_v = 32767 x v_per_lsb, the + digital values are the counts. + """ + h = half_range(full_scale_v * 1e6) + uv = counts.astype(np.float64) * (v_per_lsb * 1e6) + out = np.abs(uv) > h + clipped = [(labels[c], n) for c, n in enumerate(out.sum(axis=0)) if n] + if clipped: + LOG.warning("Values outside ±%g uV clipped (not connected or " + "saturated input) in %d channels: %s", h, len(clipped), + ", ".join(f"{n}={k}" for n, k in clipped)) + LOG.info("Range for all channels: ±%g uV, %.5f uV/bit", h, + 2 * h / (DIGITAL_RANGE[1] - DIGITAL_RANGE[0])) + np.clip(uv, -h, h, out=uv) + return [EdfSignal( + uv[:, c], fs, + label=to_ascii(labels[c])[:LABEL_LEN], + transducer_type=transducers[c], + physical_dimension="uV", + physical_range=(-h, h), + digital_range=DIGITAL_RANGE, + ) for c in range(counts.shape[1])] diff --git a/src/tea_modulo/export/ktlx.py b/src/tea_modulo/export/ktlx.py new file mode 100644 index 0000000..d06aaf5 --- /dev/null +++ b/src/tea_modulo/export/ktlx.py @@ -0,0 +1,720 @@ +""" +Reader for Natus/Xltek NeuroWorks (KTLX) studies. + +Ported from examples/xltek_convert.py (the WAVE TXT / calibration code and the +NPZ/HDF5 writers are not included). Function names are kept so that each one +can be traced back to its origin. + +Design rule: the signal is NOT altered. Samples come out as the exact int32 +ADC counts stored in the .erd; gaps are reported, never filled here. + +Format references: 352 B generic header shared by every file; .erd/.etc/.stc/ +.snc/.ent fields as in the open implementation wonambi.ioeeg.ktlx +(Piantoni/O'Byrne, GPLv3) and the Xltek documentation. This is an independent +reimplementation with extra checks. +""" + +from __future__ import annotations + +import logging +import re +import struct +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import numpy as np + +from tea_modulo.export import text as _txt + +LOG = logging.getLogger(__name__) + +# ---------------------------------------------------------------- constantes + +GENERIC_HDR_LEN = 352 +HEADBOX_OFFSET = 4464 # offset absoluto del bloque headbox en .erd +EPOCH_AS_FILETIME = 116444736000000000 +HUNDREDS_OF_NS = 10_000_000 + +SCHEMAS_SOPORTADOS = (8, 9) + +# Constante de hardware del headbox, en uV, medida para el headbox 26 (ver +# examples/lote.py). uV/LSB = constante / (2^21 - 0.5) * 2^discardbits +# El headbox 26 es el HB-3 v32/v44: ADC de 16 bits, entrada maxima +-5 mV, +# resolucion 0,153 uV/bit en la hoja de datos (= 10 mV / 65536 redondeado). +# Con discardbits 6, 5000 / (2^21 - 0,5) * 2^6 = 0,152588 uV/bit. Ver ADR-010. +CONSTANTES_HEADBOX = {26: 5000.0} +CONST_CLASICA = 8711.0 + +# --------------------------------------------------------------- utilidades + + +def _cstr(raw: bytes) -> str: + """ + Decodifica hasta el primer NUL, probando varias codificaciones. + + NeuroWorks escribe los nombres en la codificacion local de Windows, asi + que un paciente llamado MUNOZ con enye aparece como el byte 0xd1. Si se + decodifica a la fuerza como utf-8 queda "MU?OZ", y como ese nombre forma + parte del nombre de segmento del .stc, el .erd correspondiente deja de + encontrarse y el estudio entero falla. + """ + i = raw.find(b"\x00") + if i >= 0: + raw = raw[:i] + return _txt.leer_bytes(raw).strip() + + +def filetime_to_dt(ft: int): + """FILETIME de Windows (100 ns desde 1601-01-01) -> datetime naive UTC.""" + if ft <= 0: + return None + s, ns100 = divmod(int(ft) - EPOCH_AS_FILETIME, HUNDREDS_OF_NS) + try: + dt = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=s) + except (OverflowError, OSError, ValueError): + return None + return dt.replace(microsecond=int(ns100) // 10, tzinfo=None) + + +# ------------------------------------------------------- lectores de archivo + + +def read_generic_header(path: Path) -> dict: + """Cabecera generica de 352 B presente en .erd/.etc/.stc/.snc/.ent/.eeg.""" + with path.open("rb") as f: + raw = f.read(GENERIC_HDR_LEN) + if len(raw) < GENERIC_HDR_LEN: + raise ValueError(f"{path.name}: archivo mas corto que la cabecera") + hdr = { + "file_guid": raw[:16].hex(), + "file_schema": struct.unpack_from(" dict: + """Cabecera especifica de .erd (schema >= 7).""" + hdr = read_generic_header(path) + schema = hdr["file_schema"] + with path.open("rb") as f: + f.seek(GENERIC_HDR_LEN) + hdr["sample_freq"] = struct.unpack("= 8: + hdr["shorted"] = list( + struct.unpack("<1024h", f.read(2048))[:n_chan]) + hdr["frequency_factor"] = list( + struct.unpack("<1024h", f.read(2048))[:n_chan]) + hdr["data_offset"] = f.tell() + else: + hdr["shorted"] = [0] * n_chan + hdr["frequency_factor"] = [1] * n_chan + hdr["data_offset"] = None # el .etc manda de todos modos + return hdr + + +ETC_DTYPE = np.dtype([ + ("offset", " np.ndarray: + """Tabla de contenidos de un .erd: offset de cada paquete.""" + with path.open("rb") as f: + f.seek(GENERIC_HDR_LEN) + etc = np.fromfile(f, dtype=ETC_DTYPE) + # las entradas finales suelen venir en cero + keep = (etc["sample_span"] > 0) & (etc["offset"] > 0) + if keep.any(): + last = np.flatnonzero(keep)[-1] + etc = etc[: last + 1] + etc = etc[etc["sample_span"] > 0] + else: + etc = etc[:0] + return etc + + +STC_PREAMBLE_LEN = 56 +STC_DTYPE = np.dtype([ + ("segment_name", "S256"), + ("start_stamp", " FILETIME) para tiempo absoluto.""" + with path.open("rb") as f: + f.seek(GENERIC_HDR_LEN) + snc = np.fromfile(f, dtype=SNC_DTYPE) + return snc + + +def read_ent(path: Path) -> list: + """Notas del .ent: anotaciones, montajes, impedancias.""" + notes = [] + with path.open("rb") as f: + f.seek(GENERIC_HDR_LEN) + while True: + head = f.read(16) + if len(head) < 16: + break + ntype, nlen, prev_len, unused = struct.unpack("<4i", head) + if ntype == 0 or nlen <= 16: + break + body = f.read(nlen - 16) + if len(body) < nlen - 16: + break + text = _cstr(body) + notes.append({ + "type": ntype, + "length": nlen, + "prev_length": prev_len, + "unused": unused, + "text": text, + }) + return notes + + +# ------------------------------------------------- parseo de notas del .ent + +# NeuroWorks escribe (."Clave", valor): la coma es separador, no un token +_TOKEN_RE = re.compile(r'\(\.|\(|\)|"(?:[^"\\]|\\.)*"|[^\s,()"]+') +_RE_GUID = re.compile(r"^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-", re.I) +_RE_QUOTED = re.compile(r'"((?:[^"\\]|\\.)*)"') + + + +def _atom(tok: str): + try: + return int(tok) + except ValueError: + pass + try: + return float(tok) + except ValueError: + return tok + + +def sexp_parse(text: str): + """Parser tolerante de la sintaxis '(.Clave valor)' del .ent.""" + stack = [[]] + for tok in _TOKEN_RE.findall(text): + if tok in ("(", "(."): + node = [] + stack[-1].append(node) + stack.append(node) + elif tok == ")": + if len(stack) > 1: + stack.pop() + elif tok.startswith('"'): + stack[-1].append(tok[1:-1]) + else: + stack[-1].append(_atom(tok)) + return stack[0] + + +def sexp_pairs(node, out=None) -> dict: + """Aplana el arbol en pares clave -> valor (primera aparicion gana).""" + if out is None: + out = {} + if isinstance(node, list): + if node and isinstance(node[0], str) and re.match(r"^[A-Za-z][\w ]*$", + node[0]): + key, rest = node[0], node[1:] + escalares = [r for r in rest if not isinstance(r, list)] + if len(escalares) == 1 and len(rest) == 1: + out.setdefault(key.lower(), []).append(escalares[0]) + elif escalares and len(escalares) == len(rest): + out.setdefault(key.lower(), []).append(escalares) + for item in node: + sexp_pairs(item, out) + return out + + +def parse_note(text: str) -> dict: + """ + Extrae stamp / fin / texto de una nota (usuario solo para descartarlo + como texto en la heuristica). + + Las claves se recorren por PRIORIDAD, no por orden de aparicion: una nota + de NeuroWorks trae Comment antes que Text y un Type interno (un GUID) + antes del Type real, asi que quedarse con la primera coincidencia daria + el campo equivocado. + """ + out = {} + es_montaje = ("ChanNames" in text) or len(text) > 4000 + try: + pares = sexp_pairs(sexp_parse(text)) + except Exception as e: + LOG.debug("parse_note: s-expression no parseable (%s), se usa la " + "heuristica", e) + pares = {} + + def elegir(claves, valida): + for k in claves: + for v in pares.get(k, []): + if valida(v): + return v + return None + + v = elegir(["stamp", "samplestamp", "sample_stamp"], + lambda x: isinstance(x, (int, float))) + if v is not None: + out["stamp"] = int(v) + v = elegir(["endstamp", "end_stamp"], lambda x: isinstance(x, (int, float))) + if v is not None: + out["fin"] = int(v) + v = elegir(["text", "annotation", "label", "note", "description", + "eventtext", "comment"], + lambda x: isinstance(x, str) and x.strip()) + if v is not None: + out["texto"] = v.strip() + v = elegir(["user", "username", "author", "creator"], + lambda x: isinstance(x, str) and x.strip()) + if v is not None: + out["usuario"] = v.strip() + + if "stamp" not in out: + m = re.search(r"\(\.\s*\"?(?:Stamp|SampleStamp)\"?[,\s]+(-?\d+)", + text, re.I) + if m: + out["stamp"] = int(m.group(1)) + if "texto" not in out and not es_montaje: + for cand in _RE_QUOTED.findall(text): + c = cand.strip() + if (len(c) >= 2 and not _RE_GUID.match(c.strip("{}")) + and c != out.get("usuario") and not c.isdigit() + and c.lower() not in ("true", "false")): + out["texto"] = c + break + return out + + +def find_chan_names(notes: list, n_chan: int): + """Nombres de canal desde la nota de montaje (clave ChanNames).""" + for note in reversed(notes): + t = note["text"] + i = t.find("ChanNames") + if i < 0: + continue + a = t.find("(", i) + b = t.find(")", a + 1) + if a < 0 or b < 0: + continue + names = [x.strip(' "\t') for x in t[a + 1:b].split(",")] + names = [n for n in names if n] + if len(names) >= 1: + return names[:n_chan] + return None + + +# ------------------------------------------------ descompresion delta (.erd) + +_LAYOUT_CACHE: dict = {} + + +def _layout_for_mask(mask: bytes, n_chan: int): + """(struct de los deltas, canales de 16 bit) para una mascara.""" + key = (mask, n_chan) + lay = _LAYOUT_CACHE.get(key) + if lay is None: + bits = np.unpackbits(np.frombuffer(mask, np.uint8), + bitorder="little")[:n_chan] + lay = (struct.Struct("<" + "".join("h" if b else "b" for b in bits)), + bits.astype(bool)) + _LAYOUT_CACHE[key] = lay + return lay + + +def decode_packet(buf, pos: int, n_smp: int, n_chan: int, l_mask: int, + sentinel: int, prev: np.ndarray): + """ + Decodifica un paquete comprimido del .erd. + + Estructura por muestra (schema 8/9): + 1 B event byte (bit 0 = trigger externo / fotica) + l_mask B delta mask (bit c = 1 -> delta de 16 bit; 0 -> 8 bit) + deltas en orden de canal, ancho segun la mascara + valores absolutos int32 para los canales cuyo delta == centinela + + Devuelve (datos[n_smp, n_chan] int32, eventos[n_smp] uint8, cursor_final). + `prev` es el estado acumulado (se modifica in place). + """ + dat = np.empty((n_smp, n_chan), dtype=np.int32) + ev = np.zeros(n_smp, dtype=np.uint8) + cur = pos + for t in range(n_smp): + ev[t] = buf[cur] & 0x01 + cur += 1 + st, big = _layout_for_mask(bytes(buf[cur:cur + l_mask]), n_chan) + cur += l_mask + vals = np.array(st.unpack_from(buf, cur), dtype=np.int32) + cur += st.size # 1 B por chico, 2 B por grande + read_abs = big & (vals == sentinel) + n_abs = int(read_abs.sum()) + prev += vals # basura en read_abs, se pisa + if n_abs: + absvals = np.frombuffer(buf, dtype=" 1: + raise OSError("Mas de un .stc: " + ", ".join(p.name for p in stc)) + self.stem = stc[0].stem + self.stc_path = stc[0] + self.stc_hdr, self.stamps = read_stc(self.stc_path) + + self.erd_paths = self._map_segments() + if not self.erd_paths: + raise FileNotFoundError("No se localizo ningun .erd del .stc") + self.hdr = read_erd_header(self.erd_paths[0][1]) + self._check_supported() + + self.n_chan = self.hdr["num_channels"] + self.fs = self.hdr["sample_freq"] + self.l_mask = (self.n_chan + 7) // 8 + self.sentinel = -1 # schema 8/9 (los unicos soportados) + + self.notes = [] + for ext in (".ent", ".ent.old"): + p = self.folder / (self.stem + ext) + if p.exists(): + self.notes = read_ent(p) + self.ent_path = p + break + else: + self.ent_path = None + + self.chan_names = (find_chan_names(self.notes, self.n_chan) + if self.notes else None) + if not self.chan_names: + LOG.warning("Sin ChanNames en el .ent: se usan nombres genericos") + self.chan_names = [f"ch{i:03d}" for i in range(self.n_chan)] + if len(self.chan_names) < self.n_chan: + self.chan_names += [ + f"ch{i:03d}" for i in range(len(self.chan_names), self.n_chan)] + + p = self.folder / (self.stem + ".snc") + self.snc = read_snc(p) if p.exists() else None + p = self.folder / (self.stem + ".eeg") + self.eeg_path = p if p.exists() else None + + self.etc_cache: dict = {} + self.n_samples = self._total_samples() + + @property + def guid(self) -> str: + """ + Parte del stem tras el ultimo '_' (el GUID del estudio). + + El stem es '~_': lleva el nombre del paciente, asi + que no debe usarse tal cual en ninguna salida anonimizada. + """ + return self.stem.rsplit("_", 1)[-1] + + # -- descubrimiento ---------------------------------------------------- + + def _map_segments(self): + by_stem = {p.stem.lower(): p for p in self.folder.glob("*.erd")} + out = [] + for i, s in enumerate(self.stamps): + name = _cstr(s["segment_name"]) + p = by_stem.get(Path(name).stem.lower()) + if p is None: + LOG.warning("Falta el .erd del segmento %r (indice %d)", + name, i) + continue + out.append((i, p)) + return out + + def _check_supported(self): + sch = self.hdr["file_schema"] + if sch not in SCHEMAS_SOPORTADOS: + raise NotImplementedError( + f"file_schema={sch} no soportado por este lector " + f"(soportados: {SCHEMAS_SOPORTADOS}). Abortando en lugar de " + f"producir senal posiblemente incorrecta.") + n = self.hdr["num_channels"] + ff = set(self.hdr["frequency_factor"][:n]) + if len(ff) > 1: + raise NotImplementedError( + f"frequency_factor heterogeneo {sorted(ff)}: el flujo incluye " + f"un byte de frecuencia por muestra que este lector no parsea.") + if any(self.hdr["shorted"][:n]): + idx = [i for i, s in enumerate(self.hdr["shorted"][:n]) if s] + raise NotImplementedError( + f"Canales shorted {idx}: su codificacion no esta verificada. " + f"Aborta para no corromper la senal.") + + def etc_for(self, erd_path: Path) -> np.ndarray: + key = erd_path.name.lower() + if key not in self.etc_cache: + etc_path = erd_path.with_suffix(".etc") + if not etc_path.exists(): + raise FileNotFoundError(f"Falta {etc_path.name}") + self.etc_cache[key] = read_etc(etc_path) + return self.etc_cache[key] + + def _total_samples(self) -> int: + n = 0 + for _, p in self.erd_paths: + etc = self.etc_for(p) + if len(etc): + n = max(n, int(etc["samplestamp"][-1] + etc["sample_span"][-1])) + n = max(n, int(self.stamps["end_stamp"].max()) if len(self.stamps) else 0) + return n + + # -- lectura ----------------------------------------------------------- + + def iter_packets(self): + """ + Genera (samplestamp_global, datos[n, n_chan] int32, eventos[n] uint8). + Comprueba que el cursor termine exactamente donde empieza el + siguiente paquete segun el .etc: es la prueba de que el parseo es + correcto byte a byte. + """ + for _, erd_path in self.erd_paths: + etc = self.etc_for(erd_path) + if not len(etc): + continue + with erd_path.open("rb") as f: + buf = f.read() + for k in range(len(etc)): + stamp = int(etc["samplestamp"][k]) + span = int(etc["sample_span"][k]) + off = int(etc["offset"][k]) + prev = np.zeros(self.n_chan, dtype=np.int32) + dat, ev, cur = decode_packet( + buf, off, span, self.n_chan, self.l_mask, + self.sentinel, prev) + nxt = int(etc["offset"][k + 1]) if k + 1 < len(etc) else len(buf) + if cur != nxt: + raise ValueError( + f"{erd_path.name}: desalineacion en el paquete " + f"{k} (cursor={cur}, esperado={nxt}). El flujo no " + f"coincide con el formato asumido.") + yield stamp, dat, ev + + def read_all(self): + """ + Estudio completo como (int32 cuentas[n, n_chan], valid[n], trigger[n]). + + Las muestras sin paquete quedan en 0 con valid=False: los huecos se + senalan, no se rellenan con nada que parezca senal. + """ + n = self.n_samples + counts = np.zeros((n, self.n_chan), dtype=np.int32) + valid = np.zeros(n, dtype=bool) + trig = np.zeros(n, dtype=np.uint8) + n_packets = 0 + for stamp, dat, ev in self.iter_packets(): + a, b = stamp, stamp + dat.shape[0] + counts[a:b] = dat + trig[a:b] = ev + valid[a:b] = True + n_packets += 1 + LOG.info("Decoded %d packets, %d samples x %d channels", n_packets, n, + self.n_chan) + return counts, valid, trig + + # -- tiempo ------------------------------------------------------------ + + def stamp_to_datetime(self, stamp): + """ + Interpolacion con las anclas del .snc. Fuera de las anclas se + extrapola con la fs nominal (cambio respecto a examples/, ver + architecture.md). Sin .snc: creacion del .stc + stamp / fs. + """ + if self.snc is None or not len(self.snc): + base = self.stc_hdr.get("creation_time") + if base is None: + return None + return base + timedelta(seconds=float(stamp) / self.fs) + ss = self.snc["sample_stamp"].astype(np.float64) + st = self.snc["sample_time"].astype(np.float64) + # np.interp satura fuera de las anclas: antes de la primera (o tras + # la ultima) se extrapola con la fs nominal desde el ancla mas cercana + s = float(stamp) + i = 0 if s < ss[0] else (-1 if s > ss[-1] else None) + if i is None: + ft = np.interp(s, ss, st) + else: + ft = st[i] + (s - ss[i]) / self.fs * HUNDREDS_OF_NS + return filetime_to_dt(int(ft)) + + # -- eventos ----------------------------------------------------------- + + def events_from_ent(self): + out = [] + for note in self.notes: + p = parse_note(note["text"]) + if not p.get("texto"): + continue # notas de montaje/impedancia: no son anotaciones + out.append({ + "stamp": p.get("stamp"), + "stamp_fin": p.get("fin"), + "texto": p["texto"], + }) + out.sort(key=lambda e: (e["stamp"] is None, e["stamp"] or 0)) + return out + + def trains_from_trigger(self, trig: np.ndarray, max_gap_s: float = 2.0): + """ + Agrupa flancos de subida del bit de trigger externo en trenes. + Segun el manual de Xltek el unico dispositivo soportado que genera + trigger externo es el estimulador fotico. + """ + if trig is None or not trig.any(): + return [] + idx = np.flatnonzero(np.diff(trig.astype(np.int8), prepend=0) == 1) + if not len(idx): + return [] + gap = int(round(max_gap_s * self.fs)) + cuts = np.flatnonzero(np.diff(idx) > gap) + groups = np.split(idx, cuts + 1) + trains = [] + for g in groups: + if len(g) < 2: + freq = None + else: + isi = np.diff(g) / self.fs + freq = float(1.0 / np.median(isi)) if np.median(isi) > 0 else None + trains.append({ + "stamp": int(g[0]), + "stamp_fin": int(g[-1]), + "n_flancos": int(len(g)), + "frecuencia_hz": round(freq, 3) if freq else None, + }) + return trains + + +# ------------------------------------------------------------------ escala + + +def scale_v_per_lsb(hdr: dict): + """ + (V/LSB, aviso) segun la cabecera del propio estudio. + + Portado de examples/lote.py (escala_de), devuelto en voltios: + uV/LSB = constante / (2^21 - 0.5) * 2^discardbits + + `aviso` es None si el headbox esta caracterizado. + """ + hb = int(hdr["headbox_type"][0]) + db = int(hdr["discardbits"]) + const = CONSTANTES_HEADBOX.get(hb) + aviso = None + if const is None: + const = CONST_CLASICA + aviso = (f"headbox_type={hb} no esta caracterizado: se aplica la " + f"constante clasica de {CONST_CLASICA:.0f} uV y la amplitud " + f"absoluta puede ser incorrecta.") + return const / (2 ** 21 - 0.5) * 2 ** db * 1e-6, aviso + + +# Bits que el ADC de 16 bits del headbox descarta de la palabra de 22 bits. +ADC_DISCARDBITS = 6 + + +def full_scale_v(hdr: dict) -> float: + """ + Rango de entrada del ADC de 16 bits, en V: 32767 pasos del LSB con + discardbits 6 (+-5 mV en el HB-3, ver ADR-010). No depende de los + discardbits del estudio. + """ + v_per_lsb, _ = scale_v_per_lsb(hdr) + return 32767 * v_per_lsb * 2 ** (ADC_DISCARDBITS - int(hdr["discardbits"])) diff --git a/src/tea_modulo/export/patient.py b/src/tea_modulo/export/patient.py new file mode 100644 index 0000000..e82aafb --- /dev/null +++ b/src/tea_modulo/export/patient.py @@ -0,0 +1,225 @@ +""" +Patient sex and birthdate from the original NeuroWorks files. + +Ported from examples/edades.py. The .eeg stores the patient fields inside a +hex-dumped binary block; sex follows its "Gender"/"Sex" field and the +birthdate is either the patient identifier itself (ddmmyyyy in this +installation) or an OLE double right after "BirthDate". + +Changes from the original, for traceability: the .eeg is read once and its +blocks are passed to the extractors (they used to take the folder and read +the file themselves), and the identifier is the `pat_id` already read from +the generic header instead of re-reading offset 272. +""" + +from __future__ import annotations + +import logging +import re +import struct +from collections.abc import Sequence +from datetime import date, datetime, timedelta +from pathlib import Path + +from tea_modulo.export import text as _txt + +LOG = logging.getLogger(__name__) + +# Tope de edad para dar por buena una fecha de nacimiento: descarta fechas +# absurdas, no decide quien entra en el estudio. +EDAD_MAX_ANIOS = 100 + +_HEX = re.compile(rb"0x([0-9a-fA-F]{32,})") + + +def desde_hex(datos: bytes): + """ + Descodifica los bloques escritos en hexadecimal dentro del archivo. + + El .eeg guarda los datos del paciente en un campo (."Bin", 0x....) cuyo + contenido es un volcado binario escrito en hexadecimal. Ahi dentro estan + los nombres de campo y sus valores: la secuencia 416464726573735f... + es "Address_Address1" en ASCII. Sin descodificarlo, ese bloque parece + ruido y la busqueda de cadenas no encuentra nada. + """ + salida = [] + for m in _HEX.finditer(datos): + h = m.group(1) + if len(h) % 2: + h = h[:-1] + try: + salida.append(bytes.fromhex(h.decode("ascii"))) + except ValueError: + continue + return salida + + +def bloques_del_eeg(path: Path | None) -> list[bytes]: + """El .eeg entero mas sus bloques hexadecimales descodificados.""" + if path is None: + return [] + datos = Path(path).read_bytes() + return [datos] + desde_hex(datos) + + +def _zonas_tras_campo(b: bytes, nombre: str, ventana: int): + """ + Bytes tras cada aparicion de `nombre` en `b`. Se descartan las + apariciones terminadas en "Label", que son la etiqueta para mostrar y no + llevan valor. + """ + patron = nombre.encode("cp1252") + desde = 0 + while (pos := b.find(patron, desde)) >= 0: + desde = pos + 1 + ini = pos + len(patron) + if b[ini:ini + 5].lower() != b"label": + yield b[ini:ini + ventana] + + +def sexo_del_eeg(bloques: Sequence[bytes], ventana=24): + """ + Sexo del paciente, leido de los bytes que siguen a su campo. + + Un valor de un solo caracter no lo devuelve un extractor de cadenas con + longitud minima, asi que se lee directamente del bloque: se localiza el + nombre del campo y se toma la primera secuencia imprimible posterior. + """ + if not bloques: + return None, "sin .eeg" + for b in bloques: + for clave in ("Gender", "Sex"): + for zona in _zonas_tras_campo(b, clave, ventana): + act = bytearray() + for c in zona: + if 32 <= c < 127: + act.append(c) + elif act: + break + v = act.decode("cp1252", errors="replace").strip() + s = normalizar_sexo(v) + if s: + return s, f"campo {clave} = {v[:16]!r}" + return None, "sin campo de sexo" + + +def normalizar_sexo(v): + """M o F a partir de las formas habituales, o None si no se reconoce.""" + n = _txt.normalizar(str(v)).strip() + if not n: + return None + # "masculino" es M, pero "mujer"/"madre" son F: la inicial no basta + if n.startswith(("f", "muj", "mad")) or n == "2": + return "F" + if n.startswith(("h", "m")) or n == "1": + return "M" + return None + + +def fecha_tras_campo(bloques: Sequence[bytes], + nombres_campo=("BirthDate", "DateOfBirth"), + ventana=20, referencia=None, + edad_max_anios=EDAD_MAX_ANIOS): + """ + Fecha guardada como numero justo despues del nombre de su campo. + + NeuroWorks escribe la fecha de nacimiento como un double OLE (dias desde + 1899-12-30) situado unos bytes despues de la cadena "BirthDate" dentro del + bloque hexadecimal del .eeg. + + La ventana es CORTA a proposito (20 bytes). Con una ventana amplia se + cuela cualquier otra fecha cercana a la del estudio, que tambien da una + edad plausible: asi es como dos estudios del mismo paciente acabaron con + fechas de nacimiento distintas y erroneas. + + Dos cautelas mas: + + - Se prueba el DOUBLE en toda la ventana antes que el entero. Cualquier + relleno leido como entero de 4 bytes da un numero pequeno y una fecha + de principios del siglo XX, perfectamente "plausible" si solo se mira + el ano. + - Si se conoce la fecha del registro, se exige una edad plausible + (0 < edad <= edad_max_anios). Eso descarta los candidatos absurdos + mucho mejor que un rango de anos. + """ + if not bloques: + return None, "sin .eeg" + + def plausible(v): + if not (1 <= v <= 100000): + return None + try: + d = datetime(1899, 12, 30) + timedelta(days=float(v)) + except (OverflowError, ValueError): + return None + if referencia is not None: + anios = (referencia - d).days / 365.25 + return d if 0 < anios <= edad_max_anios else None + return d if 1980 <= d.year <= 2035 else None + + for fmt in (" tuple[str | None, date | None]: + """ + (sexo 'M'/'F'/None, fecha_nacimiento date/None) del estudio. + + Mismo orden de fuentes que examples/edades.py (edad_de): primero el + identificador del paciente, que son digitos explicitos; si no es una + fecha plausible, el double OLE que sigue al campo BirthDate. + """ + bloques = bloques_del_eeg(eeg_path) + sexo, motivo_sexo = sexo_del_eeg(bloques) + + def plausible(d): + if d is None or rec_date is None: + return d is not None + return 0 < (rec_date - d).days / 365.25 <= EDAD_MAX_ANIOS + + d, motivo = fecha_del_identificador(pat_id, id_order) + if not plausible(d): + LOG.debug("Birthdate not from the identifier: %s", motivo) + d, motivo = fecha_tras_campo(bloques, referencia=rec_date) + LOG.info("Sex from %s; birthdate from %s", motivo_sexo, + motivo if d is not None else "none found") + return sexo, (d.date() if d is not None else None) diff --git a/src/tea_modulo/export/text.py b/src/tea_modulo/export/text.py new file mode 100644 index 0000000..f0b01e2 --- /dev/null +++ b/src/tea_modulo/export/text.py @@ -0,0 +1,49 @@ +""" +Text helpers that survive accents, ñ and diaeresis. + +Ported from examples/texto.py. NeuroWorks writes names and notes in the local +Windows code page (cp1252), so bytes are decoded trying utf-8 first and then +falling back to cp1252 / latin-1. +""" + +from __future__ import annotations + +import unicodedata + +CODIFICACIONES = ("utf-8-sig", "utf-8", "cp1252", "latin-1") + + +def leer_bytes(datos: bytes) -> str: + """Decode bytes trying several encodings.""" + for cod in CODIFICACIONES: + try: + return datos.decode(cod) + except UnicodeDecodeError: + continue + return datos.decode("utf-8", errors="replace") + + +def sin_acentos(s: str) -> str: + """Strip accents and diaeresis, keeping ñ.""" + if not s: + return "" + s = s.replace("ñ", "\x00").replace("Ñ", "\x01") + s = "".join(c for c in unicodedata.normalize("NFD", s) + if unicodedata.category(c) != "Mn") + return s.replace("\x00", "ñ").replace("\x01", "Ñ") + + +def normalizar(s: str) -> str: + """Lower-case text without accents, for searching.""" + return sin_acentos(str(s or "")).lower().strip() + + +def to_ascii(s: str) -> str: + """ + Printable ASCII for EDF header fields. + + The EDF header only allows printable ASCII: accents are stripped, ñ + becomes n, and anything else that is not ASCII is dropped. + """ + s = sin_acentos(str(s or "")).replace("ñ", "n").replace("Ñ", "N") + return "".join(c for c in s if 32 <= ord(c) < 127) diff --git a/tests/export/test_edf_export_synthetic.py b/tests/export/test_edf_export_synthetic.py new file mode 100644 index 0000000..1b1947a --- /dev/null +++ b/tests/export/test_edf_export_synthetic.py @@ -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(" 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 diff --git a/tests/export/test_patient.py b/tests/export/test_patient.py new file mode 100644 index 0000000..301ec2b --- /dev/null +++ b/tests/export/test_patient.py @@ -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(" 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(" bytes: + b = bytearray(352) + b[0:16] = bytes(range(16)) + struct.pack_into(" bytes: + b = bytearray(DATA_OFFSET) + b[0:352] = generic_header(SCHEMA) + struct.pack_into(" 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("