Пример #1
0
	def selectTFData(self, laplacian, excl_factor):
		''' 

		Arguments
		- - - - - 


		Returns
		- - - -

		'''

		# load processed behavior and eeg
		beh = self.beh
		EEG = self.EEG

		# check whether trials need to be excluded
		if type(excl_factor) == dict: # remove unwanted trials from beh
			beh, EEG = trial_exclusion(beh, EEG, excl_factor)

		# select electrodes of interest
		picks = mne.pick_types(EEG.info, eeg=True, exclude='bads')
		eegs = EEG._data[:,picks,:]

		if laplacian:
			embed()
			x,y,z = np.vstack([EEG.info['chs'][i]['loc'][:3] for i in picks]).T
			leg_order = 10 if picks.size <=100 else 12
			eegs = laplacian_filter(eegs, x, y, z, leg_order = leg_order, smoothing = 1e-5)
	
		return eegs, beh
Пример #2
0
Файл: BDM.py Проект: jalilov/DvM
    def selectBDMData(self, EEG, beh, time, excl_factor=None):
        ''' 

		Arguments
		- - - - - 

		EEG (object):
		beh (dataFrame):
		time (tuple | list): time samples (start to end) for decoding
		excl_factor (dict): see Classify documentation

		Returns
		- - - -

		eegs (array): eeg data (trials X electrodes X time)
		beh (dict): contains variables of interest for decoding

		'''

        # check whether trials need to be excluded
        if type(excl_factor) == dict:  # remove unwanted trials from beh
            beh, EEG = trial_exclusion(beh, EEG, excl_factor)

        # apply filtering and downsampling (if specified)
        if self.bdm_type != 'broad':
            EEG = EEG.filter(h_freq=self.bdm_band[0],
                             l_freq=self.bdm_band[1],
                             method='iir',
                             iir_params=dict(ftype='butterworth', order=5))

        if self.downsample != int(EEG.info['sfreq']):
            print('downsampling data')
            EEG.resample(self.downsample)

        # select time window and EEG electrodes
        s, e = [np.argmin(abs(EEG.times - t)) for t in time]
        picks = mne.pick_types(EEG.info, eeg=True, exclude='bads')
        picks = select_electrodes(np.array(EEG.ch_names)[picks], self.elec_oi)
        eegs = EEG._data[:, picks, s:e]
        times = EEG.times[s:e]

        # if specified average over trials
        #beh, eegs = self.averageTrials(beh, eegs, self.to_decode, cnd_header, 4)

        # store dictionary with variables for plotting
        plot_dict = {
            'ch_names': EEG.ch_names,
            'times': times,
            'info': EEG.info
        }

        with open(
                self.FolderTracker(['bdm', self.to_decode],
                                   filename='plot_dict.pickle'),
                'wb') as handle:
            pickle.dump(plot_dict, handle)

        return eegs, beh, times
Пример #3
0
    def selectERPData(self, time, l_filter=False, excl_factor=None):
        ''' 

		THIS NEEDS TO BE ADJUSTED FOR TIMINGS

		Arguments
		- - - - - 


		Returns
		- - - -

		'''

        beh = self.beh
        EEG = self.eeg

        # check whether trials need to be excluded
        if type(excl_factor) == dict:  # remove unwanted trials from beh
            beh, EEG = trial_exclusion(beh, EEG, excl_factor)

        # read in eeg data
        if l_filter:
            EEG.filter(l_freq=None, h_freq=l_filter)

        # select time window and EEG electrodes
        EEG = EEG.crop(tmin=time[0], tmax=time[1])
        ch_names = EEG.ch_names

        self.eeg = EEG

        # store dictionary with variables for plotting
        plot_dict = {
            'ch_names': ch_names,
            'times': EEG.times,
            'info': EEG.info
        }

        with open(
                self.FolderTracker(['erp', self.header],
                                   filename='plot_dict.pickle'.format(
                                       self.header)), 'wb') as handle:
            pickle.dump(plot_dict, handle)
Пример #4
0
    def select_erp_data(
            self,
            excl_factor: dict = None,
            topo_flip: dict = None) -> Tuple[pd.DataFrame, mne.Epochs]:
        """
		Selects the data of interest by excluding a subset of trials

		Args:
			excl_factor (dict, optional): If specified, a subset of trials that 
			matches the specified criteria is excluded from further analysis
			(e.g., dict(target_color = ['red']) will exclude all trials 
			where the target color is red). Defaults to None.
			topo_flip (dict, optional): If specified a subset of trials is 
			flipped such that it is as if all stimuli of interest are 
			presented right (see lateralized_erp). 

		Returns:
			beh: pandas Dataframe
			epochs: epochs data of interest
		"""

        beh = self.beh.copy()
        epochs = self.epochs.copy()

        # if not already done reset index (to properly align beh and epochs)
        beh.reset_index(inplace=True, drop=True)

        # if specified remove trials matching specified criteria
        if excl_factor is not None:
            beh, epochs = trial_exclusion(beh, epochs, excl_factor)

        # check whether left stimuli should be
        # artificially transferred to left hemifield
        if topo_flip is not None:
            (header, left), = topo_flip.items()
            epochs = self.flip_topography(epochs, beh, left, header)
        else:
            print('No topography info specified. In case of a lateralized '
                  'design. It is assumed as if all stimuli of interest are '
                  'presented right (i.e., left  hemifield')

        return beh, epochs
Пример #5
0
	def selectBDMData(self, epochs, beh, time, excl_factor = None):
		''' 
		Arguments
		- - - - - 
		EEG (object):
		beh (dataFrame):
		time (tuple | list): time samples (start to end) for decoding
		excl_factor (dict): see Classify documentation
		Returns
		- - - -
		eegs (array): eeg data (trials X electrodes X time)
		beh (dict): contains variables of interest for decoding
		'''

		# check whether trials need to be excluded
		if type(excl_factor) == dict: # remove unwanted trials from beh
			beh, epochs = trial_exclusion(beh, epochs, excl_factor)

		# apply filtering and downsampling (if specified)
		if self.bdm_type != 'broad':
			print('eeg data is filtered before downsampling and slicing the time window of interest')
			epochs.filter(self.bdm_band[0],self.bdm_band[1], method = 'iir', 
						iir_params = dict(ftype = 'butterworth', order = 5))
			epochs.apply_hilbert(envelope=True)	
			tf_data = abs(epochs._data)**2
			# db convert
			# base_slice = slice(*[np.argmin(abs(epochs.times - t)) for t in self.baseline])
			# print('baseline correct TF data via db convert')
			# tf_data = tf_data.reshape(-1,epochs.times.size)
			# tf_data = np.array(np.matrix(tf_data) / np.matrix(tf_data[:,base_slice]).mean(axis = 1)
			# 		  ).reshape(-1,len(epochs.info['ch_names']),epochs.times.size)
			#epochs._data = 10 * np.log10(tf_data)

			# or 'standard' baseline correction
			epochs._data = abs(epochs._data)**2
			epochs.apply_baseline(baseline = self.baseline) # check whether this is correct???

		if self.downsample < int(epochs.info['sfreq']):
			if self.window_size[0] == 1:
				print('downsampling data')
				epochs.resample(self.downsample, npad='auto')
			else:
				self.down_factor = int(epochs.info['sfreq'])/self.downsample
				print('downsampling will be done after data averaging')

		# select time window and EEG electrodes
		s, e = [np.argmin(abs(epochs.times - t)) for t in time]
		picks = mne.pick_types(epochs.info, eeg=True, eog= True, misc = True, exclude='bads')
		picks = select_electrodes(np.array(epochs.ch_names)[picks], self.elec_oi)
		eegs = epochs._data[:,picks,s:e]
		times = epochs.times[s:e]

		# transform eeg data in case of sliding window approach
		if self.window_size[0] > 1:
			eegs = self.sliding_window(eegs, self.window_size[0], self.window_size[1], self.window_size[2])[:,:,self.window_size[0]-1:]
			times = np.linspace(times[0], times[-self.window_size[0]], eegs.shape[-1])
			s_freq =epochs.info['sfreq']
			time_red = 1/s_freq * 1000 * self.window_size[0]
			warnings.warn(f'Final timepoint in analysis is reduced by {time_red} ms as each timepoint in analysis now reflects {self.window_size[0]} data samples at a sampling rate of {s_freq} Hz', UserWarning)

		return 	eegs, beh, times