Exemplo n.º 1
0
def epochs_specgram(subject_epochs, subject, specgram_avg, tfr):
    frequencies = np.arange(4, 30, 2)
    
    for electrode in ch_names:
        if electrode not in specgram_avg:
            specgram_avg[electrode] = {}
            tfr[electrode]   = {}

        for code, epochs in subject_epochs.items():
            if code not in specgram_avg[electrode]:
                specgram_avg[electrode][code] = []
                tfr[electrode][code] = []
            electrode_epochs = epochs.copy().pick_channels([electrode]).get_data()
            electrode_epochs = electrode_epochs.reshape(electrode_epochs.shape[0], electrode_epochs.shape[2]).squeeze()
                        
            f, t, Sxx = signal.spectrogram(electrode_epochs, fs = epochs.info['sfreq'], nperseg=512, noverlap = 384)  
            Sxx_mean = np.log(Sxx.mean(axis = 0))
            specgram_avg[electrode][code].append(Sxx_mean)
            
            
            tfr_epochs = tfr_morlet(epochs.copy().pick_channels([electrode]), frequencies, n_cycles=4.,decim = 5, 
                        average=False, return_itc=False, n_jobs=1)
            
            tfr[electrode][code].append(tfr_epochs)

    return specgram_avg, f,t, tfr
Exemplo n.º 2
0
def plot_evoked_freq(epochs, name='name', figs=[]):
    print('plotting evoked on frequency domain')
    # Plot overall psd
    f = epochs.plot_psd(fmax=50, spatial_colors=True, average=True, show=False)
    f.set_figheight(2.5)
    f.suptitle(name)
    figs.append(f)

    # Plot psd topomaps for Delta, Theta, Alpha, Beta, Gamma band
    f = epochs.plot_psd_topomap(normalize=True, show=False)
    f.set_figheight(2.5)
    f.suptitle(name)
    figs.append(f)

    # Calculate tfr_morlet power and itc
    power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles,
                            use_fft=True, return_itc=True,
                            n_jobs=n_jobs, verbose=1)

    # Plot wavelet power
    timefreqs = ((0.3, 1), (0.4, 1), (0.5, 1))
    f = power.plot_joint(baseline=(-0.2, 0), mode='mean', timefreqs=timefreqs,
                         show=False)
    f.suptitle(name)
    figs.append(f)

    return figs
Exemplo n.º 3
0
def power_(epochs):
    epochs = epochs
    freqs = np.arange(4, 30, 1) 
    n_cycles = freqs / 2
    power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,
                        return_itc=True, decim=1, n_jobs=1,picks=['POz','Oz','O1','O2'])
    return power
Exemplo n.º 4
0
def compute_power(epochs: Epochs, config: dict) -> AverageTFR:
    """
    Computes Time-Frequency Representation (TFR) using complex Morlet wavelets
    averaged over epochs. Power is written to an HDF5 file.
    Parameters
    ----------
    epochs
    config
    """
    fmin = config["morlet"]["fmin"]
    fmax = config["morlet"]["fmax"]
    step = config["morlet"]["step"]
    freqs = np.logspace(*np.log10([fmin, fmax]), num=step)
    n_cycles = freqs / 2.0

    power = tfr_morlet(
        epochs.average() if config["is_evoked"] else epochs.copy(),
        freqs=freqs,
        n_cycles=n_cycles,
        use_fft=True,
        return_itc=False,
        decim=config["morlet"]["decim"],
        average=True,
        n_jobs=-1,
    )

    return power
Exemplo n.º 5
0
def test_csd_morlet():
    """Test computing cross-spectral density using Morlet wavelets."""
    epochs = _generate_coherence_data()
    sfreq = epochs.info['sfreq']

    # Compute CSDs by a variety of methods
    freqs = [10, 15, 22]
    n_cycles = [20, 30, 44]
    times = [(None, None), (1, 9)]
    as_arrays = [False, True]
    parameters = product(times, as_arrays)
    for (tmin, tmax), as_array in parameters:
        if as_array:
            csd = csd_array_morlet(epochs.get_data(),
                                   sfreq,
                                   freqs,
                                   t0=epochs.tmin,
                                   n_cycles=n_cycles,
                                   tmin=tmin,
                                   tmax=tmax,
                                   ch_names=epochs.ch_names)
        else:
            csd = csd_morlet(epochs,
                             frequencies=freqs,
                             n_cycles=n_cycles,
                             tmin=tmin,
                             tmax=tmax)
        if tmin is None and tmax is None:
            assert csd.tmin == 0 and csd.tmax == 9.98
        else:
            assert csd.tmin == tmin and csd.tmax == tmax
        _test_csd_matrix(csd)

    # CSD diagonals should contain PSD
    tfr = tfr_morlet(epochs, freqs, n_cycles, return_itc=False)
    power = np.mean(tfr.data, 2)
    csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles)
    assert_allclose(csd._data[[0, 3, 5]] * sfreq, power)

    # Test using plain convolution instead of FFT
    csd = csd_morlet(epochs,
                     frequencies=freqs,
                     n_cycles=n_cycles,
                     use_fft=False)
    assert_allclose(csd._data[[0, 3, 5]] * sfreq, power)

    # Test baselining warning
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        epochs_nobase = epochs.copy()
        epochs_nobase.baseline = None
        epochs_nobase.info['highpass'] = 0
        csd = csd_morlet(epochs_nobase, frequencies=[10], decim=20)
    assert len(w) == 1
Exemplo n.º 6
0
def mne_wavelet_plot(epochs):
    freqs = np.logspace(*np.log10([2, 42]), num=15)

    n_cycles = freqs / 4.  # different number of cycle per frequency
    power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,
                            return_itc=True, decim=3, n_jobs=1)

    channel_picks = 0

    # epochs.plot_image(picks=[channel_picks], evoked=True, combine='mean')

    power.plot(picks=[channel_picks], baseline=(0, 0.05), mode='logratio', title=power.ch_names[channel_picks])
Exemplo n.º 7
0
def compute_tfr(epochsAllMove,epoch_times,freqs = np.arange(6, 123, 3),crop_val=0.5,decim=30):
    #Time-frequency analysis (from https://plot.ly/ipython-notebooks/mne-tutorial/ -> Time-frequency analysis)
    n_cycles = freqs / 4.  # different number of cycle per frequency

    #Compute power for move trials
    print('Computing power...')
    power = tfr_morlet(epochsAllMove, freqs=freqs, n_cycles=n_cycles, use_fft=False,
                       return_itc=False, decim=decim, n_jobs=1,average=False)
    print('Power computation complete!')
    power.crop(epoch_times[0]+crop_val, epoch_times[1]-crop_val) #trim epoch to avoid edge effects
    power.data = 10*np.log10(power.data) #convert to log scale
    power.data[np.isinf(power.data)]=0 #set infinite values to 0
    return power
Exemplo n.º 8
0
def power_(epochs):
    epochs = epochs
    freqs = np.arange(4, 30, 1)
    n_cycles = freqs / 2.
    power = tfr_morlet(epochs,
                       freqs=freqs,
                       n_cycles=n_cycles,
                       use_fft=True,
                       return_itc=False,
                       decim=5,
                       n_jobs=1,
                       average=False,
                       picks=['Pz', 'Cz', 'Fz'])
    return power
Exemplo n.º 9
0
def write_TF(Name_begin, patient_f, patient_idx):
    channel_df = pd.read_csv(os.path.join(PATH, patient_f)[:-9] +
                             "_channels.tsv",
                             sep="\t",
                             encoding='unicode_escape')

    dat = io.read_raw_edf(os.path.join(PATH, patient_f))
    ttl_idx = [idx for idx, ch in enumerate(dat.ch_names)
               if "POL DC10" in ch][0]
    mov_bin = preprocess_mov(dat.get_data()[ttl_idx, :])

    idx_ecog = []
    for ch in channel_df["name"]:
        PATH_save = 'C:\\Users\\ICN_admin\\Dropbox (Brain Modulation Lab)\\Shared Lab Folders\\CRCNS\\PD_ButtonPress\\derivatives\\'+\
                        "sub_"+subjects[patient_idx] +"_ch_"+ch[4:]+'.npy'
        if os.path.exists(PATH_save) is True:
            continue
        if ch.startswith(Name_begin) is False or \
                channel_df.iloc[channel_df[channel_df.name == ch].index[0]]["status"] != "good":
            continue
        idx_ecog = [
            idx for idx, ch_ in enumerate(dat.ch_names) if ch_.startswith(ch)
        ][0]
        info = create_info(ch_names=[ch[4:]], sfreq=2000, ch_types='ecog')
        epochs = calc_epochs(dat.get_data()[idx_ecog, :],
                             mov_bin,
                             info,
                             threshold=0.5,
                             epoch_lim=2500 * 2)
        freqs = np.arange(7, 200, 1)
        power = tfr_morlet(epochs,
                           freqs=freqs,
                           n_cycles=5,
                           return_itc=False,
                           zero_mean=True,
                           picks=0)
        dat_ = power.data[
            0, :, 1000:
            9000]  # cut off borders due to Wavelet transform; 500ms till 4s post movement
        dat_z = stats.zscore(dat_, axis=1)
        #plt.imshow(dat_z, aspect='auto', extent=[-2,2,200,0])#, cmap='hot')
        #cbar = plt.colorbar()
        #cbar.set_label('Normalized spectral power [VAR]')
        #plt.clim(-1.5,1.5)
        #plt.gca().invert_yaxis()
        #plt.title(Name_begin[4:] + " " + subjects[patient_idx])
        #plt.show()
        np.save(PATH_save, dat_z)
def compute_tfr(epochsAllMove,eventType,epoch_times,freqs = np.arange(6, 123, 3),crop_val=0.5,decim=30):
    """
    Computes spectrogram using Morlet wavelets (log-scaled).
    """
    n_cycles = freqs / 4.  # different number of cycle per frequency

    #Compute power for move trials
    print('Computing power...')
    power = tfr_morlet(epochsAllMove[eventType], freqs=freqs, n_cycles=n_cycles, use_fft=False,
                       return_itc=False, decim=decim, n_jobs=1,average=False)
    print('Power computation complete!')
    power.crop(epoch_times[0]+crop_val, epoch_times[1]-crop_val) #trim epoch to avoid edge effects
    power.data = 10*np.log10(power.data+\
                             np.finfo(np.float32).eps) #convert to log scale
    power.data[np.isinf(power.data)]=0 #set infinite values to 0
    return power
Exemplo n.º 11
0
def test_csd_morlet():
    """Test computing cross-spectral density using Morlet wavelets."""
    epochs = _generate_coherence_data()
    sfreq = epochs.info['sfreq']

    # Compute CSDs by a variety of methods
    freqs = [10, 15, 22]
    n_cycles = [20, 30, 44]
    times = [(None, None), (1, 9)]
    as_arrays = [False, True]
    parameters = product(times, as_arrays)
    for (tmin, tmax), as_array in parameters:
        if as_array:
            csd = csd_array_morlet(epochs.get_data(), sfreq, freqs,
                                   t0=epochs.tmin, n_cycles=n_cycles,
                                   tmin=tmin, tmax=tmax,
                                   ch_names=epochs.ch_names)
        else:
            csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles,
                             tmin=tmin, tmax=tmax)
        if tmin is None and tmax is None:
            assert csd.tmin == 0 and csd.tmax == 9.98
        else:
            assert csd.tmin == tmin and csd.tmax == tmax
        _test_csd_matrix(csd)

    # CSD diagonals should contain PSD
    tfr = tfr_morlet(epochs, freqs, n_cycles, return_itc=False)
    power = np.mean(tfr.data, 2)
    csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles)
    assert_allclose(csd._data[[0, 3, 5]] * sfreq, power)

    # Test using plain convolution instead of FFT
    csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles,
                     use_fft=False)
    assert_allclose(csd._data[[0, 3, 5]] * sfreq, power)

    # Test baselining warning
    epochs_nobase = epochs.copy()
    epochs_nobase.baseline = None
    epochs_nobase.info['highpass'] = 0
    with pytest.warns(RuntimeWarning, match='baseline'):
        csd = csd_morlet(epochs_nobase, frequencies=[10], decim=20)
def compute_morlet(epochs, fmin, fmax, n_bins):
    EOG_chs = ['E1', 'E8', 'E25', 'E32', 'E126', 'E127']
    Unwanted = ['E43', 'E48', 'E49', 'E128', 'E113', 'E120', 'E125', 'E119']
    All_chs = epochs.info['ch_names'][0:129]
    EEG_chs = [ele for ele in All_chs if ele not in Unwanted]
    EEG_chs = [ele for ele in EEG_chs if ele not in EOG_chs]
    freqs = np.logspace(*np.log10([fmin, fmax]), num=n_bins)
    n_cycles = freqs / 2.  # different number of cycle per frequency

    morlet = tfr_morlet(epochs,
                        freqs=freqs,
                        n_cycles=n_cycles,
                        use_fft=False,
                        return_itc=False,
                        decim=3,
                        n_jobs=1,
                        picks=EEG_chs,
                        average=False)

    return morlet
Exemplo n.º 13
0
def test_get_inst_data():
    """Test _get_inst_data."""
    raw = read_raw_fif(fname_raw)
    raw.crop(tmax=1.)
    assert_array_equal(_get_inst_data(raw), raw._data)
    raw.pick_channels(raw.ch_names[:2])

    epochs = make_fixed_length_epochs(raw, 0.5)
    assert_array_equal(_get_inst_data(epochs), epochs._data)

    evoked = epochs.average()
    assert_array_equal(_get_inst_data(evoked), evoked.data)

    evoked.crop(tmax=0.1)
    picks = list(range(2))
    freqs = [50., 55.]
    n_cycles = 3
    tfr = tfr_morlet(evoked, freqs, n_cycles, return_itc=False, picks=picks)
    assert_array_equal(_get_inst_data(tfr), tfr.data)

    pytest.raises(TypeError, _get_inst_data, 'foo')
Exemplo n.º 14
0
def test_get_inst_data():
    """Test _get_inst_data"""
    raw = read_raw_fif(fname_raw, add_eeg_ref=False)
    raw.crop(tmax=1.)
    assert_equal(_get_inst_data(raw), raw._data)
    raw.pick_channels(raw.ch_names[:2])

    epochs = _segment_raw(raw, 0.5)
    assert_equal(_get_inst_data(epochs), epochs._data)

    evoked = epochs.average()
    assert_equal(_get_inst_data(evoked), evoked.data)

    evoked.crop(tmax=0.1)
    picks = list(range(2))
    freqs = np.array([50., 55.])
    n_cycles = 3
    tfr = tfr_morlet(evoked, freqs, n_cycles, return_itc=False, picks=picks)
    assert_equal(_get_inst_data(tfr), tfr.data)

    assert_raises(TypeError, _get_inst_data, 'foo')
Exemplo n.º 15
0
def test_get_inst_data():
    """Test _get_inst_data."""
    raw = read_raw_fif(fname_raw)
    raw.crop(tmax=1.)
    assert_equal(_get_inst_data(raw), raw._data)
    raw.pick_channels(raw.ch_names[:2])

    epochs = _segment_raw(raw, 0.5)
    assert_equal(_get_inst_data(epochs), epochs._data)

    evoked = epochs.average()
    assert_equal(_get_inst_data(evoked), evoked.data)

    evoked.crop(tmax=0.1)
    picks = list(range(2))
    freqs = np.array([50., 55.])
    n_cycles = 3
    tfr = tfr_morlet(evoked, freqs, n_cycles, return_itc=False, picks=picks)
    assert_equal(_get_inst_data(tfr), tfr.data)

    assert_raises(TypeError, _get_inst_data, 'foo')
Exemplo n.º 16
0
def morlet_analysis(epochs, n_cycles=4):
    """

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

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

    """
    frequencies = np.arange(6., 30., 2.)
    # n_cycles = frequencies / 2.

    power, plv = tfr_morlet(epochs, freqs=frequencies, n_cycles=n_cycles,
                            return_itc=True,
                            verbose=True)

    return power, plv
Exemplo n.º 17
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)
Exemplo n.º 18
0
def _compute_tfr_morlet(epo_fpath, freqs, n_cycles):

    assert os.path.exists(epo_fpath)

    epochs = read_epochs(epo_fpath)

    power = tfr_morlet(epochs,
                       freqs=freqs,
                       n_cycles=n_cycles,
                       use_fft=True,
                       return_itc=False,
                       decim=3,
                       n_jobs=1)

    data_path, basename, ext = split_filename(epo_fpath)

    tfr_fname = os.path.abspath(basename + '-tfr.h5')
    print((power.data.shape))
    print(('*** save {} ***'.format(tfr_fname)))
    write_tfrs(tfr_fname, power, overwrite=True)

    return tfr_fname
Exemplo n.º 19
0
    def plotTFMaps(self):
        if self.data:
            if self.n_cycles == 'scale':
                number = self.freqs / 2.
            else:
                number = self.n_cycles

            power = tfr_morlet(self.data,
                               freqs=self.freqs,
                               n_cycles=number,
                               return_itc=False)

            if (self.b1.isChecked() == True):
                power.plot([self.channel],
                           baseline=(self.baselineA, self.baselineB),
                           mode=self.mode,
                           title=power.ch_names[self.channel])

            if (self.b2.isChecked() == True):
                power.plot_topo(baseline=(self.baselineA, self.baselineB),
                                mode=self.mode,
                                title='Average power')
Exemplo n.º 20
0
def EEG_to_TF_mne(dataset):
    ch_names = [str(i) for i in range(global_vars.get('eeg_chans'))]
    ch_types = ['eeg' for i in range(global_vars.get('eeg_chans'))]
    info = mne.create_info(ch_names=ch_names,
                           sfreq=global_vars.get('frequency'),
                           ch_types=ch_types)
    freqs = np.arange(1, global_vars.get('max_tf_freq'),
                      1)  # frequencies of interest
    n_cycles = freqs / 4.  # different number of cycle per frequency
    for segment in dataset.keys():
        TF_list = []
        epochs = mne.EpochsArray(dataset[segment].X,
                                 info=info,
                                 baseline=(0, 0.5))
        for idx in range(len(dataset[segment].X)):
            power = tfr_morlet(epochs[idx],
                               freqs=freqs,
                               n_cycles=n_cycles,
                               return_itc=False,
                               decim=3,
                               n_jobs=1)
            TF_list.append(power.data.astype(np.float32))
        dataset[segment].X = np.stack(TF_list, axis=0)
Exemplo n.º 21
0
def tf_single_trial(epochs, log):
    # Window of interest
    fmin = 8
    fmax = 12
    tmin = -0.1
    tmax = 0.1

    # TF parameters
    freqs = np.arange(fmin, fmax, 0.1)  # frequencies of interest
    n_cycles = 4.

    power = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, average=False,
                       return_itc=False, n_jobs=n_jobs)

    power.apply_baseline(baseline=(-0.95, -0.75), mode='mean')

    for ix_r, r in enumerate(sorted(rois)):
        roi = rois[r]
        pow_subj_c = power.copy()
        roi_pow = pow_subj_c.pick_channels(roi)
        tr_pow = np.mean(roi_pow.crop(tmin, tmax).data, axis=(1, 2, 3))
        log.loc[epochs.selection, r] = tr_pow
    return log
Exemplo n.º 22
0
def test_tfr():
    with tempfile.TemporaryDirectory() as dirpath:

        sample_folder = mne.datasets.sample.data_path()
        sample_fname = os.path.join(sample_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')

        name = 'TestTFR'
        cond_name = 'cond_1'
        tfr_dir = os.path.join(dirpath, 'tfr')

        raw = mne.io.read_raw_fif(sample_fname, preload=True)
        events = find_events(raw, id_=1)
        freqs = [8, 9, 10, 11, 12]
        n_cycles = 2
        mne_tfr = tfr_morlet(mne.Epochs(raw, events),
                             freqs,
                             n_cycles,
                             return_itc=False)

        # As meggie-style tfrs can be based on multiple mne TFR objects,
        # content is dict-type. conditions-param is added to avoid accidents
        # in content loading..
        content = {cond_name: mne_tfr}
        params = {'conditions': [cond_name]}

        # Create meggie-TFR object
        # and save it to tfr directory
        tfr = TFR(name, tfr_dir, params, content=content)
        ensure_folders([tfr_dir])
        tfr.save_content()

        # Creating meggie-TFR object with same name and folder should allow
        # accessing the saved content.
        loaded_tfr = TFR(name, tfr_dir, params)

        assert (loaded_tfr.content[cond_name].nave == 72)
Exemplo n.º 23
0
def get_power(file = 'data/caroltrio_eeg_2019.06.20_23.57.27.edf', show = False):
  '''
  Get power according to time and frequency

  Parameters
  ----------
  file : EEG file
  
  Return 
  ------
  raw : raw cleaned of eog arteact
  power, times 
  '''



  ncycle_dict = {'data/caroltrio_eeg_2019.06.20_23.57.27.edf':50, 'data/caroltrio_eeg_2019.03.16_14.07.07.edf': 20}
  raw = import_file(file)
  raw = run_preprocessing_eog(raw, show = show)

  epochs = creating_epochs(raw, duration = raw.times[-1])
  freqs = np.arange(2,30, 4)
  n_cycles = freqs*ncycle_dict[file] # different number of cycle per frequency
  power, _ = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,
                          return_itc=True, decim=3, n_jobs=1)


  power.plot([4],dB = True,tmin = 60, title=power.ch_names[0])#, vmin = -50)
  if file == 'data/caroltrio_eeg_2019.06.20_23.57.27.edf':
      power.crop(tmax = 1467)
  
  else :
    power.crop(tmax = 583)
  
  times = np.linspace(0, power.times[-1], num = power.data[0].shape[1])

  return raw, power, times
Exemplo n.º 24
0
def procesamiento(raw, picks, canales):
    n_cycles = 5
    freqs = np.arange(8, 34, 3) 
    events = mne.find_events(raw, stim_channel = 'STI 014')
    event_id = dict(aud_l=1) 
    tmin = 0
    tmax = 0.5 
    baseline = (None, 0)
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=baseline, preload=False)
    power = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, return_itc=False, decim=3, n_jobs=1)
    promedio = power.data[0]
    for i in range(1, canales):
        promedio = promedio + power.data[i]
    promedio = promedio / canales
    promedio1 = promedio[0]
    for i in range(1, 8):
        promedio1 = promedio1 + promedio[i]
    promedio1 = promedio1 / 8
    promedio2 = 0
    for i in range(0, len(promedio1)):
        promedio2 = promedio2 + promedio1[i]
    promedio2 = promedio2 / len(promedio[0])
    print 'Potencia promedio: ', promedio2
    return power
Exemplo n.º 25
0
axs[1].set_xlabel('Frequency (Hz)')

axs[0].legend()
axs[1].legend()

plt.show();

# With this visualization we can clearly see distinct peaks at 30hz and 20hz in the PSD, corresponding to the frequency of the visual stimulation. The peaks are much larger at the POz electrode, but still visible at TP9 and TP10

####################################################################################################
# Spectrogram
# -----------

# We can also look for SSVEPs in the spectrogram, which uses color to represent the power of frequencies in the EEG signal over time

frequencies = np.logspace(1, 1.75, 60)
tfr, itc = tfr_morlet(epochs['30 Hz'], freqs=frequencies,picks='all',
                              n_cycles=15, return_itc=True)
tfr.plot(picks=[4], baseline=(-0.5, -0.1), mode='logratio', 
                 title='POz - 30 Hz stim');

tfr, itc = tfr_morlet(epochs['20 Hz'], freqs=frequencies,picks='all',
                              n_cycles=15, return_itc=True)
tfr.plot(picks=[4], baseline=(-0.5, -0.1), mode='logratio', 
                 title='POz - 20 Hz stim');

plt.tight_layout()

# Once again we can see clear SSVEPs at 30hz and 20hz
Exemplo n.º 26
0
    def plotERP(
        self,
        event_code1=769,
        event_code2=770,
        filename="",
        bad_ch=[
            'Channel 14', "Channel 15", "EMG1", "Channel 17", "Channel 18",
            "Channel 19", "T10"
        ],
    ):
        tmin, tmax = -1., 4.
        event_id = dict(class1=event_code1, class2=event_code2)

        # load file
        raw_fnames = [filename]
        raw_files = [
            read_raw_edf(f, preload=True, stim_channel='auto')
            for f in raw_fnames
        ]
        raw = concatenate_raws(raw_files)
        montage = channels.read_montage('standard_1020')
        raw.set_montage(montage)

        raw.info['bads'] = bad_ch
        events = find_events(raw, shortest_event=0)

        # select what to print and what to exclude
        picks = pick_types(raw.info,
                           meg=False,
                           eeg=True,
                           stim=False,
                           eog=False,
                           exclude='bads')

        reject = dict(eeg=180e-6)

        evoked_no_ref = Epochs(raw,
                               events,
                               event_id,
                               tmin,
                               tmax,
                               proj=True,
                               picks=picks,
                               baseline=(-0.5, 0),
                               reject=reject,
                               preload=True).average()

        title = 'EEG'
        evoked_no_ref.plot(titles=dict(eeg=title),
                           time_unit='s',
                           spatial_colors=True)

        # define frequencies of interest (log-spaced)
        freqs = np.logspace(*np.log10([6, 35]), num=8)
        n_cycles = freqs / 2.  # different number of cycle per frequency
        power, itc = tfr_morlet(epochs,
                                freqs=freqs,
                                n_cycles=n_cycles,
                                use_fft=True,
                                return_itc=True,
                                decim=3,
                                n_jobs=1)

        power.plot_joint(baseline=(-0.5, 0),
                         mode='logratio',
                         tmin=tmin,
                         tmax=tmax,
                         timefreqs=[(.5, 10), (1.3, 8)])
Exemplo n.º 27
0
def test_compute_csd():
    """Test computing cross-spectral density from ndarray."""
    epochs = _get_real_data()

    tmin = 0.04
    tmax = 0.15
    tmp = np.where(np.logical_and(epochs.times >= tmin,
                                  epochs.times <= tmax))[0]

    picks_meeg = mne.pick_types(epochs[0].info, meg=True, eeg=True, eog=False,
                                ref_meg=False, exclude='bads')

    epochs_data = [e[picks_meeg][:, tmp].copy() for e in epochs]
    n_trials = len(epochs)
    n_series = len(picks_meeg)
    X = np.concatenate(epochs_data, axis=0)
    X = np.reshape(X, (n_trials, n_series, -1))
    X_list = epochs_data

    sfreq = epochs.info['sfreq']

    # Check data types and sizes are checked
    diff_types = [np.random.randn(3, 5), "error"]
    err_data = [np.random.randn(3, 5), np.random.randn(2, 4)]
    with warnings.catch_warnings(record=True):  # deprecation
        raises(ValueError, csd_array, err_data, sfreq)
        raises(ValueError, csd_array, diff_types, sfreq)
        raises(ValueError, csd_array, np.random.randn(3), sfreq)

        # Check that wrong parameters are recognized
        raises(ValueError, csd_array, X, sfreq, mode='notamode')
        raises(ValueError, csd_array, X, sfreq, fmin=20, fmax=10)
        raises(ValueError, csd_array, X, sfreq, fmin=20, fmax=20.1)

    # Test deprecation warning
    with warnings.catch_warnings(record=True) as ws:
        warnings.simplefilter('always')
        csd_mt = csd_array(X, sfreq, mode='multitaper', fmin=8, fmax=12)
    assert len([w for w in ws
                if issubclass(w.category, DeprecationWarning)]) == 1

    with warnings.catch_warnings(record=True):  # deprecation
        csd_fourier = csd_array(X, sfreq, mode='fourier', fmin=8, fmax=12)

    # Test as list too
    with warnings.catch_warnings(record=True):  # deprecation
        csd_mt_list = csd_array(X_list, sfreq, mode='multitaper',
                                fmin=8, fmax=12)
        csd_fourier_list = csd_array(X_list, sfreq, mode='fourier', fmin=8,
                                     fmax=12)

    assert_array_equal(csd_mt._data, csd_mt_list._data)
    assert_array_equal(csd_fourier._data, csd_fourier_list._data)
    assert_array_equal(csd_mt.frequencies, csd_mt_list.frequencies)
    assert_array_equal(csd_fourier.frequencies, csd_fourier_list.frequencies)

    # Check shape of the CSD matrix
    n_chan = len(epochs.ch_names)
    csd_mt_data = csd_mt.get_data()
    csd_fourier_data = csd_fourier.get_data()
    assert csd_mt_data.shape == (n_chan, n_chan)
    assert csd_fourier_data.shape == (n_chan, n_chan)

    # Check if the CSD matrix is hermitian
    assert_array_equal(np.tril(csd_mt_data).T.conj(),
                       np.triu(csd_mt_data))
    assert_array_equal(np.tril(csd_fourier_data).T.conj(),
                       np.triu(csd_fourier_data))

    # Computing induced power for comparison
    epochs.crop(tmin=0.04, tmax=0.15)
    tfr = tfr_morlet(epochs, freqs=[10], n_cycles=0.6, return_itc=False)
    power = np.mean(tfr.data, 2)

    # Maximum PSD should occur for specific channel
    max_ch_power = power.argmax()
    max_ch_mt = csd_mt_data.diagonal().argmax()
    max_ch_fourier = csd_fourier_data.diagonal().argmax()
    assert max_ch_mt == max_ch_power
    assert max_ch_fourier == max_ch_power

    # Maximum CSD should occur for specific channel
    ch_csd_mt = np.abs(csd_mt_data[max_ch_power])
    ch_csd_mt[max_ch_power] = 0.
    max_ch_csd_mt = np.argmax(ch_csd_mt)
    ch_csd_fourier = np.abs(csd_fourier_data[max_ch_power])
    ch_csd_fourier[max_ch_power] = 0.
    max_ch_csd_fourier = np.argmax(ch_csd_fourier)
    assert max_ch_csd_mt == max_ch_csd_fourier

    # Check a list of CSD matrices is returned for multiple frequencies within
    # a given range when fsum=False
    with warnings.catch_warnings(record=True):  # deprecation
        csd_fsum = csd_array(X, sfreq, mode='fourier', fmin=8, fmax=20,
                             fsum=True)
        csds = csd_array(X, sfreq, mode='fourier', fmin=8, fmax=20,
                         fsum=False)

    assert csds._data.shape[1] == 2
    assert len(csds.frequencies) == 2
    assert_array_equal(csd_fsum.frequencies[0], csds.frequencies)
    assert_array_equal(csd_fsum._data, csds._data.sum(axis=1, keepdims=True))
###############################################################################
# Time-frequency analysis: power and inter-trial coherence
# --------------------------------------------------------
#
# We now compute time-frequency representations (TFRs) from our Epochs.
# We'll look at power and inter-trial coherence (ITC).
#
# To this we'll use the function :func:`mne.time_frequency.tfr_morlet`
# but you can also use :func:`mne.time_frequency.tfr_multitaper`
# or :func:`mne.time_frequency.tfr_stockwell`.

# define frequencies of interest (log-spaced)
freqs = np.logspace(*np.log10([6, 35]), num=8)
n_cycles = freqs / 2.  # different number of cycle per frequency
power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,
                        return_itc=True, decim=3, n_jobs=1)

###############################################################################
# Inspect power
# -------------
#
# .. note::
#     The generated figures are interactive. In the topo you can click
#     on an image to visualize the data for one sensor.
#     You can also select a portion in the time-frequency plane to
#     obtain a topomap for a certain time-frequency region.
power.plot_topo(baseline=(-0.5, 0), mode='logratio', title='Average power')
power.plot([82], baseline=(-0.5, 0), mode='logratio', title=power.ch_names[82])

fig, axis = plt.subplots(1, 2, figsize=(7, 4))
power.plot_topomap(ch_type='grad', tmin=0.5, tmax=1.5, fmin=8, fmax=12,
Exemplo n.º 29
0
import numpy as np
from my_settings import (epochs_folder, tf_folder)
from mne.time_frequency import tfr_morlet
import sys

subject = sys.argv[1]

freqs = np.arange(8, 13, 1)  # define frequencies of interest
n_cycles = 4.  # freqs / 2.  # different number of cycle per frequency

sides = ["left", "right"]
conditions = ["ctl", "ent"]

epochs = mne.read_epochs(
    epochs_folder + "%s_trial_start-epo.fif" % subject,
    preload=False)
for cond in conditions:
    for side in sides:
        power, itc = tfr_morlet(epochs[cond + "/" + side],
                                freqs=freqs,
                                n_cycles=n_cycles,
                                use_fft=True,
                                return_itc=False,
                                decim=2,
                                average=False,
                                n_jobs=1)
        power.save(tf_folder + "%s_%s_%s-4-tfr.h5" % (subject, cond, side),
                   overwrite=True)
        itc.save(tf_folder + "%s_%s_%s-4-tfr.h5" % (subject, cond, side),
                 overwrite=True)
Exemplo n.º 30
0
    epochs.pick_channels([ch_name])
    
    evoked = epochs.average()
    
    
    
    
    # Factor to down-sample the temporal dimension of the TFR computed by
    # tfr_morlet. Decimation occurs after frequency decomposition and can
    # be used to reduce memory usage (and possibly computational time of downstream
    # operations such as nonparametric statistics) if you don't need high
    # spectrotemporal resolution.
    decim = 5
    frequencies = np.arange(8, 30, 2)  # define frequencies of interest
    sfreq = raw.info['sfreq']  # sampling in Hz
    tfr_epochs = tfr_morlet(epochs, frequencies, n_cycles=4., decim=decim,
                            average=False, return_itc=False, n_jobs=1)
    
    # Baseline power
    tfr_epochs.apply_baseline(mode='logratio', baseline=(-.100, 0))
    
    # Crop in time to keep only what is between 0 and 400 ms
    evoked.crop(0., 0.5)
    tfr_epochs.crop(0., 0.5)
    
    epochs_power = tfr_epochs.data[:, 0, :, :]  # take the 1 channel

###############################################################################
# Compute statistic
# -----------------
threshold = 2.5
T_obs, clusters, cluster_p_values, H0 = \
decim = 2
freqs = np.arange(7, 30, 3)  # define frequencies of interest
n_cycles = freqs / freqs[0]
zero_mean = False  # don't correct morlet wavelet to be of mean zero
# To have a true wavelet zero_mean should be True but here for illustration
# purposes it helps to spot the evoked response.

###############################################################################
# Create TFR representations for all conditions
# ---------------------------------------------
epochs_power = list()
for condition in [epochs[k] for k in event_id]:
    this_tfr = tfr_morlet(condition,
                          freqs,
                          n_cycles=n_cycles,
                          decim=decim,
                          average=False,
                          zero_mean=zero_mean,
                          return_itc=False)
    this_tfr.apply_baseline(mode='ratio', baseline=(None, 0))
    this_power = this_tfr.data[:, 0, :, :]  # we only have one channel.
    epochs_power.append(this_power)

###############################################################################
# Setup repeated measures ANOVA
# -----------------------------
#
# We will tell the ANOVA how to interpret the data matrix in terms of factors.
# This is done via the factor levels argument which is a list of the number
# factor levels for each factor.
Exemplo n.º 32
0
def test_compute_csd():
    """Test computing cross-spectral density from ndarray. """

    epochs = _get_data(mode='real')

    tmin = 0.04
    tmax = 0.15
    tmp = np.where(np.logical_and(epochs.times >= tmin,
                                  epochs.times <= tmax))[0]

    picks_meeg = mne.pick_types(epochs[0].info, meg=True, eeg=True, eog=False,
                                ref_meg=False, exclude='bads')

    epochs_data = [e[picks_meeg][:, tmp].copy() for e in epochs]
    n_trials = len(epochs)
    n_series = len(picks_meeg)
    X = np.concatenate(epochs_data, axis=0)
    X = np.reshape(X, (n_trials, n_series, -1))
    X_list = epochs_data

    sfreq = epochs.info['sfreq']

    # Check data types and sizes are checked
    diff_types = [np.random.randn(3, 5), "error"]
    err_data = [np.random.randn(3, 5), np.random.randn(2, 4)]
    assert_raises(ValueError, csd_array, err_data, sfreq)
    assert_raises(ValueError, csd_array, diff_types, sfreq)
    assert_raises(ValueError, csd_array, np.random.randn(3), sfreq)

    # Check that wrong parameters are recognized
    assert_raises(ValueError, csd_array, X, sfreq, mode='notamode')
    assert_raises(ValueError, csd_array, X, sfreq, fmin=20, fmax=10)
    assert_raises(ValueError, csd_array, X, sfreq, fmin=20, fmax=20.1)

    data_csd_mt, freqs_mt = csd_array(X, sfreq, mode='multitaper',
                                      fmin=8, fmax=12)
    data_csd_fourier, freqs_fft = csd_array(X, sfreq, mode='fourier',
                                            fmin=8, fmax=12)

    # Test as list too
    data_csd_mt_list, freqs_mt_list = csd_array(X_list, sfreq,
                                                mode='multitaper',
                                                fmin=8, fmax=12)
    data_csd_fourier_list, freqs_fft_list = csd_array(X_list, sfreq,
                                                      mode='fourier',
                                                      fmin=8, fmax=12)

    assert_array_equal(data_csd_mt, data_csd_mt_list)
    assert_array_equal(data_csd_fourier, data_csd_fourier_list)
    assert_array_equal(freqs_mt, freqs_mt_list)
    assert_array_equal(freqs_fft, freqs_fft_list)

    # Check shape of the CSD matrix
    n_chan = len(epochs.ch_names)
    assert_equal(data_csd_mt.shape, (n_chan, n_chan))
    assert_equal(data_csd_fourier.shape, (n_chan, n_chan))

    # Check if the CSD matrix is hermitian
    assert_array_equal(np.tril(data_csd_mt).T.conj(),
                       np.triu(data_csd_mt))
    assert_array_equal(np.tril(data_csd_fourier).T.conj(),
                       np.triu(data_csd_fourier))

    # Computing induced power for comparison
    epochs.crop(tmin=0.04, tmax=0.15)
    tfr = tfr_morlet(epochs, freqs=[10], n_cycles=0.6, return_itc=False)
    power = np.mean(tfr.data, 2)

    # Maximum PSD should occur for specific channel
    max_ch_power = power.argmax()
    max_ch_mt = data_csd_mt.diagonal().argmax()
    max_ch_fourier = data_csd_fourier.diagonal().argmax()
    assert_equal(max_ch_mt, max_ch_power)
    assert_equal(max_ch_fourier, max_ch_power)

    # Maximum CSD should occur for specific channel
    ch_csd_mt = np.abs(data_csd_mt[max_ch_power])
    ch_csd_mt[max_ch_power] = 0.
    max_ch_csd_mt = np.argmax(ch_csd_mt)
    ch_csd_fourier = np.abs(data_csd_fourier[max_ch_power])
    ch_csd_fourier[max_ch_power] = 0.
    max_ch_csd_fourier = np.argmax(ch_csd_fourier)
    assert_equal(max_ch_csd_mt, max_ch_csd_fourier)

    # Check a list of CSD matrices is returned for multiple frequencies within
    # a given range when fsum=False
    csd_fsum, freqs_fsum = csd_array(X, sfreq, mode='fourier', fmin=8,
                                     fmax=20, fsum=True)
    csds, freqs = csd_array(X, sfreq, mode='fourier', fmin=8, fmax=20,
                            fsum=False)

    csd_sum = np.sum(csds, axis=2)

    assert_equal(csds.shape[2], 2)
    assert_equal(len(freqs), 2)
    assert_array_equal(freqs_fsum, freqs)
    assert_array_equal(csd_fsum, csd_sum)
# Factor to down-sample the temporal dimension of the TFR computed by
# tfr_morlet.
decim = 2
freqs = np.arange(7, 30, 3)  # define frequencies of interest
n_cycles = freqs / freqs[0]
zero_mean = False  # don't correct morlet wavelet to be of mean zero
# To have a true wavelet zero_mean should be True but here for illustration
# purposes it helps to spot the evoked response.

###############################################################################
# Create TFR representations for all conditions
# ---------------------------------------------
epochs_power = list()
for condition in [epochs[k] for k in event_id]:
    this_tfr = tfr_morlet(condition, freqs, n_cycles=n_cycles,
                          decim=decim, average=False, zero_mean=zero_mean,
                          return_itc=False)
    this_tfr.apply_baseline(mode='ratio', baseline=(None, 0))
    this_power = this_tfr.data[:, 0, :, :]  # we only have one channel.
    epochs_power.append(this_power)

###############################################################################
# Setup repeated measures ANOVA
# -----------------------------
#
# We will tell the ANOVA how to interpret the data matrix in terms of factors.
# This is done via the factor levels argument which is a list of the number
# factor levels for each factor.

n_conditions = len(epochs.event_id)
n_replications = epochs.events.shape[0] // n_conditions
# Take only one channel
ch_name = 'MEG 1332'
epochs.pick_channels([ch_name])

evoked = epochs.average()

# Factor to down-sample the temporal dimension of the TFR computed by
# tfr_morlet. Decimation occurs after frequency decomposition and can
# be used to reduce memory usage (and possibly computational time of downstream
# operations such as nonparametric statistics) if you don't need high
# spectrotemporal resolution.
decim = 5
freqs = np.arange(8, 40, 2)  # define frequencies of interest
sfreq = raw.info['sfreq']  # sampling in Hz
tfr_epochs = tfr_morlet(epochs, freqs, n_cycles=4., decim=decim,
                        average=False, return_itc=False, n_jobs=1)

# Baseline power
tfr_epochs.apply_baseline(mode='logratio', baseline=(-.100, 0))

# Crop in time to keep only what is between 0 and 400 ms
evoked.crop(0., 0.4)
tfr_epochs.crop(0., 0.4)

epochs_power = tfr_epochs.data[:, 0, :, :]  # take the 1 channel

###############################################################################
# Compute statistic
# -----------------
threshold = 2.5
T_obs, clusters, cluster_p_values, H0 = \
#mne.io.Raw.plot(raw=raw_memmaped, duration=2, start=20, n_channels=20, scalings={'eeg': 8000}, remove_dc=True)

id = 1
events_mne = np.c_[np.array(events), np.zeros(len(events), dtype=int), id * np.ones(len(events), dtype=int)]
baseline = (-2.5, -2.3)
event_id = dict(left_paw=id)
epochs = mne.Epochs(raw_memmaped, events_mne, event_id, -3, 3, proj=True, picks=None, baseline=baseline, preload=True, reject=None)
averaged = epochs.average()

power = pickle.load( open(os.path.join(path, "Analysis\\tfr_power.p"), "rb"))

n_cycles = 3
frequencies = np.arange(5, 60, 3)

from mne.time_frequency import tfr_morlet
power, phase_lock = tfr_morlet(epochs, freqs=frequencies, n_cycles=n_cycles, decim=3000, n_jobs=10)



import gui_tfr_viewer
gui_tfr_viewer.TFR_Viewer(power)

box = (0, 0.8, 0, 1.1)
w, h = [.09, .05]

pos = [[ut.normList([x, y], normalizeTo=0.8, vMin=1, vMax=8)[0], ut.normList([x, y], vMin=1, vMax=16)[1], w, h] for [n, s, (x,y)] in cp.sort_index(0, by='Numbers', ascending=True).values]
layout = mne.layouts.Layout(box, pos, cp.sort_index(0, by='Numbers', ascending=True).Strings, cp.sort_index(0, by='Numbers', ascending=True).Numbers, '128ch')

power.plot_topo(picks=None, tmin=-3, tmax=3, fmin=5, fmax=60, vmin=-3e10, vmax=3e10, layout=layout, layout_scale=None)
    ax.set_title('Sim: Using S transform, width = {:0.1f}'.format(width))
plt.tight_layout()

###############################################################################
# Morlet Wavelets
# ===============
#
# Finally, show the TFR using morlet wavelets, which are a sinusoidal wave
# with a gaussian envelope. We can control the balance between spectral and
# temporal resolution with the ``n_cycles`` parameter, which defines the
# number of cycles to include in the window.

fig, axs = plt.subplots(1, 3, figsize=(15, 5), sharey=True)
all_n_cycles = [1, 3, freqs / 2.]
for n_cycles, ax in zip(all_n_cycles, axs):
    power = tfr_morlet(epochs, freqs=freqs,
                       n_cycles=n_cycles, return_itc=False)
    power.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax,
               axes=ax, show=False, colorbar=False)
    n_cycles = 'scaled by freqs' if not isinstance(n_cycles, int) else n_cycles
    ax.set_title('Sim: Using Morlet wavelet, n_cycles = %s' % n_cycles)
plt.tight_layout()

###############################################################################
# Calculating a TFR without averaging over epochs
# -----------------------------------------------
#
# It is also possible to calculate a TFR without averaging across trials.
# We can do this by using ``average=False``. In this case, an instance of
# :class:`mne.time_frequency.EpochsTFR` is returned.

n_cycles = freqs / 2.
Exemplo n.º 37
0
# output
tfr_path = bp.tfr.fpath(subject=subj)
# itc_path_low = bp.itc.fpath(subject=subj, task="low")

# tfr_path_high = bp.tfr.fpath(subject=subj, task="high")
# itc_path_high = bp.itc.fpath(subject=subj, task="high")

ep = read_epochs(ep_path)

freqs = np.arange(**cfg.tfr_config["freqs"])
n_cycles = freqs / 2.0
ep_tfr = tfr_morlet(
    ep["answer"],
    average=False,
    return_itc=False,
    freqs=freqs,
    n_cycles=n_cycles,
    decim=cfg.tfr_config["decim"],
    use_fft=cfg.tfr_config["use_fft"],
)

# ep_tfr_high, ep_itc_high = tfr_morlet(
#     ep["answer/high"],
#     average=True,
#     return_itc=True,
#     freqs=freqs,
#     n_cycles=n_cycles,
#     decim=cfg.tfr_config["decim"],
#     use_fft=cfg.tfr_config["use_fft"],
# )
tfr_path.parent.mkdir(exist_ok=True, parents=True)
Exemplo n.º 38
0
# Time-Frequency: Induced power and inter trial coherence
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Define parameters:

import numpy as np  # noqa
n_cycles = 2  # number of cycles in Morlet wavelet
freqs = np.arange(7, 30, 3)  # frequencies of interest

##############################################################################
# Compute induced power and phase-locking values and plot gradiometers:

from mne.time_frequency import tfr_morlet  # noqa
power, itc = tfr_morlet(epochs,
                        freqs=freqs,
                        n_cycles=n_cycles,
                        return_itc=True,
                        decim=3,
                        n_jobs=1)
power.plot([power.ch_names.index('MEG 1332')])

##############################################################################
# Inverse modeling: MNE and dSPM on evoked and raw data
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Import the required functions:

from mne.minimum_norm import apply_inverse, read_inverse_operator  # noqa

##############################################################################
# Read the inverse operator:
Exemplo n.º 39
0
def test_compute_epochs_csd():
    """Test computing cross-spectral density from epochs
    """
    epochs, epochs_sin = _get_data()
    # Check that wrong parameters are recognized
    assert_raises(ValueError, compute_epochs_csd, epochs, mode='notamode')
    assert_raises(ValueError, compute_epochs_csd, epochs, fmin=20, fmax=10)
    assert_raises(ValueError, compute_epochs_csd, epochs, fmin=20, fmax=20.1)
    assert_raises(ValueError, compute_epochs_csd, epochs, tmin=0.15, tmax=0.1)
    assert_raises(ValueError, compute_epochs_csd, epochs, tmin=0, tmax=10)
    assert_raises(ValueError, compute_epochs_csd, epochs, tmin=10, tmax=11)

    data_csd_mt = compute_epochs_csd(epochs, mode='multitaper', fmin=8,
                                     fmax=12, tmin=0.04, tmax=0.15)
    data_csd_fourier = compute_epochs_csd(epochs, mode='fourier', fmin=8,
                                          fmax=12, tmin=0.04, tmax=0.15)

    # Check shape of the CSD matrix
    n_chan = len(data_csd_mt.ch_names)
    assert_equal(data_csd_mt.data.shape, (n_chan, n_chan))
    assert_equal(data_csd_fourier.data.shape, (n_chan, n_chan))

    # Check if the CSD matrix is hermitian
    assert_array_equal(np.tril(data_csd_mt.data).T.conj(),
                       np.triu(data_csd_mt.data))
    assert_array_equal(np.tril(data_csd_fourier.data).T.conj(),
                       np.triu(data_csd_fourier.data))

    # Computing induced power for comparison
    epochs.crop(tmin=0.04, tmax=0.15)
    tfr = tfr_morlet(epochs, freqs=[10], n_cycles=0.6, return_itc=False)
    power = np.mean(tfr.data, 2)

    # Maximum PSD should occur for specific channel
    max_ch_power = power.argmax()
    max_ch_mt = data_csd_mt.data.diagonal().argmax()
    max_ch_fourier = data_csd_fourier.data.diagonal().argmax()
    assert_equal(max_ch_mt, max_ch_power)
    assert_equal(max_ch_fourier, max_ch_power)

    # Maximum CSD should occur for specific channel
    ch_csd_mt = [np.abs(data_csd_mt.data[max_ch_power][i])
                 if i != max_ch_power else 0 for i in range(n_chan)]
    max_ch_csd_mt = np.argmax(ch_csd_mt)
    ch_csd_fourier = [np.abs(data_csd_fourier.data[max_ch_power][i])
                      if i != max_ch_power else 0 for i in range(n_chan)]
    max_ch_csd_fourier = np.argmax(ch_csd_fourier)
    assert_equal(max_ch_csd_mt, max_ch_csd_fourier)

    # Check a list of CSD matrices is returned for multiple frequencies within
    # a given range when fsum=False
    csd_fsum = compute_epochs_csd(epochs, mode='fourier', fmin=8, fmax=20,
                                  fsum=True)
    csds = compute_epochs_csd(epochs, mode='fourier', fmin=8, fmax=20,
                              fsum=False)
    freqs = [csd.frequencies[0] for csd in csds]

    csd_sum = np.zeros_like(csd_fsum.data)
    for csd in csds:
        csd_sum += csd.data

    assert(len(csds) == 2)
    assert(len(csd_fsum.frequencies) == 2)
    assert_array_equal(csd_fsum.frequencies, freqs)
    assert_array_equal(csd_fsum.data, csd_sum)
Exemplo n.º 40
0
def test_csd_epochs():
    """Test computing cross-spectral density from epochs."""
    epochs = _get_real_data()

    # Check that wrong parameters are recognized
    with warnings.catch_warnings(record=True):  # deprecation
        raises(ValueError, csd_epochs, epochs, mode='notamode')
        raises(ValueError, csd_epochs, epochs, fmin=20, fmax=10)
        raises(ValueError, csd_epochs, epochs, fmin=20, fmax=20.1)
        raises(ValueError, csd_epochs, epochs, tmin=0.15, tmax=0.1)
        raises(ValueError, csd_epochs, epochs, tmin=0, tmax=10)
        raises(ValueError, csd_epochs, epochs, tmin=10, tmax=11)

    # Test deprecation warning
    with warnings.catch_warnings(record=True) as ws:
        warnings.simplefilter('always')
        csd_mt = csd_epochs(epochs, mode='multitaper', fmin=8, fmax=12,
                            tmin=0.04, tmax=0.15)
    assert len([w for w in ws
                if issubclass(w.category, DeprecationWarning)]) == 1

    with warnings.catch_warnings(record=True):  # deprecation
        csd_fourier = csd_epochs(epochs, mode='fourier', fmin=8, fmax=12,
                                 tmin=0.04, tmax=0.15)

    # Check shape of the CSD matrix
    n_chan = len(csd_mt.ch_names)
    csd_mt_data = csd_mt.get_data()
    csd_fourier_data = csd_fourier.get_data()
    assert csd_mt_data.shape == (n_chan, n_chan)
    assert csd_fourier_data.shape == (n_chan, n_chan)

    # Check if the CSD matrix is hermitian
    assert_array_equal(np.tril(csd_mt_data).T.conj(),
                       np.triu(csd_mt_data))
    assert_array_equal(np.tril(csd_fourier_data).T.conj(),
                       np.triu(csd_fourier_data))

    # Computing induced power for comparison
    epochs.crop(tmin=0.04, tmax=0.15)
    tfr = tfr_morlet(epochs, freqs=[10], n_cycles=0.6, return_itc=False)
    power = np.mean(tfr.data, 2)

    # Maximum PSD should occur for specific channel
    max_ch_power = power.argmax()
    max_ch_mt = csd_mt_data.diagonal().argmax()
    max_ch_fourier = csd_fourier_data.diagonal().argmax()
    assert max_ch_mt == max_ch_power
    assert max_ch_fourier == max_ch_power

    # Maximum CSD should occur for specific channel
    ch_csd_mt = np.abs(csd_mt_data[max_ch_power])
    ch_csd_mt[max_ch_power] = 0.
    max_ch_csd_mt = np.argmax(ch_csd_mt)
    ch_csd_fourier = np.abs(csd_fourier_data[max_ch_power])
    ch_csd_fourier[max_ch_power] = 0.
    max_ch_csd_fourier = np.argmax(ch_csd_fourier)
    assert max_ch_csd_mt == max_ch_csd_fourier

    # Check a list of CSD matrices is returned for multiple frequencies within
    # a given range when fsum=False
    with warnings.catch_warnings(record=True):  # deprecation
        csd_fsum = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20,
                              fsum=True)
        csds = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20, fsum=False)
    assert len(csd_fsum.frequencies) == 1
    assert len(csds.frequencies) == 2
    assert_array_equal(csd_fsum.frequencies[0], csds.frequencies)

    csd_sum = csds._data.sum(axis=1, keepdims=True)
    assert_array_equal(csd_fsum._data, csd_sum)
Exemplo n.º 41
0
def test_compute_csd():
    """Test computing cross-spectral density from ndarray."""
    epochs = _get_real_data()

    tmin = 0.04
    tmax = 0.15
    tmp = np.where(np.logical_and(epochs.times >= tmin,
                                  epochs.times <= tmax))[0]

    picks_meeg = mne.pick_types(epochs[0].info,
                                meg=True,
                                eeg=True,
                                eog=False,
                                ref_meg=False,
                                exclude='bads')

    epochs_data = [e[picks_meeg][:, tmp].copy() for e in epochs]
    n_trials = len(epochs)
    n_series = len(picks_meeg)
    X = np.concatenate(epochs_data, axis=0)
    X = np.reshape(X, (n_trials, n_series, -1))
    X_list = epochs_data

    sfreq = epochs.info['sfreq']

    # Check data types and sizes are checked
    diff_types = [np.random.randn(3, 5), "error"]
    err_data = [np.random.randn(3, 5), np.random.randn(2, 4)]
    raises(ValueError, csd_array, err_data, sfreq)
    raises(ValueError, csd_array, diff_types, sfreq)
    raises(ValueError, csd_array, np.random.randn(3), sfreq)

    # Check that wrong parameters are recognized
    raises(ValueError, csd_array, X, sfreq, mode='notamode')
    raises(ValueError, csd_array, X, sfreq, fmin=20, fmax=10)
    raises(ValueError, csd_array, X, sfreq, fmin=20, fmax=20.1)

    # Test deprecation warning
    with warnings.catch_warnings(record=True) as ws:
        warnings.simplefilter('always')
        csd_mt = csd_array(X, sfreq, mode='multitaper', fmin=8, fmax=12)
    assert len([w for w in ws
                if issubclass(w.category, DeprecationWarning)]) == 1

    csd_fourier = csd_array(X, sfreq, mode='fourier', fmin=8, fmax=12)

    # Test as list too
    csd_mt_list = csd_array(X_list, sfreq, mode='multitaper', fmin=8, fmax=12)
    csd_fourier_list = csd_array(X_list,
                                 sfreq,
                                 mode='fourier',
                                 fmin=8,
                                 fmax=12)

    assert_array_equal(csd_mt._data, csd_mt_list._data)
    assert_array_equal(csd_fourier._data, csd_fourier_list._data)
    assert_array_equal(csd_mt.frequencies, csd_mt_list.frequencies)
    assert_array_equal(csd_fourier.frequencies, csd_fourier_list.frequencies)

    # Check shape of the CSD matrix
    n_chan = len(epochs.ch_names)
    csd_mt_data = csd_mt.get_data()
    csd_fourier_data = csd_fourier.get_data()
    assert csd_mt_data.shape == (n_chan, n_chan)
    assert csd_fourier_data.shape == (n_chan, n_chan)

    # Check if the CSD matrix is hermitian
    assert_array_equal(np.tril(csd_mt_data).T.conj(), np.triu(csd_mt_data))
    assert_array_equal(
        np.tril(csd_fourier_data).T.conj(), np.triu(csd_fourier_data))

    # Computing induced power for comparison
    epochs.crop(tmin=0.04, tmax=0.15)
    tfr = tfr_morlet(epochs, freqs=[10], n_cycles=0.6, return_itc=False)
    power = np.mean(tfr.data, 2)

    # Maximum PSD should occur for specific channel
    max_ch_power = power.argmax()
    max_ch_mt = csd_mt_data.diagonal().argmax()
    max_ch_fourier = csd_fourier_data.diagonal().argmax()
    assert max_ch_mt == max_ch_power
    assert max_ch_fourier == max_ch_power

    # Maximum CSD should occur for specific channel
    ch_csd_mt = np.abs(csd_mt_data[max_ch_power])
    ch_csd_mt[max_ch_power] = 0.
    max_ch_csd_mt = np.argmax(ch_csd_mt)
    ch_csd_fourier = np.abs(csd_fourier_data[max_ch_power])
    ch_csd_fourier[max_ch_power] = 0.
    max_ch_csd_fourier = np.argmax(ch_csd_fourier)
    assert max_ch_csd_mt == max_ch_csd_fourier

    # Check a list of CSD matrices is returned for multiple frequencies within
    # a given range when fsum=False
    csd_fsum = csd_array(X, sfreq, mode='fourier', fmin=8, fmax=20, fsum=True)
    csds = csd_array(X, sfreq, mode='fourier', fmin=8, fmax=20, fsum=False)

    assert csds._data.shape[1] == 2
    assert len(csds.frequencies) == 2
    assert_array_equal(csd_fsum.frequencies[0], csds.frequencies)
    assert_array_equal(csd_fsum._data, csds._data.sum(axis=1, keepdims=True))
        sesh = session_list[j]
        epoch_power = list()
        epoch_itc = list()
        for i in range(n_subj):
            ch_name = ['FZ']  ###change this to PZ or CZ or FZ
            subj = subj_list[i]
            import warnings
            warnings.filterwarnings('ignore')
            fname = word_epoch_dir + "%s_%s_%s_word-epo.fif" % (subj, sesh,
                                                                fname_suffix)
            this_epoch = mne.read_epochs(fname, preload=True)
            this_epoch.pick_channels(ch_name)
            this_epoch = this_epoch[word]
            power, itc = tfr_morlet(this_epoch,
                                    freqs=freqs,
                                    decim=decim,
                                    n_cycles=n_cycles,
                                    use_fft=True,
                                    return_itc=True)
            power.apply_baseline(mode='ratio', baseline=(-0.2, 0))
            itc.apply_baseline(mode='ratio', baseline=(-0.2, 0))
            epoch_power.append(power.data)
            print np.shape(epoch_power)
            epoch_itc.append(itc.data)
        epochs_power = np.append(epochs_power, epoch_power, axis=1)
        epochs_itc = np.append(epochs_itc, epoch_itc, axis=1)
        print "epochs_power", np.shape(epochs_power)

n_conditions = 4  #number of conditions
n_replications = n_subj

factor_levels = [2, 2]  # number of levels in each factor
                                picks=picks, baseline=(None, 0),
                                reject=reject, preload=True)
epochs_condition_2.pick_channels([ch_name])

###############################################################################
# Factor to downsample the temporal dimension of the TFR computed by
# tfr_morlet. Decimation occurs after frequency decomposition and can
# be used to reduce memory usage (and possibly comptuational time of downstream
# operations such as nonparametric statistics) if you don't need high
# spectrotemporal resolution.
decim = 2
freqs = np.arange(7, 30, 3)  # define frequencies of interest
n_cycles = 1.5

tfr_epochs_1 = tfr_morlet(epochs_condition_1, freqs,
                          n_cycles=n_cycles, decim=decim,
                          return_itc=False, average=False)

tfr_epochs_2 = tfr_morlet(epochs_condition_2, freqs,
                          n_cycles=n_cycles, decim=decim,
                          return_itc=False, average=False)

tfr_epochs_1.apply_baseline(mode='ratio', baseline=(None, 0))
tfr_epochs_2.apply_baseline(mode='ratio', baseline=(None, 0))

epochs_power_1 = tfr_epochs_1.data[:, 0, :, :]  # only 1 channel as 3D matrix
epochs_power_2 = tfr_epochs_2.data[:, 0, :, :]  # only 1 channel as 3D matrix

###############################################################################
# Compute statistic
# -----------------