def test_time_frequency(): """Test time frequency transform (PSD and phase lock) """ # Set parameters event_id = 1 tmin = -0.2 tmax = 0.5 # Setup for reading the raw data raw = fiff.Raw(raw_fname) events = read_events(event_fname) include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = fiff.pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0)) data = epochs.get_data() times = epochs.times frequencies = np.arange(6, 20, 5) # define frequencies of interest Fs = raw.info['sfreq'] # sampling in Hz n_cycles = frequencies / float(4) power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=n_cycles, use_fft=True) assert_true(power.shape == (len(picks), len(frequencies), len(times))) assert_true(power.shape == phase_lock.shape) assert_true(np.sum(phase_lock >= 1) == 0) assert_true(np.sum(phase_lock <= 0) == 0) power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=2, use_fft=False) assert_true(power.shape == (len(picks), len(frequencies), len(times))) assert_true(power.shape == phase_lock.shape) assert_true(np.sum(phase_lock >= 1) == 0) assert_true(np.sum(phase_lock <= 0) == 0) tfr = cwt_morlet(data[0], Fs, frequencies, use_fft=True, n_cycles=2) assert_true(tfr.shape == (len(picks), len(frequencies), len(times))) single_power = single_trial_power(data, Fs, frequencies, use_fft=False, n_cycles=2) assert_array_almost_equal(np.mean(single_power), power)
def test_time_frequency(): """Test time frequency transform (PSD and phase lock) """ # Set parameters event_id = 1 tmin = -0.2 tmax = 0.5 # Setup for reading the raw data raw = io.Raw(raw_fname) events = read_events(event_fname) include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0)) data = epochs.get_data() times = epochs.times frequencies = np.arange(6, 20, 5) # define frequencies of interest Fs = raw.info['sfreq'] # sampling in Hz n_cycles = frequencies / float(4) power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=n_cycles, use_fft=True) assert_true(power.shape == (len(picks), len(frequencies), len(times))) assert_true(power.shape == phase_lock.shape) assert_true(np.sum(phase_lock >= 1) == 0) assert_true(np.sum(phase_lock <= 0) == 0) power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=2, use_fft=False) assert_true(power.shape == (len(picks), len(frequencies), len(times))) assert_true(power.shape == phase_lock.shape) assert_true(np.sum(phase_lock >= 1) == 0) assert_true(np.sum(phase_lock <= 0) == 0) tfr = cwt_morlet(data[0], Fs, frequencies, use_fft=True, n_cycles=2) assert_true(tfr.shape == (len(picks), len(frequencies), len(times))) single_power = single_trial_power(data, Fs, frequencies, use_fft=False, n_cycles=2) assert_array_almost_equal(np.mean(single_power), power)
def normSignal(grid,frequencies = None,nc=None,dec=None,events=None): """Returns normalised power spectrums for events (using morlet wavelets) [n_epochs,n_channels,n_frequencies] frequencies -- Morlet frequencies nc -- Number of cycles (DEFAULT 12*np.arange(1,len(frequencies)+1) #Linear formula [Chan,Baker et al. JNS 2011]) Dec -- Decimation factor Events - events to find power of""" if frequencies is None: frequencies = np.arange(1,101) if nc is None: nc = 0.12*np.arange(1,len(frequencies)+1) #Linear formula [Chan,Baker et al. JNS 2011] print nc if dec is None: dec = 1 if events is None: events=grid.event_matrix() events = events[events['event.code']==5] #Use ISIs as baseline #Pre allocate power matrix for efficiency pows = np.zeros([len(events),len(grid.wc()),len(frequencies)]) for j,chan in enumerate(grid.wc()): for i,(on,off) in enumerate(events[['pulse.on','pulse.off']].values): logger.info( 'Normalising power on channel '+chan+' baseline event '+str(i+1)+'/'+str(len(events))) data = grid.splice(grid.wd()[chan],times=[on,off])[None,None,:] data = np.vstack([data,data]) #mne doesn't allow only 1 event so duplicate the same event (which will then be averaged) p,phase=mtf.induced_power(data, Fs=grid.fs(), frequencies=frequencies, use_fft=False, n_cycles=nc, decim=dec, n_jobs=1,normFreqs=None) pows[i,j,:]=p.mean(axis=2).squeeze() #Take average across time for each frequency return pows
def morlet(grid,dec=None,frequencies=None,fs=None,events=None,nc=None,normFreqs=None): #Performs a morlet wavelet analysis across events if events is None: events = grid.event_matrix() if fs is None: fs = grid.fs() if dec is None: dec = 1 if frequencies is None: frequencies= np.arange(1,101,dec) if nc is None: nc = 0.12*np.arange(1,len(frequencies)+1) print nc sigs = grid.wd() maxtimediff = (events['pulse.off']-events['pulse.on']).max() maxtimepoints = round(maxtimediff*fs)+1 data = np.zeros([len(events),len(grid.wc()),maxtimepoints]) for k,chan in enumerate(grid.wc()): for j,(on,off) in enumerate(events.values): print 'Pre-processing Channel:'+chan + ' | Event '+str(j)+'/'+str(len(events.values)) d=grid.splice(sigs[chan], times=[on,off]) data[j,k,:len(d)] = d pows,phase=mtf.induced_power(data, Fs=float(fs), frequencies=frequencies, use_fft=False, n_cycles=nc, decim=dec, n_jobs=1,normFreqs=normFreqs) return pows,phase
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) power, _ = induced_power(epochs.get_data(), epochs.info["sfreq"], [10], n_cycles=0.6) power = np.mean(power, 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)
def normSignal(grid, frequencies=None, nc=None, dec=None, events=None): """Returns normalised power spectrums for events (using morlet wavelets) [n_epochs,n_channels,n_frequencies] frequencies -- Morlet frequencies nc -- Number of cycles (DEFAULT 12*np.arange(1,len(frequencies)+1) #Linear formula [Chan,Baker et al. JNS 2011]) Dec -- Decimation factor Events - events to find power of""" if frequencies is None: frequencies = np.arange(1, 101) if nc is None: nc = 0.12 * np.arange( 1, len(frequencies) + 1) #Linear formula [Chan,Baker et al. JNS 2011] print nc if dec is None: dec = 1 if events is None: events = grid.event_matrix() events = events[events['event.code'] == 5] #Use ISIs as baseline #Pre allocate power matrix for efficiency pows = np.zeros([len(events), len(grid.wc()), len(frequencies)]) for j, chan in enumerate(grid.wc()): for i, (on, off) in enumerate(events[['pulse.on', 'pulse.off']].values): logger.info('Normalising power on channel ' + chan + ' baseline event ' + str(i + 1) + '/' + str(len(events))) data = grid.splice(grid.wd()[chan], times=[on, off])[None, None, :] data = np.vstack( [data, data] ) #mne doesn't allow only 1 event so duplicate the same event (which will then be averaged) p, phase = mtf.induced_power(data, Fs=grid.fs(), frequencies=frequencies, use_fft=False, n_cycles=nc, decim=dec, n_jobs=1, normFreqs=None) pows[i, j, :] = p.mean( axis=2).squeeze() #Take average across time for each frequency return pows
times = 1e3 * epochs.times # change unit to ms evoked_data = evoked.data * 1e13 # change unit to fT / cm # Take only one channel data = data[:, 97:98, :] evoked_data = evoked_data[97:98, :] frequencies = np.arange(7, 30, 3) # define frequencies of interest n_cycles = frequencies / float(7) # different number of cycle per frequency Fs = raw.info['sfreq'] # sampling in Hz decim = 3 power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=n_cycles, n_jobs=1, use_fft=False, decim=decim, zero_mean=True) # baseline corrections with ratio power /= np.mean(power[:, :, times[::decim] < 0], axis=2)[:, :, None] ############################################################################### # View time-frequency plots import matplotlib.pyplot as plt plt.clf() plt.subplots_adjust(0.1, 0.08, 0.96, 0.94, 0.2, 0.63) plt.subplot(3, 1, 1) plt.plot(times, evoked_data.T)
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) power, _ = induced_power(epochs.get_data(), epochs.info['sfreq'], [10], n_cycles=0.6) power = np.mean(power, 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)
tmax=2.5, baseline=(-0.5, 0.0), reject=dict(eeg=200e-6)) # Calculate power, plv Fs = raw.info['sfreq'] times = epochs.times plv = np.zeros((len(conds), len(freqs), len(times))) tfspec = np.zeros((len(conds), len(freqs), len(times))) condorder = np.zeros(len(conds)) # To save the order in which they come for condind, cond in enumerate(condstr): dat = epochs[cond].get_data()[:, ch, :].mean(axis=1, keepdims=True) powtemp, plvtemp = induced_power(dat, Fs=Fs, frequencies=freqs, n_cycles=n_cycles, zero_mean=True) plv[condind, :, :] = plvtemp.squeeze() tfspec[condind, :, :] = powtemp.squeeze() # Save results to the RES directory savedict = dict(tfspec=tfspec, plv=plv, times=times, conds=conds, freqs=freqs) save_name = subj + '_plv_inducedpow_2Hz_100Hz.mat' print 'Saving data for subject', subj if (not os.path.isdir(respath)): os.mkdir(respath)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6)) data = epochs.get_data() # as 3D matrix layout = mne.find_layout(epochs.info, 'meg') ############################################################################### # Calculate power and phase locking value frequencies = np.arange(7, 30, 3) # define frequencies of interest n_cycles = frequencies / float(7) # different number of cycle per frequency Fs = raw.info['sfreq'] # sampling in Hz decim = 3 power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=n_cycles, n_jobs=1, use_fft=False, decim=decim, zero_mean=True) ############################################################################### # Prepare topography plots, set baseline correction parameters baseline = (None, 0) # set the baseline for induced power mode = 'ratio' # set mode for baseline rescaling ############################################################################### # Show topography of power. title = 'Induced power - MNE sample data' plot_topo_power(epochs, power, frequencies, layout, baseline=baseline, mode=mode, decim=decim, vmin=0., vmax=14, title=title) plt.show()
# get data # OCP = epochs['OCP'].get_data() CVC = epochs['CVC'].get_data() # gather info for time freq import numpy as np n_cycles = 2 # number of cycles in Morlet wavelet frequencies = np.arange(7, 30, 3) # frequencies of interest Fs = raw.info['sfreq'] # sampling in Hz #Compute induced power and phase-locking values: from mne.time_frequency import induced_power power, phase_lock = induced_power(OCP, Fs=Fs, frequencies=frequencies, n_cycles=2, n_jobs=1) power2 = np.mean(power, axis=0) # average over sources phase = np.mean(phase_lock, axis=0) # average over sources times = epochs.times # plot result # plt.imshow(power2,extent=[times[0],times[-1],frequencies[0],frequencies[-1]],aspect='auto',origin='lower') # plt.imshow(phase,extent=[times[0],times[-1],frequencies[0],frequencies[-1]],aspect='auto',origin='lower') plt.xlabel('Time (s)') plt.ylabel('Frequency (Hz)')
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6)) data = epochs.get_data() # as 3D matrix evoked = epochs.average() # compute evoked fields times = 1e3 * epochs.times # change unit to ms evoked_data = evoked.data * 1e13 # change unit to fT / cm # Take only one channel data = data[:, 97:98, :] evoked_data = evoked_data[97:98, :] frequencies = np.arange(7, 30, 3) # define frequencies of interest Fs = raw.info['sfreq'] # sampling in Hz power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=2, n_jobs=1, use_fft=False) power /= np.mean(power[:, :, times < 0], axis=2)[:, :, None] # baseline ratio ############################################################################### # View time-frequency plots import pylab as pl pl.clf() pl.subplots_adjust(0.1, 0.08, 0.96, 0.94, 0.2, 0.63) pl.subplot(3, 1, 1) pl.plot(times, evoked_data.T) pl.title('Evoked response (%s)' % evoked.ch_names[97]) pl.xlabel('time (ms)') pl.ylabel('Magnetic Field (fT/cm)') pl.xlim(times[0], times[-1]) pl.ylim(-150, 300)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6)) data = epochs.get_data() # as 3D matrix evoked = epochs.average() # compute evoked fields times = 1e3 * epochs.times # change unit to ms evoked_data = evoked.data * 1e13 # change unit to fT / cm # Take only one channel data = data[:, 97:98, :] evoked_data = evoked_data[97:98, :] frequencies = np.arange(7, 30, 3) # define frequencies of interest Fs = raw.info['sfreq'] # sampling in Hz power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=2, n_jobs=1, use_fft=False) power /= np.mean(power[:, :, times < 0], axis=2)[:, :, None] # baseline ratio ############################################################################### # View time-frequency plots import pylab as pl pl.clf() pl.subplots_adjust(0.1, 0.08, 0.96, 0.94, 0.2, 0.63) pl.subplot(3, 1, 1) pl.plot(times, evoked_data.T) pl.title('Evoked response (%s)' % raw.info['ch_names'][picks[0]]) pl.xlabel('time (ms)') pl.ylabel('Magnetic Field (fT/cm)') pl.xlim(times[0], times[-1]) pl.ylim(-150, 300)
epo=mne.read_epochs(pin+'/'+fraw_LLon) freqs = np.arange(6, 200, 3) # define frequencies of interest n_cycles = freqs / 6. # different number of cycle per frequency power, itc = tfr_morlet(epo, freqs=freqs, n_cycles=n_cycles, use_fft=False, return_itc=True, decim=3, n_jobs=4) power.plot_topo(baseline=(-0.2, 0), mode='logratio', title='Average power') #power.plot([189], baseline=(-0.2, 0), mode='logratio') # from mne.time_frequency import induced_power power, phase_lock = induced_power(epo, Fs=Fs, frequencies=frequencies, n_cycles=2, n_jobs=1) from mne.time_frequency import tfr_stockwell power, itc = tfr_stockwell(epo, fmin=6 ,fmax=100,return_itc=True,decim=2,n_jobs=4) from mne.time_frequency import induced_power power, phase_lock = induced_power(epochs_data, Fs=Fs, frequencies=frequencies, n_cycles=2, n_jobs=1) # x(t)=cos(2*pi*5*t)+cos(2*pi*10*t)+cos(2*pi*20*t)+cos(2*pi*50*t)