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:
@@ -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"]
|
||||
@@ -0,0 +1,49 @@
|
||||
"""
|
||||
Command line entry point.
|
||||
|
||||
ktlx2edf <study_folder> [-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: <study GUID>.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())
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 <admin> X <equipment>" 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)
|
||||
@@ -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])]
|
||||
@@ -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("<H", raw, 16)[0],
|
||||
"base_schema": struct.unpack_from("<H", raw, 18)[0],
|
||||
"creation_time_raw": struct.unpack_from("<i", raw, 20)[0],
|
||||
"patient_id_num": struct.unpack_from("<i", raw, 24)[0],
|
||||
"study_id_num": struct.unpack_from("<i", raw, 28)[0],
|
||||
"pat_last_name": _cstr(raw[32:112]),
|
||||
"pat_first_name": _cstr(raw[112:192]),
|
||||
"pat_middle_name": _cstr(raw[192:272]),
|
||||
"pat_id": _cstr(raw[272:352]),
|
||||
}
|
||||
try:
|
||||
# Unix time is UTC; naive UTC like filetime_to_dt (fromtimestamp sin
|
||||
# tz daba la hora local de la maquina que convierte)
|
||||
hdr["creation_time"] = datetime.fromtimestamp(
|
||||
hdr["creation_time_raw"], timezone.utc).replace(tzinfo=None)
|
||||
except (OverflowError, OSError, ValueError):
|
||||
hdr["creation_time"] = None
|
||||
return hdr
|
||||
|
||||
|
||||
def read_erd_header(path: Path) -> 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("<d", f.read(8))[0]
|
||||
n_chan = struct.unpack("<i", f.read(4))[0]
|
||||
hdr["num_channels"] = n_chan
|
||||
hdr["deltabits"] = struct.unpack("<i", f.read(4))[0]
|
||||
if not (0 < n_chan <= 1024):
|
||||
raise ValueError(f"{path.name}: num_channels invalido ({n_chan})")
|
||||
hdr["phys_chan"] = list(struct.unpack(f"<{n_chan}i", f.read(4 * n_chan)))
|
||||
|
||||
f.seek(HEADBOX_OFFSET)
|
||||
hdr["headbox_type"] = list(struct.unpack("<4i", f.read(16)))
|
||||
hdr["headbox_sn"] = list(struct.unpack("<4i", f.read(16)))
|
||||
hdr["headbox_sw_version"] = [
|
||||
_cstr(f.read(10)) for _ in range(4)
|
||||
]
|
||||
hdr["dsp_hw_version"] = _cstr(f.read(10))
|
||||
hdr["dsp_sw_version"] = _cstr(f.read(10))
|
||||
hdr["discardbits"] = struct.unpack("<i", f.read(4))[0]
|
||||
|
||||
if schema >= 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", "<i4"),
|
||||
("samplestamp", "<i4"),
|
||||
("sample_num", "<i4"),
|
||||
("sample_span", "<i2"),
|
||||
("unknown", "<i2"),
|
||||
])
|
||||
|
||||
|
||||
def read_etc(path: Path) -> 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", "<i4"),
|
||||
("end_stamp", "<i4"),
|
||||
("sample_num", "<i4"),
|
||||
("sample_span", "<i4"),
|
||||
])
|
||||
|
||||
|
||||
def read_stc(path: Path):
|
||||
"""Indice de segmentos (pares .erd/.etc)."""
|
||||
hdr = read_generic_header(path)
|
||||
with path.open("rb") as f:
|
||||
# tras la cabecera: next_segment, final y 12 int32 de relleno
|
||||
f.seek(GENERIC_HDR_LEN + STC_PREAMBLE_LEN)
|
||||
stamps = np.fromfile(f, dtype=STC_DTYPE)
|
||||
stamps = stamps[stamps["segment_name"] != b""]
|
||||
return hdr, stamps
|
||||
|
||||
|
||||
SNC_DTYPE = np.dtype([("sample_stamp", "<i4"), ("sample_time", "<i8")])
|
||||
|
||||
|
||||
def read_snc(path: Path):
|
||||
"""Anclas (muestra -> 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="<i4", count=n_abs, offset=cur)
|
||||
cur += 4 * n_abs
|
||||
prev[read_abs] = absvals
|
||||
dat[t] = prev
|
||||
return dat, ev, cur
|
||||
|
||||
|
||||
# ------------------------------------------------------------ estudio KTLX
|
||||
|
||||
|
||||
class KtlxStudy:
|
||||
"""Descubre los archivos del estudio y expone lectura por muestras."""
|
||||
|
||||
def __init__(self, folder: Path):
|
||||
self.folder = Path(folder)
|
||||
if not self.folder.exists():
|
||||
padre = self.folder.parent
|
||||
pistas = ""
|
||||
if padre.exists():
|
||||
cerca = [d.name for d in padre.iterdir() if d.is_dir()]
|
||||
if cerca:
|
||||
import difflib
|
||||
par = difflib.get_close_matches(self.folder.name, cerca, 3)
|
||||
pistas = ("\n Quiza quisiste decir: "
|
||||
+ ", ".join(par) if par else
|
||||
"\n En " + str(padre) + " hay: "
|
||||
+ ", ".join(sorted(cerca)[:8]))
|
||||
raise FileNotFoundError(
|
||||
f"La carpeta no existe: {self.folder}{pistas}")
|
||||
if not self.folder.is_dir():
|
||||
raise NotADirectoryError(
|
||||
f"{self.folder} es un archivo, no una carpeta. Pasa la "
|
||||
f"carpeta que contiene el .stc, el .erd y los demas.")
|
||||
stc = sorted(self.folder.glob("*.stc"))
|
||||
if not stc:
|
||||
hijas = [d for d in self.folder.iterdir()
|
||||
if d.is_dir() and any(d.glob("*.stc"))]
|
||||
if hijas:
|
||||
raise FileNotFoundError(
|
||||
f"{self.folder} no es una carpeta de estudio, pero "
|
||||
f"contiene {len(hijas)} que si lo son.\n"
|
||||
f" Para una sola: ktlx2edf \"{hijas[0]}\"")
|
||||
cuantos = sum(1 for _ in self.folder.iterdir())
|
||||
raise FileNotFoundError(
|
||||
f"No hay ningun .stc en {self.folder} ({cuantos} elementos). "
|
||||
f"Sin el .stc no se puede saber que .erd componen el estudio.")
|
||||
if len(stc) > 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 '<APELLIDOS>~_<GUID>': 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"]))
|
||||
@@ -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 ("<d", "<i", "<f"): # el double manda
|
||||
n = struct.calcsize(fmt)
|
||||
for nombre in nombres_campo:
|
||||
for b in bloques:
|
||||
for zona in _zonas_tras_campo(b, nombre, ventana):
|
||||
for i in range(0, max(0, len(zona) - n + 1)):
|
||||
d = plausible(struct.unpack_from(fmt, zona, i)[0])
|
||||
if d:
|
||||
return d, f"{nombre} + {i} bytes ({fmt})"
|
||||
return None, "no hay valor tras el campo"
|
||||
|
||||
|
||||
def fecha_del_identificador(ident: str, orden="dmy"):
|
||||
"""
|
||||
Fecha de nacimiento deducida del identificador del paciente.
|
||||
|
||||
En esta instalacion el identificador ES la fecha de nacimiento escrita
|
||||
como ddmmaaaa: el campo ID vale "11012022" para un nacimiento del 11 de
|
||||
enero de 2022. Es el campo pat_id de la cabecera generica, presente en
|
||||
TODOS los archivos del estudio.
|
||||
|
||||
Ojo con la ambiguedad: con dia y mes por debajo de 13, ddmmaaaa y mmddaaaa
|
||||
dan fechas distintas y ambas validas. Conviene resolverlo con toda la
|
||||
cohorte (examples/edades.py, orden_del_identificador).
|
||||
"""
|
||||
ident = ident.strip()
|
||||
m = re.fullmatch(r"(\d{2})(\d{2})(\d{4})", ident)
|
||||
if not m:
|
||||
return None, f"el identificador no es una fecha ({ident[:20]!r})"
|
||||
a, b_, c = (int(x) for x in m.groups())
|
||||
dia, mes = (a, b_) if orden == "dmy" else (b_, a)
|
||||
try:
|
||||
return datetime(c, mes, dia), f"identificador {ident} como {orden}"
|
||||
except ValueError:
|
||||
try:
|
||||
dia, mes = mes, dia
|
||||
return datetime(c, mes, dia), f"identificador {ident} (orden inverso)"
|
||||
except ValueError:
|
||||
return None, f"identificador no interpretable ({ident})"
|
||||
|
||||
|
||||
def patient_info(eeg_path: Path | None, pat_id: str,
|
||||
rec_date: datetime | None, id_order: str = "dmy"
|
||||
) -> 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)
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user