Example #1
0
 def eeg(self):
     if self._eeg is None:
         if len(self._dfile_name)>0:
             self._eeg = eegpy.open_eeg(self._dfile_name)
             self._eeg_was_opened_here = True
         else:
             return None
     if not self._eeg.is_open:
         self.eeg = eegpy.open_eeg(self._dfile_name)
         self._eeg_was_opened_here = True
     return self._eeg
Example #2
0
def freqfilt_eeg(fn_in,fn_out,btype="lp",fl=None,fh=None,border=3,windowed=False):
    eeg = eegpy.open_eeg(fn_in)
    out = eegpy.F32(fn_out,"w+",shape=eeg.shape,cNames=eeg.channel_names,Fs=eeg.Fs)
    if btype == "lp":
        if not windowed:    
            out[:,:] = filtfilt_low(fl,eeg[:,:],Fs=eeg.Fs,border=border)
        else:
            for i in range(0,out.num_datapoints,100000):
                out[i:min(i+100000,out.num_datapoints),:] = filtfilt_low(fl,eeg[i:min(i+100000,out.num_datapoints),:],Fs=eeg.Fs,border=border)
    elif btype == "hp":
        #for i_c in range(eeg.num_channels):
        if not windowed:    
            out[:,:] = filtfilt_high(fh,eeg[:,:],Fs=eeg.Fs,border=border)
        else:
            for i in range(0,out.num_datapoints,100000):
                out[i:min(i+100000,out.num_datapoints),:] = filtfilt_high(fh,eeg[i:min(i+100000,out.num_datapoints),:],Fs=eeg.Fs,border=border)
    elif btype == "bp":
        if not windowed:    
            out[:,:] = filtfilt_band(fl,fh,eeg[:,:],Fs=eeg.Fs,border=border)
        else:
            for i in range(0,out.num_datapoints,100000):
                out[i:min(i+100000,out.num_datapoints),:] = filtfilt_band(fl,fh,eeg[i:min(i+100000,out.num_datapoints),:],Fs=eeg.Fs,border=border)
    elif btype == "bs":
        if not windowed:    
            out[:,:] = filtfilt_bandstop(fl,fh,eeg[:,:],Fs=eeg.Fs,border=border)
        else:
            for i in range(0,out.num_datapoints,100000):
                out[i:min(i+100000,out.num_datapoints),:] = filtfilt_bandstop(fl,fh,eeg[i:min(i+100000,out.num_datapoints),:],Fs=eeg.Fs,border=border)
Example #3
0
    def calculate(self, cond_name=None):
        """After doing the setup, this method actually calculates the Phase-Coherence. 
        If no argument is supplied, then the data for all conditions are calculated."""
        if cond_name == None:
            cnames = self._times.keys()
        else:
            cnames = [cond_name]

        #open file
        f = eegpy.open_eeg(self._dfile_name)
        #check timepoints
        tps_ok = self.check_timepoints()
        if tps_ok:
            for c in cnames:
                if debug:
                    print "Condition %s" % c
                #assert self._datadict.has_key(c) and self._is_calculated.has_key(c), "Key in dictionary missing!"
                #getData
                data = f.get_data_for_events(self._times[c], self._start_end)
                if self.average_over == "trials":
                    #prepare _datadict[c]
                    self._datadict[c] = n.ones(
                        (data.shape[0], data.shape[1], data.shape[1]), "d")
                    #calculate phase coherence
                    for ch1 in range(data.shape[1]):
                        for ch2 in range(ch1):
                            pc = phase_coherence(
                                data[:, ch1, ~self._is_artifact[c]],
                                data[:, ch2, ~self._is_artifact[c]])
                            self._datadict[c][:, ch1, ch2] = pc[:]
                            self._datadict[c][:, ch2, ch1] = pc[:]
                else:
                    s, e = self.average_over
                    self._datadict[c] = n.ones(
                        (data.shape[1], data.shape[1], data.shape[2]), "d")
                    for ch1 in range(data.shape[1]):
                        for ch2 in range(ch1):
                            for tr in range(data.shape[2]):
                                if self._is_artifact[c][tr]:
                                    self._datadict[c][ch1, ch2, tr] = n.nan
                                    self._datadict[c][ch1, ch2, tr] = n.nan
                                else:
                                    pc = phase_coherence(
                                        data[s - self._start_end[0]:e -
                                             self._start_end[0], ch1, tr],
                                        data[s - self._start_end[0]:e -
                                             self._start_end[0], ch2, tr])
                                    #print pc
                                    #print s,e,self._start_end
                                    self._datadict[c][ch1, ch2,
                                                      tr] = self._datadict[c][
                                                          ch2, ch1, tr] = pc
                    #print "Shape datadict:", self._datadict[c].shape
                self._is_calculated[c] = True
        else:
            #TODO: some kind of error message
            print "Some problem with the timepoints occured."
Example #4
0
def extract_part_from_eeg(fn_in,fn_out,start,end,et_in=None,et_out=None):
    """Extract a part of an EEG, write it to new file"""
    eeg = eegpy.open_eeg(fn_in)
    out = eegpy.F32(fn_out,"w+",shape=(end-start,eeg.shape[1]),cNames=eeg.channel_names,Fs=eeg.Fs)
    out[:] = eeg[start:end,:]
    if not et_in==None:
        if et_out==None:
            et_out=os.path.join(os.path.splitext(fn_out)[0],".evt")
        et = eegpy.EventTable(et_in)
        et-=start
        et.save(et_out)
Example #5
0
 def export_data(self, basename="exported_data", conditions=None):
     if conditions == None:
         conditions = self.keys()
     if self.check_timepoints():
         f = eegpy.open_eeg(self._dfile_name)
         for c in conditions:
             if c in self.keys():
                 data = f.get_data_for_events(self._times[c],
                                              self._start_end)
                 for tr in range(data.shape[2]):
                     fn = "%s_%s_%i.dat" % (basename, c, tr)
                     data[:, :, tr].tofile(fn)
         f.close()
Example #6
0
def extract_part_from_eeg(fn_in, fn_out, start, end, et_in=None, et_out=None):
    """Extract a part of an EEG, write it to new file"""
    eeg = eegpy.open_eeg(fn_in)
    out = eegpy.F32(fn_out,
                    "w+",
                    shape=(end - start, eeg.shape[1]),
                    cNames=eeg.channel_names,
                    Fs=eeg.Fs)
    out[:] = eeg[start:end, :]
    if not et_in == None:
        if et_out == None:
            et_out = os.path.join(os.path.splitext(fn_out)[0], ".evt")
        et = eegpy.EventTable(et_in)
        et -= start
        et.save(et_out)
Example #7
0
 def calculate(self, cond_name=None):
     """After doing the setup, this method actually calculates the Phase-Coherence. 
     If no argument is supplied, then the data for all conditions are calculated."""
     if cond_name == None:
         cnames = self._times.keys()
     else:
         cnames = [cond_name]
     
     #open file
     f = eegpy.open_eeg(self._dfile_name)
     #check timepoints
     tps_ok = self.check_timepoints()
     if tps_ok:
         for c in cnames:
             if debug:
                 print "Condition %s" % c
             #assert self._datadict.has_key(c) and self._is_calculated.has_key(c), "Key in dictionary missing!"
             #getData
             data = f.get_data_for_events(self._times[c],self._start_end)
             if self.average_over == "trials":
                 #prepare _datadict[c]
                 self._datadict[c] = np.ones((data.shape[0],data.shape[1],data.shape[1]),"d")
                 #calculate phase coherence
                 for ch1 in range(data.shape[1]):
                     for ch2 in range(ch1):
                         pc = phase_coherence(data[:,ch1,~self._is_artifact[c]],data[:,ch2,~self._is_artifact[c]])
                         self._datadict[c][:,ch1,ch2] = pc[:]
                         self._datadict[c][:,ch2,ch1] = pc[:]
             else:
                 s,e = self.average_over
                 self._datadict[c] = np.ones((data.shape[1],data.shape[1],data.shape[2]),"d")
                 for ch1 in range(data.shape[1]):
                     for ch2 in range(ch1):
                         for tr in range(data.shape[2]):
                             if self._is_artifact[c][tr]:
                                 self._datadict[c][ch1,ch2,tr] = np.nan
                                 self._datadict[c][ch1,ch2,tr] = np.nan
                             else:
                                 pc = phase_coherence(data[s-self._start_end[0]:e-self._start_end[0],ch1,tr],data[s-self._start_end[0]:e-self._start_end[0],ch2,tr])
                                 #print pc
                                 #print s,e,self._start_end
                                 self._datadict[c][ch1,ch2,tr] = self._datadict[c][ch2,ch1,tr] = pc
                 #print "Shape datadict:", self._datadict[c].shape
             self._is_calculated[c] = True
     else:
         #TODO: some kind of error message
         print "Some problem with the timepoints occured."
Example #8
0
    def calculate(self, cond_name=None):
        """After doing the setup, this method actually calculates the ERPs. 
        If no argument is supplied, then the data for all conditions are calculated."""
        if cond_name == None:
            cnames = self._times.keys()
        else:
            cnames = [cond_name]

        #self.check_for_artifacts()

        for c in cnames:
            if debug:
                print "Condition %s" % c
            #assert self._datadict.has_key(c) and self._is_calculated.has_key(c), "Key in dictionary missing!"
            #TODO: open file
            f = eegpy.open_eeg(self._dfile_name)
            #TODO: check timepoints
            ndp = f.numDatapoints
            tps_ok = True
            if debug:
                print ndp, str(f)
            for t in self._times[c]:
                #if debug:
                #    print "t = ", t
                if t + self._start_end[0] < 0 or t + self._start_end[1] > ndp:
                    tps_ok = False
                    break
            if tps_ok:
                #getData
                data = f.get_data_for_events(self._times[c], self._start_end)
                if self._lp_freq != None:
                    data = filtfilt_low(self._lp_freq, data, Fs=f.Fs)
                #Baseline-Korrektur
                data -= data[-self._start_end[0] - 200:-self._start_end[0],
                             ...].mean(axis=0)
                #calculate average
                self._datadict[c] = data[:, :,
                                         ~self._is_artifact[c]].mean(axis=2)
                #print "Shape datadict:", self._datadict[c].shape
                self._is_calculated[c] = True
            else:
                #TODO: some kind of error message
                print "Some problem with the timepoints occured. ndp:", ndp, "max_ts:", max(
                    self._times[c])
                pass
Example #9
0
 def check_for_artifacts(self,
                         thres1=100.0,
                         thres2=50.0,
                         exclude_channels=[]):
     f = eegpy.open_eeg(self._dfile_name)
     channels = range(f.num_channels)
     for c in exclude_channels:
         channels.remove(c)
     for k in self.keys():
         data = f.get_data_for_events(self._times[k], self._start_end)
         for tr in range(data.shape[2]):
             for ch in channels:  #.shape[1]):
                 if abs(data[:, ch, tr]).max() > thres1 or abs(
                         n.diff(data[:, ch, tr])).max() > thres2:
                     if debug:
                         print "Channel %i, Trial %i,condition %s identified as artifact" % (
                             ch, tr, k)
                     self._is_artifact[k][tr] = True
                     break
     f.close()
Example #10
0
    def calculate(self, cond_name=None):
        """After doing the setup, this method actually calculates the ERPs. 
        If no argument is supplied, then the data for all conditions are calculated."""
        if cond_name == None:
            cnames = self._times.keys()
        else:
            cnames = [cond_name]
        #Check if settings for single-trial-power are o.k.
        if "st_power" in self._measures or "st_power_nb" in self._measures:
            if self.st_power_start_end[0] > self.st_power_start_end[
                    1] or self.st_power_start_end[0] < self._start_end[
                        0] or self.st_power_start_end[1] > self._start_end[1]:
                raise ValueError(
                    "The settings for the interval for the single-trial power are incorrect: %s"
                    % (str(self.st_power_start_end)))

        for c in cnames:
            #assert self._datadict.has_key(c) and self._is_calculated.has_key(c), "Key in dictionary missing!"
            #TODO: open file
            f = eegpy.open_eeg(self._dfile_name)
            #TODO: check timepoints
            ndp = f.numDatapoints
            tps_ok = True
            for t in self._times[c]:
                if t + self._start_end[0] < 0 or t + self._start_end[1] > ndp:
                    tps_ok = False
                    break
            if tps_ok:
                self._datadict[c] = {}
                if "mean_power" in self._measures:
                    self._datadict[c]["mean_power"] = n.zeros(
                        (self._start_end[1] - self._start_end[0],
                         f.numChannels, len(self._freqs)), "d")
                if "itpc" in self._measures:
                    self._datadict[c]["itpc"] = n.zeros(
                        (self._start_end[1] - self._start_end[0],
                         f.numChannels, len(self._freqs)), "d")
                if "st_power" in self._measures:
                    self._datadict[c]["st_power"] = n.zeros(
                        (f.numChannels, len(self._times[c]), len(self._freqs)),
                        "d")
                if "st_power_nb" in self._measures:
                    self._datadict[c]["st_power_nb"] = n.zeros(
                        (f.numChannels, len(self._times[c]), len(self._freqs)),
                        "d")

                for ch in range(f.numChannels):
                    if debug:
                        print "Condition", c, "Channel", ch
                    #getData
                    data = f.get_data_for_events(self._times[c],
                                                 self._start_end, [ch])
                    #calculate wavelets
                    wts = n.zeros(
                        (data.shape[0], data.shape[2], len(self._freqs)), "D")
                    for j in range(data.shape[2]):
                        wts[:, j, :] = wt_analyze(data[:, 0, j], self._freqs,
                                                  self._Fs)
                        #print wt_analyze(data[:,i,j],self._freqs, self._Fs).shape, self._datadict[c][:,i,j,:].shape
                    if "mean_power" in self._measures:
                        tmp = (abs(
                            wts[:, ~self._is_artifact[c], :])**2).mean(axis=1)
                        #print "tmp.shape:", tmp.shape
                        for fr in range(tmp.shape[1]):
                            tmp[:, fr] = 10 * (n.log10(tmp[:, fr]) - n.log10(
                                tmp[-self._start_end[0] -
                                    200:-self._start_end[0], fr].mean()))
                        self._datadict[c]["mean_power"][:, ch, :] = tmp
                    if "itpc" in self._measures:
                        tmp = wts[:, :, :] / abs(wts[:, :, :])
                        self._datadict[c]["itpc"][:, ch, :] = abs(
                            tmp.mean(axis=1))
                    if "st_power" in self._measures:
                        tmp = abs(wts[:, :, :])**2
                        for tr in range(tmp.shape[1]):
                            for fr in range(tmp.shape[2]):
                                tmp[:, tr, fr] = 10 * (
                                    n.log10(tmp[:, tr, fr]) -
                                    n.log10(tmp[-self._start_end[0] -
                                                200:-self._start_end[0], tr,
                                                fr].mean()))
                        self._datadict[c]["st_power"][ch, :, :] = tmp[
                            -self._start_end[0] +
                            self.st_power_start_end[0]:-self._start_end[0] +
                            self.st_power_start_end[1], :, :].mean(axis=0)
                    if "st_power_nb" in self._measures:
                        tmp = abs(wts[:, :, :])**2
                        #for tr in range(tmp.shape[1]):
                        #    for fr in range(tmp.shape[2]):
                        #        tmp[:,tr,fr] = 10*( n.log10(tmp[:,tr,fr]) -n.log10 (tmp[-self._start_end[0]-200:-self._start_end[0],tr,fr].mean()))
                        self._datadict[c]["st_power_nb"][ch, :, :] = tmp[
                            -self._start_end[0] +
                            self.st_power_start_end[0]:-self._start_end[0] +
                            self.st_power_start_end[1], :, :].mean(axis=0)
                #print "Shape datadict:", self._datadict[c].shape
                self._is_calculated[c] = True
            else:
                #TODO: some kind of error message

                pass
Example #11
0
 def get_channel_names(self):
     rv = []
     f = eegpy.open_eeg(self._dfile_name)
     rv = f.getChannelNames()
     f.close()
     return rv
Example #12
0
        #        print "Error while creating array for data."

    def check_timepoints(self, remove_false=False):
        """checks all timepoints of all conditions if they make sense.
        I.e. if they are within the interval [0,numdatapoints[
        Parameters:
        remove_false: Triggers wether false timepoints are removed from the conditions."""
        ndp = 10e50
        try:
            ndp = f.numDatapoints
        except Exception, e:
            try:
                f.close()
            except Exception, e:
                pass
            f = eegpy.open_eeg(self._dfile_name)
            ndp = f.numDatapoints
        all_ok = True
        for k in self.keys():
            #            for i in range(len(self._times[k])):
            #                if self._times[k][i]+self._start_end[0]<0 or self._times[k][i]+self._start_end[1]>=ndp:
            #                    all_ok = False
            #                    if remove_false:
            #                        print "eegpy.analysis.timefreq: Removal of invalid time points not implemented yet!"
            #del self._times[k][i]
            for i in range(len(self._times[k]) - 1, -1,
                           -1):  #Go through indices in inverse order
                if self._times[k][i] + self._start_end[0] < 0 or self._times[
                        k][i] + self._start_end[1] >= ndp:
                    all_ok = False
                    if remove_false:

def main(argv):
    parse_args(sys.argv[1:])
    if debug:
        print input, output, exclude_channels
    #copy input-file to ouput-file
    try:
        shutil.copyfile(input,output)
    except Exception,e:
        print "Cannot copy file %s to %s,"%(input,output), e
        usage()
        sys.exit(2)
    #open eeg-file and rereference
    try:
        eeg = eegpy.open_eeg(output)
        bsl = np.ones((eeg.num_channels),np.bool)
        for ec in exclude_channels:
            if ec<eeg.num_channels:
                bsl[ec]=True
        start = 0
        while start<eeg.num_datapoints:
            if debug:
                print start
            length=10000
            if start+length>=eeg.num_datapoints:
                length=eeg.num_datapoints-start
            eeg[start:start+length,:] -= np.repeat(eeg[start:start+length,bsl].mean(axis=1).reshape(length,1),eeg.num_channels,axis=1)
            start+=length
        #for i in range(eeg.num_datapoints):
        #    eeg[i,:] -= eeg[i,bsl].mean()
Example #14
0
def freqfilt_eeg(fn_in,
                 fn_out,
                 btype="lp",
                 fl=None,
                 fh=None,
                 border=3,
                 windowed=False):
    eeg = eegpy.open_eeg(fn_in)
    out = eegpy.F32(fn_out,
                    "w+",
                    shape=eeg.shape,
                    cNames=eeg.channel_names,
                    Fs=eeg.Fs)
    if btype == "lp":
        if not windowed:
            out[:, :] = filtfilt_low(fl, eeg[:, :], Fs=eeg.Fs, border=border)
        else:
            for i in range(0, out.num_datapoints, 100000):
                out[i:min(i + 100000, out.num_datapoints), :] = filtfilt_low(
                    fl,
                    eeg[i:min(i + 100000, out.num_datapoints), :],
                    Fs=eeg.Fs,
                    border=border)
    elif btype == "hp":
        #for i_c in range(eeg.num_channels):
        if not windowed:
            out[:, :] = filtfilt_high(fh, eeg[:, :], Fs=eeg.Fs, border=border)
        else:
            for i in range(0, out.num_datapoints, 100000):
                out[i:min(i + 100000, out.num_datapoints), :] = filtfilt_high(
                    fh,
                    eeg[i:min(i + 100000, out.num_datapoints), :],
                    Fs=eeg.Fs,
                    border=border)
    elif btype == "bp":
        if not windowed:
            out[:, :] = filtfilt_band(fl,
                                      fh,
                                      eeg[:, :],
                                      Fs=eeg.Fs,
                                      border=border)
        else:
            for i in range(0, out.num_datapoints, 100000):
                out[i:min(i + 100000, out.num_datapoints), :] = filtfilt_band(
                    fl,
                    fh,
                    eeg[i:min(i + 100000, out.num_datapoints), :],
                    Fs=eeg.Fs,
                    border=border)
    elif btype == "bs":
        if not windowed:
            out[:, :] = filtfilt_bandstop(fl,
                                          fh,
                                          eeg[:, :],
                                          Fs=eeg.Fs,
                                          border=border)
        else:
            for i in range(0, out.num_datapoints, 100000):
                out[i:min(i +
                          100000, out.num_datapoints), :] = filtfilt_bandstop(
                              fl,
                              fh,
                              eeg[i:min(i + 100000, out.num_datapoints), :],
                              Fs=eeg.Fs,
                              border=border)