Exemple #1
0
    a = QApplication([])
    ica = ICADialog(x, channels, fs, mode=mode)
    ica.exec_()
    a.exit()
    return ica.spatial, ica.topography

def runica2(x, fs, channels, names=('Right', 'Left'), mode='ica'):
    from PyQt5.QtWidgets import QApplication
    from pynfb.protocols.ssd.topomap_selector_ica import ICADialog
    a = QApplication([])
    res = []
    decomposition = None
    for n in names:
        print('*** Select component for condition: ' + n)
        ica = ICADialog(x, channels, fs, decomposition=decomposition, mode=mode)
        ica.exec_()
        res.append(np.array((ica.spatial, ica.topography)))
        decomposition = ica.decomposition
    a.exit()
    return res


if __name__ == '__main__':
    from mne.viz import plot_topomap
    from pynfb.inlets.montage import Montage
    from pynfb.generators import ch_names32
    montage = Montage(ch_names32)
    spatial, topo = runica(np.random.normal(size=(100000, 32)), 1000, montage.get_names(), mode='csp')
    plot_topomap(spatial, montage.get_pos())
    plot_topomap(topo, montage.get_pos())
Exemple #2
0
df['block_name'] = np.concatenate([[p]*len(d) for p, d in zip(p_names, data)])
df['block_number'] = np.concatenate([[j + 1]*len(d) for j, d in enumerate(data)])
df['alpha'] = np.dot(df[channels], spat)
df['alpha_env'] = df['alpha']*0
df['time'] = np.arange(len(df)) / fs
df['signal'] = np.concatenate(signal)



fig, axes = plt.subplots(1, 5)

eeg = fft_filter(df.loc[df['block_name'].isin(['Open', 'Close']), channels], fs, band)
topo = np.dot(np.dot(eeg.T, eeg), spat)

axes[2].set_xlabel('Spat. filt.')
plot_topomap(spat, montage.get_pos(), axes=axes[2], show=False)
axes[3].set_xlabel('Topography')
plot_topomap(topo, montage.get_pos(), axes=axes[3], show=False)

axes[0].plot(df.loc[df['block_number']==2, 'time'], fft_filter(df.loc[df['block_number']==2, 'alpha'], fs, (2, 100)))
axes[0].set_xlim(31, 32)
axes[0].set_xlabel('Time, s')
axes[0].set_ylabel('Voltage, $\mu V$')
#axes[2].plot(fft_filter(df.loc[df['block_number']==2, 'alpha'], fs, (1, 45)))

axes[1].plot(*welch(df.loc[df['block_name'].isin(['Close']), 'alpha'], fs, nperseg=fs*4))
axes[1].plot(*welch(df.loc[df['block_name'].isin(['Open']), 'alpha'], fs, nperseg=fs*4))
axes[1].legend(['Close', 'Open'])
axes[1].set_xlim(5, 15)
axes[1].set_xlabel('Freq., Hz')
axes[1].set_ylabel('PSD, $\mu V^2/Hz$')
Exemple #3
0
    a = QApplication([])
    ica = ICADialog(x, channels, fs, mode=mode)
    ica.exec_()
    a.exit()
    return ica.spatial, ica.topography

def runica2(x, fs, channels, names=('Right', 'Left'), mode='ica'):
    from PyQt5.QtWidgets import QApplication
    from pynfb.protocols.ssd.topomap_selector_ica import ICADialog
    a = QApplication([])
    res = []
    decomposition = None
    for n in names:
        print('*** Select component for condition: ' + n)
        ica = ICADialog(x, channels, fs, decomposition=decomposition, mode=mode)
        ica.exec_()
        res.append(np.array((ica.spatial, ica.topography)))
        decomposition = ica.decomposition
    a.exit()
    return res


if __name__ == '__main__':
    from mne.viz import plot_topomap
    from pynfb.inlets.montage import Montage
    from pynfb.generators import ch_names32
    montage = Montage(ch_names32)
    spatial, topo = runica(np.random.normal(size=(100000, 32)), 1000, montage.get_names(), mode='csp')
    plot_topomap(spatial, montage.get_pos())
    plot_topomap(topo, montage.get_pos())
Exemple #4
0
        'block_name=="{}"'.format(block_name))[channels],
                         fs,
                         nperseg=fs,
                         axis=0)
    alpha_pow = pxx[(freq > 8) & (freq < 14)].mean(0)
    alpha_pows.append(alpha_pow)
    #plt.plot(freq, pxx, label=block_name)
    #plt.plot(df.query('block_name=="{}"'.format(block_name))['C3'])
    # plot_topomap(alpha_pow, montage.get_pos(), axes=axes[j], show=False)
    # axes[j].set_title(block_name)

fig, axes = plt.subplots(1, 3)
ers_monitor = (alpha_pows[1] - alpha_pows[0]) / alpha_pows[0]
ers_vr = (alpha_pows[3] - alpha_pows[2]) / alpha_pows[2]
plot_topomap(ers_monitor,
             montage.get_pos(),
             axes=axes[0],
             show=False,
             vmin=-0.5,
             vmax=0.5)
plot_topomap(ers_vr,
             montage.get_pos(),
             axes=axes[1],
             show=False,
             vmin=-0.5,
             vmax=0.5)
plot_topomap(ers_vr - ers_monitor,
             montage.get_pos(),
             axes=axes[2],
             show=False,
             vmin=-0.5,
Exemple #5
0
for day in [1, 2]:
    mat = loadmat(
        r'C:\Users\Nikolai\Desktop\Liza_diplom_data\Liza_diplom_data\treatment\{0}\bci\{0}_{1}1.mat'
        .format(subj, day))
    channels = [ch[0] for ch in mat['chan_names'][0]]
    montage = Montage(channels)
    df = pd.DataFrame(data=mat['data_cur'].T, columns=channels)

    df['state'] = mat['states_cur'][0]
    print(df['state'].unique())

    df = df.loc[~get_outliers_mask(df[channels], iter_numb=10, std=3)]

    plt.plot(df[channels])
    plt.show()

    a = QtGui.QApplication([])
    #ica = ICADialog(np.concatenate([df.loc[df['state']==6, channels], df.loc[df['state']==1, channels]]), channels, fs, mode='csp')
    ica = ICADialog(df[channels], channels, fs, mode='ica')
    ica.exec_()
    print(ica.table.get_checked_rows())

    ind = ica.table.get_checked_rows()
    for k in ind:
        plot_topomap(ica.topographies[:, k], montage.get_pos())

    np.save(r'treatment\{0}d{1}_filters.npy'.format(subj, day),
            ica.unmixing_matrix)
    np.save(r'treatment\{0}d{1}_topographies.npy'.format(subj, day),
            ica.topographies)
    np.save(r'treatment\{0}d{1}_smr_ind.npy'.format(subj, day), ind)
Exemple #6
0
        channels = [ch[0] for ch in mat['chan_names'][0]]
        montage = Montage(channels)
        df = pd.DataFrame(data=mat['data_cur'].T, columns=channels)
        df['state'] = mat['states_cur'][0]
        df = df.loc[~get_outliers_mask(df[channels], iter_numb=10, std=3)]
        df['block_name'] = df['state'].apply(lambda x: {6: 'Rest', 1: 'Left', 2: 'Right'}[x])
        filters = np.load(r'treatment\{0}d{1}_filters.npy'.format(subj, day+1))
        topos = np.load(r'treatment\{0}d{1}_topographies.npy'.format(subj, day+1))
        ind = np.load(r'treatment\{0}d{1}_smr_ind.npy'.format(subj, day+1))
        for k in range(2):
            spat = filters[:, ind[k]]
            topo = topos[:, ind[k]]
            df['smr'] = np.dot(df[channels], spat)

            axes[day + 2*s, 0 + 3*k].set_xlabel('Spat. filt.')
            plot_topomap(spat, montage.get_pos(), axes=axes[day + 2*s, 0+ 3*k], show=False, contours=0)
            axes[day + 2*s, 1+ 3*k].set_xlabel('Topography')
            plot_topomap(topo, montage.get_pos(), axes=axes[day + 2*s, 1+ 3*k], show=False, contours=0)


            axes[day + 2*s, 2+ 3*k].plot(*welch(df.loc[df['block_name'].isin(['Rest']), 'smr']*1000000, fs, nperseg=fs*4))
            axes[day + 2*s, 2+ 3*k].plot(*welch(df.loc[df['block_name'].isin(['Left']), 'smr']*1000000, fs, nperseg=fs*4))
            axes[day + 2*s, 2+ 3*k].plot(*welch(df.loc[df['block_name'].isin(['Right']), 'smr']*1000000, fs, nperseg=fs*4))

            if day == 0 and s == 0 and k ==1:
                axes[day + 2*s, 2+ 3*k].legend(['Rest', 'Left', 'Right'])
            axes[day + 2*s, 2+ 3*k].set_xlim(2, 30)
            axes[day + 2*s, 2+ 3*k].set_xlabel('Freq., Hz')
            axes[day + 2*s, 2+ 3*k].set_ylabel('PSD, $\mu V^2/Hz$')

plt.show()
    csp = CSPDecomposition(montage.get_names(), FS,
                           subj_bands[dataset].tolist())
    b_numbers = df.query('block_name=="FB"')['block_number'].unique()
    x = np.concatenate([
        df.query('block_number=={}'.format(b))[channels[:-1]].values
        for b in b_numbers[1:]
    ])
    y = np.concatenate([
        np.zeros(sum(df['block_number'] == b)) + int(b < b_numbers[8])
        for b in b_numbers[1:]
    ])

    csp.fit(x, y)

    #plt.figure()
    plt.plot(x.dot(csp.filters[:, 1]))
    plt.plot(df['P4'])
    [
        plot_topomap(csp.topographies[:, j],
                     montage.get_pos(),
                     axes=axes[j_dataset, j],
                     show=False,
                     contours=0,
                     mask=np.array(channels[:-1]) == 'P4') for j in range(32)
    ]
    [
        axes[j_dataset, j].set_title('{:.1f}'.format(csp.scores[j]))
        for j in range(32)
    ]
    axes[j_dataset, 0].set_ylabel('{}\n{:.1f}'.format(fb_type, snr))
channels = [ch[0] for ch in mat['chan_names'][0]]
montage = Montage(channels)
df = pd.DataFrame(data=mat['data_cur'].T, columns=channels)

print(channels)
print(1000*np.isin(np.array(channels), ['Fp1', 'Fp2', 'F7', 'F8', 'Ft9', 'Ft10', 'T7', 'T8', 'Tp9', 'Tp10']))

df['state'] = mat['states_cur'][0]
print(df['state'].unique())

df = df.loc[~get_outliers_mask(df[channels], iter_numb=10, std=3)]

plt.plot(df[channels])
plt.show()

ica = CSPDecomposition(channels, fs, band)
df = df.loc[df.state.isin([6, 1])]
scores, filters, topos = ica.decompose(df[channels].as_matrix(), df['state']-1)
for k in range(len(topos)):
    plot_topomap(topos[:, k], montage.get_pos())
sources = fft_filter(np.dot(df[channels], filters), fs, band)
desyncs = sources[df.state == 6].std(0)/sources[df.state == 1].std(0)
smr_ind = np.argmax(desyncs)
df['SMR'+str(1)] = np.dot(df[channels], filters[:, smr_ind])
plot_topomap(filters[:, smr_ind], montage.get_pos())
plot_topomap(topos[:, smr_ind], montage.get_pos())
#df['SMR-env'+str(state)] = np.abs(hilbert(fft_filter(df[state+'SMR'], fs, [9, 13])))
plt.plot(df['SMR'+str(1)])
plt.plot(df['C3'])
plt.plot(df['C4'])
plt.show()
Exemple #9
0
def ch_names_to_2d_pos(list_of_ch_names, kind='standard_1005', azimuthal=True):
    montage = Montage(list_of_ch_names)
    pos = montage.get_pos()
    return pos
Exemple #10
0
day = 1
for day in [1, 2]:
    mat = loadmat(r'C:\Users\Nikolai\Desktop\Liza_diplom_data\Liza_diplom_data\treatment\{0}\bci\{0}_{1}1.mat'.format(subj, day))
    channels = [ch[0] for ch in mat['chan_names'][0]]
    montage = Montage(channels)
    df = pd.DataFrame(data=mat['data_cur'].T, columns=channels)


    df['state'] = mat['states_cur'][0]
    print(df['state'].unique())

    df = df.loc[~get_outliers_mask(df[channels], iter_numb=10, std=3)]

    plt.plot(df[channels])
    plt.show()


    a = QtGui.QApplication([])
    #ica = ICADialog(np.concatenate([df.loc[df['state']==6, channels], df.loc[df['state']==1, channels]]), channels, fs, mode='csp')
    ica = ICADialog(df[channels], channels, fs, mode='ica')
    ica.exec_()
    print(ica.table.get_checked_rows())


    ind = ica.table.get_checked_rows()
    for k in ind:
        plot_topomap(ica.topographies[:, k], montage.get_pos())

    np.save(r'treatment\{0}d{1}_filters.npy'.format(subj, day), ica.unmixing_matrix)
    np.save(r'treatment\{0}d{1}_topographies.npy'.format(subj, day), ica.topographies)
    np.save(r'treatment\{0}d{1}_smr_ind.npy'.format(subj, day), ind)
Exemple #11
0
    filt = decomposition.filters[:, k]
    go_data = X.loc[X.block_name == 'Go', eeg_channels].values
    st_data = X.loc[X.block_name == 'Stay', eeg_channels].values
    freq, go_spec = sg.welch(go_data.dot(filt), fs)
    freq, st_spec = sg.welch(st_data.dot(filt), fs)
    freq_slice = (freq > erd_band[0]) & (freq < erd_band[1])
    erds[k] = (st_spec[freq_slice].mean() -
               go_spec[freq_slice].mean()) / st_spec[freq_slice].mean()

# plot axes
for j, k in enumerate(np.argsort(erds)[::-1]):
    topo = decomposition.topographies[:, k]
    filt = decomposition.filters[:, k]

    ax = axes[j // n_cols, j % n_cols * 2]
    plot_topomap(topo, montage.get_pos(), axes=ax, show=False, contours=0)
    ax.set_title(str(k))
    ax.set_xlabel('{:.1f}%'.format(erds[k] * 100))

    go_data = X.loc[X.block_name == 'Go', eeg_channels].values
    st_data = X.loc[X.block_name == 'Stay', eeg_channels].values
    freq, go_spec = sg.welch(go_data.dot(filt), fs)
    freq, st_spec = sg.welch(st_data.dot(filt), fs)
    freq_slice = (freq > 3) & (freq < 40)

    ax = axes[j // n_cols, j % n_cols * 2 + 1]
    ax.plot(freq[freq_slice], go_spec[freq_slice])
    ax.plot(freq[freq_slice], st_spec[freq_slice])
    ax.fill_between(freq[freq_slice],
                    go_spec[freq_slice],
                    st_spec[freq_slice],