""" 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: one Butterworth band-pass (order 4, zero phase: scipy sosfiltfilt, as eeg_io.pasa_banda) on each gap-free run -> reference (nanmean of the kept scalp channels, or of the linked ears A1+A2). EOG / ECG are filtered and never re-referenced. Gaps (BAD_ACQ_SKIP) stay NaN in every variant, as in the director's npz: modules see a gap as NaN, never as 0 µV. 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 import warnings 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 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) try: raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error") except Exception as e: # annotation texts in a Windows code page if "latin1" not in str(e): raise raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error", encoding="latin1") 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) # variants as the director builds them: one Butterworth band-pass per gap-free run # (NaN stays NaN), then the reference with nanmean, so a gap is still a gap (NaN) in # every variant and no module filters across it lp = p.step("lowpass").params["hz"] if p.step("lowpass") else None idx_ears = [keep.index(c) for c in ears] others = [i for i, c in enumerate(keep) if c not in ears] aux_idx = [i for i in others if i not in idx_scalp] base_raw = raw.copy().drop_channels(ears) variants = {} for v in p.variants: y = _signal.bandpass(x, fs, v.highpass_hz, lp) cue = y[:, idx_scalp] with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) # nanmean of a gap row if v.reference == "linked_ears": if len(ears) != 2: raise ValueError(f"variant {v.name}: linked ears need both A1 and A2 usable") ref = np.nanmean(y[:, idx_ears], axis=1, keepdims=True) else: ref = np.nanmean(cue, axis=1, keepdims=True) out = np.empty((len(y), len(others))) pos = {i: k for k, i in enumerate(others)} out[:, [pos[i] for i in idx_scalp]] = cue - ref if aux_idx: out[:, [pos[i] for i in aux_idx]] = y[:, aux_idx] # EOG/EKG: not re-referenced r = base_raw.copy() r._data = out.T * 1e-6 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()