def plvAnalysis(epochs, Type):
    # phase locking analysis
    params = dict(Fs=16384, tapers=[1, 1], fpass=[400, 600], itc=0)
    # plv to TFS
    epochs = np.transpose(epochs,
                          (1, 0, 2))  # switching the first and second columns
    plv, f = mtplv(epochs, params)
    index = np.where(plv[topchans[0], ] == max(plv[topchans[0], ]))
    plv_max = max(plv[topchans[0], ])
    f_max = f[index]
    dimen = epochs.shape
    numtrials = dimen[1]
    return plv_max, f_max, numtrials
Beispiel #2
0
def plvAnalysis(epochs, Type):
    # phase locking analysis
    params = dict(Fs=16384, tapers=[1, 1], fpass=[400, 600], itc=0)
    # plv to TFS
    epochs = np.transpose(epochs,
                          (1, 0, 2))  # switching the first and second columns
    plv, f = mtplv(epochs, params)
    index = np.where(plv[topchans[0], ] == max(plv[topchans[0], ]))
    plv_max = max(plv[topchans[0], ])
    f_max = f[index]
    dimen = epochs.shape
    numtrials = dimen[1]
    # saving plvs
    np.savez(froot + '/plvs/' + subj + Type,
             plv=plv,
             plv_max=plv_max,
             f=f_max,
             numtrials=numtrials)
    # collecting individual plvs into array for all subjects
    return plv_max, f_max, numtrials
Beispiel #3
0
def plvAnalysis(epochs, Type):
    # phase locking analysis
    params = dict(Fs=16384, tapers=[1, 1], fpass=[400, 600], itc=0)
    # plv to TFS
    epochs = np.transpose(epochs,
                          (1, 0, 2))  # switching the first and second columns
    plv, f = mtplv(epochs, params)
    index = np.where(plv[31, ] == max(
        plv[31, ]))  # CHANGE AS NEEDED: 32st channel (Cz)
    plv_32 = plv[31, ]
    plv_32_max = plv_32[index]
    f_max = f[index]
    dimen = epochs.shape
    numtrials = dimen[1]
    # saving plvs
    dictMat = {
        "plv_32": plv_32_max,
        "f": f_max,
        "Fs": fs,
        "trialNum": numtrials
    }
    savemat('/media/agudemu/Storage/Data/EEG/FFR/plvs/' + subj + Type, dictMat)
    # collecting individual plvs into array for all subjects
    return plv_32_max, f_max, numtrials
Beispiel #4
0
def bdf2mat(froot, fs, Fs_new, hpf, t_stim, topchans, trial_name):
    full_raw, full_eves = EEGconcatenateFolder(froot,
                                               nchans=34,
                                               refchans=['EXG1', 'EXG2'],
                                               exclude=[],
                                               fs_new=Fs_new)

    event_id = {'Positive': 1}

    epochs = mne.Epochs(full_raw,
                        full_eves,
                        event_id,
                        tmin=t_stim[0],
                        tmax=t_stim[1],
                        reject_tmax=1.3,
                        picks=topchans,
                        reject=dict(eeg=100e-6))
    epochs.load_data()
    epochs_filtered = epochs.filter(hpf, None)

    pos_data = epochs_filtered.get_data()

    event_id = {'Negative': 2}

    epochs = mne.Epochs(full_raw,
                        full_eves,
                        event_id,
                        tmin=t_stim[0],
                        tmax=t_stim[1],
                        reject_tmax=1.3,
                        picks=topchans,
                        reject=dict(eeg=100e-6))
    epochs.load_data()
    epochs_filtered = epochs.filter(hpf, None)

    neg_data = epochs_filtered.get_data()

    neg_l = len(neg_data)
    pos_l = len(pos_data)

    length = (neg_l >= pos_l) * pos_l + (neg_l < pos_l) * neg_l

    tot_arr = np.zeros(2 * length, dtype=np.object)

    ind = 0

    for i in range(0, length):

        tot_arr[ind] = pos_data[i]
        tot_arr[ind + 1] = neg_data[i]
        ind = ind + 2

    os.chdir(froot)
    savemat(trial_name + '_Data_full.mat',
            {(trial_name + '_tot_arr'): tot_arr})

    ###########################PLOT SPECTROGRAM/PLV####################################

    x = np.add(neg_data[:length, :, :], pos_data[:length, :, :])

    params = dict(Fs=4e3, tapers=[1, 1], fpass=[0, 1000], itc=0)

    S_psd, N_psd, f_psd = mtspec(x, params)
    mt_plv, f_plv = mtplv(x, params)

    fig, ax = plt.subplots(num=2, figsize=(12, 8))
    ax.plot(f_psd, np.subtract(S_psd, N_psd))
    #ax.plot(f_psd, N_psd)
    ax.grid(color='k', linestyle='-', linewidth=1)
    ax.set_xlabel('Freq (Hz)', fontsize=18)
    ax.set_ylabel('PSD', fontsize=18)
    ax.set_xlim([70., 500.])
    ax.set_title('psd all')

    fig, ax = plt.subplots(num=1, figsize=(12, 8))
    ax.plot(f_plv, mt_plv)
    #ax.plot(f_psd, N_psd)
    ax.grid(color='k', linestyle='-', linewidth=1)
    ax.set_xlabel('Freq (Hz)', fontsize=18)
    ax.set_ylabel('PLV', fontsize=18)
    ax.set_xlim([70., 500.])
    ax.set_title('PLV all')
    # Calculate power, plv
    if not preEpoched:
        Fs = raw.info['sfreq']
        times = epochs.times

    #########################################################################
    # Fourier domain stuff
    pl.figure()
    params = dict(Fs=Fs, fpass=[5, 140], tapers=[1, 1], itc=0)
    for badname in epochs.info['bads']:
        bad_ind = epochs.info['ch_names'].index(badname)
        if bad_ind in mags:
            mags.remove(bad_ind)

    y = x[:, mags, :].transpose((1, 0, 2))
    plv, f = spectral.mtplv(y, params, verbose='DEBUG')
    pl.plot(f, plv.T, linewidth=2)
    pl.xlabel('Frequency (Hz)', fontsize=16)
    pl.ylabel('Intertrial PLV', fontsize=16)
    pl.title('MEG Magnetometers', fontsize=16)
    if SSSR:
        pl.xlim([70, 140])
    else:
        pl.xlim([15, 90])
    pl.show()
    figname_mag = subj + '_' + condstem + ssstag + '_mag-results.pdf'
    matname_mag = subj + '_' + condstem + ssstag + '_mag_results.mat'
    io.savemat(fpath + matname_mag, dict(f=f, plv=plv, chans=mags))
    pl.savefig(fpath + figname_mag)
    lout = mne.find_layout(epochs.info)
    pos = lout.pos[mags]
dat_epochs_5 = dat_epochs_5[:, 0:32, t1:t2].transpose(1, 0, 2)
dat_epochs_6 = dat_epochs_6[:, 0:32, t1:t2].transpose(1, 0, 2)
dat_epochs_7 = dat_epochs_7[:, 0:32, t1:t2].transpose(1, 0, 2)
dat_epochs_8 = dat_epochs_8[:, 0:32, t1:t2].transpose(1, 0, 2)
dat_epochs_9 = dat_epochs_9[:, 0:32, t1:t2].transpose(1, 0, 2)

params = dict()
params['Fs'] = fs
params['tapers'] = [2, 2 * 2 - 1]
params['fpass'] = [1, 300]
params['itc'] = 1

plt.figure()
plt.plot(dat_epochs_7[31, :, :].T)

plvtap_1, f = mtplv(dat_epochs_1, params)
plvtap_2, f = mtplv(dat_epochs_2, params)
plvtap_3, f = mtplv(dat_epochs_3, params)
plvtap_4, f = mtplv(dat_epochs_4, params)
plvtap_5, f = mtplv(dat_epochs_5, params)
plvtap_6, f = mtplv(dat_epochs_6, params)
plvtap_7, f = mtplv(dat_epochs_7, params)
plvtap_8, f = mtplv(dat_epochs_8, params)
plvtap_9, f = mtplv(dat_epochs_9, params)

np.max(plvtap_8[:, 75:85], axis=1)

plt.figure()
plt.plot(f, plvtap_1.T)
plt.title(labels[0])
Beispiel #7
0
fs = 16384
chop = 0.0e-3
chop2 = 22.e-3

plv_31s = np.zeros(len(subjectList))
plv_auds = np.zeros(len(subjectList))
trialNums_ref = np.zeros(len(subjectList))

for k, subj in enumerate(subjectList):
    data_masker_sum, numtrials_masker = subjectProcessing(froot, subj, [1, 2], fs)
    
    # phase locking analysis
    params = dict(Fs = 16384, tapers = [1, 1], fpass = [100, 2000], itc = 0)
    # plv to ABR (onset response)
    data_masker_sum = np.transpose(data_masker_sum, (1, 0, 2)) # switching the first and second columns
    plv, f = mtplv(data_masker_sum, params)
    plv_31 = plv[30,]
    plv_aud = plv[[4, 26, 25, 30, 31], :].mean(axis = 0)
    plv_31_avg = plv_31.mean()
    plv_aud_avg = plv_aud.mean()
    # saving plvs
    dictMat = {"plv_31": plv_31_avg, "plv_aud": plv_aud_avg, "Fs": fs, "trialNum": numtrials_masker}
    savemat(subj + '_ABR', dictMat)
    # collecting individual plvs into array for all subjects
    #plv_31s[k] = plv_31_avg
    #plv_auds[k] = plv_aud_avg
    #trialNums_ref[k] = numtrials_masker
#dictDataArray = {"subjects": subjectList, "plv_31s": plv_31s, "plv_auds": plv_auds, "trialNums_ref": trialNums_ref}
#savemat('plvs_ABR', dictDataArray)

#plv = spectral_connectivity(data_adpt_diff, method = 'plv')
Beispiel #8
0
                             exclude=read_data_params['exclude'])
    #    raw= mne.io.read_raw_edf(fileVar)
    #    raw.load_data()
    #    eves= mne.find_events(raw, shortest_event=1, mask=255)
    raw.filter(70, 1e3, phase='zero')
    epochs = mne.Epochs(raw,
                        eves,
                        1,
                        tmin=-0.1,
                        proj=False,
                        tmax=1.2,
                        baseline=(-0.1, 0.0),
                        reject=dict(eeg=200e-6))
    evoked = epochs.average()
    params = dict(Fs=raw.info['sfreq'], tapers=[1, 1], fpass=[70, 1000], itc=0)
    x = epochs.get_data()
    x = x[:, :32, :]
    x = x.transpose((1, 0, 2))
    plv, f = mtplv(x[30, :, :], params)

    if plotYes:
        filename = op.basename(fileVar)
        filename, _ = op.splitext(filename)
        fig, ax = plt.subplots(num=1, figsize=(12, 8))
        ax.plot(f, plv)
        ax.grid(color='k', linestyle='-', linewidth=1)
        ax.set_xlabel('Freq (Hz)', fontsize=18)
        ax.set_ylabel('PLV', fontsize=18)
        ax.set_xlim([70., 500.])
        ax.set_title(filename)
        plt.savefig(dir_dict['figOut'] + filename + '.png')
#    raw.filter(70, 1e3, phase='zero') # Not needed here as mtspec/mtplv have filter params
epochs = mne.Epochs(raw,
                    eves,
                    1,
                    tmin=-0.1,
                    proj=False,
                    tmax=1.2,
                    baseline=(-0.1, 0.0),
                    picks=31,
                    reject=dict(eeg=200e-6))
evoked = epochs.average()
params = dict(Fs=raw.info['sfreq'], tapers=[1, 1], fpass=[70, 1000], itc=0)
x = epochs.get_data()
x = x[:, :32, :]
x = x.transpose((1, 0, 2))
plv, f_plv = mtplv(x[30, :, :], params)
S_psd, N_psd, f_psd = mtspec(x[30, :, :], params)

if plotYes:
    fig, ax = plt.subplots(num=1, figsize=(12, 8))
    ax.plot(f_plv, plv)
    ax.grid(color='k', linestyle='-', linewidth=1)
    ax.set_xlabel('Freq (Hz)', fontsize=18)
    ax.set_ylabel('PLV', fontsize=18)
    ax.set_xlim([70., 500.])
    ax.set_title('plv all')
    if saveYes:
        plt.savefig(dir_dict['figOut'] + 'plv_all.png')

if plotYes:
    fig, ax = plt.subplots(num=2, figsize=(12, 8))
Beispiel #10
0
# target_mods[0,:] = np.sin(2*np.pi*6*t)
# target_mods[1,:] = np.sin(2*np.pi*40*t)

dat_epochs_1 = epochs_1.get_data()
dat_epochs_2 = epochs_2.get_data()

dat_epochs_1 = dat_epochs_1[0:200, 0:32, t1:t2].transpose(1, 0, 2)
dat_epochs_2 = dat_epochs_2[0:200, 0:32, t1:t2].transpose(1, 0, 2)

params = dict()
params['Fs'] = fs
params['tapers'] = [2, 2 * 2 - 1]
params['fpass'] = [1, 300]
params['itc'] = 0

plvtap_1, f = mtplv(dat_epochs_1, params)
plvtap_2, f = mtplv(dat_epochs_2, params)

np.max(plvtap_2[:, 870:900], axis=1)

fig, ax = plt.subplots(figsize=(5.5, 5))
fontsize = 15
ax.plot(f, plvtap_2[31, :], label='CORR', linewidth=2)
ax.plot(f, plvtap_1[31, :], label='ACORR', linewidth=2)
#plt.title('223 Hz',fontsize=fontsize)
ax.legend(fontsize=fontsize)
plt.xlabel('Frequency (Hz)', fontsize=fontsize, fontweight='bold')
#plt.ylabel('PLV',fontsize=fontsize)
plt.xlim((218, 228))
plt.xticks([218, 223, 228], fontsize=fontsize)
plt.yticks([0, 0.04, 0.08], fontsize=fontsize)
evoked_AM40.plot(titles='AM 40', picks=Aud_picks, xlim=[-0.1, 2.2])

t = epochs_AM40.times
t1 = np.where(t >= 0)[0][0]
t2 = np.where(t >= 2.0)[0][0]
t = t[t1:t2]
epoch40_dat = epochs_AM40.get_data()
epoch40_dat = epoch40_dat[:, 0:27, t1:t2].transpose(1, 0, 2)

params = dict()
params['Fs'] = epochs_AM40.info['sfreq']
params['tapers'] = [2, 2 * 2 - 1]
params['fpass'] = [1, 100]
params['itc'] = 0

plvtap_1, f = spectral.mtplv(epoch40_dat, params)
Aud_inds = np.flip(np.argsort(np.max(plvtap_1[:, 75:85], axis=1)))

Aud_chans = []
for ind in Aud_inds[0:9]:
    Aud_chans.append(epochs_AM40.ch_names[ind])

fig, ax = plt.subplots(figsize=(5, 3.3))
fontsize = 10
ax.plot(f, plvtap_1.T)
plt.ylabel('PLV', fontsize=fontsize)
plt.xlabel('Frequency (Hz)', fontsize=fontsize)
plt.xticks([0, 20, 40, 60, 80, 100], fontsize=fontsize)
plt.yticks([0.1, 0.2, 0.3], fontsize=fontsize)

fig, ax = plt.subplots(figsize=(5, 3.3))
    epoch_dat.append(epoch_dat_m)

AMf = AMf[2:]  #first 2 triggers mest up
epoch_dat = epoch_dat[2:]

params = dict()
params['Fs'] = epochs_all[0].info['sfreq']
params['tapers'] = [1, 2 * 1 - 1]
params['fpass'] = [1, 4000]
params['itc'] = 0

All_plvs = []
MaxAud_plvs = np.zeros((epoch_dat[0].shape[0], len(AMf)))
tmtf_plv = np.zeros((epoch_dat[0].shape[0], len(AMf)))
for m in np.arange(len(AMf)):
    plvtap, f = spectral.mtplv(epoch_dat[m], params)
    floc1 = np.where(f >= AMf[m] - 10)[0][0]
    floc2 = np.where(f >= AMf[m] + 10)[0][0]
    MaxAud_plvs[:,
                m] = np.flip(np.argsort(np.max(plvtap[:, floc1:floc2],
                                               axis=1)))
    tmtf_plv[:, m] = np.max(plvtap[:, floc1:floc2], axis=1)
    plt.figure()
    plt.plot(f, plvtap.T)
    plt.title(str(AMf[m]))
    #plt.xlim((0,AMf[m]*3))
    All_plvs.append(plvtap)

AMlabels = []
for AM in AMf:
    AMlabels.append(str(AM))
Beispiel #13
0
        params = dict(Fs=fs,
                      fpass=[5, 1000],
                      tapers=[1, 1],
                      Npairs=2000,
                      itc=1)

        Ntrials = x.shape[1]

        print 'Running Mean Spectrum Estimation'
        (S, N, f) = spectral.mtspec(x, params, verbose=True)

        print 'Running CPCA PLV Estimation'
        (cplv, f) = spectral.mtcpca(x, params, verbose=True)

        print 'Running channel by channel PLV Estimation'
        (plv, f) = spectral.mtplv(x, params, verbose=True)

        print 'Running CPCA Power Estimation'
        (cpow, f) = spectral.mtcspec(x, params, verbose=True)

        print 'Running raw spectrum estimation'
        (Sraw, f) = spectral.mtspecraw(x, params, verbose=True)

        # Saving Results
        res = dict(cpow=cpow,
                   plv=plv,
                   cplv=cplv,
                   Sraw=Sraw,
                   f=f,
                   S=S,
                   N=N,
Beispiel #14
0
                        else:
                            x = np.concatenate((x, xtemp), axis=1)
                    else:
                        continue
            else:
                RuntimeError('No BDF files found!!')

            # Average data
            goods = [1, 5, 6, 27, 28, 30, 31]
            if ear == 'L':
                refchan = 34
            else:
                refchan = 35

            y = x[goods, :, :].mean(axis=0) - x[refchan, :, :]

            params = dict(Fs=raw.info['sfreq'], tapers=[4, 7],
                          fpass=[1, 4000], itc=0)
            plv, f = mtplv(y, params)
            ph, f_ph = mtphase(y, params)

            tdresp = np.median(y, axis=0) * 1.0e6  # Just time domain average

            # Make dictionary and save
            mdict = dict(t=t, x=tdresp, f=f, f_ph=f_ph, ph=ph, plv=plv)
            savepath = froot + '/CentralGainResults/'
            savename = subj + name + '_CentralGain.mat'
            savemat(savepath + savename, mdict)

            pl.plot(f, plv)
Beispiel #15
0
     pl.subplot(413)
     pl.plot(t, diffAdpt, 'b')
     pl.xlim([0.01, 0.04])
     pl.ylim([-4e-7, 4e-7])
     
     pl.subplot(414)
     pl.plot(t, diffAdptHp, 'b')
     pl.xlim([0.01, 0.04])
     pl.ylim([-4e-7, 4e-7])
     
     # frequency component of polarity dependent adapted component
     diffAdpt_fft = np.fft.fft(diffAdptHp)
     magAdpt = np.abs(diffAdpt_fft)
     phase = np.angle(diffAdpt_fft)
     freq = np.linspace(0, fs, len(diffAdpt_fft))
     pl.figure(3)
     pl.plot(freq, magAdpt)
     
     # PLV calculation: between stimulus and evoked response
     fstim = 500
     stim = np.sin(2*np.pi*fstim*t)
     anl_stim = hilbert(stim)
     anl_resp = hilbert(diffAdptHp)
     pAgl_stim = np.angle(anl_stim)
     pAgl_resp = np.angle(anl_resp)
     plv = np.abs(np.sum(np.exp(1j*(pAgl_stim - pAgl_resp))))/len(pAgl_stim) # plv across time works for narrow-band 
     
     # PLV calculations across trials
     mtplv()
 else:
     RuntimeError("No bdf files found!")