from importlibs import *



__author__ = "Andrea Maffezzoli"
__version__ = "$Revision: 0.47 - 08 Feb 2010$"
__name__ = "gettimestamps"
__all__ = ["mea_position", "pneuro"]



class pneuro:

    def __init__(self, filename,
                 plx_data_path,
                 startreplytime = 0, endreplytime = '',
                 min_spikes_nr = None):

        self.mintimelength, self.maxtimelength = startreplytime, endreplytime
        self.file = filename
        
        ############################################################
        # Ask and obtain the minimum required spike number 
        ############################################################
        while True:
            if min_spikes_nr >= 0: setattr(self, 'min_spikes_nr', min_spikes_nr); break
            self.min_spikes_nr = raw_input("Please define the minimum number of \
spikes required to process recordings from a neuron or press Enter if none:\n>> ")
            try:
                if self.min_spikes_nr == '': self.min_spikes_nr = 0
                else: self.min_spikes_nr = int(self.min_spikes_nr)
                break
            except:
                pass
        
        ############################################################
        # Start to collect data in different ways:
        # - at first, try with the 'plx' way
        # - if that fails, come back to the 'nex' way
        ############################################################
        try:

            filepath = '%s%s.plx' % (plx_data_path, filename)
            clsTs = readplx.readPlx(filepath)
            print "Please wait, collecting timestamps data from plx file..."
            
            start = time.time()
            clsTs()
            end = time.time()
            
            self.noc = len(clsTs.DSPChannelsTimestamps_dict)
            transplall = [[''.join((i[0], clsTs.UnitsNames[i[1]]))] + j 
                           for i, j in clsTs.DSPChannelsTimestamps_dict.iteritems()]
            transplall = filter(lambda l: len(l[1:]) >= self.min_spikes_nr, \
                                [list(filter(bool, t)) for t in transplall])
            transplall.sort(cmp = sort_neuro_names, key = operator.itemgetter(0))
            if self.maxtimelength != '':
                print "Data recorded until %f seconds" % self.maxtimelength
                transplall = [[ts for ts in t[1:] \
                               if self.mintimelength <= ts <= self.maxtimelength] \
                               for t in transplall]
        
        except:
            
            filepath = '%s%s.nex' % (plx_data_path, filename)
            clsTs = readnex.readNex(filepath)
            print "Please wait, collecting timestamps data from nex file..."
        
            start = time.time()
            clsTs()
            end = time.time()
        
            self.noc = len(clsTs.NeuronsTimestamps_dict) #set(n[:-1] for n in clsTs.NeuronsTimestamps_dict))
            transplall = [[i] + j for i, j in clsTs.NeuronsTimestamps_dict.iteritems()]
            transplall = filter(lambda l: len(l[1:]) >= self.min_spikes_nr, \
                            [list(filter(bool, t)) for t in transplall])
            transplall.sort(cmp = sort_neuro_names, key = operator.itemgetter(0))
            if self.maxtimelength != '':
                print "Data recorded until %f seconds" % self.maxtimelength
                transplall = [[ts for ts in t[1:] \
                            if self.mintimelength <= ts <= self.maxtimelength] \
                            for t in transplall]
            
        self.transplall = transplall
        self.maxt = max([tpl[- 1] for tpl in self.transplall])
        self.channels = [[z[0][3:5], mea_position(z[0])] for z in self.transplall]
        self.channels_nr = len(self.transplall)        
            
        print "Time required to get timestamps data: %f seconds." % (end - start)
        if self.min_spikes_nr > 0:
            print "There are %d neurons spiking, whose %d has been discarded based on above threshold." % (self.noc, self.noc - self.channels_nr) 
        else:
            print "There are %d neurons spiking." % self.noc 
        print "The experiment has a max duration of %f seconds." % self.maxt
