1. 程式人生 > 其它 >用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()