pycrostates.cluster.AAHCluster#

class pycrostates.cluster.AAHCluster(n_clusters, normalize_input=False)[source]#

Atomize and Agglomerate Hierarchical Clustering (AAHC) algorithm.

See Murray et al.[1] for additional information.

Parameters:
n_clustersint

The number of clusters, i.e. the number of microstates.

normalize_inputbool

If set, the input data is normalized along the channel dimension.

References

Attributes:
GEV_

Global Explained Variance.

cluster_centers_

Fitted clusters (the microstates maps).

cluster_names

Name of the clusters.

compensation_grade

The current gradient compensation grade.

fitted

Fitted state.

fitted_data

Data array used to fit the clustering algorithm.

info

Info instance with the channel information used to fit the instance.

labels_

Microstate label attributed to each sample of the fitted data.

n_clusters

Number of clusters (number of microstates).

normalize_input

If set, the input data is normalized along the channel dimension.

Methods

copy([deep])

Return a copy of the instance.

fit(inst[, picks, tmin, tmax, ...])

Compute cluster centers.

get_channel_types([picks, unique, only_data_chs])

Get a list of channel type for each channel.

get_montage()

Get a DigMontage from instance.

invert_polarity(invert)

Invert map polarities.

plot([axes, show_gradient, gradient_kwargs, ...])

Plot cluster centers as topographic maps.

predict(inst[, picks, factor, ...])

Segment Raw or Epochs into microstate sequence.

rename_clusters([mapping, new_names])

Rename the clusters.

reorder_clusters([mapping, order, template])

Reorder the clusters of the fitted model.

save(fname)

Save clustering solution to disk.

set_montage(montage[, match_case, ...])

Set EEG/sEEG/ECoG/DBS/fNIRS channel positions and digitization points.

__contains__(ch_type)#

Check channel type membership.

Parameters:
ch_typestr

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

Returns:
inbool

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
copy(deep=True)#

Return a copy of the instance.

Parameters:
deepbool

If True, deepcopy is used instead of copy.

fit(inst, picks='eeg', tmin=None, tmax=None, reject_by_annotation=True, *, verbose=None)[source]#

Compute cluster centers.

Parameters:
instRaw | Epochs | ChData

MNE Raw, Epochs or ChData object from which to extract cluster centers.

picksstr | list | slice | None

Channels to include. Note that all channels selected must have the same type. Slices and lists of integers will be interpreted as channel indices. In lists, channel name strings (e.g. ['Fp1', 'Fp2']) will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. "eeg" (default) will pick all eeg channels. Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

tminfloat

Start time of the raw data to use in seconds (must be >= 0).

tmaxfloat

End time of the raw data to use in seconds (cannot exceed data duration).

reject_by_annotationbool

Whether to omit bad segments from the data before fitting. If True (default), annotated segments whose description begins with 'bad' are omitted. If False, no rejection based on annotations is performed.

Has no effect if inst is not a mne.io.Raw object.

verboseint | str | bool | None

Sets the verbosity level. The verbosity increases gradually between "CRITICAL", "ERROR", "WARNING", "INFO" and "DEBUG". If None is provided, the verbosity is set to "WARNING". If a bool is provided, the verbosity is set to "WARNING" for False and to "INFO" for True.

get_channel_types(picks=None, unique=False, only_data_chs=False)#

Get a list of channel type for each channel.

Parameters:
picksstr | array_like | slice | None

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 pick all channels. Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

uniquebool

Whether to return only unique channel types. Default is False.

only_data_chsbool

Whether to ignore non-data channels. Default is False.

Returns:
channel_typeslist

The channel types.

get_montage()#

Get a DigMontage from instance.

Returns:
montageNone | str | DigMontage

A montage containing channel positions. If a string or DigMontage is specified, the existing channel information will be updated with the channel positions from the montage. Valid strings are the names of the built-in montages that ship with MNE-Python; you can list those via mne.channels.get_builtin_montages(). If None (default), the channel positions will be removed from the Info.

invert_polarity(invert)#

Invert map polarities.

Parameters:
invertbool | list of bool | array of bool

List of bool of length n_clusters. True will invert map polarity, while False will have no effect. If a bool is provided, it is applied to all maps.

Notes

Operates in-place.

Inverting polarities has no effect on the other steps of the analysis as polarity is ignored in the current methodology. This function is only used for tuning visualization (i.e. for visual inspection and/or to generate figure for an article).

plot(axes=None, show_gradient=False, gradient_kwargs={'color': 'black', 'linestyle': '-', 'marker': 'P'}, *, block=False, show=None, verbose=None, **kwargs)#

Plot cluster centers as topographic maps.

Parameters:
axesAxes | None

Either None to create a new figure or axes (or an array of axes) on which the topographic map should be plotted. If the number of microstates maps to plot is 1, an array of axes of size n_clusters should be provided.

show_gradientbool

If True, plot a line between channel locations with highest and lowest values.

gradient_kwargsdict

Additional keyword arguments passed to matplotlib.axes.Axes.plot() to plot gradient line.

blockbool

Whether to halt program execution until the figure is closed.

showbool | None

If True, the figure is shown. If None, the figure is shown if the matplotlib backend is interactive.

verboseint | str | bool | None

Sets the verbosity level. The verbosity increases gradually between "CRITICAL", "ERROR", "WARNING", "INFO" and "DEBUG". If None is provided, the verbosity is set to "WARNING". If a bool is provided, the verbosity is set to "WARNING" for False and to "INFO" for True.

**kwargs

Additional keyword arguments are passed to mne.viz.plot_topomap().

Returns:
fFigure

Matplotlib figure containing the topographic plots.

predict(inst, picks=None, factor=0, half_window_size=1, tol=1e-05, min_segment_length=0, reject_edges=True, reject_by_annotation=True, *, verbose=None)#

Segment Raw or Epochs into microstate sequence.

Segment instance into microstate sequence using the segmentation smoothing algorithm[2].

Parameters:
instRaw | Epochs

MNE Raw or Epochs object containing the data to use for prediction.

picksstr | list | slice | None

Channels to include. Note that all channels selected must have the same type. Slices and lists of integers will be interpreted as channel indices. In lists, channel name strings (e.g. ['Fp1', 'Fp2']) 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 pick all channels used during fitting (e.g., self.info['ch_names']). Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

factorint

Factor used for label smoothing. 0 means no smoothing. Default to 0.

half_window_sizeint

Number of samples used for the half window size while smoothing labels. The half window size is defined as window_size = 2 * half_window_size + 1. It has no effect if factor=0 (default). Default to 1.

tolfloat

Convergence tolerance.

min_segment_lengthint

Minimum segment length (in samples). If a segment is shorter than this value, it will be recursively reasigned to neighbouring segments based on absolute spatial correlation.

reject_edgesbool

If True, set first and last segments to unlabeled.

reject_by_annotationbool

Whether to omit bad segments from the data before fitting. If True (default), annotated segments whose description begins with 'bad' are omitted. If False, no rejection based on annotations is performed.

Has no effect if inst is not a mne.io.Raw object.

verboseint | str | bool | None

Sets the verbosity level. The verbosity increases gradually between "CRITICAL", "ERROR", "WARNING", "INFO" and "DEBUG". If None is provided, the verbosity is set to "WARNING". If a bool is provided, the verbosity is set to "WARNING" for False and to "INFO" for True.

Returns:
segmentationRawSegmentation | EpochsSegmentation

Microstate sequence derivated from instance data. Timepoints are labeled according to cluster centers number: 0 for the first center, 1 for the second, etc.. -1 is used for unlabeled time points.

References

rename_clusters(mapping=None, new_names=None)#

Rename the clusters.

Parameters:
mappingdict

Mapping from the old names to the new names. The keys are the old names and the values are the new names.

new_nameslist | tuple

1D iterable containing the new cluster names. The length of the iterable should match the number of clusters.

Notes

Operates in-place.

reorder_clusters(mapping=None, order=None, template=None)#

Reorder the clusters of the fitted model.

Specify one of the following arguments to change the current order:

  • mapping: a dictionary that maps old cluster positions to new positions,

  • order: a 1D iterable containing the new order,

  • template: a fitted clustering algorithm used as a reference to match the order.

Only one argument can be set at a time.

Parameters:
mappingdict

Mapping from the old order to the new order. key: old position, value: new position.

orderlist of int | tuple of int | array of int

1D iterable containing the new order. Positions are 0-indexed.

templateCluster

Fitted clustering algorithm use as template for ordering optimization. For more details about the current implementation, check the pycrostates.cluster.utils.optimize_order() documentation.

Notes

Operates in-place.

save(fname)[source]#

Save clustering solution to disk.

Parameters:
fnamepath-like

Path to the .fif file where the clustering solution is saved.

set_montage(montage, match_case=True, match_alias=False, on_missing='raise', verbose=None)#

Set EEG/sEEG/ECoG/DBS/fNIRS channel positions and digitization points.

Parameters:
montageNone | str | DigMontage

A montage containing channel positions. If a string or DigMontage is specified, the existing channel information will be updated with the channel positions from the montage. Valid strings are the names of the built-in montages that ship with MNE-Python; you can list those via mne.channels.get_builtin_montages(). If None (default), the channel positions will be removed from the Info.

match_casebool

If True (default), channel name matching will be case sensitive.

Added in version 0.20.

match_aliasbool | dict

Whether to use a lookup table to match unrecognized channel location names to their known aliases. If True, uses the mapping in mne.io.constants.CHANNEL_LOC_ALIASES. If a dict is passed, it will be used instead, and should map from non-standard channel names to names in the specified montage. Default is False.

Added in version 0.23.

on_missing‘raise’ | ‘warn’ | ‘ignore’

Can be 'raise' (default) to raise an error, 'warn' to emit a warning, or 'ignore' to ignore when channels have missing coordinates.

Added in version 0.20.1.

verbosebool | str | int | None

Control verbosity of the logging output. If None, use the default verbosity level. See the logging documentation and mne.verbose() for details. Should only be passed as a keyword argument.

Returns:
instinstance of Raw | Epochs | Evoked

The instance, modified in-place.

Notes

Warning

Only EEG/sEEG/ECoG/DBS/fNIRS channels can have their positions set using a montage. Other channel types (e.g., MEG channels) should have their positions defined properly using their data reading functions.

Warning

Applying a montage will only set locations of channels that exist at the time it is applied. This means when re-referencing make sure to apply the montage only after calling mne.add_reference_channels()

property GEV_#

Global Explained Variance.

Type:

float

__hash__ = None#
property cluster_centers_#

Fitted clusters (the microstates maps).

Returns None if cluster algorithm has not been fitted.

Type:

array of shape (n_clusters, n_channels) | None

property cluster_names#

Name of the clusters.

Type:

list

property compensation_grade#

The current gradient compensation grade.

property fitted#

Fitted state.

Type:

bool

property fitted_data#

Data array used to fit the clustering algorithm.

Type:

array of shape (n_channels, n_samples) | None

property info#

Info instance with the channel information used to fit the instance.

Type:

ChInfo

property labels_#

Microstate label attributed to each sample of the fitted data.

Type:

array of shape (n_samples, ) | None

property n_clusters#

Number of clusters (number of microstates).

Type:

int

property normalize_input#

If set, the input data is normalized along the channel dimension.

Type:

bool