### Setup and Data Download for Visualizing Bad Sensors Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/auto_examples/plot_visualize_bad_epochs.html This code snippet initializes project settings and downloads data from OpenfMRI using openneuro-py. It sets up environment variables and imports essential libraries for the visualization task. Ensure openneuro-py is installed via pip. ```python import os import openneuro import autoreject ``` -------------------------------- ### Quickstart Ransac usage Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/index.html Shows how to use the Ransac class, which implements RANSAC from the PREP pipeline, for cleaning M/EEG epochs. The API is designed to be similar to AutoReject. ```python from autoreject import Ransac rsc = Ransac() epochs_clean = rsc.fit_transform(epochs) ``` -------------------------------- ### Quickstart AutoReject usage Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/index.html Demonstrates the basic usage of the AutoReject class for cleaning M/EEG epochs. It shows how to initialize AutoReject and apply it to epochs data using fit_transform. ```python from autoreject import AutoReject ar = AutoReject() epochs_clean = ar.fit_transform(epochs) ``` -------------------------------- ### Autoreject Quickstart Cleaning Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.2/_sources/index.rst.txt Demonstrates the basic usage of the AutoReject class to clean MNE-Python epochs objects. It initializes AutoReject and applies it using fit_transform. ```python from autoreject import AutoReject ar = AutoReject() epochs_clean = ar.fit_transform(epochs) # doctest: +SKIP ``` -------------------------------- ### Install autoreject development version Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/index.html Installs the latest development version of autoreject directly from its GitHub repository. This is useful for users who want to access the newest features or contribute to the project. ```bash pip install https://github.com/autoreject/autoreject/archive/refs/heads/main.zip ``` -------------------------------- ### Install Autoreject Nightly Build Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.2/_sources/index.rst.txt Installs the latest development version (nightly build) of autoreject directly from the GitHub repository using pip. ```bash $ pip install https://api.github.com/repos/autoreject/autoreject/zipball/master ``` -------------------------------- ### Verify autoreject installation Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/index.html A simple Python command to verify that the autoreject library has been installed correctly. If no errors are reported, the installation was successful. ```python python -c 'import autoreject' ``` -------------------------------- ### Install autoreject using conda Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/index.html Installs the autoreject library from the conda-forge channel. This is a recommended method for users who prefer using the Anaconda distribution and its package manager. ```bash conda install -c conda-forge autoreject ``` -------------------------------- ### Install autoreject and dependencies Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.2/index.html Installs the necessary dependencies for autoreject using conda and pip, and then installs autoreject itself. This ensures all required libraries are present for M/EEG data processing. ```shell conda install numpy matplotlib scipy scikit-learn joblib pip install -U mne pip install -U autoreject ``` -------------------------------- ### Install autoreject using pip Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/index.html Installs the latest stable release of the autoreject library using pip. This command ensures that the package and its core dependencies are updated to their latest versions. ```bash pip install -U autoreject ``` -------------------------------- ### Compatibility Patch for MNE-Python _setup_dots Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.3/_modules/autoreject/utils.html A compatibility function that 'monkey patches' the MNE-Python `_setup_dots` function to ensure compatibility across different MNE-Python versions. It checks the installed MNE version and calls `_setup_dots` with the appropriate arguments. ```python def _patch_setup_dots(mode, info, coils, ch): """Monkey patch _setup_dots for MNE-Python >= v0.24.""" from mne.forward._field_interpolation import _setup_dots from mne.utils import check_version if not check_version('mne', '0.24'): return _setup_dots(mode, coils, ch) else: return _setup_dots(mode, info, coils, ch) ``` -------------------------------- ### Download Resting-State EEG Data using openneuro-py Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.3/_downloads/88aa0ebf52f0f32e2f92cc901577e2ba/plot_autoreject_workflow.ipynb Downloads resting-state EEG data for a Parkinson's patient from OpenNeuro. Requires the 'openneuro-py' package. Outputs data to a specified target directory. ```python %matplotlib inline import os.path as op import numpy as np import matplotlib.pyplot as plt import openneuro import mne import autoreject dataset = 'ds002778' # The id code on OpenNeuro for this example dataset subject_id = 'pd14' target_dir = op.join(op.dirname(autoreject.__file__), '..', 'examples') openneuro.download(dataset=dataset, target_dir=target_dir, include=[f'sub-{subject_id}/ses-off']) ``` -------------------------------- ### Load and Epoch EEG Data with Fixed Length Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.3/_downloads/88aa0ebf52f0f32e2f92cc901577e2ba/plot_autoreject_workflow.ipynb Loads raw BDF EEG data, sets a standard montage, and creates fixed-length epochs. It then plots the joint view of the averaged data. Assumes data is preloaded. ```python raw_fname = op.join(target_dir, f'sub-{subject_id}', 'ses-off', 'eeg', 'sub-pd14_ses-off_task-rest_eeg.bdf') raw = mne.io.read_raw_bdf(raw_fname, preload=True) dig_montage = mne.channels.make_standard_montage('biosemi32') raw.drop_channels([ch for ch in raw.ch_names if ch not in dig_montage.ch_names]) raw.set_montage(dig_montage) # use the standard montage epochs = mne.make_fixed_length_epochs(raw, duration=3, preload=True) # plot the data epochs.average().detrend().plot_joint() ``` -------------------------------- ### Get MNE Epochs Type Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/_modules/autoreject/utils.html Determines the correct base class for epochs in MNE-Python, accounting for potential changes between library versions. It checks for the presence of `_BaseEpochs` or falls back to `BaseEpochs`. This ensures compatibility across different MNE-Python installations. ```python import mne def _get_epochs_type(): if hasattr(mne.epochs, '_BaseEpochs'): BaseEpochs = mne.epochs._BaseEpochs else: BaseEpochs = mne.epochs.BaseEpochs return BaseEpochs ``` -------------------------------- ### Initialize Theme and Search Options (JavaScript) Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/search.html This script initializes the page's theme and search options by retrieving settings from local storage and setting global documentation options. It also includes placeholders for dynamically generated UI elements like the search button, theme switch button, and version switcher. ```javascript document.documentElement.dataset.mode = localStorage.getItem("mode") || "auto"; document.documentElement.dataset.theme = localStorage.getItem("theme") || "light"; DOCUMENTATION_OPTIONS.pagename = 'search'; DOCUMENTATION_OPTIONS.theme_switcher_json_url = 'https://raw.githubusercontent.com/autoreject/autoreject/master/doc/_static/versions.json'; DOCUMENTATION_OPTIONS.theme_switcher_version_match = '0.4.2'; document.write(` `); document.write(` `); document.write(` `); ``` -------------------------------- ### Initialize Documentation Options (JavaScript) Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/index.html This JavaScript code initializes global documentation options, including the current page name, the URL for theme switcher JSON data, and the version matching for the theme switcher. ```javascript DOCUMENTATION_OPTIONS.pagename = 'index'; DOCUMENTATION_OPTIONS.theme_switcher_json_url = 'https://raw.githubusercontent.com/autoreject/autoreject/master/doc/_static/versions.json'; DOCUMENTATION_OPTIONS.theme_switcher_version_match = '0.4.2'; ``` -------------------------------- ### Install Autoreject Dependencies Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.2/_sources/index.rst.txt Installs necessary dependencies for autoreject using conda and pip. Requires Python version >=3.5. Optional dependencies like tqdm and h5py can also be installed. ```bash $ conda install numpy matplotlib scipy scikit-learn joblib $ pip install -U mne ``` -------------------------------- ### Initialize Theme and Page Settings (JavaScript) Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/whats_new.html This script initializes the document's mode and theme based on local storage or defaults, and sets documentation-specific options like page name and theme switcher configuration. ```javascript document.documentElement.dataset.mode = localStorage.getItem("mode") || "auto"; document.documentElement.dataset.theme = localStorage.getItem("theme") || "light"; DOCUMENTATION_OPTIONS.pagename = 'whats_new'; DOCUMENTATION_OPTIONS.theme_switcher_json_url = 'https://raw.githubusercontent.com/autoreject/autoreject/master/doc/_static/versions.json'; DOCUMENTATION_OPTIONS.theme_switcher_version_match = '0.4.2'; ``` -------------------------------- ### Setting up High-Pass FIR Filter Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/auto_examples/plot_autoreject_workflow.html This snippet shows the configuration for setting up a high-pass FIR filter for raw data. It specifies a one-pass, zero-phase, non-causal filter using the firwin method with Hamming window. The parameters include passband ripple, stopband attenuation, lower passband edge, transition bandwidth, and filter length. ```text Filtering raw data in 1 contiguous segment Setting up high-pass filter at 1 Hz FIR filter parameters --------------------- Designing a one-pass, zero-phase, non-causal highpass filter: - Windowed time-domain design (firwin) method - Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation - Lower passband edge: 1.00 - Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 0.50 Hz) - Filter length: 1691 samples (3.303 s) ``` -------------------------------- ### Download OpenNeuro Dataset using Python Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/auto_examples/plot_visualize_bad_epochs.html This Python snippet initializes variables for dataset and subject IDs, constructs a target directory path using `os.path.join`, creates the directory if it doesn't exist with `os.makedirs`, and then initiates the download of specific files from OpenNeuro using `openneuro.download`. It highlights downloading MEG data for a particular subject and session. Dependencies include the `openneuro` library and standard Python `os` module. ```python import openneuro import os dataset = 'ds000117' # The id code on OpenNeuro for this example dataset subject_id = 16 # OpenfMRI format of subject numbering target_dir = os.path.join( os.path.dirname(autoreject.__file__), '..', 'examples', dataset) os.makedirs(target_dir, exist_ok=True) openneuro.download(dataset=dataset, target_dir=target_dir, include=[f'sub-{subject_id}/ses-meg/']) ``` -------------------------------- ### Download EEG Data with openneuro-py Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/auto_examples/plot_autoreject_workflow.html This snippet downloads resting-state EEG data from OpenNeuro using the openneuro-py library. It specifies the dataset ID and subject ID, and saves the data to a local directory. Ensure openneuro-py is installed (`pip install openneuro-py`). ```python import os import openneuro import mne import autoreject dataset = 'ds002778' # The id code on OpenNeuro for this example dataset subject_id = 'pd14' target_dir = os.path.join( os.path.dirname(autoreject.__file__), '..', 'examples', dataset) os.makedirs(target_dir, exist_ok=True) openneuro.download(dataset=dataset, target_dir=target_dir, include=[f'sub-{subject_id}/ses-off']) ``` -------------------------------- ### Download EEG Data from OpenNeuro Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/auto_examples/plot_autoreject_workflow.html This snippet demonstrates the process of downloading a dataset from OpenNeuro. It shows the progress of directory traversal and file downloads, including skipping already downloaded files and re-downloading files with size mismatches. It involves downloading a BDF file and associated metadata. ```shell Traversing directories for ds002778: 51 entities [00:15, 2.91 entities/s] Traversing directories for ds002778: 52 entities [00:15, 3.22 entities/s] ... Skipping participants.tsv: already downloaded. ... Re-downloading README: file size mismatch. ... Finished downloading ds002778. Please enjoy your brains. ``` -------------------------------- ### Bad Channels List Output (Example) Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/_sources/auto_examples/plot_ransac.rst.txt This is an example output showing the list of bad channels identified by the Ransac algorithm. The format is typically 'MEG XXXX' or 'EEG XXXX', indicating the channel type and its index. ```none MEG 0722 MEG 0813 MEG 0812 MEG 0822 MEG 0912 MEG 0942 MEG 0943 MEG 1013 MEG 1023 MEG 1022 MEG 1032 MEG 1422 MEG 1633 MEG 2443 ``` -------------------------------- ### Set up MNE Data Paths and Read Raw Data (Python) Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/auto_examples/plot_estimate_global_reject.html This snippet demonstrates how to define file paths for MNE-sample-data using pathlib and read raw MNE data. It sets up directory paths for MEG data and specific raw and event files, then loads the raw data with preprocessing information. Dependencies include MNE-Python and pathlib. ```python from pathlib import Path import mne data_path = mne.datasets.sample.data_path() meg_path = data_path / 'MEG' / 'sample' raw_fname = meg_path / 'sample_audvis_filt-0-40_raw.fif' event_fname = meg_path / 'sample_audvis_filt-0-40_raw-eve.fif' raw = mne.io.read_raw_fif(raw_fname, preload=True) events = mne.read_events(event_fname) ``` -------------------------------- ### Initialize theme and page settings — autoreject JavaScript Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/auto_examples/plot_visualize_bad_epochs.html These JavaScript snippets initialize the theme and page settings for the autoreject documentation. They load the 'mode' and 'theme' from local storage, or default to 'auto' and 'light' respectively. They also configure documentation options, including the page name and theme switcher settings. ```javascript document.documentElement.dataset.mode = localStorage.getItem("mode") || "auto"; document.documentElement.dataset.theme = localStorage.getItem("theme") || "light"; DOCUMENTATION_OPTIONS.pagename = 'auto_examples/plot_visualize_bad_epochs'; DOCUMENTATION_OPTIONS.theme_switcher_json_url = 'https://raw.githubusercontent.com/autoreject/autoreject/master/doc/_static/versions.json'; DOCUMENTATION_OPTIONS.theme_switcher_version_match = '0.4.2'; ``` -------------------------------- ### Get Rejection Threshold Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/_modules/autoreject/autoreject.html Computes global rejection thresholds for MNE-Python Epochs objects. ```APIDOC ## POST /autoreject/get_rejection_threshold ### Description Computes global rejection thresholds for MNE-Python Epochs objects. ### Method POST ### Endpoint /autoreject/get_rejection_threshold ### Parameters #### Query Parameters - **decim** (int) - Optional - The decimation factor. Defaults to 1. - **random_state** (int | np.random.RandomState | None) - Optional - The seed for the random number generator. Defaults to None. - **ch_types** (str | list of str | None) - Optional - Channel types to consider. Defaults to all supported types. - **cv** (int | sklearn.model_selection object) - Optional - Cross-validation strategy. Defaults to 5. - **verbose** (bool) - Optional - Whether to display progress messages. Defaults to True. #### Request Body - **epochs** (mne.Epochs) - Required - The epochs object from which to estimate the rejection dictionary. ### Request Example ```json { "epochs": "" } ``` ### Response #### Success Response (200) - **reject** (dict) - A dictionary with rejection thresholds for each channel type. #### Response Example ```json { "reject": { "mag": 40e-6, "grad": 4000e-6, "eeg": 80e-6 } } ``` ``` -------------------------------- ### Initialize Theme and Mode Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/auto_examples/plot_estimate_global_reject.html Initializes the document's data attributes for mode and theme based on local storage settings. It also sets documentation options for page name, theme switcher JSON URL, and version matching. ```javascript document.documentElement.dataset.mode = localStorage.getItem("mode") || "auto"; document.documentElement.dataset.theme = localStorage.getItem("theme") || "light"; DOCUMENTATION_OPTIONS.pagename = 'auto_examples/plot_estimate_global_reject'; DOCUMENTATION_OPTIONS.theme_switcher_json_url = 'https://raw.githubusercontent.com/autoreject/autoreject/master/doc/_static/versions.json'; DOCUMENTATION_OPTIONS.theme_switcher_version_match = '0.4.2'; ``` -------------------------------- ### Autoreject Get Rejection Threshold Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.2/_sources/index.rst.txt Shows how to obtain the rejection threshold dictionary from an epochs object using the get_rejection_threshold function. ```python from autoreject import get_rejection_threshold reject = get_rejection_threshold(epochs) # doctest: +SKIP ``` -------------------------------- ### Get Rejection Log for Epochs Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.3/generated/autoreject.AutoReject.html Retrieves the rejection log for the given epochs. This log contains information about which epochs were marked as bad based on the AutoReject parameters. ```python def get_reject_log(epochs[, picks]): pass ``` -------------------------------- ### Implement progress bar with multiple backends (Python) Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.2/_modules/autoreject/utils.html Provides a flexible progress bar implementation that can utilize different backends like 'progressbar', 'tqdm', or 'tqdm_notebook', or be disabled entirely. It raises a ValueError for invalid verbosity settings. ```python def _pbar(iterable, desc, leave=True, position=None, verbose='progressbar'): if verbose is not False and \ verbose not in ['progressbar', 'tqdm', 'tqdm_notebook']: raise ValueError('verbose must be one of {progressbar,' 'tqdm, tqdm_notebook, False}. Got %s' % verbose) if verbose == 'progressbar': from mne.utils import ProgressBar pbar = ProgressBar(iterable, mesg=desc, spinner=True) print('') elif verbose == 'tqdm': from tqdm import tqdm pbar = tqdm(iterable, desc=desc, leave=leave, position=position, dynamic_ncols=True) elif verbose == 'tqdm_notebook': from tqdm import tqdm_notebook pbar = tqdm_notebook(iterable, desc=desc, leave=leave, position=position, dynamic_ncols=True) elif verbose is False: pbar = iterable return pbar ``` -------------------------------- ### Serialize AutoReject State Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/_modules/autoreject/autoreject.html Methods for getting and setting the state of an AutoReject object, allowing for serialization and deserialization. This is useful for saving and loading the trained model. ```python def __getstate__(self): """Get the state of autoreject as a dictionary.""" state = dict() for param in _INIT_PARAMS: state[param] = getattr(self, param) for param in _FIT_PARAMS: if hasattr(self, param): state[param] = getattr(self, param) if hasattr(self, 'local_reject_'): state['local_reject_'] = dict() for ch_type in self.local_reject_: state['local_reject_'][ch_type] = dict() for param in _INIT_PARAMS[:4] + _FIT_PARAMS[:4]: state['local_reject_'][ch_type][param] = getattr(self.local_reject_[ch_type], param) return state def __setstate__(self, state): """Set the state of autoreject.""" for param in state.keys(): if param == 'local_reject_': local_reject_ = dict() for ch_type in state['local_reject_']: init_kwargs = { key: state['local_reject_'][ch_type][key] for key in _INIT_PARAMS[:4] } local_reject_[ch_type] = _AutoReject(**init_kwargs) for key in _FIT_PARAMS[:4]: setattr(local_reject_[ch_type], key, state['local_reject_'][ch_type][key]) self.local_reject_ = local_reject_ elif param in _INIT_PARAMS + _FIT_PARAMS: setattr(self, param, state[param]) ``` -------------------------------- ### Get rejection threshold Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/index.html Retrieves the rejection threshold dictionary for M/EEG epochs using the get_rejection_threshold function. This dictionary can be used for manual epoch rejection. ```python from autoreject import get_rejection_threshold reject = get_rejection_threshold(epochs) ``` -------------------------------- ### Load MNE Sample Data and Create Epochs (Python) Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/auto_examples/plot_estimate_global_reject.html This snippet demonstrates how to load the MNE sample dataset, read raw and event files, select specific channels, and create epoched data. It utilizes MNE-Python's data path handling, IO functions, and epoching capabilities. Dependencies include MNE-Python and NumPy. ```python from pathlib import Path import mne data_path = mne.datasets.sample.data_path() meg_path = data_path / 'MEG' / 'sample' raw_fname = meg_path / 'sample_audvis_filt-0-40_raw.fif' event_fname = meg_path / 'sample_audvis_filt-0-40_raw-eve.fif' raw = mne.io.read_raw_fif(raw_fname, preload=True) events = mne.read_events(event_fname) include = [] picks = mne.pick_types(raw.info, meg=True, eeg=True, stim=False, eog=True, include=include, exclude='bads') epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True, reject=None, verbose=False, detrend=1) ``` -------------------------------- ### Instantiate MNE Epochs with Reject=None Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/auto_examples/plot_auto_repair.html This snippet demonstrates how to create MNE Epochs objects. The `reject` parameter is set to `None` to prevent initial epoch dropping, allowing `autoreject` to handle rejection later. It uses the `mne.Epochs` class and requires `raw` data, `events`, `event_id`, `tmin`, and `tmax` as inputs. `preload` is set to `True` for immediate data loading. ```python import mne # Assuming raw, events, event_id, tmin, tmax are defined # raw.del_proj() # remove proj, don't proj while interpolating epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=(None, 0), reject=None, verbose=False, detrend=0, preload=True) ``` -------------------------------- ### AutoReject - Get Rejection Logs Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/_modules/autoreject/autoreject.html Retrieves the rejection logs for epochs, which indicate bad epochs and channels based on rejection thresholds. ```APIDOC ## GET /autoreject/get_reject_log ### Description Get rejection logs of epochs. If multiple channel types are present, reject_log['bad_epochs_idx'] reflects the union of bad trials across channel types. ### Method GET ### Endpoint /autoreject/get_reject_log ### Parameters #### Query Parameters - **epochs** (instance of mne.Epochs) - Required - The epoched data for which the reject log is computed. - **picks** (str | list | slice | None) - Optional - Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel *type* strings (e.g., ['meg', 'eeg']) will pick channels of those types, channel *name* strings (e.g., ['MEG0111', 'MEG2623']) will pick the given channels. Can also be the string values 'all' to pick all channels, or 'data' to pick data channels. None (default) will use the .picks attribute. Note that channels in info['bads'] *will be included* if their names or indices are explicitly provided. ### Response #### Success Response (200) - **reject_log** (instance of autoreject.RejectLog) - The reject log. #### Response Example { "reject_log": { "labels": [[null, null, ...], ...], "bad_epochs": [false, false, ...], "ch_names": ["MEG 0111", "MEG 0112", ...] } } ``` -------------------------------- ### Create Epochs from Raw Data using MNE-Python Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/auto_examples/plot_ransac.html Creates epochs from the loaded raw data using the specified events and parameters. It ensures no epochs are dropped initially by setting 'reject' to None and picks MEG gradiometer channels. ```python raw.info['bads'] = [] raw.del_proj() # remove proj, don't proj while interpolating epochs = Epochs(raw, events, event_id, tmin, tmax, baseline=(None, 0), reject=None, verbose=False, detrend=0, preload=True) picks = mne.pick_types(epochs.info, meg='grad', eeg=False, stim=False, eog=False, include=[], exclude=[]) ``` -------------------------------- ### Initialize and Apply AutoReject for Epoch Cleaning Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/auto_examples/plot_auto_repair.html This code demonstrates initializing and applying the `autoreject.AutoReject` class for cleaning epochs. The `AutoReject` object is instantiated with parameters like `n_interpolates`, `consensus_percs`, and `thresh_method`. It then fits the model to a subset of epochs and transforms the data to obtain cleaned epochs and subsequently cleaned evoked responses. The fitting and transforming steps can be performed on different compatible data portions. ```python from autoreject import AutoReject # Assuming epochs is an MNE Epochs object and picks is defined ar = AutoReject(n_interpolates=None, consensus_percs=None, picks=picks, thresh_method='random_search', random_state=42) # Fit and transform on a subset of epochs ar.fit(epochs['Auditory/Left']) epochs_clean = ar.transform(epochs['Auditory/Left']) # Get cleaned and original evoked responses evoked_clean = epochs_clean.average() evoked = epochs['Auditory/Left'].average() ``` -------------------------------- ### Get Reject Log API Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/_modules/autoreject/autoreject.html Retrieves rejection logs from epochs, identifying bad epochs based on channel types and consensus thresholds. ```APIDOC ## GET /api/autoreject/reject_log ### Description This endpoint retrieves rejection logs from epochs. It identifies bad epochs based on channel types and consensus thresholds. If multiple channel types are present, the `reject_log.bad_epochs` attribute reflects the union of bad epochs across all channel types. ### Method GET ### Endpoint /api/autoreject/reject_log ### Parameters #### Query Parameters - **epochs** (instance of mne.Epochs) - Required - The epochs from which to get the drop logs. - **threshes** (dict | None) - Optional - Thresholds for rejection. If None, default thresholds are used. - **picks** (str | list | slice | None) - Optional - Channels to include. Can be channel indices, channel type strings, channel name strings, 'all', or 'data'. None defaults to the .picks attribute. ### Request Example ```json { "epochs": "mne.Epochs object", "threshes": { "eeg": 150e-6, "mag": 4000e-15, "grad": 1000e-13 }, "picks": "meg" } ``` ### Response #### Success Response (200) - **reject_log** (instance of autoreject.RejectLog) - The rejection log containing `labels` and `bad_epochs`. #### Response Example ```json { "reject_log": { "labels": "numpy.ndarray", "bad_epochs": "numpy.ndarray", "ch_names": "list" } } ``` ``` -------------------------------- ### Import MNE-Python and Load Sample Data Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/auto_examples/plot_estimate_global_reject.html This snippet imports necessary libraries from MNE-Python and loads sample MEG data. It defines event IDs and time windows for epoching, specifies data paths, and reads the raw data file. Dependencies include MNE-Python. ```python import mne from mne import io from mne.datasets import sample event_id = {'Visual/Left': 3} tmin, tmax = -0.2, 0.5 data_path = sample.data_path() meg_path = data_path / 'MEG' / 'sample' raw_fname = meg_path / 'sample_audvis_filt-0-40_raw.fif' event_fname = meg_path / 'sample_audvis_filt-0-40_raw-eve.fif' raw = io.read_raw_fif(raw_fname, preload=True) events = mne.read_events(event_fname) include = [] picks = mne.pick_types(raw.info, meg=True, eeg=True, stim=False, ``` -------------------------------- ### Load and Preprocess EEG Data with MNE-Python Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/auto_examples/plot_autoreject_workflow.html This snippet shows how to load a BDF EEG file, set a standard montage, and create fixed-length epochs. It utilizes the MNE-Python library for these operations. Dependencies include 'os' and 'mne'. The input is a raw BDF file path, and the output is an MNE Epochs object. ```python import os import mne # Define file path and target directory # raw_fname = os.path.join(target_dir, f'sub-{subject_id}', 'ses-off', 'eeg', # 'sub-pd14_ses-off_task-rest_eeg.bdf') # Placeholder for actual file path raw_fname = "/path/to/sub-pd14_ses-off_task-rest_eeg.bdf" # Load the raw BDF file raw = mne.io.read_raw_bdf(raw_fname, preload=True) # Create a standard montage dig_montage = mne.channels.make_standard_montage('biosemi32') # Drop channels not in the montage raw.drop_channels([ch for ch in raw.ch_names if ch not in dig_montage.ch_names]) # Set the montage raw.set_montage(dig_montage) # use the standard montage # Create fixed-length epochs epochs = mne.make_fixed_length_epochs(raw, duration=3, preload=True) ``` -------------------------------- ### Get Rejection Threshold Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/_modules/autoreject/autoreject.html Computes global rejection thresholds for given epochs. This function can decimate epochs and select specific channel types for threshold estimation. ```APIDOC ## get_rejection_threshold(epochs, decim=1, random_state=None, ch_types=None, cv=5, verbose=True) ### Description Computes global rejection thresholds for given epochs. This function can decimate epochs and select specific channel types for threshold estimation. ### Method POST ### Endpoint /autoreject/get_rejection_threshold ### Parameters #### Path Parameters None #### Query Parameters - **decim** (int) - Optional - The decimation factor: Increment for selecting every nth time slice. Defaults to 1. - **random_state** (int | np.random.RandomState | None) - Optional - The seed of the pseudo random number generator to use. Defaults to None. - **ch_types** (str | list of str | None) - Optional - The channel types for which to find the rejection dictionary. e.g., ['mag', 'grad']. If None, the rejection dictionary will have keys ['mag', 'grad', 'eeg', 'eog', 'hbo', 'hbr', 'ecog', 'seeg']. - **cv** (int | sklearn.model_selection object) - Optional - Defaults to cv=5. - **verbose** (bool) - Optional - The verbosity of progress messages. If False, suppress all output messages. Defaults to True. #### Request Body - **epochs** (mne.Epochs) - Required - The epochs from which to estimate the epochs dictionary. ### Request Example ```json { "epochs": "mne.Epochs object" } ``` ### Response #### Success Response (200) - **reject** (dict) - The rejection dictionary with keys as specified by ch_types. #### Response Example ```json { "reject": { "mag": 40e-6, "grad": 4000e-6, "eeg": 75e-6 } } ``` ### Notes Sensors marked as bad by user will be excluded when estimating the rejection dictionary. ``` -------------------------------- ### AutoReject Initialization and Parameters Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/generated/autoreject.AutoReject.html Configuration options for initializing the AutoReject object. These parameters control the search space for optimal rejection thresholds and the cross-validation strategy. ```APIDOC ## AutoReject Initialization ### Description Initializes the AutoReject object with parameters to control the automated epoch rejection process. Supports multi-channel types and allows customization of interpolation, consensus, and channel selection. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **n_interpolate** (array | None) - Optional. The values to try for the number of channels for which to interpolate. Defaults to `np.array([1, 4, 32])`. - **consensus** (array | None) - Optional. The values to try for the percentage of channels that must agree as a fraction of the total number of channels. Defaults to `np.linspace(0, 1.0, 11)`. - **cv** (int | sklearn.model_selection object) - Optional. The cross-validation splitting strategy. Defaults to 10. - **picks** (str | list | slice | None) - Optional. Channels to include. Defaults to data channels {‘meg’, ‘eeg’}. - **thresh_method** (str) - Required. Method to use for threshold selection ('bayesian_optimization' or 'random_search'). - **n_jobs** (int) - Optional. The number of jobs to run in parallel. - **random_state** (int | np.random.RandomState | None) - Optional. Seed for the random number generator. Defaults to None. - **verbose** (bool) - Optional. Whether to display progress messages. Defaults to True. ### Request Example ```json { "n_interpolate": [1, 4, 32], "consensus": null, "cv": 10, "picks": "meg", "thresh_method": "bayesian_optimization", "n_jobs": -1, "random_state": 42, "verbose": true } ``` ### Response #### Success Response (200) An initialized AutoReject object. #### Response Example (No direct response example, as this is an initialization) ``` -------------------------------- ### Get Best Threshold with Bayesian Optimization Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.3/_downloads/706297e767237634b8a97ce84699ad2e/plot_global_reject.ipynb Obtains the optimal rejection threshold for EEG channels more efficiently using Bayesian optimization provided by autoreject's get_rejection_threshold function. ```python from autoreject import get_rejection_threshold # noqa reject2 = get_rejection_threshold(epochs, random_state=0, cv=5) ``` -------------------------------- ### Fit Autoreject Local and Get Rejection Log (MNE Python) Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.2/_sources/faq.rst.txt This snippet shows how to initialize and fit the AutoReject local algorithm on epoched data. It then demonstrates how to obtain a rejection log, which contains information about bad epochs identified by autoreject, without performing interpolation. ```python >>> ar = AutoReject() >>> _, reject_log = ar.fit(epochs).transform(epochs, return_log=True) >>> ica.fit(epochs[~reject_log.bad_epochs]) ``` -------------------------------- ### Load and Epoch MNE-Python Data Source: https://github.com/autoreject/autoreject.github.io/blob/main/dev/_downloads/8bc60be7efa55633c503453b8c46dfa9/plot_estimate_global_reject.ipynb Loads MEG and EEG data using MNE-Python, reads events, picks relevant channels, and creates epochs. Requires MNE-Python to be installed. ```python # Author: Mainak Jas # License: BSD-3-Clause import mne from mne import io from mne.datasets import sample event_id = {'Visual/Left': 3} tmin, tmax = -0.2, 0.5 data_path = sample.data_path() meg_path = data_path / 'MEG' / 'sample' raw_fname = meg_path / 'sample_audvis_filt-0-40_raw.fif' event_fname = meg_path / 'sample_audvis_filt-0-40_raw-eve.fif' raw = io.read_raw_fif(raw_fname, preload=True) events = mne.read_events(event_fname) include = [] picks = mne.pick_types(raw.info, meg=True, eeg=True, stim=False, eog=True, include=include, exclude='bads') epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True, reject=None, verbose=False, detrend=1) ``` -------------------------------- ### Internal Bad Channel Interpolation (Python) Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.3/_modules/autoreject/utils.html An internal function for interpolating bad channels within MNE-Python objects (Evoked or Epochs). It iterates through specified channels, performs interpolation, and updates the data. Requires MNE-Python to be installed. ```python def _clean_by_interp(inst, picks=None, dots=None, verbose=True): inst_interp = inst.copy() mesg = 'Creating augmented epochs' picks = _handle_picks(info=inst_interp.info, picks=picks) BaseEpochs = _get_epochs_type() ch_names = [inst.info['ch_names'][p] for p in picks] for ch_idx, (pick, ch) in enumerate(_pbar(list(zip(picks, ch_names)), desc=mesg, verbose=verbose)): inst.info['bads'] = [ch] pick_interp = mne.pick_channels(inst.info['ch_names'], [ch])[0] data_orig = inst._data[:, pick_interp].copy() interpolate_bads(inst, picks=picks, dots=dots, reset_bads=True, mode='fast') if isinstance(inst, mne.Evoked): inst_interp.data[pick] = inst.data[pick_interp] elif isinstance(inst, BaseEpochs): inst_interp._data[:, pick] = inst._data[:, pick_interp] else: raise ValueError('Unrecognized type for inst') inst._data[:, pick_interp] = data_orig.copy() inst.info['bads'] = inst_interp.info['bads'].copy() return inst_interp ``` -------------------------------- ### Configure documentation options Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/auto_examples/plot_estimate_global_reject.html This JavaScript code configures global options for the documentation site, including the current page name, the URL for theme switcher JSON data, and version matching for the theme switcher. ```javascript DOCUMENTATION_OPTIONS.pagename = 'auto_examples/plot_estimate_global_reject'; DOCUMENTATION_OPTIONS.theme_switcher_json_url = 'https://raw.githubusercontent.com/autoreject/autoreject/master/doc/_static/versions.json'; DOCUMENTATION_OPTIONS.theme_switcher_version_match = '0.4.2'; ``` -------------------------------- ### Get Random Subsets of Channels Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.4/_modules/autoreject/ransac.html Selects random subsets of channels for the RANSAC algorithm. It accounts for channels marked as 'bad' and determines the number of channels to interpolate from based on the `min_channels` parameter. ```python def _get_random_subsets(self, info): """ Get random channels""" # have to set the seed here, as here the only part with randomization # occurs. However, all subsets are precomputed outside of Parallel, # therefore, we can simply compute them once rng = check_random_state(self.random_state) picked_info = mne.io.pick.pick_info(info, self.picks) n_channels = len(picked_info['ch_names']) # number of channels to interpolate from n_samples = int(np.round(self.min_channels * n_channels)) # get picks for resamples, but ignore channels marked as bad bad_chs = info['bads'] ch_list = [ch for ch in picked_info['ch_names'] if ch not in bad_chs] ``` -------------------------------- ### Load MNE Sample Data and Events Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/auto_examples/plot_channel_thresholds.html This snippet demonstrates how to load sample MEG data and associated events using MNE-Python. It utilizes `pathlib` for path manipulation and MNE's functions to read raw data and event files. The `preload=True` argument ensures data is loaded into memory. ```python from pathlib import Path import mne data_path = mne.datasets.sample.data_path() meg_path = Path(data_path) / 'MEG' / 'sample' raw_fname = meg_path / 'sample_audvis_filt-0-40_raw.fif' raw = mne.io.read_raw_fif(raw_fname, preload=True) event_fname = meg_path / 'sample_audvis_filt-0-40_raw-eve.fif' tmin, tmax = -0.2, 0.5 events = mne.read_events(event_fname) ``` -------------------------------- ### AutoReject State Serialization (Python) Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/_modules/autoreject/autoreject.html Defines the method to get the internal state of the AutoReject object, which is useful for saving and loading trained models. It serializes initialization parameters and fitted attributes. ```python def __getstate__(self): """Get the state of autoreject as a dictionary.""" state = dict() for param in _INIT_PARAMS: state[param] = getattr(self, param) for param in _FIT_PARAMS: if hasattr(self, param): state[param] = getattr(self, param) if hasattr(self, 'local_reject_'): state['local_reject_'] = dict() for ch_type in self.local_reject_: ``` -------------------------------- ### Prepare Raw Data and Create Epochs Source: https://github.com/autoreject/autoreject.github.io/blob/main/v0.3/_downloads/eed3f885ba83c61c9448cf1df4b6e6d1/plot_ransac.ipynb Prepares the raw data by removing projections and then creates epochs. The `reject=None` parameter prevents epoch dropping during instantiation. It also picks specific MEG gradiometer channels for further processing. ```python raw.info['bads'] = [] raw.del_proj() # remove proj, don't proj while interpolating epochs = Epochs(raw, events, event_id, tmin, tmax, baseline=(None, 0), reject=None, verbose=False, detrend=0, preload=True) picks = mne.pick_types(epochs.info, meg='grad', eeg=False, stim=False, eog=False, include=[], exclude=[]) ``` -------------------------------- ### Get Base Epochs Type (Python) Source: https://github.com/autoreject/autoreject.github.io/blob/main/stable/_modules/autoreject/utils.html Determines and returns the base class for epochs in MNE-Python, checking for 'mne.epochs._BaseEpochs' or 'mne.epochs.BaseEpochs'. This is useful for instance checking across different MNE-Python versions. ```python def _get_epochs_type(): if hasattr(mne.epochs, '_BaseEpochs'): BaseEpochs = mne.epochs._BaseEpochs else: BaseEpochs = mne.epochs.BaseEpochs return BaseEpochs ```