Changeset 414 for trunk

Show
Ignore:
Timestamp:
08/05/09 10:12:04 (3 years ago)
Author:
pierre
Message:

Add one other dependency, and I know it is bad... Especially because I think that this should not be a dependency, but that it should be included in NeuroTools. There is a nice package, TableIO, that allows more efficient and fast array creation from large file text. It is much more efficient that numpy.loadtxt or others methods, so since NeuroTools often ends up in loading such big files, it is useful. I also add a NestFile? standard format in io.py for those that would nest files after stimulations not postprocessed by pyNN and that still want to load them and play with NeuroTools

Location:
trunk/src
Files:
2 modified

Legend:

Unmodified
Added
Removed
  • trunk/src/__init__.py

    r400 r414  
     1# -*- coding: utf-8 -*- 
    12""" 
    23NeuroTools 
     
    5354                'scipy' : {'website' : 'http://numpy.scipy.org/' , 'is_present' : False, 'check':False}, 
    5455                'NeuroTools.facets.hdf5' : {'website' : None, 'is_present' : False, 'check':False}, 
    55                 'srblib' : {'website' : 'http://www.sdsc.edu/srb/index.php/Python', 'is_present' : False, 'check':False}, 
    56                 'rpy' : {'website' : 'http://rpy.sourceforge.net/', 'is_present' : False, 'check':False}, 
    57                 'django': {'website': 'http://www.djangoproject.com', 'is_present': False, 'check': False}, 
    58                 'IPython': {'website': 'http://ipython.scipy.org/', 'is_present': False, 'check': False}, 
     56                'srblib'  : {'website' : 'http://www.sdsc.edu/srb/index.php/Python', 'is_present' : False, 'check':False}, 
     57                'rpy'     : {'website' : 'http://rpy.sourceforge.net/', 'is_present' : False, 'check':False}, 
     58                'django'  : {'website': 'http://www.djangoproject.com', 'is_present': False, 'check': False}, 
     59                'IPython' : {'website': 'http://ipython.scipy.org/', 'is_present': False, 'check': False}, 
    5960                'interval': {'website': 'http://pypi.python.org/pypi/interval/1.0.0', 'is_present': False, 'check': False}, 
     61                'TableIO' : {'website': 'http://kochanski.org/gpk/misc/TableIO.html', 'is_present': False, 'check': False}, 
    6062                ## Add here your extensions ### 
    6163               } 
  • trunk/src/io.py

    r401 r414  
     1# -*- coding: utf-8 -*- 
    12""" 
    23NeuroTools.io 
     
    1516StandardPickleFile - object used to manipulate pickle representation of NeuroTools objects (spikes or 
    1617                     analog signals) 
     18NestFile           - object used to manipulate raw NEST file that would not have been saved by pyNN 
     19                     (without headers) 
    1720DataHandler        - object to establish the interface between NeuroTools.signals and NeuroTools.io 
    1821 
     
    2831import os, logging, cPickle, numpy 
    2932DEFAULT_BUFFER_SIZE = -1 
     33HAVE_TABLEIO        = False #check_dependency('TableIO') 
     34 
     35if HAVE_TABLEIO: 
     36    import TableIO 
     37 
    3038 
    3139class FileHandler(object): 
     
    108116        """ 
    109117        cmd = '' 
    110         f = open(self.filename, 'r') 
     118        f   = open(self.filename, 'r') 
    111119        for line in f.readlines(): 
    112120            if line[0] == '#': 
     
    127135        if hasattr(object, "dt"): 
    128136            self.metadata['dt']     = object.dt 
    129  
     137         
    130138    def __check_params(self, params): 
    131139        """ 
     
    153161                raise Exception("dims can not be infered while reading %s" %self.filename) 
    154162        return params 
    155              
     163 
    156164    def get_data(self, sepchar = "\t", skipchar = "#"): 
    157165        """ 
    158166        Load data from a text file and returns an array of the data 
    159167        """ 
    160         try: 
    161             import TableIO 
     168        if HAVE_TABLEIO: 
    162169            data = numpy.fliplr(TableIO.readTableAsArray(self.filename, skipchar)) 
    163         except ImportError: 
    164             myfile = open(self.filename, "r", DEFAULT_BUFFER_SIZE) 
     170        else: 
     171            myfile   = open(self.filename, "r", DEFAULT_BUFFER_SIZE) 
    165172            contents = myfile.readlines() 
    166173            myfile.close() 
    167             data = [] 
    168             for line in contents: 
    169                 if (line[0] != skipchar): 
    170                     line = line.strip().split(sepchar) 
    171                     id   = [int(float(line[-1]))] 
    172                     id.extend(map(float, line[0:-1])) 
    173                     data.append(id) 
     174            data   = [] 
     175            header = True 
     176            idx    = 0 
     177            while header: 
     178                if contents[idx][0] != skipchar: 
     179                    header = False 
     180                    break 
     181                idx += 1 
     182            for i in xrange(idx, len(contents)): 
     183                line = contents[i].strip().split(sepchar) 
     184                id   = [float(line[-1])] 
     185                id  += map(float, line[0:-1]) 
     186                data.append(id) 
    174187            logging.debug("Loaded %d lines of data from %s" % (len(data), self)) 
    175188            data = numpy.array(data, numpy.float32) 
    176189        return data 
    177  
    178     #def get_data(self, sepchar = "\t", skipchar = "#"): 
    179         #return numpy.loadtxt(self.filename, dtype=numpy.float32) 
    180  
     190     
    181191    def write(self, object): 
    182192        # can we write to the file more than once? In this case, should use seek, tell 
     
    191201 
    192202    def read_spikes(self, params): 
    193         fileobj = open(self.filename, 'r', DEFAULT_BUFFER_SIZE) 
    194203        self.__read_metadata() 
    195204        p = self.__check_params(params) 
    196205        from NeuroTools.signals import spikes 
    197         return spikes.SpikeList(self.get_data(), p['id_list'], p['t_start'], p['t_stop'], p['dims']) 
     206        data = self.get_data() 
     207        return spikes.SpikeList(data, p['id_list'], p['t_start'], p['t_stop'], p['dims']) 
    198208 
    199209    def read_analogs(self, type, params): 
    200         fileobj = open(self.filename, 'r', DEFAULT_BUFFER_SIZE) 
    201210        self.__read_metadata() 
    202211        p = self.__check_params(params) 
     
    258267    def read_spikes(self, params): 
    259268        fileobj = file(self.filename,"r") 
    260         object = cPickle.load(fileobj) 
    261         object = self.__reformat(params, object) 
     269        object  = cPickle.load(fileobj) 
     270        object  = self.__reformat(params, object) 
    262271        return object 
    263272         
    264273    def read_analogs(self, type, params): 
    265274        return self.read_spikes(params) 
     275 
     276 
     277 
     278class NestFile(FileHandler): 
     279     
     280    def __init__(self, filename, padding=0, with_time=False, with_gid=True): 
     281        self.filename  = filename 
     282        self.metadata  = {} 
     283        assert (padding >= 0) and (type(padding) == int), "ERROR ! padding should be a positive int" 
     284        self.padding   = padding 
     285        self.with_time = with_time 
     286        self.with_gid  = with_gid 
     287        self.standardtxtfile = StandardTextFile(filename)  
     288     
     289    def write(self, object): 
     290        """ 
     291        Write the object to the file.  
     292         
     293        Examples: 
     294            >> handler.write(SpikeListObject) 
     295            >> handler.write(VmListObject) 
     296        """ 
     297        return self.standardtxtfile.write(object) 
     298     
     299    def __check_params(self, params): 
     300        """ 
     301        Establish a control/completion/correction of the params to create an object by  
     302        using comparison and data extracted from the metadata. 
     303        """ 
     304        if 'dt' in params: 
     305            if params['dt'] is None and 'dt' in self.metadata: 
     306                logging.debug("dt is infered from the file header") 
     307                params['dt'] = self.metadata['dt'] 
     308        if params['id_list'] is None: 
     309            print "WARNING: id_list will be infered based on active cells..." 
     310        elif isinstance(params['id_list'], int): # allows to just specify the number of neurons 
     311            params['id_list'] = range(params['id_list']) 
     312        elif not isinstance(params['id_list'], list): 
     313            raise Exception("id_list should be an int or a list !") 
     314        if params['dims'] is None: 
     315            if 'dimensions' in self.metadata: 
     316                params['dims'] = self.metadata['dimensions'] 
     317            else: 
     318                raise Exception("dims can not be infered while reading %s" %self.filename) 
     319        return params 
     320     
     321    def get_data(self, sepchar = "\t", skipchar = "#"): 
     322        """ 
     323        Load data from a text file and returns a list of data 
     324        """ 
     325        if HAVE_TABLEIO: 
     326            data = TableIO.readTableAsArray(self.filename, skipchar) 
     327        else: 
     328            myfile   = open(self.filename, "r", DEFAULT_BUFFER_SIZE) 
     329            contents = myfile.readlines() 
     330            myfile.close() 
     331            data = [] 
     332            header = True 
     333            idx    = 0 
     334            while header: 
     335                if contents[idx][0] != skipchar: 
     336                    header = False 
     337                    break 
     338                idx += 1 
     339            for i in xrange(idx, len(contents)): 
     340                line = contents[i].strip().split(sepchar) 
     341                id   = [float(line[0])] 
     342                id  += map(float, line[1:]) 
     343                data.append(id) 
     344        return numpy.array(data) 
     345 
     346    def _fix_id_list(self, data, params): 
     347        print "All gids are shifted by padding", self.padding 
     348        data[:,0] = numpy.array(data[:,0], int) - self.padding 
     349        if params['id_list'] is None: 
     350            params['id_list'] = numpy.unique(data[:,0]) 
     351        return data, params 
     352 
     353    def read_spikes(self, params): 
     354        """ 
     355        Read a SpikeList object from a file and return the SpikeList object, created from the File and 
     356        from the additional params that may have been provided 
     357         
     358        Examples: 
     359            >> params = {'id_list' : range(100), 't_stop' : 1000} 
     360            >> handler.read_spikes(params) 
     361                SpikeList Object (with params taken into account) 
     362        """ 
     363        p = self.__check_params(params) 
     364        from NeuroTools import signals 
     365        data      = self.get_data() 
     366        data, p   = self._fix_id_list(data, p) 
     367        return signals.SpikeList(data, p['id_list'], p['t_start'], p['t_stop'], p['dims']) 
     368     
     369    def read_analogs(self, type, params): 
     370        p       = self.__check_params(params) 
     371        data    = self.get_data() 
     372        data, p = self._fix_id_list(data, p) 
     373        from NeuroTools.signals import analogs 
     374        if type == "vm": 
     375            return analogs.VmList(data, p['id_list'], p['dt'], p['t_start'], p['t_stop'], p['dims']) 
     376        elif type == "current": 
     377            return analogs.CurrentList(data, p['id_list'], p['dt'], p['t_start'], p['t_stop'], p['dims']) 
     378        elif type == "conductance": 
     379            if len(data[0,:]) > 2: 
     380                g_exc = analogs.ConductanceList(data[:,[0,1]] , p['id_list'], p['dt'], p['t_start'], p['t_stop'], p['dims']) 
     381                g_inh = analogs.ConductanceList(data[:,[0,2]] , p['id_list'], p['dt'], p['t_start'], p['t_stop'], p['dims']) 
     382                return [g_exc, g_inh] 
     383            else: 
     384                return analogs.ConductanceList(data, p['id_list'], p['dt'], p['t_start'], p['t_stop'], p['dims']) 
     385 
    266386 
    267387