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:
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
Edge cases on synthetic KTLX studies (tests/ktlx_synth.py): internal gap, edge padding, photic train, accented annotations, headbox
|
||||
constants, schema 8, clamping and 8-character header fields.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import struct
|
||||
import warnings
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import edfio
|
||||
import mne
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
import ktlx_synth as tr
|
||||
from edfio import EdfSignal
|
||||
|
||||
from tea_modulo.export import edf_export as ex
|
||||
from tea_modulo.export import ktlx
|
||||
from tea_modulo.export.edf_annotations import BAD_ACQ_SKIP, clamped
|
||||
from tea_modulo.export.edf_header import EDF_RECORDING_LEN, recording_header
|
||||
from tea_modulo.export.edf_signals import DIGITAL_RANGE, build_signals, half_range
|
||||
|
||||
ACCENTED = "Fotoestimulación ñandú"
|
||||
ACCENTED_STAMP = 200
|
||||
|
||||
|
||||
def _append_note(folder, text, stamp):
|
||||
"""Add an annotation to the synthetic .ent (before its terminator)."""
|
||||
ent = next(folder.glob("*.ent"))
|
||||
blob = ent.read_bytes()[:-16]
|
||||
payload = f'(."Annotation" (.Stamp {stamp}) (.Text "{text}"))'.encode(
|
||||
"cp1252") + b"\x00\x00"
|
||||
blob += struct.pack("<4i", 1, 16 + len(payload), 0, 0) + payload
|
||||
ent.write_bytes(blob + struct.pack("<4i", 0, 0, 0, 0))
|
||||
|
||||
|
||||
def _set_headbox(folder, headbox):
|
||||
for erd in folder.glob("*.erd"):
|
||||
b = bytearray(erd.read_bytes())
|
||||
struct.pack_into("<i", b, ktlx.HEADBOX_OFFSET, headbox)
|
||||
erd.write_bytes(bytes(b))
|
||||
|
||||
|
||||
def _read(path):
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
raw = mne.io.read_raw_edf(path, preload=True, verbose="warning")
|
||||
assert [str(w.message) for w in caught] == []
|
||||
return raw
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def study(tmp_path):
|
||||
folder = tmp_path / "study"
|
||||
data, events, stamps, spans, n_tot = tr.build_study(folder)
|
||||
_append_note(folder, ACCENTED, ACCENTED_STAMP)
|
||||
return SimpleNamespace(folder=folder, data=data, stamps=stamps,
|
||||
spans=spans, n_tot=n_tot)
|
||||
|
||||
|
||||
def test_synthetic_roundtrip(study, tmp_path):
|
||||
out = ex.ktlx_to_edf(study.folder, tmp_path / "s.edf")
|
||||
raw = _read(out)
|
||||
fs = tr.FS
|
||||
k_v, _ = ktlx.scale_v_per_lsb(ktlx.KtlxStudy(study.folder).hdr)
|
||||
|
||||
# values: every packet lands at its global stamp, in volts
|
||||
got = raw.get_data()
|
||||
sigs = edfio.read_edf(out).signals
|
||||
step = np.array([(s.physical_range.max - s.physical_range.min)
|
||||
/ (s.digital_range.max - s.digital_range.min)
|
||||
for s in sigs]) * 1e-6 # uV -> V
|
||||
assert len({tuple(s.physical_range) for s in sigs}) == 1
|
||||
assert all(s.physical_range.min == -s.physical_range.max for s in sigs)
|
||||
full_v = sigs[0].physical_range.max * 1e-6
|
||||
a = 0
|
||||
for stamp, n in zip(study.stamps, study.spans):
|
||||
exp = np.clip(study.data[a:a + n].T.astype(np.float64) * k_v,
|
||||
-full_v, full_v)
|
||||
assert np.all(np.abs(got[:, stamp:stamp + n] - exp)
|
||||
<= step[:, None] / 2 + 1e-12)
|
||||
a += n
|
||||
|
||||
# internal gap (zero-filled) and edge padding, both BAD_ACQ_SKIP
|
||||
gap_a = int(study.stamps[1] + study.spans[1])
|
||||
gap_b = int(study.stamps[2])
|
||||
assert all(np.all(sig.digital[gap_a:gap_b] == 0) for sig in sigs)
|
||||
assert np.allclose(got[:, gap_a:gap_b], 0, rtol=0, atol=1e-15)
|
||||
n_data = study.n_tot
|
||||
n_pad = raw.n_times - n_data
|
||||
assert n_pad == (-n_data) % int(fs) and n_pad > 0
|
||||
assert np.all(got[:, n_data:] == got[:, [n_data - 1]])
|
||||
bad = sorted((round(o * fs), round(d * fs)) for o, d, t in zip(
|
||||
raw.annotations.onset, raw.annotations.duration,
|
||||
raw.annotations.description) if t == BAD_ACQ_SKIP)
|
||||
assert bad == [(gap_a, gap_b - gap_a), (n_data, n_pad)]
|
||||
|
||||
# events: .ent notes (incl. UTF-8 text), photic train, IDS
|
||||
desc = dict(zip(raw.annotations.description, raw.annotations.onset))
|
||||
assert desc["Fotica 10 Hz"] == pytest.approx(100 / fs)
|
||||
assert desc["Ojos abiertos"] == pytest.approx(620 / fs)
|
||||
assert desc[ACCENTED] == pytest.approx(ACCENTED_STAMP / fs)
|
||||
photic = [d for d in desc if d.startswith("Photic ")]
|
||||
assert len(photic) == 1 and photic[0].endswith(" Hz (20 flashes)")
|
||||
assert desc[photic[0]] == pytest.approx(100 / fs)
|
||||
assert any(d.startswith("IDS guid=abc123 ") for d in desc)
|
||||
|
||||
# header: name anonymized, synthetic ID kept, stem name not leaked
|
||||
si = raw.info["subject_info"]
|
||||
assert si["his_id"] == "ID-0001" and si.get("last_name") == "X"
|
||||
assert b"PEREZ" not in out.read_bytes()
|
||||
|
||||
|
||||
def test_unknown_headbox_uses_classic_constant(study, tmp_path, caplog):
|
||||
_set_headbox(study.folder, 15)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
ex.ktlx_to_edf(study.folder, tmp_path / "hb15.edf")
|
||||
assert "headbox_type=15" in caplog.text
|
||||
k15, aviso = ktlx.scale_v_per_lsb({"headbox_type": [15], "discardbits": 0})
|
||||
k26, ok = ktlx.scale_v_per_lsb({"headbox_type": [26], "discardbits": 0})
|
||||
assert aviso and ok is None
|
||||
assert k15 / k26 == pytest.approx(8711 / 5000)
|
||||
assert k26 == pytest.approx(5000 / (2 ** 21 - 0.5) * 1e-6)
|
||||
|
||||
|
||||
def test_schema_8(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(tr, "SCHEMA", 8)
|
||||
folder = tmp_path / "s8"
|
||||
tr.build_study(folder)
|
||||
raw = _read(ex.ktlx_to_edf(folder, tmp_path / "s8.edf"))
|
||||
assert len(raw.ch_names) == tr.N_CHAN
|
||||
|
||||
|
||||
@pytest.mark.parametrize("onset, dur, text, expected", [
|
||||
(-30, 40, "early", (0.0, 10, "early [pre-start -0.1 s]")),
|
||||
(-30, 10, "early", (0.0, None, "early [pre-start -0.1 s]")),
|
||||
(300, None, "late", (299 / 256, None, "late [post-end +0.0 s]")),
|
||||
(250, 100, "long", (250 / 256, 50, "long")),
|
||||
])
|
||||
def test_clamped(onset, dur, text, expected):
|
||||
a = clamped(onset, dur, 300, 256.0, text)
|
||||
exp_onset, exp_dur, exp_text = expected
|
||||
assert a.onset == pytest.approx(exp_onset)
|
||||
assert a.text == exp_text
|
||||
if exp_dur is None:
|
||||
assert a.duration is None
|
||||
else:
|
||||
assert a.duration == pytest.approx(exp_dur / 256)
|
||||
|
||||
|
||||
HB3 = {"headbox_type": [26], "discardbits": 6}
|
||||
HB3_V_PER_LSB = ktlx.scale_v_per_lsb(HB3)[0]
|
||||
|
||||
|
||||
def test_hb3_resolution():
|
||||
"""Datasheet: ±5 mV over 16 bits, 0.153 uV/bit (rounded)."""
|
||||
assert HB3_V_PER_LSB * 1e6 == pytest.approx(10_000 / 65536, rel=1e-6)
|
||||
for db in (0, 6):
|
||||
assert ktlx.full_scale_v({**HB3, "discardbits": db}) == pytest.approx(
|
||||
32767 * HB3_V_PER_LSB)
|
||||
|
||||
|
||||
def test_fixed_range_lossless_and_clipped(caplog):
|
||||
counts = np.array([[0, 131070], [32767, 131070], [-32768, 131070],
|
||||
[-5, 131070], [12345, 131070]], np.int32)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
sigs = build_signals(counts, HB3_V_PER_LSB, ktlx.full_scale_v(HB3),
|
||||
256.0, ["Cz", "DC"],
|
||||
["Xltek phys=7 erd=0", "Xltek phys=32 erd=1"])
|
||||
assert "Cz=1, DC=5" in caplog.text
|
||||
for s in sigs:
|
||||
assert (s.physical_range.min, s.physical_range.max) == (-4999.9,
|
||||
4999.9)
|
||||
assert tuple(s.digital_range) == DIGITAL_RANGE
|
||||
assert s.physical_dimension == "uV" and s.prefiltering == ""
|
||||
assert sigs[0].transducer_type == "Xltek phys=7 erd=0"
|
||||
assert list(sigs[0].digital) == [0, 32767, -32767, -5, 12345]
|
||||
assert list(sigs[1].digital) == [32767] * 5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("x", [0.000873456, 0.0123456789, 0.7629394,
|
||||
0.15304122616866642, 12.3456789, 1e-4,
|
||||
4999.847])
|
||||
def test_half_range_fits_8_chars(x):
|
||||
h = half_range(x)
|
||||
assert x <= h <= 1.5 * x
|
||||
assert len(str(-h)) <= 8 and "e" not in str(h)
|
||||
sig = EdfSignal(np.array([0.0, x, -x]), 1.0, physical_range=(-h, h),
|
||||
digital_range=DIGITAL_RANGE)
|
||||
assert (sig.physical_range.min, sig.physical_range.max) == (-h, h)
|
||||
assert sig.digital[0] == 0
|
||||
assert abs(sig.data[0]) < 1e-15 * max(h, 1)
|
||||
|
||||
|
||||
def test_recording_field_fits(study):
|
||||
st = ktlx.KtlxStudy(study.folder)
|
||||
st.hdr["headbox_sw_version"] = ["9" * 10] * 4
|
||||
rec = recording_header(datetime(2020, 1, 1).date(), st.guid,
|
||||
ex._equipment(st))
|
||||
field = (f"Startdate 01-JAN-2020 {rec.hospital_administration_code} "
|
||||
f"X {rec.equipment_code}")
|
||||
assert len(field) <= EDF_RECORDING_LEN
|
||||
assert rec.equipment_code.startswith("Xltek_HB26")
|
||||
|
||||
|
||||
def test_start_time_without_snc_is_utc(study, tmp_path, monkeypatch):
|
||||
"""Without .snc the .stc creation time (Unix, UTC) is used, whatever
|
||||
the time zone of the converting machine."""
|
||||
import time
|
||||
monkeypatch.setenv("TZ", "America/Mexico_City")
|
||||
time.tzset()
|
||||
try:
|
||||
next(study.folder.glob("*.snc")).unlink()
|
||||
raw = _read(ex.ktlx_to_edf(study.folder, tmp_path / "nosnc.edf"))
|
||||
finally:
|
||||
monkeypatch.undo()
|
||||
time.tzset()
|
||||
expected = datetime.fromtimestamp(1_600_000_000, ktlx.timezone.utc)
|
||||
assert raw.info["meas_date"] == expected
|
||||
|
||||
|
||||
def test_cli_reports_errors_without_traceback(tmp_path, caplog, capsys):
|
||||
from tea_modulo.export import cli
|
||||
with caplog.at_level(logging.ERROR):
|
||||
assert cli.main([str(tmp_path / "missing")]) == 1
|
||||
assert "La carpeta no existe" in caplog.text
|
||||
assert "Traceback" not in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_cli_converts(study, tmp_path, capsys):
|
||||
from tea_modulo.export import cli
|
||||
out = tmp_path / "cli.edf"
|
||||
assert cli.main([str(study.folder), "-o", str(out)]) == 0
|
||||
assert out.exists() and str(out) in capsys.readouterr().out
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Unit tests for the sex / birthdate extraction (tea_modulo.export.patient)."""
|
||||
|
||||
import struct
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from tea_modulo.export import patient
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, expected", [
|
||||
("F", "F"), ("Female", "F"), ("Mujer", "F"), ("madre", "F"), ("2", "F"),
|
||||
("M", "M"), ("Male", "M"), ("Masculino", "M"), ("Hombre", "M"), ("1", "M"),
|
||||
("", None), ("X", None), ("unknown", None),
|
||||
])
|
||||
def test_normalizar_sexo(raw, expected):
|
||||
assert patient.normalizar_sexo(raw) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ident, orden, expected", [
|
||||
("11012022", "dmy", date(2022, 1, 11)),
|
||||
("11012022", "mdy", date(2022, 11, 1)),
|
||||
("25122019", "mdy", date(2019, 12, 25)), # month 25 impossible: swapped
|
||||
(" 01022020 ", "dmy", date(2020, 2, 1)),
|
||||
("ID-0001", "dmy", None),
|
||||
("99992020", "dmy", None),
|
||||
])
|
||||
def test_fecha_del_identificador(ident, orden, expected):
|
||||
d, motivo = patient.fecha_del_identificador(ident, orden)
|
||||
assert (d.date() if d else None) == expected
|
||||
assert motivo
|
||||
|
||||
|
||||
def _ole(d: datetime) -> bytes:
|
||||
return struct.pack("<d", (d - datetime(1899, 12, 30)) / timedelta(days=1))
|
||||
|
||||
|
||||
def test_fields_skip_label_and_read_value():
|
||||
blob = (b"GenderLabel\x00Sexo\x00" # display label: skipped
|
||||
b"Gender\x00\x00Female\x00"
|
||||
b"BirthDateLabel\x00Fecha\x00"
|
||||
b"BirthDate\x00\x00" + _ole(datetime(2021, 3, 4)))
|
||||
bloques = [blob]
|
||||
assert patient.sexo_del_eeg(bloques)[0] == "F"
|
||||
d, _ = patient.fecha_tras_campo(bloques, referencia=datetime(2025, 1, 1))
|
||||
assert d.date() == date(2021, 3, 4)
|
||||
|
||||
|
||||
def test_fields_inside_hex_block():
|
||||
inner = b"Gender\x00M\x00"
|
||||
blob = b'(."Bin", 0x' + inner.hex().encode() + b"00" * 12 + b")"
|
||||
assert patient.sexo_del_eeg(patient.desde_hex(blob))[0] == "M"
|
||||
|
||||
|
||||
def test_birthdate_rejects_implausible_age():
|
||||
blob = b"BirthDate\x00" + _ole(datetime(1850, 1, 1))
|
||||
d, _ = patient.fecha_tras_campo([blob], referencia=datetime(2025, 1, 1))
|
||||
assert d is None
|
||||
|
||||
|
||||
def test_patient_info_sources(tmp_path):
|
||||
eeg = tmp_path / "x.eeg"
|
||||
eeg.write_bytes(b"Gender\x00F\x00BirthDate\x00"
|
||||
+ _ole(datetime(2018, 6, 7)))
|
||||
rec = datetime(2025, 1, 1)
|
||||
# identifier is a date: it wins over the OLE double
|
||||
assert patient.patient_info(eeg, "11012022", rec) == ("F", date(2022, 1, 11))
|
||||
# identifier is not a date: OLE double after BirthDate
|
||||
assert patient.patient_info(eeg, "ID-0001", rec) == ("F", date(2018, 6, 7))
|
||||
# no .eeg at all
|
||||
assert patient.patient_info(None, "ID-0001", rec) == (None, None)
|
||||
@@ -0,0 +1,188 @@
|
||||
"""
|
||||
Synthetic KTLX studies for tests.
|
||||
|
||||
Writes a complete schema 8/9 study (.erd/.etc/.stc/.snc/.ent) with two
|
||||
segments, a 500-sample gap, a 10 Hz photic train and two annotations. The
|
||||
builder and the reference encoder come from examples/test_roundtrip.py and
|
||||
examples/xltek_convert.py (encode_packet); they live here so the tests do not
|
||||
depend on examples/.
|
||||
"""
|
||||
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from tea_modulo.export import ktlx
|
||||
|
||||
FS = 256.0
|
||||
N_CHAN = 20
|
||||
CHAN_NAMES = ["Fp1", "Fp2", "F3", "F4", "C3", "C4", "P3", "P4", "O1", "O2",
|
||||
"F7", "F8", "T3", "T4", "T5", "T6", "Fz", "Cz", "Pz", "EKG"]
|
||||
DISCARDBITS = 0
|
||||
SCHEMA = 9
|
||||
DATA_OFFSET = 8656 # 352 + campos + headbox + shorted/frequency_factor
|
||||
|
||||
|
||||
def encode_packet(data: np.ndarray, events: np.ndarray, n_chan: int,
|
||||
sentinel: int = -1) -> bytes:
|
||||
"""
|
||||
Codificador de referencia (solo se usa en las pruebas de ida y vuelta).
|
||||
Fuerza valores absolutos en la primera muestra del paquete.
|
||||
"""
|
||||
out = bytearray()
|
||||
l_mask = (n_chan + 7) // 8
|
||||
prev = np.zeros(n_chan, dtype=np.int64)
|
||||
for t in range(data.shape[0]):
|
||||
cur = data[t].astype(np.int64)
|
||||
delta = cur - prev
|
||||
fits8 = (delta >= -128) & (delta <= 127)
|
||||
fits16 = (delta >= -32768) & (delta <= 32767) & (delta != sentinel)
|
||||
if t == 0: # la primera muestra del paquete va siempre absoluta
|
||||
small = np.zeros(n_chan, dtype=bool)
|
||||
big_ok = np.zeros(n_chan, dtype=bool)
|
||||
else:
|
||||
small = fits8
|
||||
big_ok = fits16 & ~fits8
|
||||
absolute = ~(small | big_ok)
|
||||
bits = np.zeros(n_chan, dtype=np.uint8)
|
||||
bits[big_ok | absolute] = 1
|
||||
out.append(int(events[t]) & 0x01)
|
||||
out += np.packbits(
|
||||
np.concatenate([bits, np.zeros(l_mask * 8 - n_chan, np.uint8)]),
|
||||
bitorder="little").tobytes()
|
||||
vals = np.where(absolute, sentinel, delta).astype(np.int64)
|
||||
fmt = "<" + "".join("h" if b else "b" for b in bits)
|
||||
out += struct.pack(fmt, *[int(v) for v in vals])
|
||||
if absolute.any():
|
||||
out += cur[absolute].astype("<i4").tobytes()
|
||||
prev = cur
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def generic_header(schema: int) -> bytes:
|
||||
b = bytearray(352)
|
||||
b[0:16] = bytes(range(16))
|
||||
struct.pack_into("<H", b, 16, schema)
|
||||
struct.pack_into("<H", b, 18, 1)
|
||||
struct.pack_into("<i", b, 20, 1_600_000_000)
|
||||
struct.pack_into("<i", b, 24, 111)
|
||||
struct.pack_into("<i", b, 28, 222)
|
||||
b[32:32 + 6] = b"PEREZ\x00"
|
||||
b[112:112 + 4] = b"ANA\x00"
|
||||
b[272:272 + 7] = b"ID-0001"
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def erd_header() -> bytes:
|
||||
b = bytearray(DATA_OFFSET)
|
||||
b[0:352] = generic_header(SCHEMA)
|
||||
struct.pack_into("<d", b, 352, FS)
|
||||
struct.pack_into("<i", b, 360, N_CHAN)
|
||||
struct.pack_into("<i", b, 364, 8) # deltabits
|
||||
struct.pack_into(f"<{N_CHAN}i", b, 368, *range(N_CHAN)) # phys_chan
|
||||
off = 4464
|
||||
struct.pack_into("<4i", b, off, 26, 0, 0, 0) # headbox_type = 26
|
||||
struct.pack_into("<4i", b, off + 16, 987654, 0, 0, 0) # headbox_sn
|
||||
b[off + 32:off + 42] = b"1.2.3\x00\x00\x00\x00\x00"
|
||||
b[off + 72:off + 82] = b"HW-A\x00\x00\x00\x00\x00\x00"
|
||||
b[off + 82:off + 92] = b"SW-B\x00\x00\x00\x00\x00\x00"
|
||||
struct.pack_into("<i", b, off + 92, DISCARDBITS) # 4556
|
||||
# shorted[1024] en 4560 y frequency_factor[1024] en 6608: todo cero/uno
|
||||
struct.pack_into("<1024h", b, 4560, *([0] * 1024))
|
||||
struct.pack_into("<1024h", b, 6608, *([1] * 1024))
|
||||
assert len(b) == DATA_OFFSET
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def make_signal(n_smp: int, seed: int = 0) -> np.ndarray:
|
||||
"""Senal con deltas pequenos, saltos grandes y saturaciones ocasionales."""
|
||||
rng = np.random.default_rng(seed)
|
||||
t = np.arange(n_smp)
|
||||
x = np.zeros((n_smp, N_CHAN), dtype=np.int64)
|
||||
for c in range(N_CHAN):
|
||||
base = (12000 * np.sin(2 * np.pi * (8 + c * 0.3) * t / FS)
|
||||
+ 3000 * np.sin(2 * np.pi * 0.7 * t / FS + c))
|
||||
ruido = rng.integers(-40, 41, size=n_smp)
|
||||
x[:, c] = base.astype(np.int64) + ruido + c * 1000
|
||||
# saltos que fuerzan deltas de 16 bit y valores absolutos
|
||||
for c in range(0, N_CHAN, 5):
|
||||
x[n_smp // 3:, c] += 900 # -> delta de 16 bit
|
||||
x[2 * n_smp // 3:, c] += 5_000_000 # -> valor absoluto int32
|
||||
return x.astype(np.int32)
|
||||
|
||||
|
||||
def build_study(folder: Path, packets_smp=(300, 300, 257), gap_after=1):
|
||||
"""Crea un estudio con dos segmentos .erd y un hueco intencional."""
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
stem = "PEREZ, ANA_abc123"
|
||||
|
||||
total = sum(packets_smp)
|
||||
data = make_signal(total)
|
||||
events = np.zeros(total, dtype=np.uint8)
|
||||
# tren fotico: 10 Hz durante 2 s a partir de la muestra 100
|
||||
for k in range(20):
|
||||
events[100 + int(k * FS / 10)] = 1
|
||||
|
||||
# dos segmentos: paquetes 0-1 en el primer .erd, paquete 2 en el segundo
|
||||
reparto = [(0, [0, 1]), (1, [2])]
|
||||
stamps_ini = np.concatenate([[0], np.cumsum(packets_smp)[:-1]])
|
||||
# hueco de 500 muestras antes del ultimo paquete
|
||||
hueco = 500
|
||||
stamps_glob = stamps_ini.copy()
|
||||
stamps_glob[gap_after + 1:] += hueco
|
||||
|
||||
stc_entries = []
|
||||
for seg_i, pks in reparto:
|
||||
name = stem if seg_i == 0 else f"{stem}_{seg_i:03d}"
|
||||
erd = folder / f"{name}.erd"
|
||||
etc = folder / f"{name}.etc"
|
||||
blob = bytearray(erd_header())
|
||||
etc_rows = []
|
||||
for k in pks:
|
||||
a = int(stamps_ini[k])
|
||||
n = packets_smp[k]
|
||||
off = len(blob)
|
||||
blob += encode_packet(data[a:a + n], events[a:a + n], N_CHAN)
|
||||
etc_rows.append((off, int(stamps_glob[k]), n, n, 0))
|
||||
erd.write_bytes(bytes(blob))
|
||||
eb = bytearray(generic_header(SCHEMA))
|
||||
for row in etc_rows:
|
||||
eb += struct.pack("<iiihh", *row)
|
||||
etc.write_bytes(bytes(eb))
|
||||
a0 = int(stamps_glob[pks[0]])
|
||||
a1 = int(stamps_glob[pks[-1]] + packets_smp[pks[-1]])
|
||||
stc_entries.append((name.encode(), a0, a1, a1 - a0, a1 - a0))
|
||||
|
||||
sb = bytearray(generic_header(SCHEMA))
|
||||
sb += struct.pack("<ii", len(stc_entries), 1) + b"\x00" * 48
|
||||
for name, a0, a1, num, span in stc_entries:
|
||||
sb += name.ljust(256, b"\x00") + struct.pack("<iiii", a0, a1, num, span)
|
||||
(folder / f"{stem}.stc").write_bytes(bytes(sb))
|
||||
|
||||
# .snc: dos anclas
|
||||
nb = bytearray(generic_header(SCHEMA))
|
||||
ft0 = ktlx.EPOCH_AS_FILETIME + 1_600_000_000 * ktlx.HUNDREDS_OF_NS
|
||||
n_tot = int(stamps_glob[-1] + packets_smp[-1])
|
||||
nb += struct.pack("<iq", 0, ft0)
|
||||
nb += struct.pack("<iq", n_tot,
|
||||
int(ft0 + n_tot / FS * ktlx.HUNDREDS_OF_NS))
|
||||
(folder / f"{stem}.snc").write_bytes(bytes(nb))
|
||||
|
||||
# .ent: nota de montaje con ChanNames + dos anotaciones
|
||||
eb = bytearray(generic_header(SCHEMA))
|
||||
notas = [
|
||||
'(."Montage" (.ChanNames (' + ", ".join(f'"{c}"' for c in CHAN_NAMES)
|
||||
+ ')) (.Stamp 0))',
|
||||
'(."Annotation" (.Stamp 100) (.Text "Fotica 10 Hz") '
|
||||
'(.Data (.User "tecnico1")))',
|
||||
'(."Annotation" (.Stamp 620) (.Text "Ojos abiertos") '
|
||||
'(.Data (.User "tecnico1")))',
|
||||
]
|
||||
for nota in notas:
|
||||
payload = nota.encode() + b"\x00\x00"
|
||||
eb += struct.pack("<4i", 1, 16 + len(payload), 0, 0) + payload
|
||||
eb += struct.pack("<4i", 0, 0, 0, 0)
|
||||
(folder / f"{stem}.ent").write_bytes(bytes(eb))
|
||||
|
||||
return data, events, stamps_glob, packets_smp, n_tot
|
||||
@@ -13,6 +13,24 @@ resolution-markers = [
|
||||
"python_full_version < '3.13' and sys_platform != 'emscripten' and sys_platform != 'win32'",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aiobotocore"
|
||||
version = "3.10.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "aioitertools" },
|
||||
{ name = "botocore" },
|
||||
{ name = "jmespath" },
|
||||
{ name = "multidict" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "wrapt" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/16/40/659f2ac3915d329e3e8e5bf674d35ce1774f3117c6f60339d5e05e505c36/aiobotocore-3.10.0.tar.gz", hash = "sha256:35480ef11c51e23087273b85d97f80da2f356a46ce5f3fb88e24483cd343ffdb", size = 530781, upload-time = "2026-10-23T10:44:50.843Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/bc/3bb8965204ba51bbf4d021bc89d1357cd2179a17ef71b5fc429e21b511a2/aiobotocore-3.10.0-py3-none-any.whl", hash = "sha256:de0ccbcb82b6b0009f1b6667f48442e9d0432f9b8bfe6172fa51777cbea89d03", size = 102759, upload-time = "2026-10-23T10:44:49.109Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aiohappyeyeballs"
|
||||
version = "2.7.1"
|
||||
@@ -164,6 +182,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/68/30/173960c42b05a6c59f7558e4b12a4b0d9ba376cf6aa9bde7f9e08a30ca8d/aiohttp-3.14.5-py3-none-any.whl", hash = "sha256:efc21a454892828368b11c2c780de0ff8bc991f73f6b99c6b66e56205470929b", size = 279517, upload-time = "2026-10-11T01:05:08.523Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aioitertools"
|
||||
version = "0.13.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/fd/3c/53c4a17a05fb9ea2313ee1777ff53f5e001aefd5cc85aa2f4c2d982e1e38/aioitertools-0.13.0.tar.gz", hash = "sha256:620bd241acc0bbb9ec819f1ab215866871b4bbd1f73836a55f799200ee86950c", size = 19322, upload-time = "2025-11-06T22:17:07.609Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/10/a1/510b0a7fadc6f43a6ce50152e69dbd86415240835868bb0bd9b5b88b1e06/aioitertools-0.13.0-py3-none-any.whl", hash = "sha256:0be0292b856f08dfac90e31f4739432f4cb6d7520ab9eb73e143f4f2fa5259be", size = 24182, upload-time = "2025-11-06T22:17:06.502Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aiosignal"
|
||||
version = "1.4.0"
|
||||
@@ -276,6 +303,20 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "botocore"
|
||||
version = "1.43.117"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "jmespath" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "urllib3" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6e/a0/d0a5c44ad6a01f195681ddcb4ce203f06c712811daf1d15f8f8785e8a9f8/botocore-1.43.117.tar.gz", hash = "sha256:71993702832cc37c2495048b9945f2929d306fccb3fb767e9964e437e637fa6c", size = 16366888, upload-time = "2026-10-21T19:29:59.274Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/10/94/050e35c9febf6dd2fce4a76be587ae4a323964865700467d9d7b082f7133/botocore-1.43.117-py3-none-any.whl", hash = "sha256:5920ef9b3002e1361846549078549d9154a6e0004c22853c01ce7b279d05d495", size = 16061765, upload-time = "2026-10-21T19:29:56.001Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cachetools"
|
||||
version = "7.3.2"
|
||||
@@ -1208,6 +1249,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jmespath"
|
||||
version = "1.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d3/59/322338183ecda247fb5d1763a6cbe46eff7222eaeebafd9fa65d4bf5cb11/jmespath-1.1.0.tar.gz", hash = "sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d", size = 27377, upload-time = "2026-01-22T16:35:26.279Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "joblib"
|
||||
version = "1.6.0"
|
||||
@@ -2855,6 +2905,20 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "s3fs"
|
||||
version = "2026.9.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiobotocore" },
|
||||
{ name = "aiohttp" },
|
||||
{ name = "fsspec" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f7/fe/ab89ab94cc1293849bc1a60876b589007bdd43f59a06ca309e717bd45dc7/s3fs-2026.9.0.tar.gz", hash = "sha256:ec078ff0122d28fd21d36ea4987794e4f42ecd6e8785eeaa083208771c1464e5", size = 89163, upload-time = "2026-09-18T19:02:54.117Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl", hash = "sha256:eb185fd98e20a1c9375087d9b2a6ef506f0cd01ae0c0c94efc79f88403fb81fe", size = 33126, upload-time = "2026-09-18T19:02:52.933Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scikit-learn"
|
||||
version = "1.9.1"
|
||||
@@ -3216,6 +3280,14 @@ dependencies = [
|
||||
{ name = "yasa" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
export = [
|
||||
{ name = "edfio" },
|
||||
]
|
||||
s3 = [
|
||||
{ name = "s3fs" },
|
||||
]
|
||||
|
||||
[package.dev-dependencies]
|
||||
dev = [
|
||||
{ name = "pytest" },
|
||||
@@ -3227,6 +3299,7 @@ requires-dist = [
|
||||
{ name = "dask", specifier = ">=2026.8.0" },
|
||||
{ name = "distributed", specifier = ">=2026.8.0" },
|
||||
{ name = "edfio", specifier = ">=0.4.18" },
|
||||
{ name = "edfio", marker = "extra == 'export'", specifier = ">=0.4.18" },
|
||||
{ name = "fhir-resources", specifier = ">=8.3.0" },
|
||||
{ name = "fooof", specifier = "==1.1.1" },
|
||||
{ name = "meegkit", specifier = ">=0.2.0" },
|
||||
@@ -3234,10 +3307,12 @@ requires-dist = [
|
||||
{ name = "mne", specifier = ">=1.13.2" },
|
||||
{ name = "numpy", specifier = ">=2.5.5" },
|
||||
{ name = "pandas", specifier = ">=3.1.1" },
|
||||
{ name = "s3fs", marker = "extra == 's3'" },
|
||||
{ name = "scikit-learn", specifier = ">=1.9.1" },
|
||||
{ name = "scipy", specifier = ">=1.18.1" },
|
||||
{ name = "yasa", specifier = ">=0.8.1" },
|
||||
]
|
||||
provides-extras = ["export", "s3"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [{ name = "pytest", specifier = ">=9.2.0" }]
|
||||
|
||||
Reference in New Issue
Block a user