mne_lsl.stream.BaseStream🔗

class mne_lsl.stream.BaseStream(bufsize)[source]🔗

Stream object representing a single real-time stream.

Parameters:
bufsizefloat | int

Size of the buffer keeping track of the data received from the stream. If the stream sampling rate sfreq is regular, bufsize is expressed in seconds. The buffer will hold the last bufsize * sfreq samples (ceiled). If the stream sampling rate sfreq is irregular, bufsize is expressed in samples. The buffer will hold the last bufsize samples.

Attributes

ch_names

Name of the channels.

compensation_grade

The current gradient compensation grade.

connected

Connection status of the stream.

dtype

Channel format of the stream.

filters

List of filters applied to the real-time Stream.

info

Info of the LSL stream.

n_buffer

Number of samples that can be stored in the buffer.

n_new_samples

Number of new samples available in the buffer.

Methods

acquire()

Pull new samples in the buffer.

add_reference_channels(ref_channels[, ref_units])

Add EEG reference channels to data that consists of all zeros.

anonymize([daysback, keep_his, verbose])

Anonymize the measurement information in-place.

connect(acquisition_delay)

Connect to the stream and initiate data collection in the buffer.

del_filter([idx])

Remove a filter from the list of applied filters.

disconnect()

Disconnect from the LSL stream and interrupt data collection.

drop_channels(ch_names)

Drop channel(s).

filter(l_freq, h_freq[, picks, iir_params, ...])

Filter the stream with an IIR causal filter.

get_channel_types([picks, unique, only_data_chs])

Get a list of channel type for each channel.

get_channel_units([picks, only_data_chs])

Get a list of channel unit for each channel.

get_data([winsize, picks, exclude])

Retrieve the latest data from the buffer.

get_montage()

Get a DigMontage from instance.

notch_filter(freqs[, picks, notch_widths, ...])

Filter the stream with an IIR causal notch filter.

pick([picks, exclude])

Pick a subset of channels.

plot()

Open a real-time stream viewer.

plot_sensors([kind, ch_type, title, ...])

Plot sensor positions.

record()

Record the stream data to disk.

rename_channels(mapping[, allow_duplicates, ...])

Rename channels.

set_bipolar_reference()

Set a bipolar reference.

set_channel_types(mapping, *[, ...])

Define the sensor type of channels.

set_channel_units(mapping)

Define the channel unit multiplication factor.

set_eeg_reference(ref_channels[, ch_type])

Specify which reference to use for EEG-like data.

set_meas_date(meas_date)

Set the measurement start date.

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

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

abstract acquire()[source]🔗

Pull new samples in the buffer.

Notes

This method is not needed if the stream was connected with an acquisition delay different from 0. In this case, the acquisition is done automatically in a background thread.

add_reference_channels(ref_channels, ref_units=None)[source]🔗

Add EEG reference channels to data that consists of all zeros.

Adds EEG reference channels that are not part of the streamed data. This is useful when you need to re-reference your data to different channels. These added channels will consist of all zeros.

Parameters:
ref_channelsstr | list of str

Name of the electrode(s) which served as the reference in the recording. If a name is provided, a corresponding channel is added and its data is set to 0. This is useful for later re-referencing.

ref_unitsstr | int | list of str | list of int | None

The unit or unit multiplication factor of the reference channels. The unit can be given as a human-readable string or as a unit multiplication factor, e.g. -6 for microvolts corresponding to 1e-6. If not provided, the added EEG reference channel has a unit multiplication factor set to 0 which corresponds to Volts. Use Stream.set_channel_units to change the unit multiplication factor.

Returns:
streaminstance of Stream

The stream instance modified in-place.

Notes

Read about the processing applied to the underlying buffer.

anonymize(daysback=None, keep_his=False, *, verbose=None)[source]🔗

Anonymize the measurement information in-place.

Parameters:
daysbackint | None

Number of days to subtract from all dates. If None (default), the acquisition date, info['meas_date'], will be set to January 1ˢᵗ, 2000. This parameter is ignored if info['meas_date'] is None (i.e., no acquisition date has been set).

keep_hisbool

If True, his_id of subject_info will not be overwritten. Defaults to False.

Warning

This could mean that info is not fully anonymized. Use with caution.

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 the currently set logger’s level. If a bool is provided, the verbosity is set to "WARNING" for False and to "INFO" for True.

Returns:
streaminstance of Stream

The stream instance modified in-place.

Notes

Removes potentially identifying information if it exists in info. Specifically for each of the following we use:

  • meas_date, file_id, meas_id

    A default value, or as specified by daysback.

  • subject_info

    Default values, except for ‘birthday’ which is adjusted to maintain the subject age.

  • experimenter, proj_name, description

    Default strings.

  • utc_offset

    None.

  • proj_id

    Zeros.

  • proc_history

    Dates use the meas_date logic, and experimenter a default string.

  • helium_info, device_info

    Dates use the meas_date logic, meta info uses defaults.

If info['meas_date'] is None, it will remain None during processing the above fields.

Operates in place.

abstract connect(acquisition_delay)[source]🔗

Connect to the stream and initiate data collection in the buffer.

Parameters:
acquisition_delayfloat

Delay in seconds between 2 acquisition during which chunks of data are pulled from the connected device. If 0, the automatic acquisition in a background thread is disabled and the user must manually call the acquisition method to pull new samples.

Returns:
streaminstance of Stream

The stream instance modified in-place.

del_filter(idx='all')[source]🔗

Remove a filter from the list of applied filters.

Parameters:
idx'all' | int | list of int | tuple of int

If the string 'all' (default), remove all filters. If an integer or a list of integers, remove the filter(s) at the given index(es) from Stream.filters.

Notes

When removing a filter, the initial conditions of all the filters applied on overlapping channels are reset. The initial conditions will be re-estimated as a step response steady-state.

abstract disconnect()[source]🔗

Disconnect from the LSL stream and interrupt data collection.

Returns:
streaminstance of Stream

The stream instance modified in-place.

drop_channels(ch_names)[source]🔗

Drop channel(s).

Parameters:
ch_namesstr | list of str

Name or list of names of channels to remove.

Returns:
streaminstance of Stream

The stream instance modified in-place.

See also

pick
filter(l_freq, h_freq, picks=None, iir_params=None, *, verbose=None)[source]🔗

Filter the stream with an IIR causal filter.

Once a filter is applied, the buffer is updated in real-time with the filtered data. It is possible to apply more than one filter.

stream = Stream(2.0).connect()
stream.filter(1.0, 40.0, picks="eeg")
stream.filter(1.0, 15.0, picks="ecg").filter(0.1, 5, picks="EDA")
Parameters:
l_freqfloat | None

The lower cutoff frequency. If None, the buffer is only low-passed.

h_freqfloat | None

The higher cutoff frequency. If None, the buffer is only high-passed.

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.

iir_paramsdict | None

Dictionary of parameters to use for IIR filtering. If None, a 4th order Butterworth will be used. For more information, see mne.filter.construct_iir_filter().

Note

The output sos must be used. The ba output is not supported.

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 the currently set logger’s level. If a bool is provided, the verbosity is set to "WARNING" for False and to "INFO" for True.

Returns:
streaminstance of Stream

The stream instance modified in-place.

Notes

Read about the processing applied to the underlying buffer.

get_channel_types(picks=None, unique=False, only_data_chs=False)[source]🔗

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_channel_units(picks=None, only_data_chs=False)[source]🔗

Get a list of channel unit 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.

only_data_chsbool

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

Returns:
channel_unitslist of tuple of shape (2,)

A list of 2-element tuples. The first element contains the unit FIFF code and its associated name, e.g. 107 (FIFF_UNIT_V) for Volts. The second element contains the unit multiplication factor, e.g. -6 (FIFF_UNITM_MU) for micro (corresponds to 1e-6).

get_data(winsize=None, picks=None, exclude='bads')[source]🔗

Retrieve the latest data from the buffer.

Parameters:
winsizefloat | int | None

Size of the window of data to view. If the stream sampling rate sfreq is regular, winsize is expressed in seconds. The window will view the last winsize * sfreq samples (ceiled) from the buffer. If the stream sampling sampling rate sfreq is irregular, winsize is expressed in samples. The window will view the last winsize samples. If None, the entire buffer is returned.

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.

excludestr | list of str | tuple of str

Set of channels to exclude, only used when picking based on types (e.g., exclude="bads" when picks="meg") or when picking is set to None.

Returns:
dataarray of shape (n_channels, n_samples)

Data in the given window.

timestampsarray of shape (n_samples,)

Timestamps in the given window.

Notes

The number of newly available samples stored in the property n_new_samples is reset at every function call, even if all channels were not selected with the argument picks.

get_montage()[source]🔗

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.

notch_filter(freqs, picks=None, notch_widths=None, trans_bandwidth=1, iir_params=None, *, verbose=None)[source]🔗

Filter the stream with an IIR causal notch filter.

Once a filter is applied, the buffer is updated in real-time with the filtered data. It is possible to apply more than one filter.

stream = Stream(2.0).connect()
stream.filter(1.0, 40.0, picks="eeg")
stream.notch_filter(50, picks="ecg")
Parameters:
freqsfloat

Specific frequencies to filter out from data, e.g. 60 Hz in the US or 50 Hz in Europe for line noise.

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.

notch_widthsfloat | None

Width of the stop band in Hz. If None, freqs / 200 is used.

trans_bandwidthfloat

Width of the transition band in Hz.

iir_paramsdict | None

Dictionary of parameters to use for IIR filtering. If None, a 4th order Butterworth will be used. For more information, see mne.filter.construct_iir_filter().

Note

The output sos must be used. The ba output is not supported.

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 the currently set logger’s level. If a bool is provided, the verbosity is set to "WARNING" for False and to "INFO" for True.

Returns:
streaminstance of Stream

The stream instance modified in-place.

Notes

Read about the processing applied to the underlying buffer.

pick(picks=None, exclude=())[source]🔗

Pick a subset of channels.

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.

excludestr | list of str

Set of channels to exclude, only used when picking is based on types, e.g. exclude='bads' when picks="meg".

Returns:
streaminstance of Stream

The stream instance modified in-place.

See also

drop_channels

Notes

Contrary to MNE-Python, re-ordering channels is not supported in MNE-LSL. Thus, if explicit channel names are provided in picks, they are sorted to match the order of existing channel names.

plot()[source]🔗

Open a real-time stream viewer. Not implemented.

plot_sensors(kind='topomap', ch_type=None, title=None, show_names=False, ch_groups=None, to_sphere=True, axes=None, block=False, show=True, sphere=None, *, verbose=None)🔗

Plot sensor positions.

Parameters:
kindstr

Whether to plot the sensors as 3d, topomap or as an interactive sensor selection dialog. Available options ‘topomap’, ‘3d’, ‘select’. If ‘select’, a set of channels can be selected interactively by using lasso selector or clicking while holding control key. The selected channels are returned along with the figure instance. Defaults to ‘topomap’.

ch_typeNone | str

The channel type to plot. Available options 'mag', 'grad', 'eeg', 'seeg', 'dbs', 'ecog', 'all'. If 'all', all the available mag, grad, eeg, seeg, dbs, and ecog channels are plotted. If None (default), then channels are chosen in the order given above.

titlestr | None

Title for the figure. If None (default), equals to 'Sensor positions (%s)' % ch_type.

show_namesbool | array of str

Whether to display all channel names. If an array, only the channel names in the array are shown. Defaults to False.

ch_groups‘position’ | array of shape (n_ch_groups, n_picks) | None

Channel groups for coloring the sensors. If None (default), default coloring scheme is used. If ‘position’, the sensors are divided into 8 regions. See order kwarg of mne.viz.plot_raw(). If array, the channels are divided by picks given in the array.

Added in version 0.13.0.

to_spherebool

Whether to project the 3d locations to a sphere. When False, the sensor array appears similar as to looking downwards straight above the subject’s head. Has no effect when kind=’3d’. Defaults to True.

Added in version 0.14.0.

axesinstance of Axes | instance of Axes3D | None

Axes to draw the sensors to. If kind='3d', axes must be an instance of Axes3D. If None (default), a new axes will be created.

Added in version 0.13.0.

blockbool

Whether to halt program execution until the figure is closed. Defaults to False.

Added in version 0.13.0.

showbool

Show figure if True. Defaults to True.

spherefloat | array_like | instance of ConductorModel | None | ‘auto’ | ‘eeglab’

The sphere parameters to use for the head outline. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give just the radius (origin assumed 0, 0, 0). Can also be an instance of a spherical ConductorModel to use the origin and radius from that object. If 'auto' the sphere is fit to digitization points. If 'eeglab' the head circle is defined by EEG electrodes 'Fpz', 'Oz', 'T7', and 'T8' (if 'Fpz' is not present, it will be approximated from the coordinates of 'Oz'). None (the default) is equivalent to 'auto' when enough extra digitization points are available, and (0, 0, 0, 0.095) otherwise.

Added in version 0.20.

Changed in version 1.1: Added 'eeglab' option.

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:
figinstance of Figure

Figure containing the sensor topography.

selectionlist

A list of selected channels. Only returned if kind=='select'.

Notes

This function plots the sensor locations from the info structure using matplotlib. For drawing the sensors using PyVista see mne.viz.plot_alignment().

Added in version 0.12.0.

record()[source]🔗

Record the stream data to disk. Not implemented.

rename_channels(mapping, allow_duplicates=False, *, verbose=None)[source]🔗

Rename channels.

Parameters:
mappingdict | callable()

A dictionary mapping the old channel to a new channel name e.g. {'EEG061' : 'EEG161'}. Can also be a callable function that takes and returns a string.

allow_duplicatesbool

If True (default False), allow duplicates, which will automatically be renamed with -N at the end.

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 the currently set logger’s level. If a bool is provided, the verbosity is set to "WARNING" for False and to "INFO" for True.

Returns:
streaminstance of Stream

The stream instance modified in-place.

set_bipolar_reference()[source]🔗

Set a bipolar reference. Not implemented.

Returns:
streaminstance of Stream

The stream instance modified in-place.

set_channel_types(mapping, *, on_unit_change='warn', verbose=None)[source]🔗

Define the sensor type of channels.

If the new channel type changes the unit type, e.g. from T/m to V, the unit multiplication factor is reset to 0. Use Stream.set_channel_units to change the multiplication factor, e.g. from 0 to -6 to change from Volts to microvolts.

Parameters:
mappingdict

A dictionary mapping a channel to a sensor type (str), e.g., {'EEG061': 'eog'} or {'EEG061': 'eog', 'TRIGGER': 'stim'}.

on_unit_change'raise' | 'warn' | 'ignore'

What to do if the measurement unit of a channel is changed automatically to match the new sensor type.

Added in version MNE: 1.4

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 the currently set logger’s level. If a bool is provided, the verbosity is set to "WARNING" for False and to "INFO" for True.

Returns:
streaminstance of Stream

The stream instance modified in-place.

set_channel_units(mapping)[source]🔗

Define the channel unit multiplication factor.

The unit itself is defined by the sensor type. Use Stream.set_channel_types to change the channel type, e.g. from planar gradiometers in T/m to EEG in V.

Parameters:
mappingdict

A dictionary mapping a channel to a unit, e.g. {'EEG061': 'microvolts'}. The unit can be given as a human-readable string or as a unit multiplication factor, e.g. -6 for microvolts corresponding to 1e-6.

Returns:
streaminstance of Stream

The stream instance modified in-place.

Notes

If the human-readable unit of your channel is not yet supported by MNE-LSL, please contact the developers on GitHub to add your units to the known set.

set_eeg_reference(ref_channels, ch_type='eeg')[source]🔗

Specify which reference to use for EEG-like data.

Use this function to explicitly specify the desired reference for EEG-like channels. This can be either an existing electrode or a new virtual channel added with Stream.add_reference_channels. This function will re-reference the data in the ringbuffer according to the desired reference.

Parameters:
ref_channelsstr | list of str

Name(s) of the channel(s) used to construct the reference. Can also be set to 'average' to apply a common average reference.

ch_typestr | list of str

The name of the channel type to apply the reference to. Valid channel types are 'eeg', 'ecog', 'seeg', 'dbs'.

Returns:
streaminstance of Stream

The stream instance modified in-place.

Notes

Read about the processing applied to the underlying buffer.

set_meas_date(meas_date)[source]🔗

Set the measurement start date.

Parameters:
meas_datedatetime | float | tuple | None

The new measurement date. If datetime object, it must be timezone-aware and in UTC. A tuple of (seconds, microseconds) or float (alias for (meas_date, 0)) can also be passed and a datetime object will be automatically created. If None, will remove the time reference.

Returns:
streaminstance of Stream

The stream instance modified in-place.

See also

anonymize
set_montage(montage, match_case=True, match_alias=False, on_missing='raise', *, verbose=None)[source]🔗

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 MNE: 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 MNE: 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 MNE: 0.20.1

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 the currently set logger’s level. If a bool is provided, the verbosity is set to "WARNING" for False and to "INFO" for True.

Returns:
streaminstance of Stream

The stream 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.

property ch_names🔗

Name of the channels.

Type:

list of str

property compensation_grade🔗

The current gradient compensation grade.

Type:

int | None

property connected🔗

Connection status of the stream.

Type:

bool

property dtype🔗

Channel format of the stream.

property filters🔗

List of filters applied to the real-time Stream.

Type:

list of `StreamFilter

property info🔗

Info of the LSL stream.

Type:

Info

property n_buffer🔗

Number of samples that can be stored in the buffer.

Type:

int

property n_new_samples🔗

Number of new samples available in the buffer.

The number of new samples is reset at every Stream.get_data call.

Type:

int

Examples using mne_lsl.stream.BaseStream🔗

Introduction to real-time LSL streams

Introduction to real-time LSL streams

Player with annotations

Player with annotations

Automatic vs Manual acquisition

Automatic vs Manual acquisition

Epoching a Stream in real-time

Epoching a Stream in real-time

Real-time peak detection

Real-time peak detection

Bandpower rolling window

Bandpower rolling window

Real-time evoked responses

Real-time evoked responses

Decoding real-time data

Decoding real-time data