其他分享
首页 > 其他分享> > 用Psychopy实现SSVEP二分类闪烁块,并进行CCA计算

用Psychopy实现SSVEP二分类闪烁块,并进行CCA计算

作者:互联网

import numpy as np
from psychopy import visual, core


def present_stim(sti_fr_list=[1, 1], stim_time=3.0):
    win = visual.Window(size=(1280, 130), pos=(0, 543), color=(0, 0, 0))

    block1 = visual.Rect(win, pos=(-0.82, 0), size=(0.3, 1.8), fillColor='white')
    block1.autoDraw = True
    frq1 = sti_fr_list[0]

    block2 = visual.Rect(win, pos=(0.82, 0), size=(0.3, 1.8), fillColor='white')
    block2.autoDraw = True
    frq2 = sti_fr_list[1]

    timer = core.Clock()
    timer.reset()
    now_time = 0
    while now_time < stim_time:
        now_time = timer.getTime()
        block1.contrast = np.sin(2 * np.pi * now_time * frq1)
        block2.contrast = np.sin(2 * np.pi * now_time * frq2)
        win.flip()
    win.close()

主要思路就是调用core.Clock和visual,然后利用contrast(对比度)随时间改变来实现闪烁。

from sklearn.cross_decomposition import CCA
def ref_sig_gen(sti_fr_list, eeg_signals_len, sampling_rate=1000):
    ref_signals_all = []
    t_series = np.arange(eeg_signals_len) / sampling_rate
    for i, sti_fr in enumerate(sti_fr_list):
        sin1_0 = np.sin(2 * np.pi * sti_fr * t_series + 0.0)
        sin1_30 = np.sin(2 * np.pi * sti_fr * t_series + np.pi*0.166667)
        sin1_45 = np.sin(2 * np.pi * sti_fr * t_series + np.pi*0.25)
        sin1_60 = np.sin(2 * np.pi * sti_fr * t_series + np.pi*0.333333)
        sin1_90 = np.sin(2 * np.pi * sti_fr * t_series + np.pi*0.5)
        sin2_0 = np.sin(2 * np.pi * 2 * sti_fr * t_series + 0.0)
        sin2_90 = np.sin(2 * np.pi * 2 * sti_fr * t_series + np.pi*0.5)
        sin3_0 = np.sin(2 * np.pi * 3 * sti_fr * t_series + 0.0)
        sin3_90 = np.sin(2 * np.pi * 3 * sti_fr * t_series + np.pi*0.5)
        sin1_0 = np.sin(2 * np.pi * sti_fr * t_series + 0.0)

        ref_signals = np.vstack((sin1_0, sin1_30, sin1_45, sin1_60, sin1_90,
                                 sin2_0, sin2_90, sin3_0, sin3_90))
        ref_signals_all.append(ref_signals)
    return ref_signals_all


def process_cca(ref_sin, eeg_signals):
    ref_sin = ref_sin.T
    eeg_signals = eeg_signals.T
    cca_sklearn = CCA(n_components=1)
    cca_sklearn.fit(ref_sin, eeg_signals)
    X_c, Y_c = cca_sklearn.transform(ref_sin, eeg_signals)
    rho = np.corrcoef(X_c[:, 0], Y_c[:, 0])[0, 1]
    return rho


def get_sti_target(ref_signals_all, processed_eeg_datas):
    coef_list = []

    for i in range(len(ref_signals_all)):
        coef = process_cca(ref_signals_all[i], processed_eeg_datas)
        coef_list.append(coef)

    target_index = coef_list.index(max(coef_list))
    # target_index = 1
    print(target_index)
    return target_index

if __name__ == '__main__':
    present_stim()

标签:signals,SSVEP,sti,sin,fr,np,pi,CCA,Psychopy
来源: https://www.cnblogs.com/DWYCWWYHWYA/p/16244925.html