Files
tea/src/tea_modulo/preprocessing/api.py
T
AlbertoPMDM acfd3a70d4 preprocessing: modern Preprocessor on MNE, agreeing with the director's output
Executes a PreprocessPlan with MNE: EDF read and label normalisation, plan
bads dropped, line removal on the raw signal (interpolated notch when the
line is >= min_db on the kept scalp channels, or ZapLine via meegkit),
Raw.filter (IIR Butterworth order 4, zero phase, run by run between
BAD_ACQ_SKIP), set_eeg_reference (average of kept scalp / linked ears),
EOG/ECG filtered only. Window grid and quality spans from a private copy of
the window QC.

Within 0.25 uV of legacy.preprocessing on every channel of both default
plans away from the filter edges (max(5 s, 3/highpass)).
2026-11-18 20:50:33 -06:00

139 lines
6.0 KiB
Python

"""
Modern preprocessing: a PreprocessPlan executed with MNE.
Order (as preproceso.procesar):
read EDF (MNE) -> drop bad channels (plan.bads) -> line removal on the raw signal
(interpolated notch if the line is >= min_db over its neighbourhood, measured on the
kept scalp channels; or ZapLine, meegkit) -> per variant: high-pass + low-pass
(Raw.filter, IIR Butterworth order 4, zero phase, run by run between BAD_ACQ_SKIP)
-> reference (Raw.set_eeg_reference: average of the kept scalp channels, or the
linked ears A1+A2). EOG / ECG are filtered and never re-referenced.
Windows: the plan's grid (window_s / step_s), flagged from a 4 s back-to-back
window QC (private copy of the validation's rules); quality_spans are the QC
windows that are not clean.
"""
from __future__ import annotations
import json
from collections.abc import Mapping
from typing import Any
import numpy as np
import pandas as pd
from tea_modulo.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, sha256_of
from . import _channels, _qc, _signal
from .plan import PreprocessPlan
GAP = ("BAD_ACQ_SKIP", "edge")
KEEP = ("eeg", "orejas", "eog", "cardiaco")
_TYPE = {"eeg": "eeg", "orejas": "eeg", "eog": "eog", "cardiaco": "ecg"}
class Preprocessing:
name = "preprocessing"
version = "0.1.0"
contract_version = CONTRACT_VERSION
impl = "modern"
def plan_for(self, summary: ValidationSummary, base: Mapping[str, Any]) -> dict:
d = PreprocessPlan.from_dict(base).to_dict()
new = [c for c in summary.bad_channels if c not in d["bads"]]
d["bads"] = list(d["bads"]) + new
d["reasons"] = {**d["reasons"], **{c: summary.bad_channels[c] for c in new}}
if not summary.ears_usable:
d["variants"] = [v for v in d["variants"] if v["reference"] != "linked_ears"]
d["reasons"]["variants"] = "ears not usable: linked-ears variants dropped"
return d
# ------------------------------------------------------------------ run
def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed:
import mne
p = PreprocessPlan.from_dict(plan)
raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error")
ren, seen, drop = {}, set(), []
for c in raw.ch_names: # edf_convert: unknown dropped, first duplicate kept
n = _channels.normalize(c)
if n is None or n in seen:
drop.append(c)
else:
seen.add(n)
ren[c] = n
raw.drop_channels(drop)
raw.rename_channels({c: n for c, n in ren.items() if n != c})
classes = _channels.classify(raw.ch_names)
keep = [c for c in raw.ch_names if classes[c] in KEEP and c not in p.bads]
raw.pick(keep)
raw.set_channel_types({c: _TYPE[classes[c]] for c in keep}, verbose="error")
fs = float(raw.info["sfreq"])
scalp = [c for c in keep if classes[c] == "eeg"]
ears = [c for c in keep if classes[c] == "orejas"]
if len(scalp) < p.gates.min_scalp:
raise ValueError(f"only {len(scalp)} scalp electrodes usable (minimum {p.gates.min_scalp})")
# line removal on the raw signal
x = raw.get_data(reject_by_annotation="NaN", verbose="error").T * 1e6
idx_scalp = [keep.index(c) for c in scalp]
db_before = float(np.nanmedian(_signal.line_db(x[:, idx_scalp], fs, p.line_hz)))
removal = "none"
notch = p.step("interpolated_notch")
zap = p.step("zapline")
if notch is not None and db_before >= float(notch.params.get("min_db", 6.0)):
x = _signal.notch_interpolated(x, fs, p.line_hz, width=float(notch.params.get("width_hz", 1.5)))
removal = "interpolated_notch"
elif zap is not None:
x = _zapline(x, fs, p.line_hz, int(zap.params.get("nremove", 1)))
removal = "zapline"
gaps = ~np.isfinite(x).all(axis=1)
raw._data[:] = np.nan_to_num(x, nan=0.0).T * 1e-6
lp = p.step("lowpass").params["hz"] if p.step("lowpass") else None
iir = {"order": 4, "ftype": "butter"}
variants = {}
for v in p.variants:
r = raw.copy().filter(v.highpass_hz, lp, method="iir", iir_params=iir, phase="zero",
skip_by_annotation=GAP, verbose="error")
if v.reference == "linked_ears":
if len(ears) != 2:
raise ValueError(f"variant {v.name}: linked ears need both A1 and A2 usable")
r.set_eeg_reference(ears, verbose="error")
r.drop_channels(ears)
else:
r.drop_channels(ears)
r.set_eeg_reference("average", verbose="error")
variants[v.name] = r
# window QC (4 s back-to-back) on the kept scalp channels, notch + 0.5-45 Hz
y = x[:, idx_scalp]
y = _signal.bandpass(y, fs, 0.5, 45.0)
y[gaps] = np.nan
qc = _qc.window_qc(y, fs)
duration = raw.n_times / fs
d = p.to_dict()
d["run"] = {"line_db_before": round(db_before, 1), "line_removal": removal,
"channels": scalp, "aux": [c for c in keep if classes[c] in ("eog", "cardiaco")],
"ears": ears}
return Preprocessed(variants=variants, windows=_qc.windows_from_qc(qc, duration, p.window_s, p.step_s),
age_months=age_months, plan=d, plan_hash=p.content_hash(),
source_sha256=sha256_of(edf_path), quality_spans=_qc.spans_from_qc(qc))
def _zapline(x, fs, f0, nremove):
"""ZapLine (meegkit.dss.dss_line) on each gap-free run long enough for its FFT."""
from meegkit.dss import dss_line
def f(seg):
import contextlib
import io
with contextlib.redirect_stdout(io.StringIO()): # dss_line prints a summary
out, _ = dss_line(seg, f0, fs, nremove=nremove)
return out
return _signal.by_runs(x, f, minimum=max(int(4 * fs), 1024))
MODULE = Preprocessing()