Changeset 3

Show
Ignore:
Timestamp:
04/16/07 16:58:22 (6 years ago)
Author:
davison
Message:

Synchronised with FACETSCOMMON (r163) repository (post Code-Jam).

Location:
trunk
Files:
5 modified

Legend:

Unmodified
Added
Removed
  • trunk/common.py

    r1 r3  
    33The simulator-specific classes should inherit from these and have the same 
    44arguments. 
    5 $Id: common.py 78 2007-01-25 10:36:59Z apdavison $ 
     5$Id: common.py 146 2007-04-03 16:19:16Z Pierre $ 
    66""" 
    77__version__ = "$Revision: 284 $" 
     
    360360        pass 
    361361 
    362     def printSpikes(self,filename,gather=True): 
     362    def printSpikes(self,filename,gather=True, compatible_output=True): 
    363363        """ 
    364364        Prints spike times to file in the two-column format 
     
    367367        This allows easy plotting of a `raster' plot of spiketimes, with one 
    368368        line for each cell. 
    369         """ 
    370         pass 
    371      
    372     def print_v(self,filename,gather=True): 
     369        On the first line, we have the dimension of the populations 
     370        By defaut, we should use a common format for that could be provided independent 
     371        of the simulator used to run the simulation. This will include post processing 
     372        of the raw file provided by the simulator, so for speed up increase one can 
     373        prefer to use avoid this step and use the format proposed by the different simulators 
     374        """ 
     375        pass 
     376     
     377    def print_v(self,filename,gather=True, compatible_output=True): 
    373378        """ 
    374379        Write membrane potential traces to file. 
  • trunk/nest.py

    r1 r3  
    22""" 
    33PyNEST implementation of the PyNN API. 
    4 $Id: nest.py 78 2007-01-25 10:36:59Z apdavison $ 
     4$Id: nest.py 152 2007-04-04 15:43:10Z Pierre $ 
    55""" 
    66__version__ = "$Revision: 284 $" 
     
    152152def end(): 
    153153    """Do any necessary cleaning up before exiting.""" 
    154     for file in spike_files + v_files: 
     154    for file in spike_files: 
    155155        pynest.sr('%s close' % file) 
     156    for couples in v_files: 
     157        pynest.sr('%s close' % couples[1]) 
    156158    pynest.end() 
    157159 
     
    316318            id.setPosition(self.locate(id)) 
    317319             
    318          
    319320        if self.cellparams: 
    320321            pynest.setDict(self.cell, self.cellparams) 
     
    459460        pynest.setDict(self.spike_detector,{'withtime':True,  # record time of spikes 
    460461                                            'withpath':True}) # record which neuron spiked 
     462         
     463        fixed_list = False 
     464         
    461465        if record_from: 
    462466            if type(record_from) == types.ListType: 
     467                fixed_list = True 
     468                n_rec = len(record_from) 
     469            elif type(record_from) == types.IntType: 
     470                n_rec = record_from 
     471            else: 
     472                raise "record_from must be a list or an integer" 
     473        else: 
     474            n_rec = self.size 
     475        pynest.resCons(self.spike_detector[0],n_rec) 
     476 
     477        if (fixed_list == True): 
     478            for neuron in record_from: 
     479                pynest.connect(pynest.getAddress(neuron),self.spike_detector[0]) 
     480        else: 
     481            for neuron in numpy.reshape(self.cell,(self.cell.size,))[0:n_rec]: # should change this to pick randomly 
     482                pynest.connect(pynest.getAddress(neuron),self.spike_detector[0]) 
     483                 
     484        # Open temporary output file & register file with detectors 
     485        # This should be redone now that Eilif has implemented the pythondatum datum type 
     486        pynest.sr('/tmpfile_%s (tmpfile_%s) (w) file def' % (self.label,self.label)) 
     487        pynest.sr('%s << /output_stream tmpfile_%s >> SetStatus' % (pynest.getGID(self.spike_detector[0]),self.label)) 
     488        spike_files.append('tmpfile_%s' % self.label) 
     489        self.n_rec = n_rec 
     490 
     491    def record_v(self,record_from=None,rng=None): 
     492        """ 
     493        If record_from is not given, record the membrane potential for all cells in 
     494        the Population. 
     495        record_from can be an integer - the number of cells to record from, chosen 
     496        at random (in this case a random number generator can also be supplied) 
     497        - or a list containing the ids of the cells to record. 
     498        """ 
     499        global v_files 
     500         
     501        fixed_list = False 
     502         
     503        if record_from: 
     504            if type(record_from) == types.ListType: 
     505                fixed_list = True 
    463506                n_rec = len(record_from) 
    464507            elif type(record_from) == types.IntType: 
     
    468511        else: 
    469512            n_rec = self.size 
    470         pynest.resCons(self.spike_detector[0],n_rec) 
    471          
    472         for neuron in numpy.reshape(self.cell,(self.cell.size,))[0:n_rec]: # should change this to pick randomly 
    473             pynest.connect(pynest.getAddress(neuron),self.spike_detector[0]) 
    474  
    475         # Open temporary output file & register file with detectors 
    476         # This should be redone now that Eilif has implemented the pythondatum datum type 
    477         pynest.sr('/tmpfile_%s (tmpfile_%s) (w) file def' % (self.label,self.label)) 
    478         pynest.sr('%s << /output_stream tmpfile_%s >> SetStatus' % (pynest.getGID(self.spike_detector[0]),self.label)) 
    479         spike_files.append('tmpfile_%s' % self.label) 
    480         self.n_rec = n_rec 
    481  
    482     def record_v(self,record_from=None,rng=None): 
    483         """ 
    484         If record_from is not given, record the membrane potential for all cells in 
    485         the Population. 
    486         record_from can be an integer - the number of cells to record from, chosen 
    487         at random (in this case a random number generator can also be supplied) 
    488         - or a list containing the ids of the cells to record. 
    489         """ 
    490         global v_files 
    491          
    492         if record_from: 
    493             if type(record_from) == types.ListType: 
    494                 n_rec = len(record_from) 
    495             elif type(record_from) == types.IntType: 
    496                 n_rec = record_from 
    497             else: 
    498                 raise "record_from must be a list or an integer" 
    499         else: 
    500             n_rec = self.size 
    501              
    502         for neuron in numpy.reshape(self.cell,(self.cell.size,))[0:n_rec]: # should change this to pick randomly 
    503             filename = 'tmpfile_%s_%d.v' % (self.label, neuron) 
    504             v_files.append(filename) 
    505             pynest.record_v(pynest.getAddress(neuron),filename) 
    506      
    507      
    508     def printSpikes(self,filename,gather=True): 
     513 
     514        if (fixed_list == True): 
     515            for neuron in record_from: 
     516                filename = 'tmpfile_%s_%d.v' % (self.label, neuron) 
     517                v_files.append([neuron, filename]) 
     518                pynest.record_v(pynest.getAddress(neuron),filename) 
     519        else: 
     520            for neuron in numpy.reshape(self.cell,(self.cell.size,))[0:n_rec]: # should change this to pick randomly 
     521                filename = 'tmpfile_%s_%d.v' % (self.label, neuron) 
     522                v_files.append([neuron, filename]) 
     523                pynest.record_v(pynest.getAddress(neuron),filename) 
     524     
     525     
     526    def printSpikes(self,filename,gather=True, compatible_output=True): 
    509527        """ 
    510528        Prints spike times to file in the two-column format 
     
    520538            spike_files.remove(tempfilename) 
    521539        shutil.move(tempfilename,filename) 
     540        if (compatible_output): 
     541            # Here we postprocess the file to have effectively the 
     542            # desired format : 
     543            # First line: dimensions of the population 
     544            # Then spiketime cell_id-min(cell_id) 
     545            f = open(filename,'r',1) 
     546            g = open("temp",'w',1) 
     547            # Writing dimensions of the population: 
     548            g.write("# ") 
     549            for dimension in self.dim: 
     550                g.write("%d\t" %dimension) 
     551            g.write("\n") 
     552         
     553            # Writing spiketimes, cell_id-min(cell_id) 
     554            padding = numpy.reshape(self.cell,self.cell.size)[0] 
     555            lines = f.readlines() 
     556            f.close() 
     557            for line in lines: 
     558                single_line = line.split("\t", 1) 
     559                neuron = int(single_line[0][1:len(single_line[0])]) - padding 
     560                spike_time = dt*float(single_line[1]) 
     561                g.write("%g\t%d" %(spike_time, neuron)) 
     562            #    for i in range(0,len(self.locate(neuron))):     
     563            #           g.write("%d\t" %self.locate(neuron)[i]) 
     564                g.write("\n") 
     565            g.close() 
     566            os.system("mv temp %s" %filename) 
     567         
    522568 
    523569    def meanSpikeCount(self,gather=True): 
     
    536582        """ 
    537583        cells = numpy.reshape(self.cell,self.cell.size) 
    538         rvals = rand_distr.next(n=self.dim) 
     584        rvals = rand_distr.next(n=self.cell.size) 
    539585        for node, v_init in zip(cells,rvals): 
    540586            pynest.setDict([node],{'u': v_init}) 
    541587     
    542     def print_v(self,filename,gather=True): 
     588    def print_v(self,filename,gather=True, compatible_output=True): 
    543589        """ 
    544590        Write membrane potential traces to file. 
    545591        """ 
    546592        global v_files 
    547         for tempfile in v_files: 
    548             pynest.sr('%s close' % tempfile) 
    549593        #os.system("paste %s > %s" % (" ".join(v_files), filename)) 
    550         f = open('temp','w') 
     594        result = open(filename,'w',1) 
    551595        dt = pynest.getNESTStatus()['resolution'] 
    552596        n = int(pynest.getNESTStatus()['time']/dt) 
    553         f.write("# dt = %f\n# n = %d\n" % (dt,n)) 
    554         f.close() 
    555         os.system("cat temp %s > %s" % (" ".join(v_files), filename)) 
    556         for tempfile in v_files: 
    557             v_files.remove(tempfile) 
    558         #shutil.move(tempfile,filename) 
     597        result.write("# dt = %f\n# n = %d\n" % (dt,n)) 
     598        if (compatible_output): 
     599            result.write("# ") 
     600            for dimension in self.dim: 
     601               result.write("%d\t" %dimension) 
     602            result.write("\n") 
     603            padding = numpy.reshape(self.cell,self.cell.size)[0] 
     604        for couples in v_files: 
     605            if couples[0] in self.cell: 
     606                pynest.sr('%s close' % couples[1]) 
     607                if (compatible_output): 
     608                    # We add the cell number to the recorded potential: 
     609                    f = open(couples[1],'r',1) 
     610                    lines = f.readlines() 
     611                    input_tuples = [] 
     612                    for line in lines: 
     613                        single_line = line.rstrip() 
     614                        neuron = couples[0] 
     615                        result.write("%s\t%d\t\n" %(single_line, neuron-padding)) 
     616                    f.close() 
     617                    os.system("rm %s" %couples[1]) 
     618                else: 
     619                    os.system("cat %s > %s" %(couples[1], filename)) 
     620                    os.system("rm %s" %couples[1]) 
     621        for couples in v_files: 
     622            if couples[0] in self.cell: 
     623                v_files.remove(couples) 
     624         
    559625         
    560626     
  • trunk/neuron2.py

    r1 r3  
    899899                            'strdef fmt'] 
    900900            if header: 
    901                 hoc_commands += ['tmp = fileobj.printf("%s")' % header]    
     901                hoc_commands += ['tmp = fileobj.printf("%s\\n")' % header]    
    902902            if gather: 
    903903                hoc_commands += ['objref gatheredvec'] 
     904            padding = self.fullgidlist[0] 
    904905            for id in self.record_from[print_what]: 
    905906                addr = self.locate(id) 
    906                 hoc_commands += ['fmt = "%s\\t%s\\n"' % (num_format, "\\t".join([str(j) for j in addr]))] 
     907                #hoc_commands += ['fmt = "%s\\t%s\\n"' % (num_format, "\\t".join([str(j) for j in addr]))] 
     908                hoc_commands += ['fmt = "%s\\t%d\\n"' % (num_format, id-padding)] 
    907909                if id in self.gidlist: 
    908910                    hoc_commands += ['tmp = %s.object(%d).%s.printf(fileobj,fmt)' % (self.label,self.gidlist.index(id),print_what)] 
     
    914916            hoc_execute(hoc_commands,"--- Population[%s].__print()__ ---" %self.label) 
    915917 
    916     def printSpikes(self,filename,gather=True): 
     918    def printSpikes(self,filename,gather=True, compatible_output=True): 
    917919        """ 
    918920        Prints spike times to file in the two-column format 
     
    926928        """ 
    927929        hoc_comment("--- Population[%s].__printSpikes()__ ---" %self.label) 
    928         self.__print('spiketimes',filename,"%.2f",gather) 
    929  
    930     def print_v(self,filename,gather=True): 
     930        header = "# %d" %self.dim[0] 
     931        for dimension in list(self.dim)[1:]: 
     932                header = "%s\t%d" %(header,dimension) 
     933        self.__print('spiketimes',filename,"%.2f",gather, header) 
     934 
     935    def print_v(self,filename,gather=True, compatible_output=True): 
    931936        """ 
    932937        Write membrane potential traces to file. 
     
    934939        tstop = HocToPy.get('tstop','float') 
    935940        header = "# dt = %f\\n# n = %d\\n" % (dt,int(tstop/dt)) 
     941        header = "%s # %d" %(header,self.dim[0]) 
     942        for dimension in list(self.dim)[1:]: 
     943                header = "%s\t%d" %(header,dimension) 
    936944        hoc_comment("--- Population[%s].__print_v()__ ---" %self.label) 
    937945        self.__print('vtrace',filename,"%.4g",gather,header) 
  • trunk/test/nesttests.py

    r1 r3  
    11""" 
    22Unit tests for pyNN/nest.py. 
    3 $Id: nesttests.py 78 2007-01-25 10:36:59Z apdavison $ 
     3$Id: nesttests.py 146 2007-04-03 16:19:16Z Pierre $ 
    44""" 
    55 
     
    280280    """Tests of the record(), record_v(), printSpikes(), print_v() and 
    281281       meanSpikeCount() methods of the Population class.""" 
    282     pass 
    283  
    284 # ============================================================================== 
    285 class PopulationOtherTest(unittest.TestCase): # to write later 
    286     """Tests of the randomInit() method of the Population class.""" 
    287     pass 
     282    def setUp(self): 
     283        nest.setup() 
     284        nest.Population.nPop = 0 
     285        self.pop1 = nest.Population((3,3), nest.SpikeSourcePoisson,{'rate': 20}) 
     286        self.pop2 = nest.Population((3,3), nest.IF_curr_alpha) 
     287 
     288    def testRecordAll(self): 
     289        """Population.record(): not a full test, just checking there are no Exceptions raised.""" 
     290        self.pop1.record() 
     291         
     292    def testRecordInt(self): 
     293        """Population.record(n): not a full test, just checking there are no Exceptions raised.""" 
     294        # Partial record         
     295        self.pop1.record(5) 
     296         
     297    def testRecordWithRNG(self): 
     298        """Population.record(n,rng): not a full test, just checking there are no Exceptions raised.""" 
     299        self.pop1.record(5,random.NumpyRNG()) 
     300         
     301    def testRecordList(self): 
     302        """Population.record(list): not a full test, just checking there are no Exceptions raised.""" 
     303        # Selected list record 
     304        record_list = [] 
     305        for i in range(0,2): 
     306            record_list.append(self.pop1[i,1]) 
     307        self.pop1.record(record_list)    
     308    
     309    def testSpikeRecording(self): 
     310        # We test the mean spike count by checking if the rate of the poissonian sources are 
     311        # close to 20 Hz. Then we also test how the spikes are saved 
     312        self.pop1.record() 
     313        simtime = 1000 
     314        nest.run(simtime) 
     315        self.pop1.printSpikes("temp_nest.ras") 
     316        rate = self.pop1.meanSpikeCount()*1000/simtime 
     317        assert (20*0.8 < rate) and (rate < 20*1.2) 
     318         
     319    def testPotentialRecording(self): 
     320        """Population.record_v() and Population.print_v(): not a full test, just checking  
     321        # there are no Exceptions raised.""" 
     322        rng = random.NumpyRNG(123) 
     323        v_reset  = -65.0 
     324        v_thresh = -50.0 
     325        uniformDistr = random.RandomDistribution(rng,'uniform',[v_reset,v_thresh]) 
     326        self.pop2.randomInit(uniformDistr) 
     327        self.pop2.record_v([self.pop2[0,0], self.pop2[1,1]]) 
     328        simtime = 10 
     329        nest.run(simtime) 
     330        self.pop2.print_v("temp_nest.v") 
    288331 
    289332# ============================================================================== 
  • trunk/test/neuron2tests.py

    r1 r3  
    330330     
    331331    def setUp(self): 
    332         neuron.Population.nPop = 0 
    333         self.net = neuron.Population((3,3),neuron.IF_curr_alpha) 
    334          
     332        self.pop1 = neuron.Population((3,3), neuron.SpikeSourcePoisson,{'rate': 20}) 
     333        self.pop2 = neuron.Population((3,3), neuron.IF_curr_alpha) 
     334 
    335335    def testRecordAll(self): 
    336336        """Population.record(): not a full test, just checking there are no Exceptions raised.""" 
    337         self.net.record() 
     337        self.pop1.record() 
    338338         
    339339    def testRecordInt(self): 
    340340        """Population.record(n): not a full test, just checking there are no Exceptions raised.""" 
    341         self.net.record(5) 
    342          
     341        # Partial record         
     342        self.pop1.record(5) 
     343         
    343344    def testRecordWithRNG(self): 
    344345        """Population.record(n,rng): not a full test, just checking there are no Exceptions raised.""" 
    345         self.net.record(5,random.NumpyRNG()) 
     346        self.pop1.record(5,random.NumpyRNG()) 
    346347         
    347348    def testRecordList(self): 
    348349        """Population.record(list): not a full test, just checking there are no Exceptions raised.""" 
    349         self.net.record([self.net[(2,2)],self.net[(1,2)],self.net[(0,0)]]) 
     350        # Selected list record 
     351        record_list = [] 
     352        for i in range(0,2): 
     353            record_list.append(self.pop1[i,1]) 
     354        self.pop1.record(record_list) 
     355 
     356    def testSpikeRecording(self): 
     357        # We test the mean spike count by checking if the rate of the poissonian sources are 
     358        # close to 20 Hz. Then we also test how the spikes are saved 
     359        self.pop1.record() 
     360        simtime = 1000.0 
     361        neuron.run(simtime) 
     362        self.pop1.printSpikes("temp_neuron2.ras") 
     363        rate = self.pop1.meanSpikeCount()*1000/simtime 
     364        assert (20*0.8 < rate) and (rate < 20*1.2) 
     365 
     366    def testPotentialRecording(self): 
     367        """Population.record_v() and Population.print_v(): not a full test, just checking  
     368        # there are no Exceptions raised.""" 
     369        rng = NumpyRNG(123) 
     370        v_reset  = -65.0 
     371        v_thresh = -50.0 
     372        uniformDistr = RandomDistribution(rng,'uniform',[v_reset,v_thresh]) 
     373        self.pop2.randomInit(uniformDistr) 
     374        self.pop2.record_v([self.pop2[0,0], self.pop2[1,1]]) 
     375        simtime = 10.0 
     376        neuron.run(simtime) 
     377        self.pop2.print_v("temp_neuron2.v") 
    350378 
    351379# ==============================================================================