Exemplo n.º 1
0
def ca_tfr_baseline(data, list_pick, size):
    freqs = np.arange(1, 40, 1)
    n_cycles = freqs / 2
    first = tfr_multitaper(data[0],
                           freqs=freqs,
                           n_cycles=n_cycles,
                           use_fft=True,
                           return_itc=False,
                           average=True,
                           picks=list_pick)
    power_baseline = np.empty(
        [len(data),
         len(list_pick),
         len(freqs), first._data.shape[2]])
    for i in range(len(data)):
        power_baseline[i] = tfr_multitaper(data[i],
                                           freqs=freqs,
                                           n_cycles=n_cycles,
                                           use_fft=True,
                                           return_itc=False,
                                           average=True,
                                           picks=list_pick)._data
    baseline_pool = pool_into_one2(power_baseline)
    baseline_pool = bootstrapping2(baseline_pool, size)
    return baseline_pool
Exemplo n.º 2
0
Arquivo: viz.py Projeto: cbrnr/mnelab
def plot_erds(data, freqs, n_cycles, baseline, times=(None, None)):
    tfr = tfr_multitaper(data, freqs, n_cycles, average=False, return_itc=False)
    tfr.apply_baseline(baseline, mode="percent")
    tfr.crop(*times)

    figs = []
    n_rows, n_cols = _get_rows_cols(data.info["nchan"])
    widths = n_cols * [10] + [1]  # each map has width 10, each colorbar width 1

    for event in data.event_id:  # separate figures for each event ID
        fig, axes = plt.subplots(n_rows, n_cols + 1, gridspec_kw={"width_ratios": widths})
        tfr_avg = tfr[event].average()
        vmin, vmax = -1, 2  # default for ERDS maps
        cmap = center_cmap(plt.cm.RdBu, vmin, vmax)
        for ch, ax in enumerate(axes[..., :-1].flat):  # skip last column
            tfr_avg.plot([ch], vmin=vmin, vmax=vmax, cmap=(cmap, False), axes=ax,
                         colorbar=False, show=False)
            ax.set_title(data.ch_names[ch], fontsize=10)
            ax.axvline(0, linewidth=1, color="black", linestyle=":")
            ax.set(xlabel="t (s)", ylabel="f (Hz)")
            ax.label_outer()
        for ax in axes[..., -1].flat:  # colorbars in last column
            fig.colorbar(axes.flat[0].images[-1], cax=ax)

        fig.suptitle(f"ERDS ({event})")
        figs.append(fig)
    return figs
Exemplo n.º 3
0
def spectrogram_multitaper(dat, fs):

    dat = dat.reshape([1, 1, 2500])  # Canal, segmento, muestras
    n_epochs = len(dat)
    montage = mne.channels.read_montage('standard_1020', ch_names=['Fp1'])
    info = mne.create_info(['Fp1'], fs, montage=montage, ch_types='eeg')
    #raw=mne.io.RawArray(eegdata,info)
    events = np.array(
        [np.arange(n_epochs),
         np.ones(n_epochs),
         np.ones(n_epochs)]).T.astype(int)
    # Construct Epochs. #  eegdata:  epochs, channels, samples
    event_id, tmin, tmax = 1, 0, 5
    #eegdata=eegdata[np.newaxis,:,:]
    epochs = mne.EpochsArray(dat, info, None, 0.0, event_id)

    freqs = np.logspace(*np.log10([0.5, 50]), num=100)
    n_cycles = freqs / 1.  # different number of cycle per frequency
    time_bandwidth = 4.0
    #power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,return_itc=True, n_jobs=1)
    #power.plot([0], baseline=(-0.5, 0), mode='mean', title=power.ch_names[0],colorbar=True)
    power, itc = tfr_multitaper(epochs,
                                freqs=freqs,
                                n_cycles=n_cycles,
                                time_bandwidth=time_bandwidth,
                                return_itc=True,
                                n_jobs=1)
    #power.plot([0], baseline=(-0.5, 0), mode='mean', title=power.ch_names[0],colorbar=True)
    return power
Exemplo n.º 4
0
def itc(t, epochs, cond, channels):
    # channels in the format of [4, 26, 25, 30, 31], auditory channels
    # itc_data_mean_all = itc_data.mean(axis = 0) # CHANGE AS NEEDED: average across all channels 
    
    # computation of inter-trial-coherence (itc)
    freqs = np.arange(1., 50., 1.) # CHANGE AS NEEDED
    n_cycles = freqs/4. # time resolution is 0.25 s (1 s has "freq" number of cycles)
    time_bandwidth = 2.0 # number of taper = time_bandwidth product - 1 
    # usually n_cycles and time_bandwidth are fixed, which determines the frequency resolution 
    power, itc = tfr_multitaper(epochs, freqs = freqs,  n_cycles = n_cycles,
               time_bandwidth = time_bandwidth, return_itc = True, n_jobs = 4)
    # itc.plot([channel number], mode = 'mean')
    # itc.plot_topo(baseline = (-0.5, 0), mode = 'zscore') 
    itc_copy = itc.copy()
    itc_data = itc_copy.data
    # averaging across channels
    itc_data_mean = itc_data[channels, :, :].mean(axis = 0) 
    
    np.savez(froot+'/'+'itcCz' + '/'+subj+'_'+'itc'+str(cond), itc = itc_data, t = t, freqs = freqs, itc_avg = itc_data_mean); 
    # npzFile = np.load(fpath+'/'+'itc_power.npz'), npzFiles.files, npzFile['itc']
    # if bad channels were added manually, select good channels
    power_copy = power.copy()
    power_data = power_copy.data
    np.savez(froot+'/'+'powerCz' + '/'+subj+'_'+'power'+str(cond), power = power_data, t = t, freqs = freqs);
    
    plot_spectrogram(itc_data_mean, t, freqs, cond)
    pl.savefig(froot + '/ITCfigures/' + subj + '/' + subj + '_spectrogram_' + cond + '.png')
    
    return itc_data_mean
Exemplo n.º 5
0
def mt_hga_julien(epoch, f=100., n_cycles=12, time_bandwidth=4., **kw):
    """Extract high-gamma activity (HGA) around a central frequency.

    The HGA is extracted using the `mne.time_frequency.tfr_multitaper`
    function but the parameters provided by Julien Bastin.

    Parameters
    ----------
    epoch : mne.Epochs
        Instance of mne.Epochs
    f : float | 100.
        The central high-gamma frequency
    n_cycles : int | 12
        The number of cycles to use for the frequency resolution.
    time_bandwidth : float | 20.
        Time x (Full) Bandwidth product.
    karg : dict | {}
        Additional arguments are passed to the `tfr_multitaper` function.

    Returns
    -------
    tf : AverageTFR | EpochsTFR
        The averaged or single-trial HGA.
    """
    assert isinstance(f, (int, float))
    freq = np.array([f])
    tf = tfr_multitaper(epoch,
                        freq,
                        .2 * freq,
                        return_itc=False,
                        time_bandwidth=time_bandwidth,
                        **kw)
    return tf
Exemplo n.º 6
0
def cal_tfr2(data, index, mean, std, list_pick):
    freqs = np.arange(1, 40, 1)
    n_cycles = freqs / 2
    # power_pfcs_pretrials_intact = tfr_multitaper(ctrl_encmain_le[0], freqs=freqs, n_cycles=n_cycles, use_fft=True,return_itc=False, average=True,picks=["P1","P3","P5","P7","P9","PO3","PO7","O"])
    data[index] = data[index].resample(sfreq=256,
                                       npad=1715,
                                       pad='constant',
                                       window='hann')
    power_data = tfr_multitaper(data[index],
                                freqs=freqs,
                                n_cycles=n_cycles,
                                use_fft=True,
                                return_itc=False,
                                average=True,
                                picks=list_pick)

    power_mean = np.empty([8, 2])

    for ch in range(power_data.data.shape[0]):
        for fr in range(power_data.data.shape[1]):
            power_data.data[ch, fr] = np.divide(
                np.subtract(power_data.data[ch, fr, :], mean[ch, fr]), std[ch,
                                                                           fr])

    return power_data
Exemplo n.º 7
0
def erds_plot(epochs):
    # compute ERDS maps ###########################################################
    # idx = np.array(list(range(7, 11)) + list(range(12, 15)) + list(range(17, 21)) + list(range(32, 41)))
    # chans = np.array(epochs.ch_names)[idx].tolist()
    epochs.pick_channels(["C3","Cz","C4"])


    event_ids = epochs.event_id
    tmin, tmax = -1, 4
    freqs = np.arange(60, 90, 1)  # frequencies from 2-35Hz
    n_cycles = freqs  # use constant t/f resolution
    vmin, vmax = -1, 1.5  # set min and max ERDS values in plot
    # vmin, vmax = -0.5, 0.5  # set min and max ERDS values in plot
    baseline = [-1, 0.3]  # baseline interval (in s)
    cmap = center_cmap(plt.cm.RdBu, vmin, vmax)  # zero maps to white
    kwargs = dict(n_permutations=100, step_down_p=0.05, seed=1,
                  buffer_size=None, out_type='mask')  # for cluster test

    # Run TF decomposition overall epochs
    tfr = tfr_multitaper(epochs, freqs=freqs, n_cycles=n_cycles,
                         use_fft=True, return_itc=False, average=False,
                         decim=2)
    tfr.crop(tmin, tmax)
    tfr.apply_baseline(baseline, mode="percent")
    for event in event_ids:
        # select desired epochs for visualization
        tfr_ev = tfr[event]
        fig, axes = plt.subplots(1, 4, figsize=(12, 4),
                                 gridspec_kw={"width_ratios": [10, 10, 10, 1]})
        for ch, ax in enumerate(axes[:-1]):  # for each channel
            # positive clusters
            _, c1, p1, _ = pcluster_test(tfr_ev.data[:, ch, ...], tail=1, **kwargs)
            # negative clusters
            _, c2, p2, _ = pcluster_test(tfr_ev.data[:, ch, ...], tail=-1,
                                         **kwargs)

            # note that we keep clusters with p <= 0.05 from the combined clusters
            # of two independent tests; in this example, we do not correct for
            # these two comparisons
            c = np.stack(c1 + c2, axis=2)  # combined clusters
            p = np.concatenate((p1, p2))  # combined p-values
            mask = c[..., p <= 0.05].any(axis=-1)

            # plot TFR (ERDS map with masking)
            tfr_ev.average().plot([ch], vmin=vmin, vmax=vmax, cmap=(cmap, False),
                                  axes=ax, colorbar=False, show=False, mask=mask,
                                  mask_style="mask")

            ax.set_title(epochs.ch_names[ch], fontsize=10)
            ax.axvline(0, linewidth=1, color="black", linestyle=":")  # event
            if not ax.is_first_col():
                ax.set_ylabel("")
                ax.set_yticklabels("")
        fig.colorbar(axes[0].images[-1], cax=axes[-1])
        fig.suptitle("ERDS ({})".format(event))
        fig.show()
def multitaper_analysis(epochs):
    """

    Parameters
    ----------
    epochs : list of epochs

    Returns
    -------
    result : numpy array
        The result of the multitaper analysis.

    """
    frequencies = np.arange(6., 90., 2.)
    n_cycles = frequencies / 2.
    time_bandwidth = 4  # Same time-smoothing as (1), 7 tapers.
    power, plv = tfr_multitaper(epochs, freqs=frequencies, n_cycles=n_cycles,
                                time_bandwidth=time_bandwidth, return_itc=True)

    return power, plv
Exemplo n.º 9
0
def extract_frequencies(subject, freqs, decim):
    """Filter TNT epochs using multitaper.

    Input
    -----
    * subject: str
        Subject reference.

    freqs: array like
        Frequency range to extract.

    decim: int
        Decimation parameter

    Output
    ------

    Save -tfr.h5 in the '/All_frequencies_multitaper' directory

    """
    n_cycles = freqs / 2

    # TNT
    tnt, tnt_df = data_tnt(subject)

    this_tfr = tfr_multitaper(tnt,
                              freqs,
                              n_cycles=n_cycles,
                              n_jobs=6,
                              decim=decim,
                              average=False,
                              return_itc=False)

    this_tfr = this_tfr.crop(-0.5, 3.0)

    this_tfr = this_tfr.apply_baseline(mode='percent', baseline=(-0.5, 0))

    np.save(path + 'TNT/All_frequencies_multitaper/' + subject + '.npy',
            this_tfr._data)

    tnt_df.to_csv(path + 'TNT/All_frequencies_multitaper/' + subject + '.txt')
Exemplo n.º 10
0
def compute_erds(epoch_trains, triggers, trf_window):
    """
    Compute and display the Event-Related desynchronisations/synchronisations
    """
    freqs = np.arange(2, 40, 1)  # frequencies from 2-40Hz
    n_cycles = freqs / 2  # use constant t/f resolution

    # Run TF decomposition overall epochs
    tfr = {}
    for ev in triggers:
        tfr[ev] = tfr_multitaper(epoch_trains[ev],
                                 freqs=freqs,
                                 n_cycles=n_cycles,
                                 use_fft=True,
                                 return_itc=False,
                                 average=True,
                                 decim=2)
        tfr[ev].crop(trf_window[0], trf_window[1])

    #Plotting
    plot_erds(tfr, epoch_trains, triggers)
Exemplo n.º 11
0
    def __init__(self,
                 epochs,
                 freqs,
                 n_cycles,
                 method='multitaper',
                 time_bandwidth=4.,
                 n_fft=512,
                 width=1,
                 picks=None):
        """
        Initialize the class with an instance of EpochsTFR corresponding
        to the method
        """
        self.picks = picks
        self.cmap = 'inferno'
        self.info = epochs.info

        if method == 'multitaper':
            from mne.time_frequency import tfr_multitaper
            self.tfr, _ = tfr_multitaper(epochs,
                                         freqs,
                                         n_cycles,
                                         time_bandwidth=time_bandwidth,
                                         picks=self.picks)

        if method == 'morlet':
            from mne.time_frequency import tfr_morlet
            self.tfr, _ = tfr_morlet(epochs, freqs, n_cycles, picks=self.picks)

        if method == 'stockwell':
            from mne.time_frequency import tfr_stockwell
            # The stockwell function does not handle picks like the two other
            # ones ...
            picked_ch_names = [epochs.info['ch_names'][i] for i in self.picks]
            picked = epochs.copy().pick_channels(picked_ch_names)
            self.tfr = tfr_stockwell(picked,
                                     fmin=freqs[0],
                                     fmax=freqs[-1],
                                     n_fft=n_fft,
                                     width=width)
def get_events(fif,f,validation_windowsize=2,l_threshold=0.4,h_threshold=3.4,channelList = None):

    raw = mne.io.read_raw_fif(fif,preload=True)
    anno = pd.read_csv(f)
    model = Filter_based_and_thresholding(l_freq=8,h_freq=20)
    
    if channelList == None:
        channelList = ['F3','F4','C3','C4','O1','O2']
    else:
        channelList = raw.ch_names[:32]
    model.channelList = channelList
    model.get_raw(raw,)
    model.get_epochs(resample=256)
    model.get_annotation(anno)
    model.validation_windowsize = 3
    model.syn_channels = int(len(channelList)/2)
    model.find_onset_duration(0.4,3.4)
    model.sleep_stage_check()
    model.make_manuanl_label()
    event_interval = model.epochs.events[:,0] / 1000
    event_interval = np.vstack([event_interval, event_interval + 3]).T
    sleep_stage_interval = np.array(model.stage_on_off)
    row_idx = [sum([getOverlap(interval,temp) for temp in sleep_stage_interval]) != 0 for interval in event_interval]
    labels = model.manual_labels[row_idx]
    
    data = model.epochs.get_data()[row_idx]
    info = model.epochs.info
    events = model.epochs.events[row_idx]
    events[:,0] = events[:,0] / model.epochs.info['sfreq']
    events[:,-1] = labels
    event_id = {'spindle':1,'non spindle':0}
    epochs_ = mne.EpochsArray(data,info,events=events,tmin=0,event_id=event_id,)
    freqs = np.arange(8,21,1)
    n_cycles = freqs / 2.
    time_bandwidth = 2.0  # Least possible frequency-smoothing (1 taper)
    power = tfr_multitaper(epochs_,freqs,n_cycles=n_cycles,time_bandwidth=time_bandwidth,return_itc=False,average=False,)
    power.info['event'] = events
    del raw
    return power,epochs_,model
Exemplo n.º 13
0
    def __init__(self,
                 epochs,
                 freqs,
                 n_cycles,
                 method='multitaper',
                 time_bandwidth=4.,
                 n_fft=512,
                 width=1,
                 picks=None):
        """
        Initialize the class with an instance of EpochsTFR corresponding
        to the method
        """
        from backend.util import eeg_to_montage

        self.cmap = 'jet'
        self.info = epochs.info

        if picks is not None:
            self.picks = picks
        else:
            self.picks = list(range(0, len(epochs.info['ch_names'])))
        for bad in epochs.info['bads']:
            try:
                bad_pick = epochs.info['ch_names'].index(bad)
                self.picks.remove(bad_pick)
            except Exception as e:
                print(e)

        montage = eeg_to_montage(epochs)
        if montage is not None:
            # First we create variable head_pos for a correct plotting
            self.pos = montage.get_pos2d()
            scale = 0.85 / (self.pos.max(axis=0) - self.pos.min(axis=0))
            center = 0.5 * (self.pos.max(axis=0) + self.pos.min(axis=0))
            self.head_pos = {'scale': scale, 'center': center}

            # Handling of possible channels without any known coordinates
            no_coord_channel = False
            try:
                names = montage.ch_names
                indices = [
                    names.index(epochs.info['ch_names'][i]) for i in self.picks
                ]
                self.pos = self.pos[indices, :]
            except Exception as e:
                print(e)
                no_coord_channel = True

            # If there is not as much positions as the number of Channels
            # we have to eliminate some channels from the data of topomaps
            if no_coord_channel:
                from mne.channels import read_montage
                from numpy import array

                index = 0
                self.pos = []  # positions
                # index in the self.data of channels with coordinates
                self.with_coord = []

                for i in self.picks:
                    ch_name = epochs.info['ch_names'][i]
                    try:
                        ch_montage = read_montage(montage.kind,
                                                  ch_names=[ch_name])
                        coord = ch_montage.get_pos2d()
                        self.pos.append(coord[0])
                        self.with_coord.append(index)
                    except Exception as e:
                        print(e)
                    index += 1
                self.pos = array(self.pos)

            else:
                self.with_coord = [i for i in range(len(self.picks))]

        else:  # If there is no montage available
            self.head_pos = None
            self.with_coord = []

        if method == 'multitaper':
            from mne.time_frequency import tfr_multitaper
            self.tfr, _ = tfr_multitaper(epochs,
                                         freqs,
                                         n_cycles,
                                         time_bandwidth=time_bandwidth,
                                         picks=self.picks)

        if method == 'morlet':
            from mne.time_frequency import tfr_morlet
            self.tfr, _ = tfr_morlet(epochs, freqs, n_cycles, picks=self.picks)

        if method == 'stockwell':
            from mne.time_frequency import tfr_stockwell
            # The stockwell function does not handle picks like the two other
            # ones ...
            picked_ch_names = [epochs.info['ch_names'][i] for i in self.picks]
            picked = epochs.copy().pick_channels(picked_ch_names)
            self.tfr = tfr_stockwell(picked,
                                     fmin=freqs[0],
                                     fmax=freqs[-1],
                                     n_fft=n_fft,
                                     width=width)
Exemplo n.º 14
0
                count  = 2
            else:
                #Stack trials
                X_data = np.vstack((X_data, X_cond))
        
        # In[]
        # Calculated TFR for a particular clase in a particular condition for the selected subjects
        print("Calculated " + TFR_method + " for Class: " + Classes +" in Condition: " + Cond )
        print("with the information of Subjects: " + str(N_S_list ))
        
        # Create a subject with all trials
        X_S._data = X_data
        
        if TFR_method == "Multitaper":
            power , itc = tfr_multitaper(X_S, freqs=freqs, n_cycles=n_cycles, use_fft=use_fft,
                                    return_itc=return_itc, decim=decim, n_jobs=n_jobs,
                                    average=average,picks=picks)

            if save_bool:
                Ensure_dir(save_dir)
                file_name = save_dir + TFR_method + "_" + Cond + "_" + Classes + "_power-tfr.h5"
                power.save(fname = file_name, overwrite = overwrite)
                if return_itc: 
                    file_name = save_dir + TFR_method + "_" + Cond + "_" + Classes + "_itc-tfr.h5"
                    itc.save(fname = file_name, overwrite = overwrite)
            
            
        elif TFR_method == "Morlet": 
            power , itc = tfr_morlet(X_S, freqs=freqs, n_cycles=n_cycles, use_fft=use_fft,
                                    return_itc=return_itc, decim=decim, n_jobs=n_jobs,
                                    average=average,zero_mean=zero_mean,picks=picks)
# First we'll use the multitaper method for calculating the TFR.
# This creates several orthogonal tapering windows in the TFR estimation,
# which reduces variance. We'll also show some of the parameters that can be
# tweaked (e.g., ``time_bandwidth``) that will result in different multitaper
# properties, and thus a different TFR. You can trade time resolution or
# frequency resolution or both in order to get a reduction in variance.

freqs = np.arange(5., 100., 3.)
vmin, vmax = -3., 3.  # Define our color limits.

###############################################################################
# **(1) Least smoothing (most variance/background fluctuations).**

n_cycles = freqs / 2.
time_bandwidth = 2.0  # Least possible frequency-smoothing (1 taper)
power = tfr_multitaper(epochs, freqs=freqs, n_cycles=n_cycles,
                       time_bandwidth=time_bandwidth, return_itc=False)
# Plot results. Baseline correct based on first 100 ms.
power.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax,
           title='Sim: Least smoothing, most variance')

###############################################################################
# **(2) Less frequency smoothing, more time smoothing.**

n_cycles = freqs  # Increase time-window length to 1 second.
time_bandwidth = 4.0  # Same frequency-smoothing as (1) 3 tapers.
power = tfr_multitaper(epochs, freqs=freqs, n_cycles=n_cycles,
                       time_bandwidth=time_bandwidth, return_itc=False)
# Plot results. Baseline correct based on first 100 ms.
power.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax,
           title='Sim: Less frequency smoothing, more time smoothing')
Exemplo n.º 16
0
    explanation='2 Channels (C3, C4) Merged \nPSD of All Stages',
    picks='csd',
    saving_directory=saving_directory)

#Multi-taper Parameters
freqs = np.arange(0.1, 48, 0.1)  # frequencies from 2-35Hz
n_cycles = freqs  # use constant t/f resolution
vmin, vmax = -1, 1.5  # set min and max ERDS values in plot
n_cycles = freqs * 2  # use constant t/f resolution

#========= 6 Channels ==========
fig, ax = plt.subplots(3, 1,
                       figsize=(12, 4))  #gridspec_kw={"width_ratios": [5, 5]})

merged_icacsd_6channels.load_data()
power = tfr_multitaper(merged_icacsd_6channels['Lucid'], freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=False, time_bandwidth = 8.0, decim=2,\
                       average=True)
power.apply_baseline([-0.2, 0], mode='mean')
avg_power = np.mean(power._data, 0)
power._data = np.expand_dims(avg_power,
                             axis=0)  #expand dimension from axis=0 [1,x,y]
power.plot([0], vmin=vmin, vmax=vmax, axes=ax[0], colorbar=False, show=False)

power = tfr_multitaper(merged_icacsd_6channels['REM'], freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=False, time_bandwidth = 8.0, decim=2,\
                       average=True)
power.apply_baseline([-0.2, 0], mode='mean')
avg_power = np.mean(power._data, 0)
power._data = np.expand_dims(avg_power,
                             axis=0)  #expand dimension from axis=0 [1,x,y]
power.plot([0], vmin=vmin, vmax=vmax, axes=ax[1], colorbar=False, show=False)

power = tfr_multitaper(merged_icacsd_6channels['Wake'], freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=False, time_bandwidth = 8.0, decim=2,\
model.sleep_stage_check()
model.make_manuanl_label()
event_interval = model.epochs.events[:,0] / 1000
event_interval = np.vstack([event_interval, event_interval + 3]).T
sleep_stage_interval = np.array(model.stage_on_off)
row_idx = [sum([getOverlap(interval,temp) for temp in sleep_stage_interval]) != 0 for interval in event_interval]
labels = model.manual_labels[row_idx]

data = model.epochs.get_data()[row_idx]
info = model.epochs.info
events = model.epochs.events[row_idx]
events[:,0] = events[:,0] / model.epochs.info['sfreq']
events[:,-1] = labels
event_id = {'spindle':1,'non spindle':0}
epochs_ = mne.EpochsArray(data,info,events=events,tmin=0,event_id=event_id,)
power = tfr_multitaper(model.epochs,freqs,n_cycles=n_cycles,time_bandwidth=time_bandwidth,return_itc=False,average=False,)
data = power.data


power = tfr_multitaper(epochs_,freqs,n_cycles=n_cycles,time_bandwidth=time_bandwidth,return_itc=False,average=False,)
data_ = power.data

labels_ = epochs_.events[:,-1]
labels = model.manual_labels
clf = Pipeline([('vectorizer',Vectorizer()),
                ('scaler',StandardScaler()),
                ('est',exported_pipeline)])
#fpr,tpr=[],[];AUC=[];confM=[];sensitivity=[];specificity=[]
#for train, test in cv.split(data_,labels_):
#    C = np.array(list(dict(Counter(labels_[train])).values()))
#    ratio_threshold = C.min() / C.sum()
Exemplo n.º 18
0
epochs = mne.Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    picks=picks,
                    baseline=baseline,
                    reject=dict(grad=4000e-13))

###############################################################################
# Calculate power

freqs = np.arange(5., 50., 2.)  # define frequencies of interest
n_cycles = freqs / 2.  # 0.5 second time windows for all frequencies

# Choose time x (full) bandwidth product
time_bandwidth = 4.0  # With 0.5 s time windows, this gives 8 Hz smoothing

power, itc = tfr_multitaper(epochs,
                            freqs=freqs,
                            n_cycles=n_cycles,
                            use_fft=True,
                            time_bandwidth=time_bandwidth,
                            return_itc=True,
                            n_jobs=1)

# Plot results (with baseline correction only for power)
power.plot([0], baseline=(-0.5, 0), mode='mean', title='MEG 1142 - Power')
itc.plot([0], title='MEG 1142 - Intertrial Coherence')
Exemplo n.º 19
0
def mt_hga_split(epoch,
                 time_bandwidth=4.,
                 hga_start=60,
                 hga_end=160,
                 n_hga=None,
                 norm='1/f',
                 **kw):
    """Extract high-gamma activity (HGA) using a splited method.

    Step by step procedure :

        * Define a lineary spaced frequency vector (e.g. [60, 160]])
        * Extract each sub-gamma band
        * Normalize each sub-band
        * Take the mean across sub-bands to obtain the final HG

    Parameters
    ----------
    epoch : mne.Epochs
        Instance of mne.Epochs
    time_bandwidth : float | 4.
        Time x (Full) Bandwidth product.
    hga_start : float | 60.
        Lower boundary of the gamma band
    hga_end : float | 160.
        Higher boundary of the gamma band
    n_hga : int | None
        Number of HG sub-bands between (hga_start, hga_end)
    norm : {'1/f', 'constant'} | None
        Normalization method before taking the mean across sub-gamma bands
    kw : dict | {}
        Additional arguments are passed to the `tfr_multitaper` function.

    Returns
    -------
    tf : AverageTFR | EpochsTFR
        The averaged or single-trial HGA.
    """
    need_average = kw.get('average', False)
    if 'average' in kw.keys(): del kw['average']  # noqa
    # Define a linear frequency vector
    if not isinstance(n_hga, int):
        n_hga = int(np.round((hga_end - hga_start) / 10))
    freqs = np.linspace(hga_start, hga_end, n_hga, endpoint=True)
    n_cycles = .2 * freqs
    # Compute multitaper
    tf = tfr_multitaper(epoch,
                        freqs,
                        n_cycles,
                        return_itc=False,
                        time_bandwidth=time_bandwidth,
                        average=False,
                        **kw)
    # Get the data and apply a 1/f normalization
    tf_data = tf.data
    if norm == '1/f':
        tf_data *= freqs.reshape(1, 1, -1, 1)
    elif norm == 'constant':
        tf_data -= tf_data.mean(3, keepdims=True)
    # Mean the data across sub-gamma bands
    tf_data = tf_data.mean(2, keepdims=True)
    freqs = np.array([tf.freqs.mean()])
    # Rebuilt the EpochsTFR
    etf = EpochsTFR(tf.info, tf_data, tf.times, freqs)
    return etf.average() if need_average else etf
Exemplo n.º 20
0
                         eves, [
                             5,
                         ],
                         tmin=-0.5,
                         proj=True,
                         tmax=6.0,
                         baseline=(-0.5, 0.0),
                         reject=dict(eeg=200e-6))

freqs = np.arange(2, 80, 2)  # define frequencies of interest
n_cycles = freqs / float(5)  # different number of cycle per frequency
n_cycles[freqs < 5] = 1
# epochs.subtract_evoked()
powerL, itcL = tfr_multitaper(epochsL,
                              freqs=freqs,
                              n_cycles=n_cycles,
                              time_bandwidth=2.0,
                              n_jobs=-1)
powerL.data = 20 * np.log10(powerL.data)
powerL.plot_topo(dB=False, baseline=(-0.5, 0.))

powerR, itcR = tfr_multitaper(epochsR,
                              freqs=freqs,
                              n_cycles=n_cycles,
                              time_bandwidth=2.0,
                              n_jobs=-1)
powerR.data = 20 * np.log10(powerR.data)
powerL.plot_topo(dB=False, baseline=(-0.5, 0.))

powerLR = powerR - powerL
powerLR.plot_topo(dB=False, baseline=(-0.5, 0.))
Exemplo n.º 21
0
# epoch data ##################################################################
tmin, tmax = -1, 4  # define epochs around events (in s)
event_ids = dict(hands=2, feet=3)  # map event IDs to tasks

epochs = mne.Epochs(raw, events, event_ids, tmin - 0.5, tmax + 0.5,
                    picks=picks, baseline=None, preload=True)

# compute ERDS maps ###########################################################
freqs = np.arange(2, 36, 1)  # frequencies from 2-35Hz
n_cycles = freqs  # use constant t/f resolution
vmin, vmax = -1, 1.5  # set min and max ERDS values in plot
cmap = center_cmap(plt.cm.RdBu, vmin, vmax)  # zero maps to white

for event in event_ids:
    power = tfr_multitaper(epochs[event], freqs=freqs, n_cycles=n_cycles,
                           use_fft=True, return_itc=False, decim=2)
    power.crop(tmin, tmax)

    fig, ax = plt.subplots(1, 4, figsize=(12, 4),
                           gridspec_kw={"width_ratios": [10, 10, 10, 1]})
    for i in range(3):
        power.plot([i], baseline=[-1, 0], mode="percent", vmin=vmin, vmax=vmax,
                   cmap=(cmap, False), axes=ax[i], colorbar=False, show=False)
        ax[i].set_title(epochs.ch_names[i], fontsize=10)
        ax[i].axvline(0, linewidth=1, color="black", linestyle=":")  # event
        if i > 0:
            ax[i].set_ylabel("")
            ax[i].set_yticklabels("")
    fig.colorbar(ax[0].collections[0], cax=ax[-1])
    fig.suptitle("ERDS ({})".format(event))
    fig.show()
pickle.dump([raw_data, fake_epochs, new_periods], open('Lucireta_lucidneighbour_interval','wb'))    
#%% =============== FILD Load Data for Spectrogram Analysis ============
from mne.time_frequency import tfr_multitaper

os.chdir('/home/caghangir/Desktop/PhD/Lucid Dream EEG/Extracted Dataset/Lucid Neighbour Interval')
FILD_raw_data, FILD_epoch, FILD_periods = pickle.load(open('FILD_lucidneighbour_interval','rb'))

temp_epoch = FILD_epoch[0]

#Multi-taper Parameters
freqs = np.arange(2, 48, 0.1)  # frequencies from 2-35Hz
n_cycles = freqs  # use constant t/f resolution
vmin, vmax = -1, 1.5  # set min and max ERDS values in plot
n_cycles = freqs * 2  # use constant t/f resolution

power = tfr_multitaper(temp_epoch, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=False, time_bandwidth = 8.0, decim=2,\
                       average=True)
baseline_period = 5 #second
beginner = power.times[0]
finish = power.times[-1]
states = lucidity_period_fild[0][1]
difference = states[1] - states[0]

power.apply_baseline([beginner, beginner+20], mode='mean')

avg_power = np.mean(power._data, 0)
power._data = np.expand_dims(avg_power, axis=0) #expand dimension from axis=0 [1,x,y]

power._data = np.absolute(power._data) ** (1/2.)
power._data = 10 * np.log10(power._data)
# power._data = power._data[power._data < 0] = 0
#%% =============== Erlacher Load Data for Spectrogram Analysis ============
Exemplo n.º 23
0
Arquivo: erp.py Projeto: pchholak/MNE
# set up pick list: MEG - bad channels
picks = mne.pick_types(raw.info,
                       meg=True,
                       eeg=False,
                       stim=False,
                       eog=False,
                       exclude='bads')

# Read epochs
epochs = mne.Epochs(raw,
                    events,
                    event_id,
                    tmin - 2,
                    tmax,
                    picks=picks,
                    baseline=(tmin, tmax))

# Compute ERDS maps
freqs = np.arange(5, 8, .1)
n_cycles = freqs  # use constant t/f resolution

power = tfr_multitaper(epochs,
                       freqs=freqs,
                       n_cycles=n_cycles,
                       return_itc=False)

#ch = range(2, 306, 3)
ch = [68]
power.plot(ch, baseline=(-1., 0.), mode='mean')
Exemplo n.º 24
0
                            event_id=condlist,
                            tmin=-0.4,
                            proj=True,
                            tmax=1.0,
                            baseline=(-0.2, 0.0),
                            reject=dict(grad=5000e-13, mag=5e-12))
        evokeds += [
            epochs.average(),
        ]
        fstem = subj + ssstag + '_' + para
        if doTFR:
            freqs = np.arange(5., 70., 1.)
            n_cycles = freqs * 0.2
            power, itc = tfr_multitaper(epochs,
                                        freqs,
                                        n_cycles,
                                        time_bandwidth=2.0,
                                        n_jobs=-1)
            fname_pow = fstem + '_pow_' + condstem + '-tfr.h5'
            fname_itc = fstem + '_itc_' + condstem + '-tfr.h5'
            power.save(respath + fname_pow, overwrite=True)
            itc.save(respath + fname_itc, overwrite=True)

        if saveEpochs:
            fname_epochs = fstem + '_' + condstem + '-epo.fif'
            epochs.save(respath + fname_epochs)

    # Now save overall onset N100
    epochs = mne.Epochs(raw,
                        eves,
                        event_id=condlists,
epochs = mne.Epochs(raw, events, event_ids, tmin - 0.5, tmax + 0.5,
                    picks=picks, baseline=None, preload=True)

# compute ERDS maps ###########################################################
freqs = np.arange(2, 36, 1)  # frequencies from 2-35Hz
n_cycles = freqs  # use constant t/f resolution
vmin, vmax = -1, 1.5  # set min and max ERDS values in plot
baseline = [-1, 0]  # baseline interval (in s)
cmap = center_cmap(plt.cm.RdBu, vmin, vmax)  # zero maps to white
kwargs = dict(n_permutations=100, step_down_p=0.05, seed=1,
              buffer_size=None)  # for cluster test

# Run TF decomposition overall epochs
tfr = tfr_multitaper(epochs, freqs=freqs, n_cycles=n_cycles,
                     use_fft=True, return_itc=False, average=False,
                     decim=2)
tfr.crop(tmin, tmax)
tfr.apply_baseline(baseline, mode="percent")
for event in event_ids:
    # select desired epochs for visualization
    tfr_ev = tfr[event]
    fig, axes = plt.subplots(1, 4, figsize=(12, 4),
                             gridspec_kw={"width_ratios": [10, 10, 10, 1]})
    for ch, ax in enumerate(axes[:-1]):  # for each channel
        # positive clusters
        _, c1, p1, _ = pcluster_test(tfr_ev.data[:, ch, ...], tail=1, **kwargs)
        # negative clusters
        _, c2, p2, _ = pcluster_test(tfr_ev.data[:, ch, ...], tail=-1,
                                     **kwargs)
Exemplo n.º 26
0
                    baseline=None,
                    preload=True)

# compute ERDS maps ###########################################################
freqs = np.arange(2, 36, 1)  # frequencies from 2-35Hz
n_cycles = freqs  # use constant t/f resolution
vmin, vmax = -1, 1.5  # set min and max ERDS values in plot
baseline = [-1, 0]  # baseline interval (in s)
cmap = center_cmap(plt.cm.RdBu, vmin, vmax)  # zero maps to white
kwargs = dict(n_permutations=100, step_down_p=0.05, seed=1)  # for cluster test

for event in event_ids:
    tfr = tfr_multitaper(epochs[event],
                         freqs=freqs,
                         n_cycles=n_cycles,
                         use_fft=True,
                         return_itc=False,
                         average=False,
                         decim=2)
    tfr.crop(tmin, tmax)
    tfr.apply_baseline(baseline, mode="percent")

    fig, axes = plt.subplots(1,
                             4,
                             figsize=(12, 4),
                             gridspec_kw={"width_ratios": [10, 10, 10, 1]})
    for ch, ax in enumerate(axes[:-1]):  # for each channel
        # positive clusters
        _, c1, p1, _ = pcluster_test(tfr.data[:, ch, ...], tail=1, **kwargs)
        # negative clusters
        _, c2, p2, _ = pcluster_test(tfr.data[:, ch, ...], tail=-1, **kwargs)
Exemplo n.º 27
0
# Stuff to reject
reject = dict(eog=150e-6)

# Frequency Analysis
freqs = numpy.arange(2, 32)  # define frequencies of interest
n_cycles = freqs / 2.0  # 0.5 second time windows for all frequencies

# Choose time x (full) bandwidth product
time_bandwidth = 4.0  # With 0.5 s time windows, this gives 8 Hz smoothing


# Extract epochs
# for x in range(0, 3):
event_id = dict(aud_l=121, aud_r=1000)  # event trigger and conditions
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=baseline, preload=False, reject=reject)
power = tfr_multitaper(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, time_bandwidth=time_bandwidth, return_itc=False, n_jobs=1)
# mne.viz.plot_epochs(epochs, picks=None, scalings=None, n_epochs=20, n_channels=61, title=None, show=True, block=False)
evoked = epochs['aud_l'].average()
mne.viz.plot_evoked(evoked, picks=None, exclude='bads', unit=True, show=False, ylim=None, xlim='tight', proj=False, hline=None, units=None, scalings=None, titles=None, axes = ax[0], gfp=False)
# plot(evoked.data)
# draw()
# plt.pause(0.7)
mne.viz.plot_evoked_image(evoked, picks=None, exclude='bads', unit=True, show=False, clim=None, xlim='tight', proj=False, units=None, scalings=None, titles=None, axes=ax[1], cmap='RdBu_r')

power.plot([0], baseline=(-0.5, 0), mode='mean', axes = ax[2])
show()

# evoked.plot(axes = ax)
# draw()
# ax.cla()
# plt.pause(0.5)
Exemplo n.º 28
0
#first_event_sample = 100
#event_id = dict(sin50hz=1)
#for k in range(n_epochs):
#    events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz']
#
#epochs = EpochsArray(data=data, info=info, events=events, event_id=event_id,
#                     reject=reject)

freqs = np.arange(5., 100., 3.)
vmin, vmax = -3., 3.  # Define our color limits.

n_cycles = freqs / 2.
time_bandwidth = 2.0  # Least possible frequency-smoothing (1 taper)
power = tfr_multitaper(epochs,
                       freqs=freqs,
                       n_cycles=n_cycles,
                       time_bandwidth=time_bandwidth,
                       return_itc=False)
# Plot results. Baseline correct based on first 100 ms.
power.plot([0],
           baseline=(0., 0.1),
           mode='mean',
           vmin=vmin,
           vmax=vmax,
           title='Sim: Least smoothing, most variance')

#freqs = np.arange(0, 20., 2.)
#vmin, vmax = -300., 300.  # Define our color limits.
#
#
##
    raw_fif.filter(8,20,) # filer between 8 - 20 Hz, leaving most of the parameters default
    sfreq = raw_fif.info['sfreq'] # get sampling frequency
    info = raw_fif.info
    info.normalize_proj()
    raw_fif.info = info
    info = raw_fif.info
    
    df = pd.read_csv(f) # read the annotation table
    idx_row = df['Annotation'].apply(spindle) # find the spindle rows
    df_spindle = df[idx_row] # only take the spindle rows and form a data frame
    df_spindle = df_spindle.drop_duplicates(['Onset'])
    events_={'start':(df_spindle['Onset'].values - 0.5)*sfreq,
             'empty':np.zeros(df_spindle.shape[0],dtype=int),
             'code':np.ones(df_spindle.shape[0],dtype=int)}
    events_=pd.DataFrame(events_,dtype=int)
    events_=events_.drop_duplicates(['start'])
    events_=events_[['start','empty','code']].values.astype(int)
    epochs_spindle = mne.Epochs(raw_fif,events_,tmin=0,tmax=2,event_id=1,baseline=None,detrend=0,preload=True)   
    del raw_fif # save memory
    
    freqs = np.arange(8,21,1)
    n_cycles = freqs / 2.
    time_bandwidth = 2.0  # Least possible frequency-smoothing (1 taper)
    power = tfr_multitaper(epochs_spindle,freqs,n_cycles=n_cycles,time_bandwidth=time_bandwidth,return_itc=False,average=False,)
    power.save(saving_dir + 'sub%s_%s'%(sub,day) + '-tfr.h5',overwrite=True)
    del power