zoukankan      html  css  js  c++  java
  • Python-EEG工具库MNE中文教程(4)-MNE中数据结构Evoked及其对象创建

    本教程为脑机学习者Rose发表于公众号:脑机接口社区(微信号:Brain_Computer).QQ交流群:903290195

    Evoked结构

    Evoked potential(EP)诱发电位或诱发反应是指在出现诸如闪光或纯音之类的刺激后,从人类或其他动物的神经系统,特别是大脑的特定部分记录的特定模式的电位。不同形式和类型的刺激会产生不同类型的电位。

    诱发电位振幅往往较低,从小于1微伏到数微伏不等,而脑电图为数十微伏,肌电图为毫伏,心电图通常接近20毫伏。为了在EEG、ECG、EMG等生物信号和环境噪声的背景下解决这些低幅度电位,通常需要对信号进行平均。信号被时间锁定在刺激上,大部分噪声是随机产生的,这样就可以通过对重复响应来平均掉噪声。

    诱发电位(Evoked)结构主要用于存储实验期间的平均数据,在MNE中,创建Evoked对象通常使用mne.Epochs.average()来平均epochs数据来实现。

    Evoked结构简介

    #导入包
    import os.path as op
    import matplotlib.pyplot as plt
    import mne
    

    从fif文件中读取诱发数据

    """
    从文件中读取诱发数据集
    """
    data_path = mne.datasets.sample.data_path()
    fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')
    evokeds = mne.read_evokeds(fname, baseline=(None, 0), proj=True)
    print(evokeds)
    
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Left Auditory)
        0 CTF compensation matrices available
        nave = 55 - aspect type = 100
        Projections have already been applied. Setting proj attribute to True.
        Applying baseline correction (mode: mean)
    

    使用read_evokeds函数加载诱发文件,并返回evoked实例列表,可以使用condition参数来读取指定类别

    这里有['Left Auditory', 'Right Auditory', 'Left Visual', 'Right Visual']等类别,

    evoked = mne.read_evokeds(fname, condition='Left Auditory')
    evoked.apply_baseline((None, 0)).apply_proj()
    print(evoked)
    

    在这里插入图片描述

    # 打印evoked的信息,这个信息和Raw对象以及Epochs对象中的info很相似
    print(evoked.info)
    print(evoked.times)
    
    # 查看evoked结构其他属性
    print(evoked.nave)  # Number of averaged epochs.
    print(evoked.first)  # First time sample.
    print(evoked.last)  # Last time sample.
    print(evoked.comment)  # Comment on dataset. Usually the condition.
    print(evoked.kind)  # Type of data, either average or standard_error.
    

    55
    -120
    300
    Left Auditory
    average

    快速提取并绘制全局能量谱(Global Field Power, GFP)作为跨通道的标准偏差

    这里仅对EEG显示

    gfp = evoked.copy().pick_types(eeg=True, meg=False).data.std(axis=0)
    fig, ax = plt.subplots(1)
    ax.plot(evoked.times, gfp / 1e6)  # scale to uV
    ax.set(xlabel='Time (sec)', ylabel='GFP (uV)')
    fig.tight_layout()
    

    在这里插入图片描述

    a. 读取evoked文件,创建evoked对象

    sample_audvis-ave.fif文件包含了听觉诱发电位

    1) 读取fif文件,创建evoked对象

    from mne import read_evokeds
    from mne.datasets import sample
    import matplotlib.pyplot as plt
    
    """
    文件存放地址
    """
    data_path = sample.data_path()
    fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
    
    """
    读取fif文件:
    sample_audvis-ave.fif
    
    只读取左听觉的电位数据
    """ 
    condition = 'Left Auditory'
    evoked = read_evokeds(fname, condition=condition, baseline=(None, 0),
                          proj=True)
    
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Left Auditory)
        0 CTF compensation matrices available
        nave = 55 - aspect type = 100
        Projections have already been applied. Setting proj attribute to True.
        Applying baseline correction (mode: mean)
    

    2)绘制evoked数据

    将结果显示为蝶形图
    可以通过使用exclude=[],这里不排除不良通道,将不良通道以红色显示

    evoked.plot(exclude=[], time_unit='s')
    plt.show()
    

    在这里插入图片描述
    将结果以二维图片的形式显示 (x: time, y: channels, color: amplitude)

    evoked.plot_image(exclude=[], time_unit='s')
    plt.show()
    

    在这里插入图片描述

    b. MNE 从头创建Evoked对象

    在实际过程中,有时需要从头自动构建数据来创建Evoked对象,
    方式:利用mne.EvokedArray创建Evoked对象,创建时直接构建numpy数组即可,数组的形状必须是(n_epochs, n_chans, n_times)

    数据对应的单位:
    V: eeg, eog, seeg, emg, ecg, bio, ecog
    T: mag
    T/m: grad
    M: hbo, hbr
    Am: dipole
    AU: misc

    案例1

    #导入工具包
    import mne
    import numpy as np
    import matplotlib.pyplot as plt
    

    第一步:构建数据

    构建一个大小为10x5x200的三维数组,数组中数据是随机数;
    第一维数据表示:10 epochs
    第二维数据表示:5 channels
    第三维数据表示: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
    )
    

    第二步:创建evoked对象

    利用mne.EvokedArray创建Evoked对象

    """
    tmin:event开始前的时间,如果未指定,则默认为0
    """
    # 设置事件开始前时间为-0.1s
    tmin = -0.1
    
    # 对数据求平均
    data_evoked = data.mean(0)
    
    # epochs的数量
    nave = data.shape[0]
    
    # 给evoked起一个名称
    comment = "Smiley faces"
    
    """
    利用mne.EvokedArray创建Evoked对象
    """
    evoked_array = mne.EvokedArray(data_evoked, info, tmin,
                                   comment=comment, nave=nave)
    print(evoked_array)
    _ = evoked_array.plot(time_unit='s')
    

    在这里插入图片描述

    案例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
    
    nave = len(epochs_data)  # Number of averaged epochs
    evoked_data = np.mean(epochs_data, axis=0)
    
    evokeds = mne.EvokedArray(evoked_data, info=info, tmin=-0.2,
                              comment='Arbitrary', nave=nave)
    
    picks = mne.pick_types(info, meg=True, eeg=False, misc=False)
    
    evokeds.plot(picks=picks, show=True, units={'mag': '-'},
                 titles={'mag': 'sin and cos averaged'}, time_unit='s')
    plt.show()
    

    在这里插入图片描述

    脑机接口 QQ交流群:903290195
    更多分享,请关注公众号

  • 相关阅读:
    promise请求数据(all方法)
    右键的点击事件
    微信小程序的接口调用封装
    微信小程序HTTP接口请求封装
    微信小程序得路由跳转
    管理系统得操作与解决思路
    HTTP协议
    动态语言概述
    AsynclAwait
    三种跨域解决方案
  • 原文地址:https://www.cnblogs.com/RoseVorchid/p/11924808.html
Copyright © 2011-2022 走看看