Python-EEG tool library MNE Chinese Tutorial (2) -MNE data structures and how to create Epoch

This tutorial is a brain-computer learner Rose published in the public number: BCI community (Micro Signal: Brain_Computer) .QQ exchange group: 903 290 195

Epoch concept Introduction

Many people believe that when the first contact epoch, there will be doubts, the term refers to in the end in the EEG is.
The following will explain in detail.
Extract some specific time window signal from continuous EEG signals, these time windows can be referred to as epochs.
Due to continuous EEG is collected to analyze EEG event-related potentials, the signal needs to be "sliced" into time fragments, these fragments are time locked to an event (e.g., irritation) time segment.
For example, in EEGLAB analysis, EEGLAB by the continuous data as a long period of time (long epoch) composition, but after the data segmentation, which consists of a plurality of smaller periods (small epoch) composition.
For example,
suppose we have a signal length x 60s, the sampling frequency of 1 Hz.
EEG 1x60 matrix represented as a matrix, if the signal into a signal of some 2s, there will be 30 Peoch (each signal Epoch is a 2s)
in the MNE, Epoch is a method of an object to a continuous data collection period,
shape (n_events, n_channels, n_times) array form:
Create Epochs objects in three ways:
(1) Raw objects and events point events (event Times)
(2) Epoch objects generated by reading .fif data file
created by mne.EpochsArray Epoch objects from scratch (3)
where the use of Modes 2 and 3 create objects Epochs

a. fif read files created Epoch objects

Step:
1) to read the file fif constructed raw objects;
2) creates an event object;
3) to create an object epoch;
4) superimposed on the averaged evoked epoch objects;
5) rendering evoked.

import mne
from mne import io
from mne.datasets import sample

data_path = sample.data_path()

raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id, tmin, tmax = 1, -0.2, 0.5

# 读取fif文件,创建raw对象
raw = io.read_raw_fif(raw_fname)
# 读取包含event的fif文件,创建event对象
events = mne.read_events(event_fname)

"""
 挑选通道:EEG + MEG - bad channels 
"""
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                       exclude='bads')

# 读取Epoch数据
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=picks, baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
"""
对epochs数据进行求平均获取诱发响应
"""
evoked = epochs.average()

evoked.plot(time_unit='s')
plt.show()

Here Insert Picture Description
Here Insert Picture Description

b. Epoch objects created from scratch

In the actual process, may be created from scratch to build data objects Epochs,
constructed directly utilizing mne.EpochsArray numpy array to create Epochs object, creating the shape of the array must be (n_epochs, n_chans, n_times): the way
data corresponding to the unit :
V: EEG, EOG, SEEG, EMG, ECG, Bio, ECOG
T: MAG
T / m: Grad
m: HBO, HBr
Am: Dipole
AU: Misc

Case 1


import mne
import numpy as np
import matplotlib.pyplot as plt

Step: Construction of data
to build a three-dimensional array of size 10x5x200, the data in the array is a random number;
a first dimension data represents: 10 epochs
second dimension data represents: 5 channels
third dimensional data represented: 2 seconds per epoch

# 采样频率
sfreq = 100
data = np.random.randn(10, 5, sfreq * 2)

# 创建一个info结构
info = mne.create_info(
    ch_names=['MEG1', 'MEG2', 'EEG1', 'EEG2', 'EOG'],
    ch_types=['grad', 'grad', 'eeg', 'eeg', 'eog'],
    sfreq=sfreq
)

Step: Construction of events
when creating Epochs object, you must provide a "events" array,
event (event) is the starting point of a certain kind described in the waveform (symptoms), which is a triple, shape (n_events, 3):
events of the first column elements described starting integer sampling point;
a second row element corresponding to the current event is the source of stimulation channels (stimulus channel) the previous value (previous value), which in most cases is the value 0 ;
third column indicates that the element of event id.

events = np.array([
    [0, 0, 1],
    [1, 0, 2],
    [2, 0, 1],
    [3, 0, 2],
    [4, 0, 1],
    [5, 0, 2],
    [6, 0, 1],
    [7, 0, 2],
    [8, 0, 1],
    [9, 0, 2],
])

Id for an event
if a dict, you can later use these access keys associated with the event. Example: dict (= 1 auditory, visual = 3)
If int, creates a dict string of id's.
If it is a list of all the events specified in the list ID is used.
If not, all events will be used in conjunction with, and create a dict name using a string integer integer corresponding to the event id.


# 创建event id,受试者或者微笑或者皱眉
event_id = dict(smiling=1, frowning=2)
"""
tmin:event开始前的时间,如果未指定,则默认为0
"""
# 设置事件开始前时间为-0.1s
tmin = -0.1

Step 3: Create epochs objects

"""
利用mne.EpochsArray创建epochs对象
"""
custom_epochs = mne.EpochsArray(data, info, events, tmin, event_id)
print(custom_epochs)
# 绘制
_ = custom_epochs['smiling'].average().plot(time_unit='s')

Here Insert Picture Description
Here Insert Picture Description

Case 2

import numpy as np
import neo

import mne
import matplotlib.pyplot as plt

"""
设置event id,用来识别events.
"""
event_id = 1
# 第一列表示样本编号
events = np.array([[200, 0, event_id],
                   [1200, 0, event_id],
                   [2000, 0, event_id]])  # List of three arbitrary events

sfreq = 1000  # 采样频率
times = np.arange(0, 10, 0.001)  # Use 10000 samples (10s)

sin = np.sin(times * 10)  # 乘以 10 缩短周期
cos = np.cos(times * 10)

"""
利用sin和cos创建一个2个通道的700 ms epochs的数据集

只要是(n_epochs, n_channels, n_times)形状的数据,都可以被用来创建
"""
epochs_data = np.array([[sin[:700], cos[:700]],
                        [sin[1000:1700], cos[1000:1700]],
                        [sin[1800:2500], cos[1800:2500]]])

ch_names = ['sin', 'cos']
ch_types = ['mag', 'mag']
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)

epochs = mne.EpochsArray(epochs_data, info=info, events=events,
                         event_id={'arbitrary': 1})

epochs.plot(scalings='auto' )
plt.show()

Here Insert Picture Description

This article was shared by brain-computer learner Rose notes, QQ exchange group: 903 290 195
more to share, please pay attention to the public No.

Guess you like

Origin www.cnblogs.com/RoseVorchid/p/11924785.html