bemobil_mne.preproc.EEGPreprocessor#

class bemobil_mne.preproc.EEGPreprocessor(loader, *, channel_types=None, rename_channels=None, pre_hook=None, line_noise_freq='europe', zapline_method='adaptive', get_bad_chs_kwargs=None, annotate_breaks=False, annotate_break_kwargs=None, filter_bands=(0.1, 100.0), subset_chs=None, asr=False, filter_bands_ica=(1.75, None), downsample_ica=250.0, ica_method='amica', amica_kwargs=None, fit_ica=True, thresh=-1, exclude_labels=None, include_labels=frozenset({'brain', 'channel noise', 'heart beat', 'line noise', 'muscle artifact', 'other'}), fit_dipoles=False, trans=None, rv_thresh=None, remove_outside_head=False, rng_seed=None, event_id=None, skip_if_exists=False, make_report=True, verbose=True)[source]#

Bases: object

Preprocess EEG.

preprocessing pipeline: ZapLine → bad channels → filter → ASR → ICA → dipole fitting → average re-reference → interpolate → save.

Parameters are listed in pipeline order.

Parameters:
loaderXDFLoader | None

Configured loader used by run() to read raw files. Not required when calling run_raw() directly.

channel_typesdict | None

Channel name → MNE type mapping applied right after loading (only used by run()).

rename_channelsdict | str | None

Channel renaming applied at the very start of run_raw().

  • dict: explicit {old_name: new_name} mapping.

  • str: strip this prefix from every channel name that starts with it (e.g. "BrainVision RDA_").

  • None (default): no renaming.

pre_hookcallable() | None

Arbitrary transformation applied to the raw object after channel renaming and before any signal processing.

The callable receives the mne.io.Raw object as its only argument and must return one of:

  • the modified raw object, or

  • a (raw, description) tuple, where description is a short string (≤ 120 characters) describing what the hook did. The description is appended to the provenance metadata stored on the raw object and saved with the pipeline outputs.

Use pre_hook for one-off operations that do not belong in the general pipeline but must happen before filtering, such as cropping the recording, injecting custom annotations, correcting a known hardware artefact, or converting units. The hook runs before ZapLine, bad-channel detection, and all subsequent steps, so any changes it makes are seen by the entire pipeline.

Example:

def my_hook(raw):
    raw.crop(tmin=5.0)          # drop the first 5 s
    return raw, "cropped first 5 s"

preprocessor = EEGPreprocessor(loader, pre_hook=my_hook)
line_noise_freqfloat | "europe" | "usa"

Fundamental line-noise frequency in Hz. Harmonics are computed automatically up to (but not exceeding) the Nyquist frequency of the recording. Accepted values:

  • float: explicit fundamental (e.g. 50.0 or 60.0).

  • "europe": shortcut for 50 Hz (default).

  • "usa": shortcut for 60 Hz.

The resulting harmonic array is used both by the ZapLine spectral cleaning step (when zapline_method is not None) and by get_bad_chs() for notch-filtered bad-channel detection.

zapline_methodstr | None

DSS-based spectral cleaning algorithm applied before bandpass filtering. None skips ZapLine entirely. Default is "adaptive" (matching BeMoBIL). One of:

"adaptive"

ZapLine-plus (mne-denoise) with adaptive frequency detection.

"zapline"

Standard ZapLine (mne-denoise), fixed-frequency.

"dss_line"

Single-pass DSS (meegkit).

"dss_line_iter"

Iterative DSS (meegkit).

get_bad_chs_kwargsdict | None

Extra keyword arguments forwarded to get_bad_chs(). Supported keys (all optional):

  • "pyprep_kwargs" (dict): passed to PyPREP’s NoisyChannels; random_state is always overwritten with rng_seed.

  • "notch_width" (float, default 1.0): width of the notch filter used during bad-channel detection.

  • "line_noise_crit" (float | None, default None): z-score threshold for the per-channel line-noise criterion; None (default) disables this check - recommended when ZapLine has run.

  • "deviation_threshold" (float, default 3.5): z-score threshold for PyPREP’s amplitude-deviation criterion. Tighter than PyPREP’s built-in default of 5.0 to improve sensitivity on MoBI data; raise to reduce false positives.

  • "ransac" (bool | None, default None): run PyPREP RANSAC when None (auto) or True; auto-detects from montage presence. Set False to disable explicitly.

annotate_breaksbool

If True, run mne.preprocessing.annotate_break() to mark inter-block breaks (and other gaps between events) as BAD_break annotations, which are then excluded (via reject_by_annotation) from bad-channel detection, ICA fitting, and other downstream steps. Break detection can be overzealous on some recordings (e.g. sparse or irregular event structure), flagging most of the recording as “bad” even though the data itself is fine. Default False (skip this step entirely); set True to enable it, tuning behaviour via annotate_break_kwargs if needed.

annotate_break_kwargsdict | None

Forwarded to mne.preprocessing.annotate_break(). Ignored when annotate_breaks=False.

filter_bandstuple of float

(l_freq, h_freq) for the main bandpass filter applied to raw_minimal.

subset_chslist of str | None

Channels for the raw_subset output (minimally processed, without average reference). Defaults to some central and frontal channels when None but produces None if none are found in the data.

asrbool | dict

Controls Artifact Subspace Reconstruction (ASR).

  • False (default): skip ASR; raw_asr is a copy of raw_minimal.

  • True: run ASR with the default parameters of compute_asr().

  • dict: run ASR and pass the dict as keyword arguments to compute_asr() (e.g. {"cutoff": 10, "estimator": "lwf"}).

filter_bands_icatuple of float

(l_freq, h_freq) for the ICA-specific bandpass filter.

downsample_icafloat | None

Target sampling rate for ICA fitting. None skips downsampling.

ica_methodstr

ICA algorithm. "amica" (default) uses AMICA via amica-python and converts to MNE ICA; falls back to picard if the package is not installed. Any other string is forwarded as the method argument to mne.preprocessing.ICA (e.g. "picard", "fastica"). Ignored when fit_ica=False.

amica_kwargsdict | None

Extra keyword arguments forwarded to amica.AMICA when ica_method="amica". Useful for controlling convergence, e.g. {"max_iter": 2000}. None uses AMICA defaults. Ignored when a non-AMICA method is used or fit_ica=False.

fit_icabool

If False, skip ICA entirely (raw_clean equals raw_asr).

threshfloat

ICLabel decision threshold. Set to -1 (default, matching BeMoBIL) to use popularity-vote mode: each IC is assigned to whichever class has the highest predicted probability; it is excluded if that class is not in include_labels (or is in exclude_labels). Any value in [0, 1] switches to probability-threshold mode: an IC is excluded only when its artifact-class probability meets or exceeds this value.

exclude_labelslist of str | None

ICLabel categories to exclude. Mutually exclusive with include_labels.

include_labelsset of str | None

ICLabel categories to keep; all others are excluded. Defaults to all classes except "eye blink" (matching BeMoBIL’s iclabel_classes = [1 2 4 5 6 7]). Mutually exclusive with exclude_labels.

fit_dipolesbool

If True, fit a dipole to each ICA component topography using the fsaverage BEM. Requires a montage with digitisation.

transmne.transforms.Transform | "fit" | "fsaverage" | None

Head→MRI transform for dipole fitting. None and "fsaverage" use the MNE built-in template; "fit" runs automatic coregistration. Ignored when fit_dipoles=False.

rv_threshfloat | None

Residual-variance threshold for dipole fitting. Components whose best-fitting dipole has RV >= rv_thresh are set to None in the dipoles and residuals output lists. None keeps all dipoles. Typical value: 0.15 (15 %).

remove_outside_headbool

If True, components whose dipole falls outside the head model (position norm > 0.13 m) are set to None in the output lists.

rng_seedint | None

Random seed for ICA and PyPREP.

event_iddict | None

Event map recorded in provenance metadata (no effect on processing).

skip_if_existsbool

If True and overwrite=False, skip the entire computation when the primary output file {fname_out}_clean.fif.gz already exists and return the previously saved results instead.

make_reportbool

If True (default) and fname_out is provided, generate an mne.Report summarising the preprocessing outputs and save it alongside the other derivatives as {fname_out}_report.html.

verbosebool | str | int

MNE verbosity level during processing.

Parameters:
__init__(loader, *, channel_types=None, rename_channels=None, pre_hook=None, line_noise_freq='europe', zapline_method='adaptive', get_bad_chs_kwargs=None, annotate_breaks=False, annotate_break_kwargs=None, filter_bands=(0.1, 100.0), subset_chs=None, asr=False, filter_bands_ica=(1.75, None), downsample_ica=250.0, ica_method='amica', amica_kwargs=None, fit_ica=True, thresh=-1, exclude_labels=None, include_labels=frozenset({'brain', 'channel noise', 'heart beat', 'line noise', 'muscle artifact', 'other'}), fit_dipoles=False, trans=None, rv_thresh=None, remove_outside_head=False, rng_seed=None, event_id=None, skip_if_exists=False, make_report=True, verbose=True)[source]#
Parameters:

Methods

__init__(loader, *[, channel_types, ...])

run(fname_in[, fname_out, overwrite])

Load fname_in and run the full preprocessing pipeline.

run_raw(raw[, fname_out, overwrite, tier2])

Run the preprocessing pipeline on an already-loaded raw object.

run(fname_in, fname_out=None, *, overwrite=False)[source]#

Load fname_in and run the full preprocessing pipeline.

Uses loader (an XDFLoader), whose load() returns a MultimodalRecording. Only the Tier-1 raw object is preprocessed; tier2 is forwarded to run_raw() for the report’s drop-out plots, and events is discarded (call run_raw() directly if you need it).

Parameters:
fname_instr | Path

Path to the raw input file (XDF or any MNE-readable format).

fname_outstr | Path | None

Output stem for saving derivatives. Pass None to skip saving.

overwritebool

Overwrite existing output files.

Returns:
Same as run_raw().
Parameters:
Return type:

tuple

run_raw(raw, fname_out=None, *, overwrite=False, tier2=None)[source]#

Run the preprocessing pipeline on an already-loaded raw object.

Channel types and montage must already be set by the caller.

Parameters:
rawmne.io.BaseRaw

Recording to preprocess.

fname_outstr | Path | None

Output stem for saving derivatives. Pass None to skip saving.

overwritebool

Overwrite existing output files.

tier2dict | None

Tier-2 streams from MultimodalRecording (e.g. rec.tier2), kept at native rate and not merged into raw. When provided and make_report=True, each stream is plotted in full (decimated envelope, with drop-outs shaded) in its own report section. None (default) skips this section.

Returns:
raw_cleanmne.io.Raw

ASR + ICA cleaned recording with bad channels interpolated.

reportmne.Report | None

Quality report (populated when make_report=True, else None).

metadatadict

All other pipeline outputs keyed by name: raw_minimal, raw_asr, raw_subset, ica, ic_labels, dipoles, residuals, trans, bad_ch_dict.

Parameters:
Return type:

tuple