Exemplo n.º 1
0
def data_load(file, filtering=True):
    path = 'E:/Richard/EEG/Competition/raw/'
    cnt, mrk, dur, y = com.load_cnt_mrk_y(path + file)
    if filtering:
        cnt = csp.arr_bandpass_filter(cnt, 8, 30, 250, 5)
    epo = com.cnt_to_epo(cnt, mrk, dur)
    epo, y = com.out_label_remover(epo, y)
    return epo, y
Exemplo n.º 2
0
def load_tscsp_nested(sub='1'):
    path = 'data/A0' + sub + 'T.npz'
    data = scipy.io.loadmat('F:/KIST/source/BCI/BCI/BCI/mat/tscsp_rev/A0' +
                            sub + 'T.mat')
    x_, y = Competition.load_one_data(path)
    x = data['csp_2']
    import feature_selection as FS
    y = np.array(BCI.lab_inv_translator(y, 4))
    kv = BCI.gen_kvt_idx(y, 10)
    for train_idx, valid_idx, test_idx in kv:
        x_train, y_train = x[:, train_idx, :], y[train_idx]
        x_valid, y_valid = x[:, valid_idx, :], y[valid_idx]
        x_test, y_test = x[:, test_idx, :], y[test_idx]
        opt_idx = FS.lsvm_filter_pp(x_train, y_train, x_valid, y_valid)

        x_train = np.transpose(x_train[:, :, opt_idx])
        x_test = np.transpose(x_test[:, :, opt_idx])

        clf = LinearDiscriminantAnalysis()
        clf.fit(x_train, y_train.argmax(axis=1))
        x_train = clf.transform(x_train)
        x_test = clf.transform(x_test)
        clf2 = GaussianNB()
        clf2.fit(x_train, y_train.argmax(axis=1))
        y_predict = clf2.predict(x_test)

        cohen_score = cohen_kappa_score(y_predict, y_test.argmax(axis=1))
        score = clf2.score(x_test, y_test.argmax(axis=1))
        pen = open("FE_LSVM_nested_rev2.csv", 'a')
        pen.write(sub + ',' + str(cohen_score) + ',' + str(score) + ',' +
                  str(opt_idx) + '\n')
    print('abc')
Exemplo n.º 3
0
def RCNN_batch(sub='1', epoch=100):
    path = 'data/A0' + sub + 'T.npz'
    data = scipy.io.loadmat('F:/KIST/source/BCI/BCI/BCI/mat/tscsp_rev/A0' +
                            sub + 'T.mat')
    x_, y = Competition.load_one_data(path)
    x = data['csp_2']
    import feature_selection as FS
    y = np.array(BCI.lab_inv_translator(y, 4))
    kv = BCI.gen_kv_idx(y, 10)
    import RCNN, data_trans
    fold = 1
    for train_idx, test_idx in kv:
        x_train, y_train = x[:, train_idx, :], y[train_idx]
        x_test, y_test = x[:, test_idx, :], y[test_idx]
        x_train = data_trans.x_translator(x_train)
        x_test = data_trans.x_translator(x_test)
        model = RCNN.create_model2((48, 45, 1))
        model.fit(x_train,
                  y_train,
                  validation_data=(x_test, y_test),
                  epochs=epoch,
                  batch_size=10)
        metrics = model.evaluate(x_test, y_test)
        pen = open('rcnn_competition_2.csv', 'a')
        pen.write('RCNN,' + sub + ',' + str(fold) + ',' + str(epoch) + ',' +
                  str(metrics[1]) + '\n')
        pen.close()
        fold += 1
Exemplo n.º 4
0
def load_fbcsp(path='data/A01T.npz'):
    data = scipy.io.loadmat(
        'F:/KIST/source/BCI/BCI/BCI/mat/fbcsp_rev/A01T.mat')
    x, y = Competition.load_one_data(path)
    x_ = data['csp_tot']

    mi_idx = MIBIF.fb_mibif_with_csp(x, y, x_)
    optimal_csp = np.transpose(x_[:, :, mi_idx])
    y = np.array(BCI.lab_inv_translator(y, 4))
    kv = BCI.gen_kv_idx(y, 10)
    for train_idx, test_idx in kv:
        print('1')
        x_train, y_train = optimal_csp[train_idx], y[train_idx]
        x_test, y_test = optimal_csp[test_idx], y[test_idx]
        clf = LinearDiscriminantAnalysis()
        clf.fit(x_train, y_train.argmax(axis=1))
        x_train = clf.transform(x_train)
        x_test = clf.transform(x_test)
        clf2 = GaussianNB()
        clf2.fit(x_train, y_train.argmax(axis=1))
        y_predict = clf2.predict(x_test)

        cohen_score = cohen_kappa_score(y_predict, y_test.argmax(axis=1))
        score = clf2.score(x_test, y_test.argmax(axis=1))
        print('pen!')
        pen = open("cohen_score_fb.csv", 'a')
        pen.write(str(cohen_score) + ',' + str(score) + '\n')
    print('abc')
Exemplo n.º 5
0
def load_new_mat():
    import BCI, scipy.io, Competition
    from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
    from sklearn.naive_bayes import GaussianNB
    from sklearn.metrics import cohen_kappa_score
    aa = scipy.io.loadmat('F:/KIST/source/BCI/BCI/BCI/mat/res/A01T_CSP.mat')
    x, y = Competition.load_one_data('data/A01T.npz')
    y = np.array(BCI.lab_inv_translator(y, 4))
    x_ = np.transpose(aa['csp_res'])
    kv = BCI.gen_kv_idx(y, 10)
    for train_idx, test_idx in kv:
        x_train, y_train = x_[train_idx], y[train_idx]
        x_test, y_test = x_[test_idx], y[test_idx]
        clf = LinearDiscriminantAnalysis()
        x_train = clf.fit_transform(x_train, y_train.argmax(axis=1))
        x_test = clf.transform(x_test)
        clf2 = GaussianNB()
        clf2.fit(x_train, y_train.argmax(axis=1))
        y_predict = clf2.predict(x_test)

        cohen_score = cohen_kappa_score(y_predict, y_test.argmax(axis=1))
        score = clf2.score(x_test, y_test.argmax(axis=1))
        pen = open("cohen_score7.csv", 'a')
        pen.write(str(cohen_score) + ',' + str(score) + '\n')
    print('abc')
Exemplo n.º 6
0
def gen_tscsp(sub='1'):
    path = 'data/A0' + sub + 'T.npz'
    cnt, mrk, dur, y = Competition.load_cnt_mrk_y(path)
    epo = []
    for i in range(1, 10):  # band-pass filtering
        cnt_fs = CSP.arr_bandpass_filter(cnt, i * 4, (i + 1) * 4, 250, 4)
        cur_epo = cnt_to_epo(cnt_fs, mrk, dur)
        cur_epo, y_ = out_label_remover(cur_epo, y)
        epo.append(cur_epo)
    y = BCI.lab_inv_translator(y_, 4)
    kv = BCI.gen_kv_idx(y, 5)
    k = 1
    for train_idx, test_idx in kv:
        train_x = epo_temporal_dividing(
            np.array(epo)[:, train_idx, :, :], 4, 0.5, 250)
        test_x = epo_temporal_dividing(
            np.array(epo)[:, test_idx, :, :], 4, 0.5, 250)
        train_y = np.transpose(np.array(y)[train_idx])
        test_y = np.transpose(np.array(y)[test_idx])
        res = {
            'train_x': train_x,
            'test_x': test_x,
            'train_y': train_y,
            'test_y': test_y
        }
        scipy.io.savemat(
            'competition/ori_4_0.5/' + sub + '_' + str(k) + '.mat', res)
        k += 1
Exemplo n.º 7
0
def make_topos(sub='1'):
    optimal_bank = [20, 30, 19, 9, 9, 20, 20, 19, 22]
    import matplotlib.pyplot as plt
    plt.rcParams["font.family"] = "Times New Roman"
    path = 'data/A0' + sub + 'T.npz'
    data = scipy.io.loadmat('F:/KIST/source/BCI/BCI/BCI/mat/tscsp_rev/A0' +
                            sub + 'T.mat')
    x, y_ = Competition.load_one_data(path)
    x_ = data['csp_2']
    import feature_selection as FS
    y = np.array(BCI.lab_inv_translator(y, 4))
    kv = BCI.gen_kv_idx(y, 10)
    x[:, :, optimal_bank[int(sub) - 1]]
    for train_idx, test_idx in kv:
        x_train, y_train = x[:, train_idx, :], y[train_idx]
        x_test, y_test = x[:, test_idx, :], y[test_idx]
        opt_idx = FS.lsvm_filter_pp2(x_train, y_train)

        x_train = np.transpose(x_train[:, :, opt_idx])
        x_test = np.transpose(x_test[:, :, opt_idx])

    res_val = res_val / 10
    plt.rcParams["font.family"] = "Times New Roman"
    ax = sns.heatmap(res_val,
                     cmap="BuGn",
                     vmin=0.5,
                     vmax=0.85,
                     square=True,
                     annot=True)
    plt.savefig('fig/' + sub + '_2.eps', format='eps', dpi=1000)
    plt.close()
    print('abc')
Exemplo n.º 8
0
def new_numpy_to_mat(path='data/A01T.npz'):
    import Competition, BCI, scipy.io
    x, y = Competition.load_one_data(path)
    file = [{
        'clab': [],
        'fs': 250,
        'x': [],
        'y': []
    }, {
        'clab': [],
        'fs': 250,
        'x': [],
        'y': []
    }, {
        'clab': [],
        'fs': 250,
        'x': [],
        'y': []
    }]
    file[0]['clab'] = ['01', '23']
    file[1]['clab'] = ['02', '13']
    file[2]['clab'] = ['03', '12']
    for i in range(len(y)):
        if y[i] == 0:
            file[0]['x'].append(x[i])
            file[0]['y'].append([1, 0])
            file[1]['x'].append(x[i])
            file[1]['y'].append([1, 0])
            file[2]['x'].append(x[i])
            file[2]['y'].append([1, 0])
        elif y[i] == 1:
            file[0]['x'].append(x[i])
            file[0]['y'].append([1, 0])
            file[1]['x'].append(x[i])
            file[1]['y'].append([0, 1])
            file[2]['x'].append(x[i])
            file[2]['y'].append([0, 1])
        elif y[i] == 2:
            file[0]['x'].append(x[i])
            file[0]['y'].append([0, 1])
            file[1]['x'].append(x[i])
            file[1]['y'].append([1, 0])
            file[2]['x'].append(x[i])
            file[2]['y'].append([0, 1])
        elif y[i] == 3:
            file[0]['x'].append(x[i])
            file[0]['y'].append([0, 1])
            file[1]['x'].append(x[i])
            file[1]['y'].append([0, 1])
            file[2]['x'].append(x[i])
            file[2]['y'].append([1, 0])
    scipy.io.savemat('mat/' + path.split('/')[-1].split('.')[0] + '_1.mat',
                     file[0])
    scipy.io.savemat('mat/' + path.split('/')[-1].split('.')[0] + '_2.mat',
                     file[1])
    scipy.io.savemat('mat/' + path.split('/')[-1].split('.')[0] + '_3.mat',
                     file[2])
Exemplo n.º 9
0
def gen_fbcsp(path='data/A01T.npz'):
    x, y = Competition.load_one_data(path)
    for i in range(1, 10):
        print(i)
        x_ = CSP.arr_bandpass_filter(x, i * 4, (i + 1) * 4, 250)
        f = one_fbcsp(x_, y)
        scipy.io.savemat('mat/fbcsp_ori/A01T_' + str(i) + '_1.mat', f[0])
        scipy.io.savemat('mat/fbcsp_ori/A01T_' + str(i) + '_2.mat', f[1])
        scipy.io.savemat('mat/fbcsp_ori/A01T_' + str(i) + '_3.mat', f[2])
Exemplo n.º 10
0
def comp_to_mat(sub):
  import Competition, Com_test
  path = 'data/A0'+ sub + 'T.npz'
  cnt, mrk, dur, y = Competition.load_cnt_mrk_y(path)
  epo = Com_test.cnt_to_epo(cnt, mrk, dur)
  epo, y = Com_test.out_label_remover(epo, y)
  y = BCI.lab_inv_translator(y, 4)
  res = {'epo': np.transpose(epo), 'y': np.transpose(y)}
  scipy.io.savemat('Access/com/'+sub+'.mat', res)
  print("abc")
Exemplo n.º 11
0
def createTournament(name):
    """
        Creates a tournament and returns the created tournament id
        Args:
            name: name of new tournament
        Returns:
            id: the tournament id of newly created tournament
    """

    return Competition.create(name)
Exemplo n.º 12
0
def numpy_to_mat(path='data/A01T.npz'):
    import Competition, BCI, scipy.io
    x, y = Competition.load_one_data(path)
    file = {}
    file['clab'] = [i for i in range(25)]
    file['fs'] = 250
    file['y'] = np.transpose(BCI.lab_inv_translator(y, 4))
    #file['x'] = bandpass_filter(x, 5, 30, 250)
    file['x'] = x
    file['t'] = [i for i in range(750)]
    file['className'] = np.transpose(['a', 'b', 'c', 'd'])

    scipy.io.savemat(path.split('/')[-1].split('.')[0] + '.mat', file)
Exemplo n.º 13
0
def playerStandings(tournament_id):
    """
        Queries tournament data for current ranking of players
        Args:
            tournament_id =  id of tournament to be queried
        Returns:
          A list of tuples, each of which contains (id, name, wins, matches):
            id = the player's unique id (assigned by the database)
            name =  the player's full name (as registered)
            wins =  the number of matches the player has won
            matches = the number of matches the player has played
    """

    return Competition.getStandings(tournament_id)
Exemplo n.º 14
0
def gen_cnt_data():
    import os
    os.chdir('E:/Richard/Competition/')
    for i in range(1, 10):
        path = 'raw/A0' + str(i) + 'T.npz'
        cnt, mrk, dur, y = Competition.load_cnt_mrk_y(path)
        f_cnt = CSP.arr_bandpass_filter(cnt, 8, 30, 250, 5)
        epo = cnt_to_epo(f_cnt, mrk, dur)
        epo, y_ = out_label_remover(epo, y)
        new_epo = []
        for v in epo:
            new_epo.append(v[750:1500, :])
        new_epo = np.array(new_epo)
        data = {'x': new_epo, 'y': y_}
        scipy.io.savemat('epo_f/A0' + str(i), data)
Exemplo n.º 15
0
def checkByes(tournament, ranks, index):
    """
        Logic to handle tournament checking of byes
        Args:
            tournament =  id of tournament to query
            ranks = a list of tuples of rankings of players  from tournament
                standing
        Returns:
    """

    if abs(index) > len(ranks):
        return -1
    elif not Competition.hasBye(ranks[index][0], tournament):
        return index
    else:
        return checkByes(tournament, ranks, (index - 1))
Exemplo n.º 16
0
def load_tscsp_nested2(sub='1'):
    path = 'data/A0' + sub + 'T.npz'
    data = scipy.io.loadmat('F:/KIST/source/BCI/BCI/BCI/mat/tscsp_rev/A0' +
                            sub + 'T.mat')
    x_, y = Competition.load_one_data(path)
    x = data['csp_2']
    import feature_selection as FS
    y = np.array(BCI.lab_inv_translator(y, 4))
    kv = BCI.gen_kv_idx(y, 10)
    accs = []
    pres = []
    recs = []
    f1s = []
    cohens = []
    conf1 = np.zeros((4, 4))
    conf2 = np.zeros((4, 4))
    for train_idx, test_idx in kv:
        x_train, y_train = x[:, train_idx, :], y[train_idx]
        x_test, y_test = x[:, test_idx, :], y[test_idx]
        opt_idx = FS.lsvm_filter_pp2(x_train, y_train)

        x_train = np.transpose(x_train[:, :, opt_idx])
        x_test = np.transpose(x_test[:, :, opt_idx])

        #clf = LinearDiscriminantAnalysis()
        #clf.fit(x_train, y_train.argmax(axis=1))
        #x_train = clf.transform(x_train)
        #x_test = clf.transform(x_test)
        #clf2 = GaussianNB()
        #clf2.fit(x_train, y_train.argmax(axis=1))
        #y_predict = clf2.predict(x_test)
        clf1 = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')
        from sklearn.svm import SVC
        clf2 = SVC(kernel='rbf')

        #clf2 = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')
        clf1.fit(x_train, y_train.argmax(axis=1))
        clf2.fit(x_train, y_train.argmax(axis=1))
        y_predict1 = clf1.predict(x_test)
        y_predict2 = clf2.predict(x_test)

        from sklearn.metrics import confusion_matrix
        confusion1 = confusion_matrix(y_test.argmax(axis=1), y_predict1)
        confusion2 = confusion_matrix(y_test.argmax(axis=1), y_predict2)

        conf1 += confusion1
        conf2 += confusion2
Exemplo n.º 17
0
def test_api(sub='1'):
    import matplotlib.pyplot as plt
    plt.rcParams["font.family"] = "Times New Roman"
    import seaborn as sns
    sns.set()
    path = 'data/A0' + sub + 'T.npz'
    data = scipy.io.loadmat('F:/KIST/source/BCI/BCI/BCI/mat/tscsp_rev/A0' +
                            sub + 'T.mat')
    x, y_ = Competition.load_one_data(path)
    x_ = data['csp_2']

    #mi_idx = MIBIF.fb_mibif_with_csp(x, y, x_)]
    #import feature_selection as FS
    #mi_idx = FS.lsvm_filter(x_, y)
    res_val = np.zeros((9, 5))
    for i in range(0, 45):
        mi_idx = i
        optimal_csp = np.transpose(x_[:, :, mi_idx])
        y = np.array(BCI.lab_inv_translator(y_, 4))
        kv = BCI.gen_kv_idx(y, 10)
        for train_idx, test_idx in kv:
            x_train, y_train = optimal_csp[train_idx], y[train_idx]
            x_test, y_test = optimal_csp[test_idx], y[test_idx]
            clf2 = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')
            clf2.fit(x_train, y_train.argmax(axis=1))
            y_predict = clf2.predict(x_test)
            cohen_score = cohen_kappa_score(y_predict, y_test.argmax(axis=1))
            x_val = i % 9
            y_val = int(i / 9)
            res_val[x_val, y_val] += cohen_score

    res_val = res_val / 10
    plt.rcParams["font.family"] = "Times New Roman"
    ax = sns.heatmap(res_val,
                     cmap="BuGn",
                     vmin=0.5,
                     vmax=0.85,
                     square=True,
                     annot=True)
    plt.savefig('fig/' + sub + '_2.eps', format='eps', dpi=1000)
    plt.close()
    print('abc')
Exemplo n.º 18
0
def batch(sub='1'):
    path = 'data/A0' + sub + 'T.npz'
    cnt, mrk, dur, y = Competition.load_cnt_mrk_y(path)
    epo = Com_test.cnt_to_epo(cnt, mrk, dur)
    epo, y = Com_test.out_label_remover(epo, y)
    wd = pywt.dwt2(epo, 'bior1.3')
    LL, (LH, HL, HH) = wd
    fig = plt.figure(figsize=(12, 3))
    titles = [
        'Approximation', ' Horizontal detail', 'Vertical detail',
        'Diagonal detail'
    ]
    for i, a in enumerate([LL, LH, HL, HH]):
        ax = fig.add_subplot(1, 4, i + 1)
        ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray)
        ax.set_title(titles[i], fontsize=10)
        ax.set_xticks([])
        ax.set_yticks([])
    fig.tight_layout()
    plt.show()
Exemplo n.º 19
0
def test_csp():
    import Competition, BCI
    x, y = Competition.load_one_data('data/A01T.npz')
    x = np.array(x)
    y = np.array(BCI.lab_inv_translator(y, 4))
    kv = BCI.gen_kv_idx(y, 10)
    for train_idx, test_idx in kv:
        x_train, y_train = x[train_idx], y[train_idx]
        x_test, y_test = x[test_idx], y[test_idx]
        csp_train = CSP(x_train)
        csp_test = CSP(x_test)
        from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

        clf = LinearDiscriminantAnalysis()
        csp_train = np.reshape(csp_train, (len(csp_train), 25))
        clf.fit(csp_train, y_train.argmax(axis=1))

        csp_test = np.reshape(csp_test, (len(csp_test), 25))
        clf.predict(csp_test)

        print('adfd')
Exemplo n.º 20
0
def load_new_mat(sub='1'):

    aa = scipy.io.loadmat('F:/KIST/source/BCI/BCI/BCI/mat/res_original/A0' +
                          sub + 'T_CSP.mat')
    x, y = Competition.load_one_data('data/A0' + sub + 'T.npz')
    y = np.array(BCI.lab_inv_translator(y, 4))
    x_ = np.transpose(aa['csp_res'])
    kv = BCI.gen_kv_idx(y, 10)
    accs = []
    pres = []
    recs = []
    f1s = []
    cohens = []
    for train_idx, test_idx in kv:
        x_train, y_train = x_[train_idx], y[train_idx]
        x_test, y_test = x_[test_idx], y[test_idx]
        from sklearn.svm import SVC
        clf2 = SVC(kernel='rbf')

        #clf2 = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')

        clf2.fit(x_train, y_train.argmax(axis=1))
        y_predict = clf2.predict(x_test)

        cohens.append(cohen_kappa_score(y_predict, y_test.argmax(axis=1)))

        accs.append(accuracy_score(y_test.argmax(axis=1), y_predict))
        pres.append(
            precision_score(y_test.argmax(axis=1), y_predict, average='macro'))
        recs.append(
            recall_score(y_test.argmax(axis=1), y_predict, average='macro'))
        f1s.append(f1_score(y_test.argmax(axis=1), y_predict, average='macro'))

        # PRE, REC, ACC, F1, KAP
    pen = open("CSP_SVM.csv", 'a')
    pen.write(sub + ',' + str(np.mean(accs)) + ',' + str(np.mean(pres)) + ',' +
              str(np.mean(recs)) + ',' + str(np.mean(f1s)) + ',' +
              str(np.mean(cohens)) + '\n')

    print('abc')
def SLC(CostFunction,
        max_eval=50000,
        dim=30,
        nteams=5,
        nmain=10,
        nsubs=10,
        lower_bound=0,
        upper_bound=10,
        max_it=10**8,
        mutation_probability=0.1,
        mutation_rate=0.2):

    # Domain of the problem, tuple including lower and upper bounds
    domain = (lower_bound, upper_bound)

    # Creation of the initial league
    league_main, league_subs, fitness_main, fitness_subs, initial_evals = CreateInitialLeague(
        CostFunction, nteams, nmain, nsubs, dim, domain)

    # Starting number of evaluations
    neval = initial_evals

    # Seasons keep on launching until 'max_it' seasons have been played, or until 'neval' reaches number of Cost
    # Function evaluations that was indicated as a ceiling parameter
    for it in range(0, max_it):
        league_main, league_subs, fitness_main, fitness_subs, evals_competition = Competition(
            CostFunction, league_main, league_subs, fitness_main, fitness_subs,
            domain, mutation_rate, mutation_probability)
        neval += evals_competition
        league_main, league_subs, fitness_main, fitness_subs = Takhsis(
            league_main, league_subs, fitness_main, fitness_subs)

        print("Season {:4}, best solution: {:e}".format(
            it, fitness_main[0][0]))
        print("\tNumber of evaluations: {}".format(neval))

        if (neval > max_eval) or (fitness_main[0][0] == 0.0):
            break
Exemplo n.º 22
0
def gen_tscsp_trick(sub):
    path = 'data/A0' + sub + 'T.npz'
    cnt, mrk, dur, y = Competition.load_cnt_mrk_y(path)
    epo = []
    for i in range(1, 10):  # band-pass filtering
        cnt_fs = CSP.arr_bandpass_filter(cnt, i * 4, (i + 1) * 4, 250, 4)
        cur_epo = cnt_to_epo(cnt_fs, mrk, dur)
        cur_epo, y_ = out_label_remover(cur_epo, y)
        epo.append(cur_epo)
    y = BCI.lab_inv_translator(y_, 4)
    kv = BCI.gen_kv_idx(y, 5)
    k = 1
    for train_idx, test_idx in kv:
        train_x = epo_temporal_dividing(
            np.array(epo)[:, train_idx, :, :], 3.5, 0.5, 250)
        test_x = epo_temporal_dividing(
            np.array(epo)[:, test_idx, :, :], 3.5, 0.5, 250)
        cls = trick_ori(train_x, test_x,
                        np.array(y)[train_idx].argmax(axis=1),
                        np.array(y)[test_idx].argmax(axis=1))
        scipy.io.savemat(
            'competition/trick/ori_3.5_0.5/' + sub + '_' + str(k) + '.mat',
            {'cls': cls})
        k += 1
Exemplo n.º 23
0
def gen_ts_topo(sub='1'):
    optimal_bank = [20, 30, 19, 9, 9, 20, 20, 19, 22]
    path = 'data/A0' + sub + 'T.npz'
    x, y = Competition.load_one_data(path)
    x = np.array(x)
    step = int(len(x[0][0]) / 5)
    for i in range(0, 5):
        cur_x = x[:, :, step * i:step * (i + 1)]
        for j in range(1, 10):
            optimal_idx = optimal_bank[int(sub) - 1]
            pred_j = optimal_idx % 9
            pred_i = int(optimal_idx / 9)
            if pred_i == i and pred_j == j - 1:
                lab_1 = {
                    'clab': [
                        'Fz', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'C5', 'C3',
                        'C1', 'Cz', 'C2', 'C4', 'C6', 'CP3', 'CP1', 'CPz',
                        'CP2', 'CP4', 'P1', 'Pz', 'P2', 'POz'
                    ],
                    'fs':
                    250,
                    'x': [],
                    'y': []
                }
                lab_2 = {
                    'clab': [
                        'Fz', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'C5', 'C3',
                        'C1', 'Cz', 'C2', 'C4', 'C6', 'CP3', 'CP1', 'CPz',
                        'CP2', 'CP4', 'P1', 'Pz', 'P2', 'POz'
                    ],
                    'fs':
                    250,
                    'x': [],
                    'y': []
                }
                lab_3 = {
                    'clab': [
                        'Fz', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'C5', 'C3',
                        'C1', 'Cz', 'C2', 'C4', 'C6', 'CP3', 'CP1', 'CPz',
                        'CP2', 'CP4', 'P1', 'Pz', 'P2', 'POz'
                    ],
                    'fs':
                    250,
                    'x': [],
                    'y': []
                }
                lab_4 = {
                    'clab': [
                        'Fz', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'C5', 'C3',
                        'C1', 'Cz', 'C2', 'C4', 'C6', 'CP3', 'CP1', 'CPz',
                        'CP2', 'CP4', 'P1', 'Pz', 'P2', 'POz'
                    ],
                    'fs':
                    250,
                    'x': [],
                    'y': []
                }
                cur_cur_x = CSP.arr_bandpass_filter(cur_x, j * 4, (j + 1) * 4,
                                                    250)
                for k in range(len(y)):
                    if y[k] == 0:
                        lab_1['x'].append(np.transpose(cur_cur_x[k]))
                        lab_1['y'].append([1, 0, 0, 0])
                    elif y[k] == 1:
                        lab_2['x'].append(np.transpose(cur_cur_x[k]))
                        lab_2['y'].append([0, 1, 0, 0])
                    elif y[k] == 2:
                        lab_3['x'].append(np.transpose(cur_cur_x[k]))
                        lab_3['y'].append([0, 0, 1, 0])
                    elif y[k] == 3:
                        lab_4['x'].append(np.transpose(cur_cur_x[i]))
                        lab_4['y'].append([0, 0, 0, 1])
                scipy.io.savemat('mat/topo_ori/A0' + sub + 'T_1.mat', lab_1)
                scipy.io.savemat('mat/topo_ori/A0' + sub + 'T_2.mat', lab_2)
                scipy.io.savemat('mat/topo_ori/A0' + sub + 'T_3.mat', lab_3)
                scipy.io.savemat('mat/topo_ori/A0' + sub + 'T_4.mat', lab_4)

                print('abc')
Exemplo n.º 24
0
def new_numpy_to_mat(sub='1'):
    path = 'data/A0' + sub + 'T.npz'
    x, y = Competition.load_one_data(path)
    x = CSP.bandpass_filter(x, 5, 30, 250)
    file = [{
        'clab': [],
        'fs': 250,
        'x': [],
        'y': []
    }, {
        'clab': [],
        'fs': 250,
        'x': [],
        'y': []
    }, {
        'clab': [],
        'fs': 250,
        'x': [],
        'y': []
    }]
    file[0]['clab'] = ['01', '23']
    file[1]['clab'] = ['02', '13']
    file[2]['clab'] = ['03', '12']
    for i in range(len(y)):
        if y[i] == 0:
            file[0]['x'].append(x[i])
            file[0]['y'].append([1, 0])
            file[1]['x'].append(x[i])
            file[1]['y'].append([1, 0])
            file[2]['x'].append(x[i])
            file[2]['y'].append([1, 0])
        elif y[i] == 1:
            file[0]['x'].append(x[i])
            file[0]['y'].append([1, 0])
            file[1]['x'].append(x[i])
            file[1]['y'].append([0, 1])
            file[2]['x'].append(x[i])
            file[2]['y'].append([0, 1])
        elif y[i] == 2:
            file[0]['x'].append(x[i])
            file[0]['y'].append([0, 1])
            file[1]['x'].append(x[i])
            file[1]['y'].append([1, 0])
            file[2]['x'].append(x[i])
            file[2]['y'].append([0, 1])
        elif y[i] == 3:
            file[0]['x'].append(x[i])
            file[0]['y'].append([0, 1])
            file[1]['x'].append(x[i])
            file[1]['y'].append([0, 1])
            file[2]['x'].append(x[i])
            file[2]['y'].append([1, 0])
    for v in file:
        v['x'] = np.transpose(np.array(v['x']))
        v['y'] = np.transpose(np.array(v['y']))

    scipy.io.savemat(
        'mat/ori_original/' + path.split('/')[-1].split('.')[0] + '_1.mat',
        file[0])
    scipy.io.savemat(
        'mat/ori_original/' + path.split('/')[-1].split('.')[0] + '_2.mat',
        file[1])
    scipy.io.savemat(
        'mat/ori_original/' + path.split('/')[-1].split('.')[0] + '_3.mat',
        file[2])
Exemplo n.º 25
0
def test():
    import Competition, BCI
    x, y = Competition.load_one_data('data/A01T.npz')
    x = np.array(x)
    y = np.array(BCI.lab_inv_translator(y, 4))
    kv = BCI.gen_kv_idx(y, 10)
    accuracies = []
    accuracies_fb = []
    accuracies_st = []
    accuracies_ts = []
    for train_idx, test_idx in kv:
        x_train, y_train = x[train_idx], y[train_idx]
        x_test, y_test = x[test_idx], y[test_idx]

        start_time = time.time()
        csp_train = CSP(x_train)
        csp_test = CSP(x_test)
        print("CSP seconds: %", (time.time() - start_time))

        start_time = time.time()
        fb_csp_train = filterbank_CSP(x_train)
        fb_csp_test = filterbank_CSP(x_test)
        print("FBCSP seconds: %", (time.time() - start_time))

        start_time = time.time()
        st_csp_train = spectral_temporal_CSP(x_train)
        st_csp_test = spectral_temporal_CSP(x_test)
        print("STCSP seconds: %", (time.time() - start_time))

        start_time = time.time()
        ts_csp_train = temporal_spectral_CSP(x_train)
        ts_csp_test = temporal_spectral_CSP(x_test)
        print("TSCSP seconds: %", (time.time() - start_time))

        from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
        clf_csp = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')
        clf_fb = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')
        clf_st = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')
        clf_ts = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')

        res = {}
        res['csp'] = {}
        res['fbcsp'] = {}
        res['stcsp'] = {}
        res['tscsp'] = {}
        res['csp']['train_x'] = csp_train
        res['csp']['test_x'] = csp_test
        res['fbcsp']['train_x'] = fb_csp_train
        res['fbcsp']['test_x'] = fb_csp_test
        res['stcsp']['train_x'] = st_csp_train
        res['stcsp']['test_x'] = st_csp_test
        res['tscsp']['train_x'] = ts_csp_train
        res['tscsp']['test_x'] = ts_csp_test
        res['y_train'] = y_train.argmax(axis=1)
        res['y_test'] = y_test.argmax(axis=1)
        import pickle
        with open('tmp_data/tmp.pic', 'wb') as f:
            pickle.dump(res, f)

        cur_csp_x_test = pca_csp.transform(cur_csp_x_test)
        cur_fbcsp_x_test = pca_fb.transform(cur_fbcsp_x_test)
        cur_stcsp_x_test = pca_st.transform(cur_stcsp_x_test)
        cur_tscsp_x_test = pca_ts.transform(cur_tscsp_x_test)

        clf_csp.fit(cur_csp_x_train, y_train.argmax(axis=1))
        clf_fb.fit(cur_fbcsp_x_train, y_train.argmax(axis=1))
        clf_st.fit(cur_stcsp_x_train, y_train.argmax(axis=1))
        clf_ts.fit(cur_tscsp_x_train, y_train.argmax(axis=1))

        csp_score = clf_csp.score(cur_csp_x_test, y_test.argmax(axis=1))
        fbcsp_score = clf_fb.score(cur_fbcsp_x_test, y_test.argmax(axis=1))
        stcsp_score = clf_st.score(cur_stcsp_x_test, y_test.argmax(axis=1))
        tscsp_score = clf_ts.score(cur_tscsp_x_test, y_test.argmax(axis=1))

        print(csp_score)
        print(fbcsp_score)
        print(stcsp_score)
        print(tscsp_score)

        accuracies.append(csp_score)
        accuracies_fb.append(fbcsp_score)
        accuracies_st.append(stcsp_score)
        accuracies_ts.append(tscsp_score)

    pen = open('csp_res.csv', 'w')
    sentence = 'CSP'
    for v in accuracies:
        sentence += ',' + str(v)
    pen.write(sentence + '\n')
    sentence = 'FBCSP'
    for v in accuracies_fb:
        sentence += ',' + str(v)
    pen.write(sentence + '\n')
    sentence = 'STCSP'
    for v in accuracies_st:
        sentence += ',' + str(v)
    pen.write(sentence + '\n')
    sentence = 'TSCSP'
    for v in accuracies_ts:
        sentence += ',' + str(v)
    pen.write(sentence)
    pen.close()
Exemplo n.º 26
0
def load_data(path='data/A01T.npz'):
    import Competition, BCI
    x, y = Competition.load_one_data(path)
    x = np.array(x)
    y = np.array(BCI.lab_inv_translator(y, 4))
    return x, y
Exemplo n.º 27
0
def test(sub='1'):
    import scipy.interpolate
    import numpy
    import matplotlib
    import matplotlib.pyplot as plt
    import Competition
    path = 'data/A0' + sub + 'T.npz'
    x, y = Competition.load_one_data(path)

    # close old plots
    plt.close("all")

    # some parameters
    N = 300  # number of points for interpolation
    xy_center = [2, 2]  # center of the plot
    radius = 2  # radius

    # mostly original code
    """
  meanR = [9.95184937,   9.87947708,   9.87628496,   9.78414422,
           9.79365258,   9.96168969,   9.87537519,   9.74536093,
          10.16686878,  10.04425475,  10.10444126,  10.2917172 ,
          10.16745917,  100.0235203 ,   9.89914   ,  10.11263505,
           9.99756449,  10.17861254,  10.04704248]
  
  
  koord = [[1,4],[3,4],[1,3],[3,3],[2,3],[1,2],[3,2],[2,2],[1,1],[3,1],[2,1],[1,0],[3,0],[0,3],[4,3],[0,2],[4,2],[0,1],[4,1]]
  """

    meanR = np.array(x)[0, 0:22, 10]
    koord = [[2, 4], [0, 3], [1, 3], [2, 3], [3, 3], [4, 3], [-1, 2], [0, 2],
             [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [0, 1], [1, 1], [2, 1],
             [3, 1], [4, 1], [0.9, 0], [2, 0], [3, 0], [2, -1]]
    x, y = [], []
    for i in koord:
        x.append(i[0])
        y.append(i[1])

    z = meanR

    xi = numpy.linspace(-2, 6, N)
    yi = numpy.linspace(-2, 6, N)
    zi = scipy.interpolate.griddata((x, y),
                                    z, (xi[None, :], yi[:, None]),
                                    method='cubic')

    # set points > radius to not-a-number. They will not be plotted.
    # the dr/2 makes the edges a bit smoother
    dr = xi[1] - xi[0]
    for i in range(N):
        for j in range(N):
            r = numpy.sqrt((xi[i] - xy_center[0])**2 +
                           (yi[j] - xy_center[1])**2)
            if (r - dr / 2) > radius:
                zi[j, i] = "nan"

    # make figure
    fig = plt.figure()

    # set aspect = 1 to make it a circle
    ax = fig.add_subplot(111, aspect=1)

    # use different number of levels for the fill and the lines
    CS = ax.contourf(xi, yi, zi, 60, cmap=plt.cm.jet, zorder=1)
    ax.contour(xi, yi, zi, 15, colors="grey", zorder=2)

    # make a color bar
    cbar = fig.colorbar(CS, ax=ax)

    # add the data points
    # I guess there are no data points outside the head...
    ax.scatter(x, y, marker='o', c='k', s=15, zorder=3)

    # draw a circle
    # change the linewidth to hide the
    circle = matplotlib.patches.Circle(xy=xy_center,
                                       radius=radius,
                                       edgecolor="k",
                                       facecolor="none")
    ax.add_patch(circle)

    # make the axis invisible
    for loc, spine in ax.spines.items():
        # use ax.spines.items() in Python 3
        spine.set_linewidth(0)

    # remove the ticks
    ax.set_xticks([])
    ax.set_yticks([])

    # Add some body parts. Hide unwanted parts by setting the zorder low
    # add two ears
    circle = matplotlib.patches.Ellipse(xy=[0, 2],
                                        width=0.5,
                                        height=1.0,
                                        angle=0,
                                        edgecolor="k",
                                        facecolor="w",
                                        zorder=0)
    ax.add_patch(circle)
    circle = matplotlib.patches.Ellipse(xy=[4, 2],
                                        width=0.5,
                                        height=1.0,
                                        angle=0,
                                        edgecolor="k",
                                        facecolor="w",
                                        zorder=0)
    ax.add_patch(circle)
    # add a nose
    xy = [[1.5, 3], [2, 4.5], [2.5, 3]]
    polygon = matplotlib.patches.Polygon(xy=xy, facecolor="w", zorder=0)
    ax.add_patch(polygon)

    # set axes limits
    ax.set_xlim(-0.5, 4.5)
    ax.set_ylim(-0.5, 4.5)

    plt.show()
Exemplo n.º 28
0
def deleteTournaments():
    """Removes all match records from the database."""

    Competition.deleteAll()