Exemple #1
0
    def get_eeg(self, eegpath):

        assert (self.params.has_key('Filename'))
        #assert(len(self.channels)==self.params['NchanFile'])

        fullpath = self.params['Filename']
        amp = data.Amp()
        amp.extend(self.channels)

        if eegpath is None:
            raise RuntimeError('Could not find %s' % eegpath)

        if self.params.has_key('Date') and self.params.has_key('Time'):
            sd = self.params['Date'].strftime('%Y-%m-%d')
            st = self.params['Time'].strftime('%H:%M:%S')
            datestr = '%s %s' % (sd, st)

            basename, fname = os.path.split(eegpath)

        print "FileFormat_BNI.get_eeg(): date is ", datestr

        print "FileFormat_BNI.get_eeg(): channels is ", self.params[
            'NchanFile']

        params = {
            'pid':
            self.params.get('PatientId', 'Unknown'),
            'date':
            datetime.datetime.combine(self.params['Date'],
                                      self.params['Time']),
            'filename':
            fname,
            'description':
            self.params.get('Comment', ''),
            'channels':
            self.params['NchanFile'],
            'freq':
            self.params.get('Rate'),
            'classification':
            99,
            'file_type':
            1,
            'behavior_state':
            99,
        }

        eeg = data.EEGFileSystem(eegpath, amp, params)
        scale = self.params.get('UvPerBit', None)
        eeg.scale = scale
        eeg.amp = amp

        #print "FileFormat_BNI.get_eeg(): eeg.amp=", eeg.amp
        return eeg
    def __init__(self, path):
        """
        Given a .axonascii filename, create a EEGFileSystem object w/ appropriate member variables
        (e.g. date, filename, channels, freq, fiel_type, raw_data)

        This is ugly, but so is the file format.
        """
        ascfile = file(path)
        ascfile.readline() # skip blank line
        ascfile.readline() # skip blank line
        name_line = ascfile.readline().split(": ")
        name = ((name_line[1])[:-2])
        #print "load_axonascii(): name is \'%s\'" % name
        date_line = ascfile.readline().split(":  ")
        date = (date_line[1])[:-2]
        [datestamp, timestamp] = date.split(", ")
        axondate = self.get_axondate(datestamp, timestamp)
        #print "load_axonascii(): date is", axondate # we want to use the first date in the data stream, though, not this one

        ampset = set()
        n_channels = 0
        channels = []
        n_lines = 0

        beginning_position = ascfile.tell()

        # do loop to determine # of channels and their indices/names.. and also to find sampling rate!
        curr_amp_num = 1 # we fake the "amplifier" indices
        
        old_axondate = None
        have_calculated_sr = False
        sampling_rate = -1

        sampling_rate_counter = 0
        sampling_rate_counter_channel = -1
    
        while 1:
            ascline = ascfile.readline()
            asc_split = ascline.split(',')
            if (len(asc_split) <2): # last (presumably blank) line
                break

            #curr_amp_num = int(asc_split[0])  # mcc XXX
            channel_str = asc_split[1]
            channel_str = re.sub('\"', '', channel_str)
            channel_str_split = channel_str.split(':')
            curr_channel_num = int(channel_str_split[0])
            curr_channel_name = channel_str_split[1]
        
            curr_axondate = self.get_axondate(asc_split[2], asc_split[3])
        
            curr_vals = (asc_split[4:])

            #if curr_amp_num in ampset:
            if curr_channel_num in ampset:
                if (have_calculated_sr == False):
                    #print "load_axonascii(): ", curr_channel_num, "curr_axondate = ", curr_axondate, " and old_axondate=", old_axondate, "len(curr_vals)=", len(curr_vals)
                    #print "load_axonascii(): curr-old axondates=", curr_axondate - old_axondate, type(curr_axondate-old_axondate)
                    if (round(float((curr_axondate-old_axondate).seconds)) == 0):
                        if (sampling_rate_counter_channel == -1):
                            #print "initializing sampling_rate_counter_channel=", curr_channel_num, "with value ", len(curr_vals)
                            sampling_rate_counter_channel = curr_channel_num
                            sampling_rate_counter += len(curr_vals)
                        elif (sampling_rate_counter_channel == curr_channel_num):
                            #print "got another bunch of ", len(curr_vals) , "on sampling_rate_counter_channel=", sampling_rate_counter_channel
                            sampling_rate_counter += len(curr_vals)
                        
                    else:
                        # mcc: XXX should this next if statement be commented ?? this seems necessary for certain example files
                        #if (sampling_rate_counter == 0):
                        sampling_rate_counter += len(curr_vals)
                        sampling_rate = float(sampling_rate_counter)/float((curr_axondate-old_axondate).seconds)
                        print "load_axonascii(): sampling rate = " , float(sampling_rate_counter), "/ " , float((curr_axondate-old_axondate).seconds) , "=",  sampling_rate
                        have_calculated_sr = True
                n_channels = len(ampset)
            else:
                #print "load_axonascii(): axon channel %d/%s: read %d vals at date %s" % (curr_channel_num, curr_channel_name, len(curr_vals), str(curr_axondate))
                old_axondate = curr_axondate
                #ampset.add(curr_amp_num)
                ampset.add(curr_channel_num)
                #print "load_axonascii(): adding to channels:  ", curr_amp_num, curr_channel_name, curr_channel_num
                channels.append((curr_amp_num, curr_channel_name, curr_channel_num))
                #print "load_axonascii(): adding %d/%s/%d" % (curr_amp_num, curr_channel_name, curr_channel_num)
            n_lines = n_lines + 1
            curr_amp_num += 1

        channel_data = zeros((n_lines, 500), 'f')

        #print "load_axonascii(): ok we found n_channels=%d" % (n_channels)

        # seek back to beginning
        ascfile.seek(beginning_position, 0)

        curr_line_num = 0
        # repeat until end of file...
        for ascline in ascfile:
            asc_split = ascline.split(',')
            if (len(asc_split) <2): # last (presumably blank) line
                break

            # XXX: we will be building a standard "Amp" class for eegview
            curr_amp_num = int(asc_split[0]) 

            channel_str = asc_split[1]
            channel_str = re.sub('\"', '', channel_str)
            channel_str_split = channel_str.split(':')
            curr_channel_num = int(channel_str_split[0])
            curr_channel_name = channel_str_split[1]
        
            curr_axondate = self.get_axondate(asc_split[2], asc_split[3])
            if (curr_line_num == 0):
                # save the first time! get_date() should now work on the EEGFileSystem object
                axondate = curr_axondate

            curr_vals = (asc_split[4:])

            #print "channel %d/%s: read %d vals at date %s" % (curr_channel_num, curr_channel_name, len(curr_vals), str(curr_axondate))

            index = 0
            for x in curr_vals:
                channel_data[curr_line_num][index] = float(x)
                index = index + 1

            #print "computed channel_data[%d] = " % curr_line_num, channel_data[curr_line_num][0:4], "..."
    
            curr_line_num = curr_line_num+1
        
        #print "n_channels = ", n_channels
        #print "and channels = ", channels
       
        params = {
            'date' : axondate,
            'filename' : path,     
            'channels' : n_channels,
            'freq' : sampling_rate,
            'file_type': 6,
            'raw_data': channel_data
        }

        amp = data.Amp()
        amp.extend(channels)

        #print "called amp.extend(channels); amp=", amp

        self.eeg = data.EEGFileSystem(path, amp, params)
    def __init__(self, path):
        newheader = 0
        almostdone = 0
        line_count = 0
        self.xmin = 0
        with open(path) as ascfile:
            for line in ascfile:
                found_eof = 0
                n_channels = -1
        
                ascline = line.strip()
                #the following few lines are a hack to get around a problem I've been having with random EOFs strangely peppered through neuroscanascii files before the true EOF -eli
                if not ascline:
                    almostdone = 1
                    continue
                if almostdone == 1:
                    if not ascline:
                        break
                    else:
                        almostdone = 0
                if (ascline[0] == '['):
                    # on initial parse, grab "electrode_labels" (a.k.a. "channels" for Amp class)
                    if newheader == 1:
                        print "parsing electrode_labels: ",ascline
                        electrode_labels = self.parse_electrode_labels(ascline)
                        newheader = 0
                    #skip to the next line:
                    if (ascline == '[Electrode Labels]'):
                        newheader = 1
                    
                    elif (ascline.find('[Rate]') == 0):
                        sampling_rate = self.parse_sampling_rate(ascline)
                    elif (ascline.find('[Xmin]') == 0):
                        self.xmin = self.parse_xmin(ascline)
                else:
                    if (n_channels == -1):
                        n_channels = len(ascline.split('\t'))
                    else:
                        if (n_channels != len(ascline.split('\t'))):
                            print "wtf , got %d channels but already had %d n_channels", (len(ascline.split('\t')), n_channels)
                    line_count = line_count + 1

        print "line_count is " , line_count
        #changing channel data to a numpy array
        #default dtype is numpy.float64
        #note: tested for validity; also seems to speed up program noticably
        channel_data = numpy.zeros((n_channels, line_count))
        print "channel_data.shape is " , channel_data.shape

        line_count = 0
        almostdone = 0
        with open(path) as ascfile:
            for line in ascfile:
                ascline = line.strip()
                if almostdone == 1:
                    if not ascline:
                        break
                    else:
                        almostdone = 0
                if not ascline:
                    almostdone = 1
                    continue
                elif (ascline[0] == '['):
                    continue
                asc_split = ascline.split('	')
                # we now have n_channels channel values which basically consist of a column of data in channel_data, sweet
                #slicing works pretty much the same for numpy arrays
                #print asc_split[0:n_channels]
                channel_data[:, line_count] = map(float, asc_split[0:n_channels])
                line_count += 1

        #"ok, done with channel_data. assigned " , channel_assign_count, " channels"
        print "new linecount!! ", line_count
        amp = data.Amp()

        channels = []
                        
        for i in range(0, len(self.electrode_labels)):
            print "appending to channels " , ((i+1, self.channel_names[i], self.channel_numbers[i]))
            channels.append((i+1, self.channel_names[i], self.channel_numbers[i]))

        print "electrode_labels = ", self.electrode_labels
        print "channels = ", channels
        
        n_channels, channels, channel_data = self.manipulate_channels(n_channels,channels,channel_data)
        #pass forward the zeroed channel info so that coherence results aren't skewed!
        #self.zerochans.append(self.newchannels)
            
        amp.extend(channels)

        params = {
            'date' : datetime.datetime.now(),
            'filename' : path,     
            'channels' : n_channels,
            'freq' : self.sampling_rate,
            'xmin' : self.xmin,
            'file_type': 7,
            'raw_data': channel_data
        }


        print "called amp.extend(channels); amp=", amp

        self.eeg = data.EEGFileSystem(path, amp, params)
    def __init__(self, path):
        ascfile = file(path)
        beginning_position = ascfile.tell() 
        topline = ascfile.readline()
        #print "FileFormat_AlphaomegaAscii(): top line is: ", topline
        p = re.compile('[\ \t\r\n]*')
        top_split = p.split(topline)
        #print "FileFormat_AlphaomegaAscii(): top split is: ", top_split
        # ['C:\\Logging_Data\\A2112001.map', 'Thr', '21/12/2005', '21:39:21', '']
        date_str = top_split[2]
        time_str = top_split[3]
        date_split = date_str.split('/')
        time_split = time_str.split(':')
        alphaomegadate = datetime.datetime(int(date_split[2]), int(date_split[1]), int(date_split[0]), int(time_split[0]), int(time_split[1]), int(time_split[2])) 
        
        
        
        channel_name_map, channel_num_map, channel_sr_map, channel_count = self.get_channel_maps(ascfile)
        ascfile.seek(0) 
        ascline = ascfile.readline()
        print "FileFormat_AlphaomegaAscii(): top line is this crap ", ascline

        # XXX: arbitrarily choose which channels to take
        #dbs_0_channelname = 'DBS_0'
        dbs_0_channelname = 'LFP_1'

        print "channel_num_map is ", channel_num_map
        dbs0_num = channel_num_map[dbs_0_channelname]
        arbitrary_sr = channel_sr_map[dbs0_num]
        arbitrary_ndatapts = channel_count[dbs0_num]
        arbitrary_channel_list = []
        arbitrary_channel_map = {}
        i = 0
        for k,v in channel_count.iteritems():
            if (channel_sr_map[k] == arbitrary_sr):
                arbitrary_channel_list.append(k)
                arbitrary_channel_map[k]= i
                i = i + 1

        print "channels with appropriate sampling rate: ", arbitrary_channel_list

        print "allocating channel_data of size (%d, %d)" % ( len(arbitrary_channel_list), arbitrary_ndatapts)
        channel_data = zeros((len(arbitrary_channel_list), arbitrary_ndatapts), 'f')


        self.fill_channel_data(ascfile, channel_data, arbitrary_channel_map, channel_name_map)

        print "WHOA ok channel_data[0,0:10] looks like", channel_data[0, 0:10]

        amp = data.Amp()
        amp_channels = []
        i = 1
        for k,v in arbitrary_channel_map.iteritems():
            print "appending (", i, channel_name_map[k], k, ")"
            amp_channels.append((i, channel_name_map[k], k))
            i = i + 1
        amp.extend(amp_channels)
        
        params = {
            'date' : alphaomegadate,
            'filename' : path,     
            'channels' : len(arbitrary_channel_list),
            'freq' : arbitrary_sr,
            'file_type': 8,
            'raw_data': channel_data
        }

        self.eeg = data.EEGFileSystem(path, amp, params)