Changeset 315

Show
Ignore:
Timestamp:
11/10/08 19:17:08 (2 months ago)
Author:
LaurentPerrinet
Message:

Unit Test of signals.py was not working / fixed the computation of CV_KL / some clean-up on the example with a simple neuron

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/examples/single_neuron/CRF_neuron_vs_signal.py

    r173 r315  
    2323 
    2424# this is not mandatory but just a "easy_install progressbar" away 
    25 # else remove all corresponding lines in this code... 
     25# else remove all corresponding 3 lines in this code... 
    2626import progressbar # see http://projects.scipy.org/pipermail/scipy-dev/2008-January/008200.html 
    2727 
     
    3030N_exp_noise = 10 
    3131N_exp_snr = 25 
    32 p.snr = ParameterRange(list(numpy.linspace(-1.,4.,N_exp_snr))) 
    33 p.noise_std = ParameterRange(list(10.**(numpy.linspace(-.50,1.,N_exp_noise)))) 
     32 
     33ps =  ParameterSpace({ 
     34                'snr' : ParameterRange(list(numpy.linspace(-1.,4.,N_exp_snr))), 
     35                'noise_std' : ParameterRange(list(10.**(numpy.linspace(-.50,1.,N_exp_noise))))}) 
     36 
    3437 
    3538name = sys.argv[0].split('.')[0] # name of the current script withpout the '.py' part 
     
    4043 
    4144    # calculates the dimension of the parameter space 
    42     results_dim, results_label = p.parameter_space_dimension_labels() 
     45    results_dim, results_label = ps.parameter_space_dimension_labels() 
    4346 
    4447    # creates results array with size of parameter space dimension 
     
    4952    pbar=progressbar.ProgressBar(widgets=[name, " ", progressbar.Percentage(), ' ', 
    5053            progressbar.Bar(), ' ', progressbar.ETA()], maxval=numpy.prod(results_dim)) 
    51     for i_exp,experiment in enumerate(p.iter_inner()): 
     54    for i_exp,experiment in enumerate(ps.iter_inner()): 
    5255        params = myFibers.params 
    5356        params.update(experiment) # updates what changed in the dictionary 
     
    5558        data = myFibers.run(params,verbose=False) 
    5659        # calculating the index in the parameter space 
    57         index = p.parameter_space_index(experiment) 
     60        index = ps.parameter_space_index(experiment) 
    5861        # put the data at the right position in the results array 
    5962        CRF[index] = data.mean_rate()# 
     
    6568results.close() 
    6669 
    67 #print CRFsr 
    6870#numpy.array(p.noise_std._values),numpy.array(p.snr._values), 
    6971pylab.plot(CRF.transpose()) #color = (sin(2*pi*noise_list)**2,cos(2*pi*noise_list)**2,1)) 
  • trunk/examples/single_neuron/fiber.param

    r171 r315  
    77    "connectseed": 12345789, 
    88  }, 
    9   "snr": 1.0, 
    10   "noise_std": 8.0, 
     9  "snr": 2.0, 
     10  "noise_std": 2.0, 
    1111  "weight": 1.0, 
    12   "N": 50, 
     12  "N": 100, 
    1313} 
  • trunk/examples/single_neuron/simple_single_neuron.py

    r227 r315  
    2121import sys, os, tempfile 
    2222# choosing the simulator 
    23 import pyNN.brian as sim 
     23import pyNN.nest2 as sim 
    2424# the link to read SpikeList files with NeuroTools 
    2525from NeuroTools.signals import load_spikelist 
     
    2727from NeuroTools.parameters import ParameterSet 
    2828 
    29 def define(N=100): 
    30     """ 
    31     defines the parameter set the first time 
    32  
    33     """ 
    34     #these are fixed 
    35     simulation_params = ParameterSet({'dt'        : 0.1,# discretization step in simulations (ms) 
    36                 'simtime'   : 40000*0.1,      # float; (ms) 
    37                 'syn_delay' : 1.0,         # float; (ms) 
    38                 'kernelseed' : 4321097,       # array with one element per thread 
    39                 'connectseed' : 12345789  # seed for random generator(s) used during simulation 
    40                 }) 
    41     # these may change 
    42     P = ParameterSet({'simulation': simulation_params, 
    43                     'N'         : N, 
    44                     'noise_std' : 8.0,       # (nA??) standard deviation of the internal noise 
    45                     'snr'       : 1.0,      # (nA??) size of the input signal 
    46                     'weight'    : 1.0 }, 
    47                     label="fiber_params") 
    48  
    49     P.save('file://' + os.getcwd() + '/fiber.param') 
    5029 
    5130class FiberChannel(object): 
     
    5534    """ 
    5635    def __init__(self,N=100): 
    57         try : 
    58             url = "https://neuralensemble.org/svn/NeuroTools/trunk/examples/single_neuron/fiber.param" 
    59             self.params = ParameterSet(url) 
    60             print "Loaded parameters from SVN" 
    61         except : 
    62             #if you are off-line takes a local copy; use define to create file 
    63             self.params =  ParameterSet('file://' + os.getcwd() + '/fiber.param') 
    64             print "Loaded parameters from local file" 
     36        # simulator specific 
     37        simulation_params = ParameterSet({'dt'        : 0.1,# discretization step in simulations (ms) 
     38                    'simtime'   : 40000*0.1,      # float; (ms) 
     39                    'syn_delay' : 1.0,         # float; (ms) 
     40                    'kernelseed' : 4321097,       # array with one element per thread 
     41                    'connectseed' : 12345789  # seed for random generator(s) used during simulation 
     42                    }) 
     43        # these may change 
     44        self.params = ParameterSet({'simulation': simulation_params, 
     45                        'N'         : N, 
     46                        'noise_std' : 6.0,       # (nA??) standard deviation of the internal noise 
     47                        'snr'       : 1.0,      # (nA??) size of the input signal 
     48                        'weight'    : 1.0 }, 
     49                        label="fiber_params") 
    6550 
    66         # keep all parameters just change the size 
    67         self.params.N = N 
    6851        print self.params.pretty() 
    6952 
     
    7962        N = params.N 
    8063        #dc_generator 
    81         current_source = sim.SpikeSourcePoisson({'rate':params.snr, 
    82                                         'start':params.simulation.simtime/4, 
    83                                         'duration':params.simulation.simtime/2.}) 
    84  
    85  
    86         # internal noise model TODO : does not exist in pyNN! 
    87         noise = sim.Population(N,sim.SpikeSourcePoisson,{'rate':params.snr, 
    88                                                         'start':0., 
    89                                                         'duration':params.simulation.simtime}) 
    90  
     64        current_source = sim.DCSource(  amplitude= params.snr, 
     65                                        start=params.simulation.simtime/4, 
     66                                        stop=params.simulation.simtime/4*3) 
     67         
     68        # internal noise model (NEST specific) 
     69        noise = sim.Population(N,'noise_generator',{'mean':0.,'std':params.noise_std})  
    9170        # target population 
    9271        output = sim.Population(N , sim.IF_cond_exp) 
     
    10180        sim.Projection(noise, output, conn) 
    10281 
    103         #for cell in output: 
    104         #    cell.inject(current_source) 
     82        for cell in output: 
     83            cell.inject(current_source) 
    10584 
    10685        output.record() 
     
    11897        Timer.reset()  # start timer on construction 
    11998 
    120         output_filename=os.path.join(tmpdir,'output.gdf') 
    121         print output_filename 
     99        output_filename = os.path.join(tmpdir,'output.gdf') 
     100        #print output_filename 
    122101        output.printSpikes(output_filename)# 
    123102        output_DATA = load_spikelist(output_filename,N, 
     
    138117        return output_DATA 
    139118 
    140  
    141  
    142119if __name__ == '__main__': 
    143     define(N=50) 
    144     myFibers = FiberChannel() 
     120    myFibers = FiberChannel(N=50) 
    145121    spikes = myFibers.run(myFibers.params) 
    146122    spikes.raster_plot() 
  • trunk/src/signals.py

    r314 r315  
    262262    def mean_rate(self, t_start=None, t_stop=None): 
    263263        """  
    264         Return the mean firing rate between t_start and t_stop, in Hz 
     264        Returns the mean firing rate between t_start and t_stop, in Hz 
    265265         
    266266        Inputs: 
     
    302302         
    303303        See also 
    304             isi 
     304            isi, cv_kl 
     305             
    305306        """ 
    306307        isi = self.isi() 
     
    310311            logging.debug("Warning, a CV can't be computed because there are not enough spikes") 
    311312            return numpy.nan 
     313 
     314 
     315 
     316    def cv_kl(self, bins=100): 
     317        """ 
     318        Provides a measure for the coefficient of variation to describe the 
     319        regularity in spiking networks. It is based on the Kullback-Leibler 
     320        divergence and decribes the difference between a given 
     321        interspike-interval-distribution and an exponential one (representing 
     322        poissonian spike trains) with equal mean. 
     323        It yields 1 for poissonian spike trains and 0 for regular ones. 
     324         
     325        Reference: 
     326            http://incm.cnrs-mrs.fr/LaurentPerrinet/Publications/Voges08fens 
     327         
     328         
     329        Examples: 
     330            >> spklist.cv_kl() 
     331                0.98 
     332         
     333        See also: 
     334            cv_isi 
     335             
     336        """ 
     337        isi = self.isi() / 1000. 
     338        if newnum: 
     339            proba_isi, xaxis = numpy.histogram(isi, bins=bins, normed=True, new=True) 
     340            #xaxis = xaxis[:len(xaxis)-1] 
     341        else: 
     342            proba_isi, xaxis = numpy.histogram(isi, bins=bins, normed=True) 
     343 
     344        proba_isi /= numpy.sum(proba_isi) 
     345        bin_size = xaxis[1]-xaxis[0] 
     346 
     347        # differential entropy: http://en.wikipedia.org/wiki/Differential_entropy 
     348        KL = - numpy.sum(proba_isi * numpy.log(proba_isi+1e-16)) + numpy.log(bin_size) 
     349        KL -= -numpy.log(self.mean_rate()) + 1. 
     350        CVkl=numpy.exp(-KL) 
     351         
     352        return CVkl 
     353     
    312354 
    313355    def fano_factor_isi(self): 
     
    11241166            pylab.draw() 
    11251167 
    1126      
     1168         
    11271169    def cv_isi(self, float_only=False): 
    11281170        """ 
    1129         Return the list of all the cv coefficients for all the SpikeTrains objects 
     1171        Return the list of all the CV coefficients for each SpikeTrains object 
    11301172        within the SpikeList. Return NaN when not enough spikes are present 
    11311173         
     
    11411183 
    11421184        See also: 
    1143             cv_isi_hist, cv_local, cv_kl 
    1144         """ 
    1145         cvs_isi = [] 
     1185            cv_isi_hist, cv_local, cv_kl, SpikeTrain.cv_isi 
     1186             
     1187        """ 
     1188        cvs_isi = numpy.empty(len(self.id_list())) 
    11461189        for id in self.id_list(): 
    1147             cvs_isi.append(self.spiketrains[id].cv_isi()
    1148         cvs_isi = numpy.array(cvs_isi) 
     1190            cvs_isi[id] = self.spiketrains[id].cv_isi(
     1191 
    11491192        if float_only: 
    11501193            cvs_isi = numpy.extract(numpy.logical_not(numpy.isnan(cvs_isi)),cvs_isi) 
     
    11521195 
    11531196 
     1197    def cv_kl(self, bins = 50): 
     1198        """ 
     1199        Return the list of all the CV coefficients for each SpikeTrains object 
     1200        within the SpikeList. 
     1201         
     1202        See also: 
     1203            cv_isi_hist, cv_local, cv_isi, SpikeTrain.cv_kl 
     1204             
     1205        """ 
     1206        cvs_kl = numpy.empty(len(self.id_list())) 
     1207        for id in self.id_list(): 
     1208            cvs_kl[id] = self.spiketrains[id].cv_kl(bins = bins) 
     1209        return cvs_kl 
    11541210 
    11551211    def cv_isi_hist(self, bins=50, display=False, kwargs={}): 
     
    11881244 
    11891245 
    1190  
    1191     def cv_kl(self): 
    1192         """ 
    1193         Provides another (new?) measure for the coefficient of variation to describe the 
    1194         regularity in spiking networks. It is based on the Kullback-Leibler 
    1195         divergence and decribes the difference between a given 
    1196         interspike-interval-distribution and an exponential one (representing 
    1197         poissonian spike trains) with equal mean. 
    1198         It yields approx. 1 for poissonian spike trains and 0 for regular ones. 
    1199          
    1200         Attention: Contrary to the normal cv which is calculated for each 
    1201         single neuron and then averaged, this function needs to synchronously 
    1202         consider the spike times of all neurons. 
    1203          
    1204         Examples: 
    1205             >> spklist.cv_kl() 
    1206                 0.98 
    1207          
    1208         See also: 
    1209             cv_isi, cv_isi_hist, cv_local 
    1210         """ 
    1211          
    1212         isis=numpy.concatenate(self.isi()) 
    1213         mISI=numpy.mean(isis) 
    1214         norm=len(isis) 
    1215         min=numpy.min(isis) 
    1216         max=numpy.max(isis) 
    1217         bins = numpy.arange(min,max,1) 
    1218         #print 'CV-KL   norm=',norm,' #bins=',len(bins),' ev=',mISI 
    1219         hist = numpy.histogram(isis,bins) 
    1220         dist = hist[0].astype(float)/norm 
    1221         testsum = numpy.sum(dist) 
    1222         if testsum>1.1 or testsum<0.9 : 
    1223             print 'CV-KL   testsum=',testsum 
    1224         H=0. 
    1225         for j in range(len(dist)): 
    1226             if dist[j] > 0. : 
    1227                 H = H - (dist[j]*numpy.log(dist[j])) 
    1228         KL=0. 
    1229         KL=-H+numpy.log(mISI)+1. 
    1230         CVkl=numpy.exp(-KL) 
    1231          
    1232         return CVkl 
    12331246 
    12341247 
  • trunk/test/test_signals.py

    r313 r315  
    133133        assert 0.9 < spk1.cv_isi() < 1.1 
    134134        self.assertEqual(spk2.cv_isi(), 0) 
     135 
     136 
     137    def testCvKL(self): 
     138        poisson_param = 1./10 # 1 / firing_frequency 
     139        isi           = numpy.random.exponential(poisson_param, 10000) 
     140        poisson_times = numpy.cumsum(isi)*1000. # To convert the spikes_time in ms 
     141        spk1 = signals.SpikeTrain(poisson_times) 
     142        assert 0.9 < spk1.cv_kl(bins = 1000) < 1.1 
     143        # does not depend on bin size 
     144        assert 0.9 < spk1.cv_kl(bins = 100) < 1.1 
     145        # does not depend on time 
     146        poisson_param = 1./4 
     147        isi           = numpy.random.exponential(poisson_param, 10000) 
     148        poisson_times = numpy.cumsum(isi)*1000. # To convert the spikes_time in ms 
     149        spk1 = signals.SpikeTrain(poisson_times) 
     150        assert 0.9 < spk1.cv_kl() < 1.1 
     151        spk2 = signals.SpikeTrain(range(10), t_stop=10) 
     152        self.assertEqual(spk2.cv_isi(), 0) 
    135153     
    136154    def testHistogram(self): 
    137155        poisson_param = 1./40 
    138         isi           = numpy.random.exponential(poisson_param, 1000
     156        isi           = numpy.random.exponential(poisson_param, 10000
    139157        poisson_times = numpy.cumsum(isi)*1000. # To convert the spikes_time in ms 
    140158        spk = signals.SpikeTrain(poisson_times) 
     
    191209        for idx in xrange(nb_cells): 
    192210            param   = 1./frequencies[idx] 
    193             isi     = numpy.random.exponential(param, 100
     211            isi     = numpy.random.exponential(param, 1000
    194212            pspikes = numpy.cumsum(isi)*1000. # To convert the spikes_time in ms 
    195213            for spike in pspikes:  
     
    279297     
    280298    def testCVKL(self): 
    281         assert 0.8 < self.spk.cv_kl() < 1.2 
     299        assert 0.8 < numpy.mean(self.spk.cv_kl()) < 1.2 
    282300     
    283301    def testCVLocal(self): 
     
    370388        cc1 = self.spk.pairwise_cc_zero([(i,i) for i in xrange(5)], time_bin=0.1) 
    371389        cc2 = self.spk.pairwise_cc_zero(5, time_bin=0.1) 
     390        #print cc1, cc2 
     391 
    372392        assert (0 <= cc1 <= 1) and (cc1 > cc2) 
    373393