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)
# picks MEG gradiometers picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True, stim=False) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6), preload=True) ############################################################################### # Calculate power and intertrial coherence epochs = epochs.pick_channels([epochs.ch_names[82]]) # reduce computation power, itc = tfr_stockwell(epochs, fmin=6., fmax=30., decim=4, n_jobs=2, width=.3, return_itc=True) power.plot([0], baseline=(-0.5, 0), mode=None, title='S-transform (power)') itc.plot([0], baseline=None, mode=None, title='S-transform (ITC)')
############################################################################### # Set parameters data_path = somato.data_path() raw_fname = data_path + '/MEG/somato/sef_raw_sss.fif' event_id, tmin, tmax = 1, -1., 3. # Setup for reading the raw data raw = io.Raw(raw_fname) baseline = (None, 0) events = mne.find_events(raw, stim_channel='STI 014') # picks MEG gradiometers picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True, stim=False) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6), preload=True) ############################################################################### # Calculate power and intertrial coherence epochs = epochs.pick_channels([epochs.ch_names[82]]) # reduce computation power, itc = tfr_stockwell(epochs, fmin=6., fmax=30., decim=4, n_jobs=2, width=.3, return_itc=True) power.plot([0], baseline=(-0.5, 0), mode=None, title='S-transform (power)') itc.plot([0], baseline=None, mode=None, title='S-transform (ITC)')
mode='mean', vmin=-1., vmax=3., title='Sim: Less time smoothing, more frequency smoothing') ################################################################################ # Stockwell (S) transform # S uses a Gaussian window to balance temporal and spectral resolution # Importantly, frequency bands are phase-normalized, hence strictly comparable # with regard to timing, and, the input signal can be recoverd from the # transform in a lossless way if we disregard numerical errors. fmin, fmax = freqs[[0, -1]] for width in (0.7, 3.0): power = tfr_stockwell(epochs, fmin=fmin, fmax=fmax, width=width) power.plot([0], baseline=(0., 0.1), mode='mean', title='Sim: Using S transform, width ' '= {:0.1f}'.format(width), show=True) ################################################################################ # Finally, compare to morlet wavelet n_cycles = freqs / 2. power = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, return_itc=False) power.plot([0], baseline=(0., 0.1), mode='mean',
epochs.pick_types(meg="grad") epochs.crop(-0.2, 1.3).apply_baseline() epochs.resample(200.0, npad="auto") epochs.drop_bad() evoked = epochs.average() if np.isnan(evoked.data).any(): xs.append(subject.split("_")[1]) continue evokeds.append(evoked) if op.isfile(out): tfrs.append(read_tfrs(out)) else: print("computing TFRAverage data for %s: " % subject) tfr = tfr_stockwell(epochs, fmin=fmin, fmax=fmax, n_jobs=12, return_itc=True) write_tfrs(out, tfr, overwrite=write) # %% # partition around 4mos out = features["id"].isin(xs) features = features[~out] ix = np.where(features["age"].values == 120)[0][0] aix = np.argpartition(features["age"].values, ix) assert len(aix) == len(evokeds) # %% A = np.array(evokeds)[aix[:ix]] assr_two = mne.combine_evoked(A.tolist(), "nave")
############################################################################## # Stockwell (S) transform # ======================= # # Stockwell uses a Gaussian window to balance temporal and spectral resolution. # Importantly, frequency bands are phase-normalized, hence strictly comparable # with regard to timing, and, the input signal can be recoverd from the # transform in a lossless way if we disregard numerical errors. In this case, # we control the spectral / temporal resolution by specifying different widths # of the gaussian window using the ``width`` parameter. fig, axs = plt.subplots(1, 3, figsize=(15, 5), sharey=True) fmin, fmax = freqs[[0, -1]] for width, ax in zip((0.2, .7, 3.0), axs): power = tfr_stockwell(epochs, fmin=fmin, fmax=fmax, width=width) power.plot([0], baseline=(0., 0.1), mode='mean', axes=ax, show=False, colorbar=False) 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)
# Setup for reading the raw data raw = io.Raw(raw_fname) baseline = (None, 0) events = mne.find_events(raw, stim_channel="STI 014") # picks MEG gradiometers picks = mne.pick_types(raw.info, meg="grad", eeg=False, eog=True, stim=False) epochs = mne.Epochs( raw, events, event_id, tmin, tmax, picks=picks, baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6), preload=True, ) ############################################################################### # Calculate power and intertrial coherence epochs = epochs.pick_channels([epochs.ch_names[82]]) # reduce computation power, itc = tfr_stockwell(epochs, fmin=6.0, fmax=30.0, decim=4, n_jobs=1, width=0.3, return_itc=True) power.plot([0], baseline=(-0.5, 0), mode=None, title="S-transform (power)") itc.plot([0], baseline=None, mode=None, title="S-transform (ITC)")
power.plot([0], baseline=(13, 14.5), mode='zscore', vmin=-4, vmax=4) # method: multitaper method. # More freq smothing with larger time_bandwidth time_bandwidth = 4.0 freqs = np.linspace(2, 300, num=150) # different number of cycle for each frequency. # More time smothing whei larger cycles. n_cycles = np.linspace(10, 160, num=150) # time smothing: cycle/frequency = timeWidow # freq smothing: time_bandwidth=2.0= timeWindow * bandwidth, so frequency smothing(bandwidth)=time_bandwidth/(timeWindow) power = tfr_multitaper(epochs, picks=[7], freqs=freqs, n_cycles=n_cycles, time_bandwidth=time_bandwidth, return_itc=False) power.plot([0], baseline=(13, 14.5), mode='zscore', vmin=-4, vmax=4) fig, axs = plt.subplots(2, 3, figsize=(15, 5), sharey=True) ass = np.asarray(axs).reshape(1, -1) for type, ax in zip( ['mean', 'ratio', 'logratio', 'percent', 'zscore', 'zlogratio'], ass.T): power.plot([0], baseline=(13, 14), mode=type, axes=ax, vmin=-4, vmax=4) # method: stockwell method epochs.load_data() epoch7 = epochs.pick([7]) power = tfr_stockwell(epoch7, fmin=2, fmax=300, width=0.3) # no picks argument in stockwell power.plot([0], baseline=(13, 14), mode='zscore', vmin=-4, vmax=4, show=False)
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)
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)