Changeset 202

Show
Ignore:
Timestamp:
09/19/08 17:12:29 (4 months ago)
Author:
pierre
Message:

Finish a lot of documentation, delete spikes.py, and create a io.py file to regroup all the read/write function that will handles SpikeList. Now all function can be plotted in subplots, with extra params. Need to be continued

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • branches/cleanup/src/__init__.py

    r190 r202  
    1 __all__ = ['analysis', 'benchmark', 'parameters', 'plotting', 'sandbox', 'spikes', 'signals', 'stgen', 'utilities'] 
     1__all__ = ['analysis', 'benchmark', 'parameters', 'plotting', 'sandbox', 'signals', 'stgen', 'utilities', 'io'] 
    22 
    33"""from tables import __version__ 
  • branches/cleanup/src/analysis.py

    r199 r202  
    1212def ccf(x, y, axis=None): 
    1313    """Computes the cross-correlation function of two series `x` and `y`. 
    14 Note that the computations are performed on anomalies (deviations from 
    15 average). 
    16 Returns the values of the cross-correlation at different lags. 
    17 Lags are given as [0,1,2,...,n,n-1,n-2,...,-2,-1] (not any more) 
    18  
    19 :Parameters: 
    20     `x` : 1D MaskedArray 
    21         Time series. 
    22     `y` : 1D MaskedArray 
    23         Time series. 
    24     `axis` : integer *[None]* 
    25         Axis along which to compute (0 for rows, 1 for cols). 
    26         If `None`, the array is flattened first. 
     14        Note that the computations are performed on anomalies (deviations from 
     15        average). 
     16        Returns the values of the cross-correlation at different lags. 
     17        Lags are given as [0,1,2,...,n,n-1,n-2,...,-2,-1] (not any more) 
     18         
     19        :Parameters: 
     20            `x` : 1D MaskedArray 
     21                Time series. 
     22            `y` : 1D MaskedArray 
     23                Time series. 
     24            `axis` : integer *[None]* 
     25                Axis along which to compute (0 for rows, 1 for cols). 
     26                If `None`, the array is flattened first. 
    2727    """ 
    2828    assert(x.ndim == y.ndim, "Inconsistent shape !") 
  • branches/cleanup/src/signals.py

    r201 r202  
    66import numpy, os, logging, re 
    77from NeuroTools import analysis 
     8from NeuroTools import io 
    89 
    910try : 
     
    1415    print "Warning: pylab not detected, plots will be disabled" 
    1516 
    16  
    17 DEFAULT_BUFFER_SIZE = 10000 
    1817 
    1918class SpikeTrain(object): 
     
    8685        size = len(spike_times) 
    8786        if size == 0: 
    88             if self.t_start is None: 
     87            if self.t_start is None:  
    8988                self.t_start = 0 
    9089            if self.t_stop is None: 
     
    161160        """ 
    162161        return self.t_stop - self.t_start 
     162     
     163    def merge(self, spiketrain): 
     164        """ 
     165        Add the spike times from a spiketrain to the current SpikeTrain 
     166         
     167        Inputs: 
     168            spiketrain     - The SpikeTrain that should be added 
     169         
     170        Examples: 
     171            >> a = SpikeTrain(range(0,100,10),0.1,0,100) 
     172            >> b = SpikeTrain(range(400,500,10),0.1,400,500) 
     173            >> a.merge(b) 
     174            >> a.spike_times 
     175            >> [   0.,   10.,   20.,   30.,   40.,   50.,   60.,   70.,   80., 
     176                90.,  400.,  410.,  420.,  430.,  440.,  450.,  460.,  470., 
     177                480.,  490.] 
     178            >> a.t_stop 
     179            >> 500 
     180        """ 
     181        self.spike_times = numpy.concatenate((self.spike_times, spiketrain.spike_times)) 
     182        self.spike_times = numpy.sort(self.spike_times) 
     183        self.t_start     = min(self.t_start, spiketrain.t_start) 
     184        self.t_stop      = max(self.t_stop, spiketrain.t_stop) 
    163185 
    164186    def format(self, relative=False, quantized=False): 
     
    210232        return numpy.diff(self.spike_times) 
    211233 
    212     # Returns the mean firing rate of the SpikeTrain 
    213234    def mean_rate(self, t_start=None, t_stop=None): 
    214235        """  
     
    229250        return 1000.*len(idx)/(t_stop-t_start) 
    230251 
    231     # Returns the cv of the isi of the SpikeTrain 
    232252    def cv_isi(self): 
    233253        """ 
     
    255275    def fano_factor_isi(self): 
    256276        """  
    257         Return the fano factor of this spike trains ISI  
     277        Return the fano factor of this spike trains ISI. 
     278         
     279        The Fano Factor is defined as the variance of the isi divided by the mean of the isi 
    258280         
    259281        See also 
     
    285307        return numpy.arange(self.t_start, self.t_stop, time_bin) 
    286308 
    287  
    288309    def raster_plot(self, t_start=None, t_stop=None, display=True, kwargs={}): 
    289310        """ 
     
    310331        subplot = self.__getdisplay__(display) 
    311332        if not subplot or not ENABLE_PLOTS: 
    312             return spikes 
     333            print "Plots are unfortunately disabled... Please install matplotlib" 
     334            return 
    313335        else: 
    314336            if len(spikes) > 0: 
     
    372394            self.t_start      = 0.0 
    373395 
     396 
     397    #################################################################### 
     398    ### TOO SPECIFIC METHOD ? 
     399    ### Better documentation 
     400    #################################################################### 
    374401    def tuning_curve(self, var_array, normalized=False, method='sum'): 
    375402        """ 
     
    418445        return tuning_curve 
    419446 
     447 
     448    #################################################################### 
     449    ### TOO SPECIFIC METHOD ? 
     450    ### Better documentation 
     451    #################################################################### 
    420452    def frequency_spectrum(self, time_bin): 
    421453        """ 
     
    423455        frequency axis. 
    424456        """ 
    425         hist = self.time_histogram(time_bin, normalized=False) 
     457        hist       = self.time_histogram(time_bin, normalized=False) 
    426458        freq_spect = analysis.simple_frequency_spectrum(hist) 
    427         freq_bin = 1000.0/self.duration() # Hz 
    428         freq_axis = numpy.arange(len(freq_spect)) * freq_bin     
     459        freq_bin   = 1000.0/self.duration() # Hz 
     460        freq_axis = numpy.arange(len(freq_spect)) * freq_bin     
    429461        return freq_spect, freq_axis     
    430462 
     463 
     464    #################################################################### 
     465    ### TOO SPECIFIC METHOD ? 
     466    ### Better documentation 
     467    #################################################################### 
    431468    def f1f0_ratio(self, time_bin, f_stim): 
    432469        """ 
     
    444481            raise Exception(errmsg) 
    445482        return F1/F0 
    446      
    447     def merge(self, spiketrain, relative_times=False): 
    448         """ 
    449         Add the spike times from `spiketrain` to this `SpikeTrain`s spike list. 
    450         """ 
    451         if relative_times: 
    452             self.relative_times() 
    453             spiketrain.relative_times() 
    454         self.spike_times = numpy.concatenate((self.spike_times, spiketrain.spike_times)) 
    455         self.spike_times.sort() 
    456         self.t_start = min(self.t_start, spiketrain.t_start) 
    457         self.t_stop  = max(self.t_stop, spiketrain.t_stop) 
    458483         
    459484 
     
    500525        self.dt      = dt 
    501526        self.label   = label 
    502         self.dimensions = None 
    503         self.N       = len(id_list) 
     527        self.dimensions = dims 
     528        self.N           = len(id_list) 
    504529        self.spiketrains = {} 
    505530 
     
    607632         
    608633        See also 
    609             concatenate 
     634            concatenate, __setitem__ 
    610635        """ 
    611636        assert isinstance(spktrain, SpikeTrain), "A SpikeList object can only contain SpikeTrain objects" 
    612637        if id in self.id_list: 
    613             raise Exception("id %d already present in SpikeList. Use setitem instead()" %id) 
     638            raise Exception("id %d already present in SpikeList. Use __setitem__ (spk[id]=...) instead()" %id) 
    614639        else: 
    615640            self.spiketrains[id] = spktrain.time_slice(self.t_start, self.t_stop) 
     
    641666            spklists - could be a single SpikeList or a list of SpikeLists 
    642667         
    643         The concatenated SpikeLists must have similar t_start and t_stop, and 
    644         they can't shared similar cells. All theirs ids have to be different 
    645          
    646         See also 
    647             append 
     668        The concatenated SpikeLists must have similar (t_start, t_stop, dt), and 
     669        they can't shared similar cells. All their ids have to be different. 
     670         
     671        See also 
     672            append, merge, __setitem__ 
    648673        """ 
    649674        if isinstance(spklists, SpikeList): 
     
    675700    def id_slice(self, id_list): 
    676701        """ 
    677         Generate a new SpikeList truncated from a particular sublist of cells. The 
    678         new sub SpikeList keeps the time parameters of the old one (dt, t_start, t_stop) 
    679          
    680         id_list could be an integer, and N cells will be randomly selected, or 
    681         a sublist of the ids. 
    682          
    683         See also 
    684             timesubSpikeList 
    685         """ 
    686         new_SpkList = SpikeList([], [], self.dt, self.t_start, self.t_stop) 
     702        Return a new SpikeList obtained by selecting particular ids 
     703         
     704        Inputs: 
     705            id_list - Can be an integer (and then N random cells will be selected) 
     706                      or a sublist of the current ids 
     707         
     708        The new SpikeList inherits the time parameters (t_start, t_stop, dt) 
     709         
     710        Examples: 
     711            >>> spklist.id_list 
     712            >>> [830, 1959, 1005, 416, 1011, 1240, 729, 59, 1138, 259] 
     713            >>> new_spklist = spklist.id_slice(5) 
     714            >>> new_spklist.id_list 
     715            >>> [1011, 729, 1138, 416, 59] 
     716 
     717        See also 
     718            time_slice 
     719        """ 
     720        new_SpkList = SpikeList([], [], self.dt, self.t_start, self.t_stop, self.dimensions) 
    687721        if isinstance(id_list, int): 
    688722            id_list = numpy.random.permutation(self.id_list)[0:id_list] 
     
    696730    def time_slice(self, t_start, t_stop): 
    697731        """ 
    698         Generate a new SpikeList truncated from particular time boundaries 
    699          
    700         See also 
    701             idsubSpikeList 
    702         """ 
    703         new_SpkList = SpikeList([], [], self.dt, t_start, t_stop) 
     732        Return a new SpikeList obtained by slicing between t_start and t_stop 
     733         
     734        Inputs: 
     735            t_start - begining of the new SpikeTrain, in ms. 
     736            t_stop  - end of the new SpikeTrain, in ms. 
     737         
     738        See also 
     739            id_slice 
     740        """ 
     741        new_SpkList = SpikeList([], [], self.dt, t_start, t_stop, self.dimensions) 
    704742        for id in self.id_list: 
    705743            new_SpkList.append(id, self.spiketrains[id].time_slice(t_start, t_stop)) 
    706744        new_SpkList.__calc_startstop() 
    707745        return new_SpkList 
     746         
     747     
     748    def save(self, filename): 
     749        """ 
     750        Save the SpikeList in a text file 
     751         
     752        Inputs: 
     753            filename - name of the file 
     754        """ 
     755        ## Should implement a way of saving the new SpikeList, using io class 
     756        pass 
    708757 
    709758 
     
    713762 
    714763     
    715     def isi(self, nbins=100): 
     764    def isi(self): 
    716765        """ 
    717766        Return the list of all the isi vectors for all the SpikeTrains objects 
     
    730779        """ 
    731780        Return the histogram of the ISI. 
    732         bins may either be an integer, giving the number of bins (between the 
    733         min and max of the data) or a list/array containing the lower edges of 
    734         the bins. 
    735         If display is True or is a plot object, then the histogram is plotted 
    736         Otherwise, the function returns a tuple, (histogram values, bin edges) 
    737          
     781         
     782        Inputs: 
     783            bins    - the number of bins (between the min and max of the data)  
     784                      or a list/array containing the lower edges of the bins. 
     785            display - if True, a new figure is created. Could also be a subplot 
     786            kwargs  - dictionary contening extra parameters that will be sent to the plot  
     787                      function 
     788         
     789        Examples: 
     790            >>> z = subplot(221) 
     791            >>> spklist.isi_hist(10, display=z, kwargs={'color':'r'}) 
     792 
    738793        See also: 
    739794            isi 
     
    752807 
    753808     
    754     def cv_isi(self, nbins=100): 
     809    def cv_isi(self): 
    755810        """ 
    756811        Return the list of all the cv coefficients for all the SpikeTrains objects 
     
    771826        """ 
    772827        Return the histogram of the cv coefficients. 
    773         bins may either be an integer, giving the number of bins (between the 
    774         min and max of the data) or a list/array containing the lower edges of 
    775         the bins. 
    776         If display is True or is a plot object, then the histogram is plotted 
    777         Otherwise, the function returns a tuple, (histogram values, bin edges) 
     828         
     829        Inputs: 
     830            bins    - the number of bins (between the min and max of the data)  
     831                      or a list/array containing the lower edges of the bins. 
     832            display - if True, a new figure is created. Could also be a subplot 
     833            kwargs  - dictionary contening extra parameters that will be sent to the plot  
     834                      function 
     835         
     836        Examples: 
     837            >>> z = subplot(221) 
     838            >>> spklist.cv_isi_hist(10, display=z, kwargs={'color':'r'}) 
    778839         
    779840        See also: 
     
    791852            subplot.plot(xaxis, values, **kwargs) 
    792853            pylab.draw() 
    793              
    794  
    795     def time_axis(self, time_bin): 
    796         return numpy.arange(self.t_start, self.t_stop, time_bin) 
    797854 
    798855 
     
    800857        """ 
    801858        Return the mean firing rate averaged accross all SpikeTrains between t_start and t_stop. 
    802  
    803         See also 
    804             mean_rates 
     859         
     860        Inputs: 
     861            t_start - begining of the selected area to compute mean_rate, in ms 
     862            t_stop  - end of the selected area to compute mean_rate, in ms 
     863         
     864        If t_start or t_stop are not defined, those of the SpikeList are used 
     865         
     866        Examples: 
     867            >>> spklist.mean_rate() 
     868            >>> 12.63 
     869         
     870        See also 
     871            mean_rates, mean_rate_std 
    805872        """ 
    806873        return numpy.mean(self.mean_rates(t_start, t_stop)) 
     
    809876    def mean_rate_std(self, t_start=None, t_stop=None): 
    810877        """ 
    811         Std deviation of the Mean firing rate averaged accross all SpikeTrains between t_start and t_stop 
    812  
    813         See also 
    814             mean_rate 
     878        Standard deviation of the Mean firing rate averaged accross all SpikeTrains  
     879        between t_start and t_stop 
     880 
     881        Inputs: 
     882            t_start - begining of the selected area to compute std(mean_rate), in ms 
     883            t_stop  - end of the selected area to compute std(mean_rate), in ms 
     884         
     885        If t_start or t_stop are not defined, those of the SpikeList are used 
     886         
     887        Examples: 
     888            >>> spklist.mean_rate_std() 
     889            >>> 13.25 
     890 
     891        See also 
     892            mean_rate, mean_rates 
    815893        """ 
    816894        return numpy.std(self.mean_rates(t_start, t_stop)) 
     
    821899        Returns a vector of the size of id_list giving the mean rate for each neuron 
    822900 
    823         See also 
    824             SpikeTrain.mean_rate 
     901        Inputs: 
     902            t_start - begining of the selected area to compute std(mean_rate), in ms 
     903            t_stop  - end of the selected area to compute std(mean_rate), in ms 
     904         
     905        If t_start or t_stop are not defined, those of the SpikeList are used 
     906         
     907        See also 
     908            mean_rate, mean_rate_std 
    825909        """ 
    826910        rates = [] 
     
    833917        """ 
    834918        Return a vector with all the mean firing rates for all SpikeTrains. 
    835         If display is True, then it plots the distribution of the rates 
     919         
     920        Inputs: 
     921            bins    - the number of bins (between the min and max of the data)  
     922                      or a list/array containing the lower edges of the bins. 
     923            display - if True, a new figure is created. Could also be a subplot 
     924            kwargs  - dictionary contening extra parameters that will be sent to the plot  
     925                      function 
     926         
     927        See also 
     928            mean_rate, mean_rates 
    836929        """ 
    837930        rates   = self.mean_rates() 
     
    852945        """ 
    853946        Generate an array with all the spike_histograms of all the SpikeTrains 
    854         objects within the SpikeList. If display is True, then it plots the 
    855         mean firing rate of the all population along time 
    856          
    857         See also 
    858             firing_rate 
    859         """ 
    860         if hasattr(time_bin, '__len__'): 
    861             nbins = len(time_bin) 
    862         else: 
    863             nbins = numpy.ceil((self.t_stop-self.t_start)/float(time_bin)) 
    864         spike_hist = numpy.zeros((self.N, nbins), float) 
    865         logging.debug("nbins = %d" % nbins) 
    866         subplot = self.__getdisplay__(display) 
     947        objects within the SpikeList. 
     948         
     949        Inputs: 
     950            time_bin   - the time bin used to gather the data 
     951            normalized - if True, the histogram are in Hz (spikes/second), otherwise they are 
     952                         in spikes/bin 
     953            display    - if True, a new figure is created. Could also be a subplot. The averaged 
     954                         spike_histogram over the whole population is then plotted 
     955            kwargs     - dictionary contening extra parameters that will be sent to the plot  
     956                         function 
     957         
     958        See also 
     959            firing_rate, time_axis 
     960        """ 
     961        nbins      = self.time_axis(time_bin) 
     962        spike_hist = numpy.zeros((self.N, len(nbins)), float) 
     963        subplot    = self.__getdisplay__(display) 
    867964        for idx,id in enumerate(self.id_list): 
    868             try: 
    869                 spike_hist[idx,:] = self.spiketrains[id].time_histogram(time_bin,normalized) 
    870             except ValueError: 
    871                 print spike_hist[idx,:].shape, self.spiketrains[id].time_histogram(time_bin,normalized).shape 
    872                 print nbins, self.t_start, self.t_stop 
    873                 print self.spiketrains[id].t_start, self.spiketrains[id].t_stop 
    874                 raise 
     965            spike_hist[idx,:] = self.spiketrains[id].time_histogram(time_bin, normalized) 
    875966        if not subplot or not ENABLE_PLOTS: 
    876967            return spike_hist 
    877968        else: 
    878             ylabel = "Spikes per bin" 
     969            if normalized: 
     970                ylabel = "Firing rate (Hz)" 
     971            else: 
     972                ylabel = "Spikes per bin" 
    879973            xlabel = "Time (ms)" 
    880974            self.__labels__(subplot, xlabel, ylabel) 
    881             subplot.plot(self.time_axis(time_bin),sum(spike_hist)/self.N,**kwargs) 
     975            subplot.plot(self.time_axis(time_bin),numpy.sum(spike_hist, axis=0)/self.N,**kwargs) 
    882976            pylab.draw() 
    883977             
     
    885979    def firing_rate(self, time_bin, display=False, kwargs={}): 
    886980        """ 
    887         Calculate firing rate traces (in Hz) from arrays of spike times. 
    888  
    889         Spike times and binwidth should are in milliseconds. 
    890         Returns a tuple (list_of_firing_rate_traces,bins) 
    891  
    892         >>> pylab.plot(output[0].time_axis(dt),sum(output.firing_rate(dt))) 
     981        Generate an array with all the instantaneous firing rates along time (in Hz)  
     982        of all the SpikeTrains objects within the SpikeList. 
     983         
     984        Inputs: 
     985            time_bin   - the number of bins (between the min and max of the data)  
     986                         or a list/array containing the lower edges of the bins. 
     987            display    - if True, a new figure is created. Could also be a subplot. The averaged 
     988                         spike_histogram over the whole population is then plotted 
     989            kwargs     - dictionary contening extra parameters that will be sent to the plot  
     990                         function 
     991         
     992        See also 
     993            spike_histogram, time_axis 
    893994        """ 
    894995        return self.spike_histogram(time_bin, normalized=True, display=display, kwargs=kwargs) 
    895996 
    896997 
    897     # Compute the Fano Factor of the population. Need to be checked 
    898998    def fano_factor(self, time_bin): 
     999        """ 
     1000        Compute the Fano Factor of the population activity. 
     1001         
     1002        Inputs: 
     1003            time_bin   - the number of bins (between the min and max of the data)  
     1004                         or a list/array containing the lower edges of the bins. 
     1005         
     1006        The Fano Factor is computed as the variance of the averaged activity divided by its 
     1007        mean 
     1008         
     1009        See also 
     1010            spike_histogram, firing_rate 
     1011        """ 
    8991012        firing_rate = self.spike_histogram(time_bin) 
    900         firing_rate = sum(firing_rate
    901         fano = numpy.var(firing_rate)/numpy.mean(firing_rate) 
     1013        firing_rate = numpy.sum(firing_rate,axis=0
     1014        fano        = numpy.var(firing_rate)/numpy.mean(firing_rate) 
    9021015        return fano 
    9031016 
     
    9201033 
    9211034     
    922     def id2position(self, id, dims): 
    923         """ 
    924         Allow to translate a gid (ranging from 0 to N*M) into 
    925         a position on a N*M grid. dims should be given as a tuple 
    926         (N,M) 
    927         """ 
    928         # Then we translate it in 2D 
    929         if len(dims) == 1: 
     1035    def id2position(self, id): 
     1036        """ 
     1037        Return a position (x,y) from an id if the cells are aranged on a 
     1038        grid of size dims, as defined in the dims attribute of the SpikeList object 
     1039         
     1040        Inputs: 
     1041            id - the id of the cell 
     1042         
     1043        The 'dimensions' attribute of the SpikeList must be defined 
     1044         
     1045        See also 
     1046            activity_map, activity_movie 
     1047        """ 
     1048        if self.dimensions is None: 
     1049            raise Exception("Dimensions of the population are not defined ! Set spikelist.dims") 
     1050        if len(self.dimensions) == 1: 
    9301051            return id 
    9311052        if len(dims) == 2: 
    932             x = numpy.floor(id/dims[0]) 
    933             y = id % dims[1] 
     1053            x = numpy.floor(id/self.dimensions[0]) 
     1054            y = id % self.dimensions[1] 
    9341055            return (x,y) 
    9351056 
    9361057     
    937     def activity_map(self, dims, t_start=None, t_stop=None, display=False, kwargs={}): 
     1058    def activity_map(self, t_start=None, t_stop=None, float_positions=None, display=False, kwargs={}): 
    9381059        """ 
    9391060        Generate a 2D map of the activity averaged between t_start and t_stop. 
    9401061        If t_start and t_stop are not defined, we used those of the SpikeList object 
    941  
    942         if dims is a tuple, then cells are placed on a grid of size 
    943         (N,M), else if dims is an array of size (2,nb_cells) with the 
    944         x (first line) and y (second line) flotting positions of the cells, 
    945         we generate a scatter plot.  
    946          
    947         bounds is a parameters allowing to specify 
    948         the range of the colorbar 
     1062         
     1063        Inputs: 
     1064            t_start         - if not defined, the one of the SpikeList is used 
     1065            t_stop          - if not defined, the one of the SpikeList is used 
     1066            float_positions - None by default, meaning that the dimensions attribute of the SpikeList 
     1067                              is used to arange the ids on a 2D grid. Otherwise, if the cells have 
     1068                              flotting positions, float_positions should be an array of size 
     1069                              (2, nb_cells) with the x (first line) and y (second line) coordinates of 
     1070                              the cells 
     1071            display         - if True, a new figure is created. Could also be a subplot. The averaged 
     1072                              spike_histogram over the whole population is then plotted 
     1073            kwargs          - dictionary contening extra parameters that will be sent to the plot  
     1074                              function 
     1075 
     1076        The 'dimensions' attribute of the SpikeList is used to turn ids into 2d positions. It should 
     1077        therefore be not empty. 
     1078         
     1079        Examples: 
     1080            >> spklist.activity_map(0,1000,display=True) 
    9491081         
    9501082        See also 
     
    9531085        subplot = self.__getdisplay__(display) 
    9541086         
    955         if t_start == None: t_start = self.t_start 
    956         if t_stop  == None: t_stop  = self.t_stop 
    957         spklist = self.time_slice(t_start, t_stop) 
    958          
    959         if isinstance(dims, tuple) or isinstance(dims, list): 
    960             activity_map = numpy.zeros(dims,float) 
     1087        if t_start == None:  
     1088            t_start = self.t_start 
     1089        if t_stop  == None:  
     1090            t_stop  = self.t_stop 
     1091        if t_start != self.t_start or t_stop != self.t_stop: 
     1092            spklist = self.time_slice(t_start, t_stop) 
     1093        else: 
     1094            spklist = self 
     1095         
     1096        if float_positions is None: 
     1097            if self.dimensions is None: 
     1098                raise Exception("Dimensions of the population are not defined ! Set spikelist.dims") 
     1099            activity_map = numpy.zeros(self.dimensions, float) 
    9611100            rates        = spklist.mean_rates() 
    9621101            for id in spklist.id_list: 
    963                 position = spklist.id2position(id, dims
     1102                position = spklist.id2position(id
    9641103                activity_map[position] = rates[id] 
    9651104            if not subplot or not ENABLE_PLOTS: 
     
    9691108                subplot.colorbar() 
    9701109                pylab.draw() 
    971         elif isinstance(dims, numpy.ndarray): 
    972             if not len(spklist.id_list) == len(dims[0]): 
    973                 raise Exception("Error, the number of positions does not match the number of cells in the SpikeList") 
     1110        elif isinstance(float_positions, numpy.ndarray): 
     1111            if not len(spklist.id_list) == len(float_positions[0]): 
     1112                raise Exception("Error, the number of flotting positions does not match the number of cells in the SpikeList") 
    9741113            rates = spklist.mean_rates() 
    9751114            if not subplot or not ENABLE_PLOTS: 
    9761115                return rates 
    9771116            else: 
    978                 x = dims[0,:] 
    979                 y = dims[1,:] 
     1117                x = float_positions[0,:] 
     1118                y = float_positions[1,:] 
    9801119                subplot.scatter(x,y,c=rates, **kwargs) 
    9811120                subplot.colorbar() 
    982  
    983  
    984     def pairwise_correlations(self, pairs, time_bin=1., display=False): 
    985         """ 
    986         Function to generate an array of cross correlation between computed 
    987         between pairs of cells within the SpikeTrains. pairs should be therefore 
    988         a list of (cell_id_1, cell_id_2). If display is True, then if plots the 
    989         averaged cross correlation over all those pairs 
    990         """ 
    991         if len(pairs[0]) != len(pairs[1]): 
    992             raise Exception("Pairs should have the same number of elements") 
    993         nb_pairs = len(pairs[0]) 
    994         spk1 = self.id_slice(pairs[0]) 
    995         spk2 = self.id_slice(pairs[1]) 
     1121                pylab.draw() 
     1122 
     1123 
     1124    def pairwise_cc(self, pairs, time_bin=1., averaged=False, display=False, kwargs={}): 
     1125        """ 
     1126        Function to generate an array of cross correlations computed 
     1127        between pairs of cells within the SpikeTrains. 
     1128         
     1129        Inputs: 
     1130            pairs    - Could be an int, and then N random pairs of cells will be selected,  
     1131                       or could be a list of tuple (id cell_1, id cell_2) 
     1132            time_bin - The time bin used to gather the spikes 
     1133            averaged - If true, only the averaged CC among all the pairs is returned (less memory needed) 
     1134            display  - if True, a new figure is created. Could also be a subplot. The averaged 
     1135                       spike_histogram over the whole population is then plotted 
     1136            kwargs   - dictionary contening extra parameters that will be sent to the plot  
     1137                       function 
     1138        """ 
     1139        subplot = self.__getdisplay__(display) 
     1140         
     1141        if type(pairs) == int: 
     1142            spk1 = self.id_slice(pairs) 
     1143            spk2 = self.id_slice(pairs) 
     1144            N    = pairs 
     1145        else: 
     1146            pairs  = numpy.array(pairs) 
     1147            N      = len(pairs[:,0]) 
     1148            spk1   = self.id_slice(pairs[:,0]) 
     1149            spk2   = self.id_slice(pairs[:,1]) 
    9961150        hist_1 = spk1.spike_histogram(time_bin) 
    9971151        hist_2 = spk2.spike_histogram(time_bin) 
    9981152        length = 2*len(hist_1[0]) 
    999         subplot = self.__getdisplay__(display) 
    1000         results = numpy.zeros((nb_pairs,length), float) 
    1001         for idx in xrange(nb_pairs): 
     1153        if not averaged: 
     1154            results = numpy.zeros((nb_pairs,length), float) 
     1155        else: 
     1156            results = numpy.zeros(length, float) 
     1157        for idx in xrange(N): 
    10021158            # We need to avoid empty spike histogram, otherwise the ccf function 
    10031159            # will give a nan vector 
    1004             if sum(hist_1[idx]) > 0 and sum(hist_2[idx] > 0): 
    1005                 results[idx,:] = ccf(hist_1[idx],hist_2[idx]) 
    1006         if subplot: 
    1007             results = sum(results)/nb_pairs 
    1008             pylab.figure() 
    1009             xaxis  = time_bin*numpy.arange(-len(results)/2, len(results)/2) 
    1010             xlabel = "Time (ms)" 
    1011             ylabel = "Cross Correlation" 
     1160            if numpy.sum(hist_1[idx]) > 0 and numpy.sum(hist_2[idx] > 0): 
     1161                if not averaged: 
     1162                    results[idx,:] = analysis.ccf(hist_1[idx],hist_2[idx]) 
     1163                else: 
     1164                    results += analysis.ccf(hist_1[idx],hist_2[idx]) 
     1165        if not subplot or not ENABLE_PLOTS: 
     1166            if not averaged: 
     1167                return results 
     1168            else: 
     1169                return results/N 
     1170        else: 
     1171            if averaged: 
     1172                results = results/N 
     1173            else: 
     1174                results = numpy.sum(results, axis=0)/N 
     1175            xaxis   = time_bin*numpy.arange(-len(results)/2, len(results)/2) 
     1176            xlabel  = "Time (ms)" 
     1177            ylabel  = "Cross Correlation" 
    10121178            subplot.plot(xaxis, results) 
    1013             if hasattr(subplot, 'xlabel'): 
    1014                 subplot.xlabel(xlabel, size="large") 
    1015                 subplot.ylabel(ylabel, size="large") 
    1016             else: 
    1017                 subplot.set_xlabel(xlabel, size="large") 
    1018                 subplot.set_ylabel(ylabel, size="large") 
    1019         else: 
    1020             return results 
    1021  
    1022     def mean_rate_variance(self, time_bin): 
    1023         """ 
    1024         Function to extract the variance of the firing rate along time, 
    1025         if events are binned with a time bin. 
    1026         """ 
    1027         firing_rate = self.firing_rate(time_bin) 
    1028         return numpy.var(sum(firing_rate)/self.N) 
    1029  
    1030     def mean_rate_covariance(self, SpkList, time_bin): 
     1179            self.__labels__(subplot, xlabel, ylabel) 
     1180            pylab.draw() 
     1181 
     1182 
     1183    def mean_rate_covariance(self, spikelist, time_bin): 
    10311184        """ 
    10321185        Function to extract the covariance of the firing rate along time, 
     
    10341187        object with same time parameters to calculate the covariance 
    10351188        """ 
    1036         if not isinstance(SpkList, SpikeList): 
     1189        if not isinstance(spikelist, SpikeList): 
    10371190            raise Exception("Error, argument should be a SpikeList object") 
    1038         if not SpkList.get_time_parameters() == self.get_time_parameters(): 
     1191        if not spikelist.get_time_parameters() == self.get_time_parameters(): 
    10391192            raise Exception("Error, both SpikeLists should share common t_start, t_stop and dt") 
    10401193        frate_1 = self.firing_rate(time_bin) 
    1041         frate_1 = sum(frate_1)/self.N 
     1194        frate_1 = numpy.sum(frate_1, axis=0)/self.N 
    10421195        frate_2 = SpkList.firing_rate(time_bin) 
    1043         frate_2 = sum(frate_2)/SpkList.N 
    1044         N = len(frate_1) 
    1045         cov = sum(frate_1*frate_2)/N-sum(frate_1)*sum(frate_2)/(N*N) 
     1196        frate_2 = numpy.sum(frate_2, axis=0)/spikelist.N 
     1197        N       = len(frate_1) 
     1198        cov     = numpy.sum(frate_1*frate_2)/N-numpy.sum(frate_1)*numpy.sum(frate_2)/(N*N) 
    10461199        return cov 
    1047      
    1048     def raster_plot(self, id_list=None, t_start=None, t_stop=None, colors='b', subplot=None, size=1): 
    1049         """ 
    1050         Generate a raster plot of a certain number of cells in the 
    1051         SpikeList object. If id_list is an integer, then N ids will be randomly choosen 
    1052         in id_list. If this is a list, those id will be selected. 
    1053         Raster is made between t_start and t_stop (region of interest, not the global ones) 
    1054         and colors can be a list of color (each for one cells) or a single string 
    1055         to apply the same color to all the raster plots. 
    1056         """ 
     1200 
     1201 
     1202    def raster_plot(self, id_list=None, t_start=None, t_stop=None, display=True, kwargs={}): 
     1203        """ 
     1204        Generate a raster plot for the SpikeList in a subwindow of interest, 
     1205        defined by id_list, t_start and t_stop.  
     1206         
     1207        Inputs: 
     1208            id_list - can be a integer (and then N cells are randomly selected) or a list of ids. If None,  
     1209                      we use all the ids of the SpikeList 
     1210            t_start - in ms. If not defined, the one of the SpikeList object is used 
     1211            t_stop  - in ms. If not defined, the one of the SpikeList object is used 
     1212            display - if True, a new figure is created. Could also be a subplot 
     1213            kwargs  - dictionary contening extra parameters that will be sent to the plot  
     1214                      function 
     1215         
     1216        Examples: 
     1217            >>> z = subplot(221) 
     1218            >>> spikelist.raster_plot(display=z, kwargs={'color':'r'}) 
     1219         
     1220        See also 
     1221            SpikeTrain.raster_plot 
     1222        """ 
     1223        subplot = self.__getdisplay__(display) 
    10571224        if id_list == None:  
    10581225            id_list = self.id_list 
    1059             spk = self.id_slice(id_list) 
     1226            spk = self 
    10601227        elif id_list != self.id_list: 
    10611228            spk = self.id_slice(id_list) 
    1062             id_list = spk.id_list 
    1063         else: 
    1064             spk = self.id_slice(id_list) 
    1065  
    1066         if t_start is None: t_start = self.t_start 
    1067         if t_stop is None:  t_stop = self.t_stop 
    1068  
    1069         if subplot is None: 
    1070             pylab.figure() 
    1071             subplot = pylab 
    1072         if isinstance(colors, str): # this is much, much faster than a different colour per row 
    1073             ids, spike_times = self.as_ids_times() 
     1229 
     1230        if t_start is None: t_start = spk.t_start 
     1231        if t_stop is None:  t_stop  = spk.t_stop 
     1232        if t_start != spk.t_start or t_stop != spk.t_stop: 
     1233            spk = spk.time_slice(t_start, t_stop) 
     1234 
     1235        if not subplot or not ENABLE_PLOTS: 
     1236            print "Plots are unfortunately disabled... Please install matplotlib" 
     1237        else: 
     1238            ids, spike_times = spk.convert(format="[ids, times]") 
    10741239            idx = numpy.where((spike_times >= t_start) & (spike_times <= t_stop))[0] 
    1075             spike_times = spike_times[idx] 
    1076             ids = ids[idx] 
    10771240            if len(spike_times) > 0: 
    1078                 print "Plotting %d points for %s" % (len(spike_times), self.label) 
    1079                 subplot.scatter(spike_times, ids, s=size, c=colors) 
    1080         elif len(colors) != len(id_list): 
    1081             raise Exception("The numbers of colors does not match the number of cells!") 
    1082         else: # this is very slow in interactive mode 
    1083             for count,id in enumerate(spk.id_list): 
    1084                 st = spk.spiketrains[id] 
    1085                 idx = numpy.where((st.spike_times >= t_start) & (st.spike_times <= t_stop))[0] 
    1086                 spikes = st.spike_times[idx] 
    1087                 if len(spikes) > 0: 
    1088                     subplot.scatter(spikes,count*numpy.ones(len(spikes)), s=size, c=colors[count]) 
    1089         xlabel = "Time (ms)" 
    1090         ylabel = "Neuron #" 
    1091         if hasattr(subplot, 'xlabel'): 
    1092             subplot.xlabel(xlabel, size="large") 
    1093             subplot.ylabel(ylabel, size="large") 
    1094         else: 
    1095             subplot.set_xlabel(xlabel, size="large") 
    1096             subplot.set_ylabel(ylabel, size="large") 
    1097         subplot.axis([t_start-10, t_stop+10, -1, len(self)+1]) 
    1098  
    1099     # Clearly not optimal, but at least this is working... The best way to 
    1100     # do that function would be to go through the sorted list of all the spike times 
    1101     def activity_movie(self, dims, time_bin=10, bounds = (0,20), output="animation.mpg", fps=10): 
     1241                logging.debug("Plotting %d points for %s" % (len(spike_times), self.label)) 
     1242                subplot.scatter(spike_times, ids, **kwargs) 
     1243            xlabel = "Time (ms)" 
     1244            ylabel = "Neuron #" 
     1245            self.__labels__(subplot, xlabel, ylabel) 
     1246            min_id = numpy.min(spk.id_list) 
     1247            max_id = numpy.max(spk.id_list) 
     1248            length = (t_stop - t_start) 
     1249            subplot.axis([t_start-0.05*length, t_stop+0.05*length, min_id-2, max_id+2]) 
     1250            pylab.draw() 
     1251 
     1252 
     1253 
     1254    def activity_movie(self, time_bin=10, t_start=None, t_stop=None, float_positions=None, output="animation.mpg", fps=10): 
     1255        """ 
     1256        Generate a movie of the activity between t_start and t_stop. 
     1257        If t_start and t_stop are not defined, we used those of the SpikeList object 
     1258         
     1259        Inputs: 
     1260            time_bin        - time step to bin activity during the movie. One frame is the mean rate during time_bin 
     1261            t_start         - if not defined, the one of the SpikeList is used, in ms 
     1262            t_stop          - if not defined, the one of the SpikeList is used, in ms 
     1263            float_positions - None by default, meaning that the dimensions attribute of the SpikeList 
     1264                              is used to arange the ids on a 2D grid. Otherwise, if the cells have 
     1265                              flotting positions, float_positions should be an array of size 
     1266                              (2, nb_cells) with the x (first line) and y (second line) coordinates of 
     1267                              the cells 
     1268            display         - if True, a new figure is created. Could also be a subplot. The averaged 
     1269                              spike_histogram over the whole population is then plotted 
     1270            kwargs          - dictionary contening extra parameters that will be sent to the plot  
     1271                              function 
     1272 
     1273        The 'dimensions' attribute of the SpikeList is used to turn ids into 2d positions. It should 
     1274        therefore be not empty. 
     1275         
     1276        Examples: 
     1277            >> spklist.activity_map(0,1000,display=True) 
     1278         
     1279        See also&nb