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:
objectPreprocess EEG.
preprocessing pipeline: ZapLine → bad channels → filter → ASR → ICA → dipole fitting → average re-reference → interpolate → save.
Parameters are listed in pipeline order.
- Parameters:
- loader
XDFLoader|None Configured loader used by
run()to read raw files. Not required when callingrun_raw()directly.- channel_types
dict|None Channel name → MNE type mapping applied right after loading (only used by
run()).- rename_channels
dict|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_hook
callable()|None Arbitrary transformation applied to the raw object after channel renaming and before any signal processing.
The callable receives the
mne.io.Rawobject as its only argument and must return one of:the modified
rawobject, ora
(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_hookfor 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_freq
float|"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.0or60.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 byget_bad_chs()for notch-filtered bad-channel detection.- zapline_method
str|None DSS-based spectral cleaning algorithm applied before bandpass filtering.
Noneskips 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_kwargs
dict|None Extra keyword arguments forwarded to
get_bad_chs(). Supported keys (all optional):"pyprep_kwargs"(dict): passed to PyPREP’sNoisyChannels;random_stateis always overwritten with rng_seed."notch_width"(float, default1.0): width of the notch filter used during bad-channel detection."line_noise_crit"(float | None, defaultNone): z-score threshold for the per-channel line-noise criterion;None(default) disables this check - recommended when ZapLine has run."deviation_threshold"(float, default3.5): z-score threshold for PyPREP’s amplitude-deviation criterion. Tighter than PyPREP’s built-in default of5.0to improve sensitivity on MoBI data; raise to reduce false positives."ransac"(bool | None, defaultNone): run PyPREP RANSAC whenNone(auto) orTrue; auto-detects from montage presence. SetFalseto disable explicitly.
- annotate_breaksbool
If
True, runmne.preprocessing.annotate_break()to mark inter-block breaks (and other gaps between events) asBAD_breakannotations, which are then excluded (viareject_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. DefaultFalse(skip this step entirely); setTrueto enable it, tuning behaviour via annotate_break_kwargs if needed.- annotate_break_kwargs
dict|None Forwarded to
mne.preprocessing.annotate_break(). Ignored whenannotate_breaks=False.- filter_bands
tupleoffloat (l_freq, h_freq)for the main bandpass filter applied toraw_minimal.- subset_chs
listofstr|None Channels for the
raw_subsetoutput (minimally processed, without average reference). Defaults to some central and frontal channels whenNonebut producesNoneif none are found in the data.- asrbool |
dict Controls Artifact Subspace Reconstruction (ASR).
False(default): skip ASR;raw_asris a copy ofraw_minimal.True: run ASR with the default parameters ofcompute_asr().dict: run ASR and pass the dict as keyword arguments tocompute_asr()(e.g.{"cutoff": 10, "estimator": "lwf"}).
- filter_bands_ica
tupleoffloat (l_freq, h_freq)for the ICA-specific bandpass filter.- downsample_ica
float|None Target sampling rate for ICA fitting.
Noneskips downsampling.- ica_method
str ICA algorithm.
"amica"(default) uses AMICA viaamica-pythonand converts to MNE ICA; falls back to picard if the package is not installed. Any other string is forwarded as themethodargument tomne.preprocessing.ICA(e.g."picard","fastica"). Ignored whenfit_ica=False.- amica_kwargs
dict|None Extra keyword arguments forwarded to
amica.AMICAwhenica_method="amica". Useful for controlling convergence, e.g.{"max_iter": 2000}.Noneuses AMICA defaults. Ignored when a non-AMICA method is used orfit_ica=False.- fit_icabool
If
False, skip ICA entirely (raw_cleanequalsraw_asr).- thresh
float 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_labels
listofstr|None ICLabel categories to exclude. Mutually exclusive with include_labels.
- include_labels
setofstr|None ICLabel categories to keep; all others are excluded. Defaults to all classes except
"eye blink"(matching BeMoBIL’siclabel_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.- trans
mne.transforms.Transform|"fit"|"fsaverage"|None Head→MRI transform for dipole fitting.
Noneand"fsaverage"use the MNE built-in template;"fit"runs automatic coregistration. Ignored whenfit_dipoles=False.- rv_thresh
float|None Residual-variance threshold for dipole fitting. Components whose best-fitting dipole has RV >= rv_thresh are set to
Nonein thedipolesandresidualsoutput lists.Nonekeeps 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 toNonein the output lists.- rng_seed
int|None Random seed for ICA and PyPREP.
- event_id
dict|None Event map recorded in provenance metadata (no effect on processing).
- skip_if_existsbool
If
Trueandoverwrite=False, skip the entire computation when the primary output file{fname_out}_clean.fif.gzalready exists and return the previously saved results instead.- make_reportbool
If
True(default) and fname_out is provided, generate anmne.Reportsummarising the preprocessing outputs and save it alongside the other derivatives as{fname_out}_report.html.- verbosebool |
str|int MNE verbosity level during processing.
- loader
- Parameters:
channel_types (dict | None)
pre_hook (object)
zapline_method (str | None)
get_bad_chs_kwargs (dict | None)
annotate_breaks (bool)
annotate_break_kwargs (dict | None)
subset_chs (list | None)
downsample_ica (float | None)
ica_method (str)
amica_kwargs (dict | None)
fit_ica (bool)
thresh (float)
exclude_labels (list | None)
include_labels (set | None)
fit_dipoles (bool)
trans (object)
rv_thresh (float | None)
remove_outside_head (bool)
rng_seed (int | None)
event_id (dict | None)
skip_if_exists (bool)
make_report (bool)
- __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:
channel_types (dict | None)
pre_hook (object)
zapline_method (str | None)
get_bad_chs_kwargs (dict | None)
annotate_breaks (bool)
annotate_break_kwargs (dict | None)
subset_chs (list | None)
downsample_ica (float | None)
ica_method (str)
amica_kwargs (dict | None)
fit_ica (bool)
thresh (float)
exclude_labels (list | None)
include_labels (set | None)
fit_dipoles (bool)
trans (object)
rv_thresh (float | None)
remove_outside_head (bool)
rng_seed (int | None)
event_id (dict | None)
skip_if_exists (bool)
make_report (bool)
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(anXDFLoader), whoseload()returns aMultimodalRecording. Only the Tier-1rawobject is preprocessed;tier2is forwarded torun_raw()for the report’s drop-out plots, andeventsis discarded (callrun_raw()directly if you need it).- Parameters:
- Returns:
Sameasrun_raw().
- Parameters:
- Return type:
- 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:
- raw
mne.io.BaseRaw Recording to preprocess.
- fname_out
str|Path|None Output stem for saving derivatives. Pass
Noneto skip saving.- overwritebool
Overwrite existing output files.
- tier2
dict|None Tier-2 streams from
MultimodalRecording(e.g.rec.tier2), kept at native rate and not merged into raw. When provided andmake_report=True, each stream is plotted in full (decimated envelope, with drop-outs shaded) in its own report section.None(default) skips this section.
- raw
- Returns:
- raw_clean
mne.io.Raw ASR + ICA cleaned recording with bad channels interpolated.
- report
mne.Report|None Quality report (populated when
make_report=True, elseNone).- metadata
dict All other pipeline outputs keyed by name:
raw_minimal,raw_asr,raw_subset,ica,ic_labels,dipoles,residuals,trans,bad_ch_dict.
- raw_clean
- Parameters:
- Return type: