mne.preprocessing.ICA

class mne.preprocessing.ICA(n_components=None, max_pca_components=None, n_pca_components=None, noise_cov=None, random_state=None, method='fastica', fit_params=None, max_iter=200, verbose=None)[source]

M/EEG signal decomposition using Independent Component Analysis (ICA).

This object can be used to estimate ICA components and then remove some from Raw or Epochs for data exploration or artifact correction.

Caveat! If supplying a noise covariance keep track of the projections available in the cov or in the raw object. For example, if you are interested in EOG or ECG artifacts, EOG and ECG projections should be temporally removed before fitting the ICA. You can say:

>> projs, raw.info['projs'] = raw.info['projs'], []
>> ica.fit(raw)
>> raw.info['projs'] = projs

Note

Methods implemented are FastICA (default), Infomax and Extended-Infomax. Infomax can be quite sensitive to differences in floating point arithmetic due to exponential non-linearity. Extended-Infomax seems to be more stable in this respect enhancing reproducibility and stability of results.

Warning

ICA is sensitive to low-frequency drifts and therefore requires the data to be high-pass filtered prior to fitting. Typically, a cutoff frequency of 1 Hz is recommended. Note that FIR filters prior to MNE 0.15 used the 'firwin2' design method, which generally produces rather shallow filters that might not work for ICA processing. Therefore, it is recommended to use IIR filters for MNE up to 0.14. In MNE 0.15, FIR filters can be designed with the 'firwin' method, which generally produces much steeper filters. This method will be the default FIR design method in MNE 0.16. In MNE 0.15, you need to explicitly set fir_design='firwin' to use this method. This is the recommended filter method for ICA preprocessing.

Parameters:

n_components : int | float | None

The number of components used for ICA decomposition. If int, it must be smaller then max_pca_components. If None, all PCA components will be used. If float between 0 and 1 components will be selected by the cumulative percentage of explained variance.

max_pca_components : int | None

The number of components used for PCA decomposition. If None, no dimension reduction will be applied and max_pca_components will equal the number of channels supplied on decomposing data. Defaults to None.

n_pca_components : int | float

The number of PCA components used after ICA recomposition. The ensuing attribute allows to balance noise reduction against potential loss of features due to dimensionality reduction. If greater than self.n_components_, the next n_pca_components minus n_components_ PCA components will be added before restoring the sensor space data. The attribute gets updated each time the according parameter for in .pick_sources_raw or .pick_sources_epochs is changed. If float, the number of components selected matches the number of components with a cumulative explained variance below n_pca_components.

noise_cov : None | instance of mne.cov.Covariance

Noise covariance used for whitening. If None, channels are just z-scored.

random_state : None | int | instance of np.random.RandomState

np.random.RandomState to initialize the FastICA estimation. As the estimation is non-deterministic it can be useful to fix the seed to have reproducible results. Defaults to None.

method : {‘fastica’, ‘infomax’, ‘extended-infomax’}

The ICA method to use. Defaults to ‘fastica’.

fit_params : dict | None.

Additional parameters passed to the ICA estimator chosen by method.

max_iter : int, optional

Maximum number of iterations during fit.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Attributes

current_fit (str) Flag informing about which data type (raw or epochs) was used for the fit.
ch_names (list-like) Channel names resulting from initial picking. The number of components used for ICA decomposition.
``n_components_`` (int) If fit, the actual number of components used for ICA decomposition.
n_pca_components (int) See above.
max_pca_components (int) The number of components used for PCA dimensionality reduction.
verbose (bool, str, int, or None) See above.
``pca_components_`` (ndarray) If fit, the PCA components
``pca_mean_`` (ndarray) If fit, the mean vector used to center the data before doing the PCA.
``pca_explained_variance_`` (ndarray) If fit, the variance explained by each PCA component
``mixing_matrix_`` (ndarray) If fit, the mixing matrix to restore observed data, else None.
``unmixing_matrix_`` (ndarray) If fit, the matrix to unmix observed data, else None.
exclude (list) List of sources indices to exclude, i.e. artifact components identified throughout the ICA solution. Indices added to this list, will be dispatched to the .pick_sources methods. Source indices passed to the .pick_sources method via the ‘exclude’ argument are added to the .exclude attribute. When saving the ICA also the indices are restored. Hence, artifact components once identified don’t have to be added again. To dump this ‘artifact memory’ say: ica.exclude = []
info (None | instance of Info) The measurement info copied from the object fitted.
``n_samples_`` (int) the number of samples used on fit.
``labels_`` (dict) A dictionary of independent component indices, grouped by types of independent components. This attribute is set by some of the artifact detection functions.

Methods

__contains__(ch_type) Check channel type membership.
__hash__() <==> hash(x)
apply(inst[, include, exclude, …]) Remove selected components from the signal.
copy() Copy the ICA object.
detect_artifacts(raw[, start_find, …]) Run ICA artifacts detection workflow.
find_bads_ecg(inst[, ch_name, threshold, …]) Detect ECG related components using correlation.
find_bads_eog(inst[, ch_name, threshold, …]) Detect EOG related components using correlation.
fit(inst[, picks, start, stop, decim, …]) Run the ICA decomposition on raw data.
get_components() Get ICA topomap for components as numpy arrays.
get_sources(inst[, add_channels, start, stop]) Estimate sources given the unmixing matrix.
plot_components([picks, ch_type, res, …]) Project unmixing matrix on interpolated sensor topogrpahy.
plot_overlay(inst[, exclude, picks, start, …]) Overlay of raw and cleaned signals given the unmixing matrix.
plot_properties(inst[, picks, axes, dB, …]) Display component properties.
plot_scores(scores[, exclude, labels, …]) Plot scores related to detected components.
plot_sources(inst[, picks, exclude, start, …]) Plot estimated latent sources given the unmixing matrix.
save(fname) Store ICA solution into a fiff file.
score_sources(inst[, target, score_func, …]) Assign score to components based on statistic or metric.
__contains__(ch_type)[source]

Check channel type membership.

Parameters:

ch_type : str

Channel type to check for. Can be e.g. ‘meg’, ‘eeg’, ‘stim’, etc.

Returns:

in : bool

Whether or not the instance contains the given channel type.

Examples

Channel type membership can be tested as:

>>> 'meg' in inst  
True
>>> 'seeg' in inst  
False
__hash__() <==> hash(x)
apply(inst, include=None, exclude=None, n_pca_components=None, start=None, stop=None)[source]

Remove selected components from the signal.

Given the unmixing matrix, transform data, zero out components, and inverse transform the data. This procedure will reconstruct M/EEG signals from which the dynamics described by the excluded components is subtracted. The data is processed in place.

Parameters:

inst : instance of Raw, Epochs or Evoked

The data to be processed. The instance is modified inplace.

include : array_like of int.

The indices referring to columns in the ummixing matrix. The components to be kept.

exclude : array_like of int.

The indices referring to columns in the ummixing matrix. The components to be zeroed out.

n_pca_components : int | float | None

The number of PCA components to be kept, either absolute (int) or percentage of the explained variance (float). If None (default), all PCA components will be used.

start : int | float | None

First sample to include. If float, data will be interpreted as time in seconds. If None, data will be used from the first sample.

stop : int | float | None

Last sample to not include. If float, data will be interpreted as time in seconds. If None, data will be used to the last sample.

Returns:

out : instance of Raw, Epochs or Evoked

The processed data.

compensation_grade

The current gradient compensation grade.

copy()[source]

Copy the ICA object.

Returns:

ica : instance of ICA

The copied object.

detect_artifacts(raw, start_find=None, stop_find=None, ecg_ch=None, ecg_score_func='pearsonr', ecg_criterion=0.1, eog_ch=None, eog_score_func='pearsonr', eog_criterion=0.1, skew_criterion=-1, kurt_criterion=-1, var_criterion=0, add_nodes=None)[source]

Run ICA artifacts detection workflow.

Note. This is still experimental and will most likely change. Over the next releases. For maximum control use the workflow exposed in the examples.

Hints and caveats: - It is highly recommended to bandpass filter ECG and EOG data and pass them instead of the channel names as ecg_ch and eog_ch arguments. - please check your results. Detection by kurtosis and variance may be powerful but misclassification of brain signals as noise cannot be precluded. - Consider using shorter times for start_find and stop_find than for start and stop. It can save you much time.

Example invocation (taking advantage of the defaults):

ica.detect_artifacts(ecg_channel='MEG 1531', eog_channel='EOG 061')
Parameters:

raw : instance of Raw

Raw object to draw sources from.

start_find : int | float | None

First sample to include for artifact search. If float, data will be interpreted as time in seconds. If None, data will be used from the first sample.

stop_find : int | float | None

Last sample to not include for artifact search. If float, data will be interpreted as time in seconds. If None, data will be used to the last sample.

ecg_ch : str | ndarray | None

The target argument passed to ica.find_sources_raw. Either the name of the ECG channel or the ECG time series. If None, this step will be skipped.

ecg_score_func : str | callable

The score_func argument passed to ica.find_sources_raw. Either the name of function supported by ICA or a custom function.

ecg_criterion : float | int | list-like | slice

The indices of the sorted skewness scores. If float, sources with scores smaller than the criterion will be dropped. Else, the scores sorted in descending order will be indexed accordingly. E.g. range(2) would return the two sources with the highest score. If None, this step will be skipped.

eog_ch : list | str | ndarray | None

The target argument or the list of target arguments subsequently passed to ica.find_sources_raw. Either the name of the vertical EOG channel or the corresponding EOG time series. If None, this step will be skipped.

eog_score_func : str | callable

The score_func argument passed to ica.find_sources_raw. Either the name of function supported by ICA or a custom function.

eog_criterion : float | int | list-like | slice

The indices of the sorted skewness scores. If float, sources with scores smaller than the criterion will be dropped. Else, the scores sorted in descending order will be indexed accordingly. E.g. range(2) would return the two sources with the highest score. If None, this step will be skipped.

skew_criterion : float | int | list-like | slice

The indices of the sorted skewness scores. If float, sources with scores smaller than the criterion will be dropped. Else, the scores sorted in descending order will be indexed accordingly. E.g. range(2) would return the two sources with the highest score. If None, this step will be skipped.

kurt_criterion : float | int | list-like | slice

The indices of the sorted skewness scores. If float, sources with scores smaller than the criterion will be dropped. Else, the scores sorted in descending order will be indexed accordingly. E.g. range(2) would return the two sources with the highest score. If None, this step will be skipped.

var_criterion : float | int | list-like | slice

The indices of the sorted skewness scores. If float, sources with scores smaller than the criterion will be dropped. Else, the scores sorted in descending order will be indexed accordingly. E.g. range(2) would return the two sources with the highest score. If None, this step will be skipped.

add_nodes : list of ica_nodes

Additional list if tuples carrying the following parameters: (name : str, target : str | array, score_func : callable, criterion : float | int | list-like | slice). This parameter is a generalization of the artifact specific parameters above and has the same structure. Example: add_nodes=(‘ECG phase lock’, ECG 01’, my_phase_lock_function, 0.5)

Returns:

self : instance of ICA

The ica object with the detected artifact indices marked for exclusion

find_bads_ecg(inst, ch_name=None, threshold=None, start=None, stop=None, l_freq=8, h_freq=16, method='ctps', reject_by_annotation=True, verbose=None)[source]

Detect ECG related components using correlation.

Note

If no ECG channel is available, routine attempts to create an artificial ECG based on cross-channel averaging.

Parameters:

inst : instance of Raw, Epochs or Evoked

Object to compute sources from.

ch_name : str

The name of the channel to use for ECG peak detection. The argument is mandatory if the dataset contains no ECG channels.

threshold : float

The value above which a feature is classified as outlier. If method is ‘ctps’, defaults to 0.25, else defaults to 3.0.

start : int | float | None

First sample to include. If float, data will be interpreted as time in seconds. If None, data will be used from the first sample.

stop : int | float | None

Last sample to not include. If float, data will be interpreted as time in seconds. If None, data will be used to the last sample.

l_freq : float

Low pass frequency.

h_freq : float

High pass frequency.

method : {‘ctps’, ‘correlation’}

The method used for detection. If ‘ctps’, cross-trial phase statistics [1] are used to detect ECG related components. Thresholding is then based on the significance value of a Kuiper statistic. If ‘correlation’, detection is based on Pearson correlation between the filtered data and the filtered ECG channel. Thresholding is based on iterative z-scoring. The above threshold components will be masked and the z-score will be recomputed until no supra-threshold component remains. Defaults to ‘ctps’.

reject_by_annotation : bool

If True, data annotated as bad will be omitted. Defaults to True.

New in version 0.14.0.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Returns:

ecg_idx : list of int

The indices of ECG related components.

scores : np.ndarray of float, shape (n_components_)

The correlation scores.

See also

find_bads_eog

References

[1] Dammers, J., Schiek, M., Boers, F., Silex, C., Zvyagintsev,
M., Pietrzyk, U., Mathiak, K., 2008. Integration of amplitude and phase statistics for complete artifact removal in independent components of neuromagnetic recordings. Biomedical Engineering, IEEE Transactions on 55 (10), 2353-2362.
find_bads_eog(inst, ch_name=None, threshold=3.0, start=None, stop=None, l_freq=1, h_freq=10, reject_by_annotation=True, verbose=None)[source]

Detect EOG related components using correlation.

Detection is based on Pearson correlation between the filtered data and the filtered EOG channel. Thresholding is based on adaptive z-scoring. The above threshold components will be masked and the z-score will be recomputed until no supra-threshold component remains.

Parameters:

inst : instance of Raw, Epochs or Evoked

Object to compute sources from.

ch_name : str

The name of the channel to use for EOG peak detection. The argument is mandatory if the dataset contains no EOG channels.

threshold : int | float

The value above which a feature is classified as outlier.

start : int | float | None

First sample to include. If float, data will be interpreted as time in seconds. If None, data will be used from the first sample.

stop : int | float | None

Last sample to not include. If float, data will be interpreted as time in seconds. If None, data will be used to the last sample.

l_freq : float

Low pass frequency.

h_freq : float

High pass frequency.

reject_by_annotation : bool

If True, data annotated as bad will be omitted. Defaults to True.

New in version 0.14.0.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Returns:

eog_idx : list of int

The indices of EOG related components, sorted by score.

scores : np.ndarray of float, shape (n_components_) | list of array

The correlation scores.

See also

find_bads_ecg

fit(inst, picks=None, start=None, stop=None, decim=None, reject=None, flat=None, tstep=2.0, reject_by_annotation=True, verbose=None)[source]

Run the ICA decomposition on raw data.

Caveat! If supplying a noise covariance keep track of the projections available in the cov, the raw or the epochs object. For example, if you are interested in EOG or ECG artifacts, EOG and ECG projections should be temporally removed before fitting the ICA.

Parameters:

inst : instance of Raw, Epochs or Evoked

Raw measurements to be decomposed.

picks : array-like of int

Channels to be included. This selection remains throughout the initialized ICA solution. If None only good data channels are used.

start : int | float | None

First sample to include. If float, data will be interpreted as time in seconds. If None, data will be used from the first sample.

stop : int | float | None

Last sample to not include. If float, data will be interpreted as time in seconds. If None, data will be used to the last sample.

decim : int | None

Increment for selecting each nth time slice. If None, all samples within start and stop are used.

reject : dict | None

Rejection parameters based on peak-to-peak amplitude. Valid keys are ‘grad’, ‘mag’, ‘eeg’, ‘seeg’, ‘ecog’, ‘eog’, ‘ecg’, ‘hbo’, ‘hbr’. If reject is None then no rejection is done. Example:

reject = dict(grad=4000e-13, # T / m (gradiometers)
              mag=4e-12, # T (magnetometers)
              eeg=40e-6, # V (EEG channels)
              eog=250e-6 # V (EOG channels)
              )

It only applies if inst is of type Raw.

flat : dict | None

Rejection parameters based on flatness of signal. Valid keys are ‘grad’, ‘mag’, ‘eeg’, ‘seeg’, ‘ecog’, ‘eog’, ‘ecg’, ‘hbo’, ‘hbr’. Values are floats that set the minimum acceptable peak-to-peak amplitude. If flat is None then no rejection is done. It only applies if inst is of type Raw.

tstep : float

Length of data chunks for artifact rejection in seconds. It only applies if inst is of type Raw.

reject_by_annotation : bool

Whether to omit bad segments from the data before fitting. If True, annotated segments with a description that starts with ‘bad’ are omitted. Has no effect if inst is an Epochs or Evoked object. Defaults to True.

New in version 0.14.0.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Returns:

self : instance of ICA

Returns the modified instance.

get_components()[source]

Get ICA topomap for components as numpy arrays.

Returns:

components : array, shape (n_channels, n_components)

The ICA components (maps).

get_sources(inst, add_channels=None, start=None, stop=None)[source]

Estimate sources given the unmixing matrix.

This method will return the sources in the container format passed. Typical usecases:

  1. pass Raw object to use raw.plot for ICA sources
  2. pass Epochs object to compute trial-based statistics in ICA space
  3. pass Evoked object to investigate time-locking in ICA space
Parameters:

inst : instance of Raw, Epochs or Evoked

Object to compute sources from and to represent sources in.

add_channels : None | list of str

Additional channels to be added. Useful to e.g. compare sources with some reference. Defaults to None

start : int | float | None

First sample to include. If float, data will be interpreted as time in seconds. If None, the entire data will be used.

stop : int | float | None

Last sample to not include. If float, data will be interpreted as time in seconds. If None, the entire data will be used.

Returns:

sources : instance of Raw, Epochs or Evoked

The ICA sources time series.

plot_components(picks=None, ch_type=None, res=64, layout=None, vmin=None, vmax=None, cmap='RdBu_r', sensors=True, colorbar=False, title=None, show=True, outlines='head', contours=6, image_interp='bilinear', head_pos=None, inst=None)[source]

Project unmixing matrix on interpolated sensor topogrpahy.

Parameters:

picks : int | array-like | None

The indices of the sources to be plotted. If None all are plotted in batches of 20.

ch_type : ‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ | None

The channel type to plot. For ‘grad’, the gradiometers are collected in pairs and the RMS for each pair is plotted. If None, then channels are chosen in the order given above.

res : int

The resolution of the topomap image (n pixels along each side).

layout : None | Layout

Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout is inferred from the data.

vmin : float | callable | None

The value specifying the lower bound of the color range. If None, and vmax is None, -vmax is used. Else np.min(data). If callable, the output equals vmin(data). Defaults to None.

vmax : float | callable | None

The value specifying the upper bound of the color range. If None, the maximum absolute value is used. If callable, the output equals vmax(data). Defaults to None.

cmap : matplotlib colormap | (colormap, bool) | ‘interactive’ | None

Colormap to use. If tuple, the first value indicates the colormap to use and the second value is a boolean defining interactivity. In interactive mode the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the range. Up and down arrows can be used to change the colormap. If None, ‘Reds’ is used for all positive data, otherwise defaults to ‘RdBu_r’. If ‘interactive’, translates to (None, True). Defaults to ‘RdBu_r’.

Warning

Interactive mode works smoothly only for a small amount of topomaps.

sensors : bool | str

Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., ‘r+’ for red plusses). If True (default), circles will be used.

colorbar : bool

Plot a colorbar.

title : str | None

Title to use.

show : bool

Show figure if True.

outlines : ‘head’ | ‘skirt’ | dict | None

The outlines to be drawn. If ‘head’, the default head scheme will be drawn. If ‘skirt’ the head scheme will be drawn, but sensors are allowed to be plotted outside of the head circle. If dict, each key refers to a tuple of x and y positions, the values in ‘mask_pos’ will serve as image mask, and the ‘autoshrink’ (bool) field will trigger automated shrinking of the positions due to points outside the outline. Alternatively, a matplotlib patch object can be passed for advanced masking options, either directly or as a function that returns patches (required for multi-axis plots). If None, nothing will be drawn. Defaults to ‘head’.

contours : int | array of float

The number of contour lines to draw. If 0, no contours will be drawn. When an integer, matplotlib ticker locator is used to find suitable values for the contour thresholds (may sometimes be inaccurate, use array for accuracy). If an array, the values represent the levels for the contours. Defaults to 6.

image_interp : str

The image interpolation to be used. All matplotlib options are accepted.

head_pos : dict | None

If None (default), the sensors are positioned such that they span the head circle. If dict, can have entries ‘center’ (tuple) and ‘scale’ (tuple) for what the center and scale of the head should be relative to the electrode locations.

inst : Raw | Epochs | None

To be able to see component properties after clicking on component topomap you need to pass relevant data - instances of Raw or Epochs (for example the data that ICA was trained on). This takes effect only when running matplotlib in interactive mode.

Returns:

fig : instance of matplotlib.pyplot.Figure or list

The figure object(s).

plot_overlay(inst, exclude=None, picks=None, start=None, stop=None, title=None, show=True)[source]

Overlay of raw and cleaned signals given the unmixing matrix.

This method helps visualizing signal quality and artifact rejection.

Parameters:

inst : instance of mne.io.Raw or mne.Evoked

The signals to be compared given the ICA solution. If Raw input, The raw data are displayed before and after cleaning. In a second panel the cross channel average will be displayed. Since dipolar sources will be canceled out this display is sensitive to artifacts. If evoked input, butterfly plots for clean and raw signals will be superimposed.

exclude : array_like of int

The components marked for exclusion. If None (default), ICA.exclude will be used.

picks : array-like of int | None (default)

Indices of channels to include (if None, all channels are used that were included on fitting).

start : int

X-axis start index. If None from the beginning.

stop : int

X-axis stop index. If None to the end.

title : str

The figure title.

show : bool

Show figure if True.

Returns:

fig : instance of pyplot.Figure

The figure.

plot_properties(inst, picks=None, axes=None, dB=True, plot_std=True, topomap_args=None, image_args=None, psd_args=None, figsize=None, show=True)[source]

Display component properties.

Properties include the topography, epochs image, ERP/ERF, power spectrum, and epoch variance.

Parameters:

inst: instance of Epochs or Raw

The data to use in plotting properties.

picks : int | array-like of int | None

The components to be displayed. If None, plot will show the first five sources. If more than one components were chosen in the picks, each one will be plotted in a separate figure. Defaults to None.

axes: list of matplotlib axes | None

List of five matplotlib axes to use in plotting: [topomap_axis, image_axis, erp_axis, spectrum_axis, variance_axis]. If None a new figure with relevant axes is created. Defaults to None.

dB: bool

Whether to plot spectrum in dB. Defaults to True.

plot_std: bool | float

Whether to plot standard deviation in ERP/ERF and spectrum plots. Defaults to True, which plots one standard deviation above/below. If set to float allows to control how many standard deviations are plotted. For example 2.5 will plot 2.5 standard deviation above/below.

topomap_args : dict | None

Dictionary of arguments to plot_topomap. If None, doesn’t pass any additional arguments. Defaults to None.

image_args : dict | None

Dictionary of arguments to plot_epochs_image. If None, doesn’t pass any additional arguments. Defaults to None.

psd_args : dict | None

Dictionary of arguments to psd_multitaper. If None, doesn’t pass any additional arguments. Defaults to None.

figsize : array-like of size (2,) | None

Allows to control size of the figure. If None, the figure size defauls to [7., 6.].

show : bool

Show figure if True.

Returns:

fig : list

List of matplotlib figures.

Notes

New in version 0.13.

plot_scores(scores, exclude=None, labels=None, axhline=None, title='ICA component scores', figsize=None, show=True)[source]

Plot scores related to detected components.

Use this function to asses how well your score describes outlier sources and how well you were detecting them.

Parameters:

scores : array_like of float, shape (n ica components) | list of arrays

Scores based on arbitrary metric to characterize ICA components.

exclude : array_like of int

The components marked for exclusion. If None (default), ICA.exclude will be used.

labels : str | list | ‘ecg’ | ‘eog’ | None

The labels to consider for the axes tests. Defaults to None. If list, should match the outer shape of scores. If ‘ecg’ or ‘eog’, the labels_ attributes will be looked up. Note that ‘/’ is used internally for sublabels specifying ECG and EOG channels.

axhline : float

Draw horizontal line to e.g. visualize rejection threshold.

title : str

The figure title.

figsize : tuple of int | None

The figure size. If None it gets set automatically.

show : bool

Show figure if True.

Returns:

fig : instance of matplotlib.pyplot.Figure

The figure object

plot_sources(inst, picks=None, exclude=None, start=None, stop=None, title=None, show=True, block=False, show_first_samp=False)[source]

Plot estimated latent sources given the unmixing matrix.

Typical usecases:

  1. plot evolution of latent sources over time based on (Raw input)
  2. plot latent source around event related time windows (Epochs input)
  3. plot time-locking in ICA space (Evoked input)
Parameters:

inst : instance of mne.io.Raw, mne.Epochs, mne.Evoked

The object to plot the sources from.

picks : int | array_like of int | None.

The components to be displayed. If None, plot will show the sources in the order as fitted.

exclude : array_like of int

The components marked for exclusion. If None (default), ICA.exclude will be used.

start : int

X-axis start index. If None, from the beginning.

stop : int

X-axis stop index. If None, next 20 are shown, in case of evoked to the end.

title : str | None

The figure title. If None a default is provided.

show : bool

Show figure if True.

block : bool

Whether to halt program execution until the figure is closed. Useful for interactive selection of components in raw and epoch plotter. For evoked, this parameter has no effect. Defaults to False.

show_first_samp : bool

If True, show time axis relative to the raw.first_samp.

Returns:

fig : instance of pyplot.Figure

The figure.

Notes

For raw and epoch instances, it is possible to select components for exclusion by clicking on the line. The selected components are added to ica.exclude on close.

New in version 0.10.0.

save(fname)[source]

Store ICA solution into a fiff file.

Parameters:

fname : str

The absolute path of the file name to save the ICA solution into. The file name should end with -ica.fif or -ica.fif.gz.

score_sources(inst, target=None, score_func='pearsonr', start=None, stop=None, l_freq=None, h_freq=None, reject_by_annotation=True, verbose=None)[source]

Assign score to components based on statistic or metric.

Parameters:

inst : instance of Raw, Epochs or Evoked

The object to reconstruct the sources from.

target : array-like | ch_name | None

Signal to which the sources shall be compared. It has to be of the same shape as the sources. If some string is supplied, a routine will try to find a matching channel. If None, a score function expecting only one input-array argument must be used, for instance, scipy.stats.skew (default).

score_func : callable | str label

Callable taking as arguments either two input arrays (e.g. Pearson correlation) or one input array (e. g. skewness) and returns a float. For convenience the most common score_funcs are available via string labels: Currently, all distance metrics from scipy.spatial and All functions from scipy.stats taking compatible input arguments are supported. These function have been modified to support iteration over the rows of a 2D array.

start : int | float | None

First sample to include. If float, data will be interpreted as time in seconds. If None, data will be used from the first sample.

stop : int | float | None

Last sample to not include. If float, data will be interpreted as time in seconds. If None, data will be used to the last sample.

l_freq : float

Low pass frequency.

h_freq : float

High pass frequency.

reject_by_annotation : bool

If True, data annotated as bad will be omitted. Defaults to True.

New in version 0.14.0.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Returns:

scores : ndarray

scores for each source as returned from score_func