mne_lsl.player.PlayerLSL🔗
- class mne_lsl.player.PlayerLSL(fname, chunk_size=10, n_repeat=inf, *, name=None, source_id='MNE-LSL', annotations=None)[source]🔗
Class for creating a mock LSL stream.
- Parameters:
- fnamepath-like |
Raw
Path to the file to re-play as a mock real-time stream. MNE-Python must be able to load the file with
mne.io.read_raw()
. AnRaw
object can be provided directly.- chunk_size
int
≥ 1
Number of samples pushed at once on the
StreamOutlet
.- n_repeat
int
|np.inf
Number of times to repeat the file. If
np.inf
, the file is re-played indefinitely.- name
str
|None
Name of the mock LSL stream. If
None
, the nameMNE-LSL-Player
is used.- source_id
str
A unique identifier of the device or source of the data. This information improves the system robustness since it allows recipients to recover from failure by finding a stream with the same
source_id
on the network. By default, the source_id is set to"MNE-LSL"
.- annotations
bool
|None
If
True
, anStreamOutlet
is created for theAnnotations
of theRaw
object. IfFalse
,Annotations
are ignored and theStreamOutlet
is not created. IfNone
(default), theStreamOutlet
is created only if theRaw
object hasAnnotations
to push. See notes for additional information on theAnnotations
timestamps.
- fnamepath-like |
Attributes
Annotations attached to the raw object, if streamed.
Name of the channels.
Number of samples in a chunk.
The current gradient compensation grade.
Path to file played.
Info of the real-time stream.
Number of times the file is repeated.
Name of the LSL stream.
Status of the player, True if it is running and pushing data.
Source ID of the LSL stream.
Methods
anonymize
([daysback, keep_his, verbose])Anonymize the measurement information in-place.
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 a DigMontage from instance.
plot_sensors
([kind, ch_type, title, ...])Plot sensor positions.
rename_channels
(mapping[, allow_duplicates, ...])Rename channels.
set_channel_types
(mapping, *[, ...])Define the sensor type of channels.
set_channel_units
(mapping)Define the channel unit multiplication factor.
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.
start
()Start streaming data on the LSL
StreamOutlet
.stop
()Stop streaming data on the LSL
StreamOutlet
.Notes
The file re-played is loaded in memory. Thus, large files are not recommended. Once the end-of-file is reached, the player loops back to the beginning which can lead to a small discontinuity in the data stream.
Each time a chunk (defined by
chunk_size
) is pushed on theStreamOutlet
, the last sample of the chunk is attributed the current time (as returned by the functionlocal_clock()
). Thus, the samplechunk[0, :]
occurred in the past and the samplechunk[-1, :]
occurred “now”. IfAnnotations
are streamed, the annotations within the chunk are pushed on the annotationStreamOutlet
. TheAnnotations
are pushed with a timestamp corrected for the annotation onset in regards to the chunk beginning. However,Annotations
push is not delayed until the the annotation timestamp or until the end of the chunk. Thus, anAnnotations
can arrived at the clientStreamInlet
“ahead” of time, i.e. earlier than the current time (as returned by the functionlocal_clock()
). Thus, it is recommended to connect to an annotation stream with theStreamInlet
orStreamLSL
with theclocksync
processing flag and to always inspect the timestamps returned for every samples.from mne_lsl.lsl import local_clock from mne_lsl.player import PlayerLSL as Player from mne_lsl.stream import StreamLSL as Stream player = Player(..., annotations=True) # file with annotations player.start() stream = Stream(bufsize=100, stype="annotations") stream.connect(processing_flags=["clocksync"]) data, ts = stream.get_data() print(ts - local_clock()) # positive values are annotations in the "future"
If
Annotations
are streamed, theStreamOutlet
name is{name}-annotations
wherename
is the name of thePlayerLSL
. Thedtype
is set tonp.float64
and each uniqueAnnotations
description is encoded as a channel. The value streamed on a channel correspond to the duration of theAnnotations
. Thus, a sample on thisStreamOutlet
is a one-hot encoded vector of theAnnotations
description/duration.- anonymize(daysback=None, keep_his=False, *, verbose=None)[source]🔗
Anonymize the measurement information in-place.
- Parameters:
- daysback
int
|None
Number of days to subtract from all dates. If
None
(default), the acquisition date,info['meas_date']
, will be set toJanuary 1ˢᵗ, 2000
. This parameter is ignored ifinfo['meas_date']
isNone
(i.e., no acquisition date has been set).- keep_his
bool
If
True
,his_id
ofsubject_info
will not be overwritten. Defaults toFalse
.Warning
This could mean that
info
is not fully anonymized. Use with caution.- verbose
int
|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.
- daysback
- Returns:
- playerinstance of
Player
The player instance modified in-place.
- playerinstance of
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']
isNone
, it will remainNone
during processing the above fields.Operates in place.
- get_channel_types(picks=None, unique=False, only_data_chs=False)[source]🔗
Get a list of channel type for each channel.
- Parameters:
- picks
str
| 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 ininfo['bads']
will be included if their names or indices are explicitly provided.- unique
bool
Whether to return only unique channel types. Default is
False
.- only_data_chs
bool
Whether to ignore non-data channels. Default is
False
.
- picks
- Returns:
- channel_types
list
The channel types.
- channel_types
- get_channel_units(picks=None, only_data_chs=False)[source]🔗
Get a list of channel unit for each channel.
- Parameters:
- picks
str
| 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 ininfo['bads']
will be included if their names or indices are explicitly provided.- only_data_chs
bool
Whether to ignore non-data channels. Default is
False
.
- picks
- Returns:
- get_montage()[source]🔗
Get a DigMontage from instance.
- Returns:
- montage
None
|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 viamne.channels.get_builtin_montages()
. IfNone
(default), the channel positions will be removed from theInfo
.
- montage
- 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:
- kind
str
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_type
None
|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.- title
str
|None
Title for the figure. If None (default), equals to
'Sensor positions (%s)' % ch_type
.- show_names
bool
|array
ofstr
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 ofmne.viz.plot_raw()
. If array, the channels are divided by picks given in the array.Added in version 0.13.0.
- to_sphere
bool
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 ofAxes3D
|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.
- block
bool
Whether to halt program execution until the figure is closed. Defaults to False.
Added in version 0.13.0.
- show
bool
Show figure if True. Defaults to True.
- sphere
float
| array_like | instance ofConductorModel
|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.- verbose
bool
|str
|int
|None
Control verbosity of the logging output. If
None
, use the default verbosity level. See the logging documentation andmne.verbose()
for details. Should only be passed as a keyword argument.
- kind
- Returns:
See also
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.
- rename_channels(mapping, allow_duplicates=False, *, verbose=None)[source]🔗
Rename channels.
- Parameters:
- mapping
dict
|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_duplicates
bool
If True (default False), allow duplicates, which will automatically be renamed with
-N
at the end.- verbose
int
|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.
- mapping
- Returns:
- playerinstance of
Player
The player instance modified in-place.
- playerinstance of
- 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
toV
, the unit multiplication factor is reset to0
. UsePlayer.set_channel_units
to change the multiplication factor, e.g. from0
to-6
to change from Volts to microvolts.- Parameters:
- mapping
dict
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
- verbose
int
|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.
- mapping
- Returns:
- playerinstance of
Player
The player instance modified in-place.
- playerinstance of
- set_channel_units(mapping)[source]🔗
Define the channel unit multiplication factor.
By convention, MNE stores data in SI units. But systems often stream in non-SI units. For instance, EEG amplifiers often stream in microvolts. Thus, to mock a stream from an MNE-compatible file, the data might need to be scale to match the unit of the system to mock. This function will both change the unit multiplication factor and rescale the associated data.
The unit itself is defined by the sensor type. Change the channel type in the
raw
recording withmne.io.Raw.set_channel_types()
before providing the recording to the player.- Parameters:
- mapping
dict
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 to1e-6
.
- mapping
- Returns:
- playerinstance of
Player
The player instance modified in-place.
- playerinstance of
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_meas_date(meas_date)[source]🔗
Set the measurement start date.
- Parameters:
- meas_date
datetime
|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.
- meas_date
- Returns:
- playerinstance of
Player
The player instance modified in-place.
- playerinstance of
See also
- 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:
- montage
None
|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 viamne.channels.get_builtin_montages()
. IfNone
(default), the channel positions will be removed from theInfo
.- match_case
bool
If True (default), channel name matching will be case sensitive.
Added in version 0.20.
- match_alias
bool
|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 adict
is passed, it will be used instead, and should map from non-standard channel names to names in the specifiedmontage
. Default isFalse
.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.
- verbose
bool
|str
|int
|None
Control verbosity of the logging output. If
None
, use the default verbosity level. See the logging documentation andmne.verbose()
for details. Should only be passed as a keyword argument.
- montage
- Returns:
See also
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()
- start()[source]🔗
Start streaming data on the LSL
StreamOutlet
.- Returns:
- playerinstance of
PlayerLSL
The player instance modified in-place.
- playerinstance of
- stop()[source]🔗
Stop streaming data on the LSL
StreamOutlet
.- Returns:
- playerinstance of
PlayerLSL
The player instance modified in-place.
- playerinstance of
- property annotations🔗
Annotations attached to the raw object, if streamed.
- Type:
- property compensation_grade🔗
The current gradient compensation grade.
- property running🔗
Status of the player, True if it is running and pushing data.
Examples using mne_lsl.player.PlayerLSL
🔗
Introduction to real-time LSL streams
Automatic vs Manual acquisition
Epoching a Stream in real-time
Replaying a file in a separate process