Changeset 708

Show
Ignore:
Timestamp:
02/12/10 16:02:09 (2 years ago)
Author:
apdavison
Message:

Various fixes from running doctests

Location:
trunk
Files:
12 modified

Legend:

Unmodified
Added
Removed
  • trunk/doc/dynamicsynapses.txt

    r632 r708  
    7373    >>> prj.getSynapseDynamics('tau_rec')[:5] 
    7474    [50.0, 50.0, 50.0, 50.0, 50.0] 
     75    >>> from pyNN.random import RandomDistribution 
    7576    >>> distr = RandomDistribution('normal', [0.02, 0.05]) 
    7677    >>> prj2.randomizeSynapseDynamics('w_max', distr) 
    7778    >>> prj2.getSynapseDynamics('w_max')[:5] 
    78     aofuha 
     79    [-0.056605932509016577, 0.063197908706714212, 0.034940801886916589, 0.010755581262934901, 0.011700727992415299] 
    7980 
    8081There are a number of examples of networks using synaptic plasticity in the ``examples`` directory of the source distribution. 
  • trunk/doc/fileformats.txt

    r707 r708  
    2323    >>> p.printSpikes(spike_file) 
    2424    >>> spike_file.close() 
    25     >>> vm_file = HDF5ArrayFile("my_Vm_data.h5") 
     25    >>> vm_file = HDF5ArrayFile("my_Vm_data.h5", "w") 
    2626    >>> p.print_v(vm_file) 
    2727    >>> vm_file.close() 
  • trunk/doc/highlevelapi.txt

    r707 r708  
    7575    Traceback (most recent call last): 
    7676      File "<stdin>", line 1, in ? 
    77       File "/usr/lib/python/site-packages/pyNN/nest1.py", line 457, in __getitem__ 
    78         id = self.cell[addr] 
    79     IndexError: index (999) out of range (0<=index<=10) in dimension 0 
     77      File "/usr/lib/python/site-packages/pyNN/common.py", line 794, in __getitem__ 
     78        id = self.all_cells[addr] 
     79    IndexError: index (999) out of range (0<=index<10) in dimension 0 
    8080 
    8181as will giving the wrong number of dimensions in the address. 
     
    107107    Traceback (most recent call last): 
    108108      File "<stdin>", line 1, in <module> 
    109       File "/home/andrew/dev/pyNN/neuron/__init__.py", line 759, in index 
     109      File "/usr/lib/python/site-packages/pyNN/neuron/__init__.py", line 759, in index 
    110110        return self.fullgidlist[n] 
    111111    IndexError: index out of bounds 
     
    228228        File "<stdin>", line 1, in <module> 
    229229          sine_wave.inject_into(p2) 
    230         File "/home/andrew/dev/pyNN/neuron/electrodes.py", line 67, in inject_into 
     230        File "/usr/lib/python/site-packages/pyNN/neuron/electrodes.py", line 67, in inject_into 
    231231          raise TypeError("Can't inject current into a spike source.") 
    232232    TypeError: Can't inject current into a spike source. 
     
    359359      File "<stdin>", line 1, in <module> 
    360360        invalid_prj = Projection(p2, p3, OneToOneConnector()) 
    361       File "/home/andrew/dev/pyNN/neuron/__init__.py", line 220, in __init__ 
     361      File "/usr/lib/python/site-packages/pyNN/neuron/__init__.py", line 220, in __init__ 
    362362        method.connect(self) 
    363       File "/home/andrew/dev/pyNN/connectors.py", line 281, in connect 
     363      File "/usr/lib/python/site-packages/pyNN/connectors.py", line 281, in connect 
    364364        raise common.InvalidDimensionsError("OneToOneConnector does not support 
    365365                   presynaptic and postsynaptic Populations of different sizes.") 
  • trunk/doc/lowlevelapi.txt

    r707 r708  
    6161stored in the ``default_values`` of the standard cell class, e.g.:: 
    6262 
    63     >>> IF_curr_alpha.default_parameters #doctest" +NORMALIZE_WHITESPACE 
     63    >>> IF_curr_alpha.default_parameters #doctest: +NORMALIZE_WHITESPACE 
    6464    {'tau_refrac': 0.0, 'tau_m': 20.0, 'i_offset': 0.0, 'cm': 1.0, 'v_init': -65.0, 
    6565     'v_thresh': -50.0, 'tau_syn_E': 0.5, 'v_rest': -65.0, 'tau_syn_I': 0.5, 
     
    7575    Traceback (most recent call last): 
    7676      File "<stdin>", line 1, in ? 
    77       File "/usr/lib/python/site-packages/pyNN/nest1.py", line 228, in create 
     77      File "/usr/lib/python/site-packages/pyNN/common.py", line 655, in create 
     78        all_cells, mask_local, first_id, last_id = simulator.create_cells(cellclass, cellparams, n) 
     79      File "/home/andrew/dev/pyNN/neuron/simulator.py", line 287, in create_cells 
    7880        celltype = cellclass(cellparams) 
    79       File "/usr/lib/python/site-packages/pyNN/nest1.py", line 68, in __init__ 
    80         common.IF_curr_alpha.__init__(self,parameters) # checks supplied parameters and adds default 
    81       File "/usr/lib/python/site-packages/pyNN/common.py", line 113, in __init__ 
    82         self.parameters = self.checkParameters(parameters, with_defaults=True) 
    83       File "/usr/lib/python/site-packages/pyNN/common.py", line 99, in checkParameters 
    84         raise NonExistentParameterError(k) 
    85     NonExistentParameterError: foo 
     81      File "/usr/lib/python/site-packages/pyNN/neuron/cells.py", line 442, in __init__ 
     82        cells.IF_curr_alpha.__init__(self, parameters) # checks supplied parameters and adds default 
     83      File "/usr/lib/python/site-packages/pyNN/common.py", line 460, in __init__ 
     84        self.parameters = self.__class__.checkParameters(parameters, with_defaults=True) 
     85      File "/usr/lib/python/site-packages/pyNN/common.py", line 504, in checkParameters 
     86        raise NonExistentParameterError(k, cls) 
     87    NonExistentParameterError: foo (valid parameters for IF_curr_alpha are: cm, i_offset, tau_m, tau_refrac, tau_syn_E, tau_syn_I, v_init, v_reset, v_rest, v_thresh) 
    8688    >>> create(IF_curr_alpha, cellparams={'tau_m': 'bar'}) 
    8789    Traceback (most recent call last): 
  • trunk/doc/testdocs.py

    r707 r708  
    1010 
    1111optionflags = doctest.IGNORE_EXCEPTION_DETAIL+doctest.NORMALIZE_WHITESPACE 
    12 #optionflags = doctest.NORMALIZE_WHITESPACE 
     12optionflags = doctest.NORMALIZE_WHITESPACE 
    1313 
    1414class MyOutputChecker(doctest.OutputChecker): 
  • trunk/examples/VAbenchmarks.py

    r705 r708  
    144144    connections['ext2i'] = Projection(ext_stim, inh_cells, ext_conn, target='excitatory') 
    145145 
    146 for prj in connections.keys(): 
    147     connections[prj].saveConnections('Results/VAbenchmark_%s_%s_%s_np%d.conn' % (benchmark, prj, simulator_name, np)) 
    148  
    149146# === Setup recording ========================================================== 
    150147print "%s Setting up recording..." % node_id 
     
    154151exc_cells.record_v(vrecord_list) 
    155152 
    156 buildCPUTime = timer.elapsedTime() 
     153buildCPUTime = timer.diff() 
     154 
     155# === Save connections to file ================================================= 
     156 
     157for prj in connections.keys(): 
     158    connections[prj].saveConnections('Results/VAbenchmark_%s_%s_%s_np%d.conn' % (benchmark, prj, simulator_name, np)) 
     159saveCPUTime = timer.diff() 
    157160 
    158161# === Run simulation =========================================================== 
    159162print "%d Running simulation..." % node_id 
    160 timer.reset() 
    161163 
    162164run(tstop) 
    163165 
    164 simCPUTime = timer.elapsedTime() 
    165  
    166 E_rate = exc_cells.meanSpikeCount()*1000./tstop 
    167 I_rate = inh_cells.meanSpikeCount()*1000./tstop 
     166simCPUTime = timer.diff() 
     167 
     168E_count = exc_cells.meanSpikeCount() 
     169I_count = inh_cells.meanSpikeCount() 
    168170 
    169171# === Print results to file ==================================================== 
    170172 
    171173print "%d Writing data to file..." % node_id 
    172 timer.reset() 
    173174 
    174175if not(os.path.isdir('Results')): 
     
    178179inh_cells.printSpikes("Results/VAbenchmark_%s_inh_%s_np%d.ras" % (benchmark, simulator_name, np)) 
    179180exc_cells.print_v("Results/VAbenchmark_%s_exc_%s_np%d.v" % (benchmark, simulator_name, np)) 
    180 writeCPUTime = timer.elapsedTime() 
    181  
    182 tmp_string = "%d e→e  %d e→i  %d i→e  %d i→i" % (connections['e2e'].size(), 
    183                                                  connections['e2i'].size(), 
    184                                                  connections['i2e'].size(), 
    185                                                  connections['i2i'].size()) 
    186  
    187 def nprint(s): 
    188     """Small function to display information only on node 0.""" 
    189     if (node_id == 0): 
    190         print s 
    191  
    192 nprint("\n--- Vogels-Abbott Network Simulation ---") 
    193 nprint("Nodes                  : %d" % np) 
    194 nprint("Simulation type        : %s" % benchmark) 
    195 nprint("Number of Neurons      : %d" % n) 
    196 nprint("Number of Synapses     : %s" % tmp_string) 
    197 nprint("Excitatory conductance : %g nS" % Gexc) 
    198 nprint("Inhibitory conductance : %g nS" % Ginh) 
    199 nprint("Excitatory rate        : %g Hz" % E_rate) 
    200 nprint("Inhibitory rate        : %g Hz" % I_rate) 
    201 nprint("Build time             : %g s" % buildCPUTime)  
    202 nprint("Simulation time        : %g s" % simCPUTime) 
    203 nprint("Writing time           : %g s" % writeCPUTime) 
     181writeCPUTime = timer.diff() 
     182 
     183connections = "%d e→e  %d e→i  %d i→e  %d i→i" % (connections['e2e'].size(), 
     184                                                  connections['e2i'].size(), 
     185                                                  connections['i2e'].size(), 
     186                                                  connections['i2i'].size()) 
     187 
     188if node_id == 0: 
     189    print "\n--- Vogels-Abbott Network Simulation ---" 
     190    print "Nodes                  : %d" % np 
     191    print "Simulation type        : %s" % benchmark 
     192    print "Number of Neurons      : %d" % n 
     193    print "Number of Synapses     : %s" % connections 
     194    print "Excitatory conductance : %g nS" % Gexc 
     195    print "Inhibitory conductance : %g nS" % Ginh 
     196    print "Excitatory rate        : %g Hz" % (E_count*1000.0/tstop,) 
     197    print "Inhibitory rate        : %g Hz" % (I_count*1000.0/tstop,) 
     198    print "Build time             : %g s" % buildCPUTime 
     199    print "Save connections time  : %g s" % saveCPUTime 
     200    print "Simulation time        : %g s" % simCPUTime 
     201    print "Writing time           : %g s" % writeCPUTime 
    204202 
    205203 
  • trunk/examples/tools/VAbenchmark_graphs.py

    r705 r708  
    44 
    55import pylab, sys 
     6import numpy 
    67from NeuroTools import signals, plotting 
    78from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas 
     
    6970         
    7071        # Plot membrane potential trace 
    71         allvdata = pylab.load("Results/VAbenchmark_%s_exc_%s_np%d.v" % (benchmark, simulator, num_nodes), comments='#') 
     72        allvdata = numpy.loadtxt("Results/VAbenchmark_%s_exc_%s_np%d.v" % (benchmark, simulator, num_nodes), comments='#') 
    7273        cell_ids = allvdata[:,1].astype(int) 
    7374        allvdata = allvdata[:,0] 
  • trunk/setup.py

    r706 r708  
    4141setup( 
    4242    name = "PyNN", 
    43     version = "0.6pre", 
     43    version = "0.6.0pre", 
    4444    package_dir={'pyNN': 'src'}, 
    4545    packages = ['pyNN','pyNN.nest', 'pyNN.pcsim', 'pyNN.neuron', 'pyNN.brian', 'pyNN.recording'], 
  • trunk/src/brian/electrodes.py

    r626 r708  
    66    StepCurrentSource  -- a step-wise time-varying current. 
    77 
    8 $Id:$ 
     8$Id$ 
    99""" 
    1010 
     
    3333    def inject_into(self, cell_list): 
    3434        """Inject this current source into some cells.""" 
     35        for cell in cell_list: 
     36            if 'v' not in cell.cellclass.recordable: 
     37                raise TypeError("Can't inject current into a spike source.") 
    3538        self.cell_list.extend(cell_list)         
    3639     
  • trunk/src/nest/simulator.py

    r702 r708  
    271271    def __getitem__(self, i): 
    272272        """Return the `i`th connection on the local MPI node.""" 
    273         if i < len(self): 
    274             return Connection(self, i) 
    275         else: 
    276             raise IndexError("%d > %d" % (i, len(self)-1)) 
     273        if isinstance(i, int): 
     274            if i < len(self): 
     275                return Connection(self, i) 
     276            else: 
     277                raise IndexError("%d > %d" % (i, len(self)-1)) 
     278        elif isinstance(i, slice): 
     279            if i.stop < len(self): 
     280                return [Connection(self, j) for j in range(i.start, i.stop, i.step or 1)] 
     281            else: 
     282                raise IndexError("%d > %d" % (i.stop, len(self)-1)) 
     283             
    277284     
    278285    def __len__(self): 
     
    395402         
    396403        if parameter_name not in ('weight', 'delay'): 
    397             if parameter_name in self.parent.synapse_dynamics.fast.translations: 
    398                 parameter_name = self.parent.synapse_dynamics.fast.translations[parameter_name]["translated_name"] # this is a hack that works because there are no units conversions 
     404            translated_name = None 
     405            if self.parent.synapse_dynamics.fast and parameter_name in self.parent.synapse_dynamics.fast.translations: 
     406                translated_name = self.parent.synapse_dynamics.fast.translations[parameter_name]["translated_name"] # this is a hack that works because there are no units conversions 
     407            elif self.parent.synapse_dynamics.slow: 
     408                for component_name in "timing_dependence", "weight_dependence", "voltage_dependence": 
     409                    component = getattr(self.parent.synapse_dynamics.slow, component_name) 
     410                    if component and parameter_name in component.translations: 
     411                        translated_name = component.translations[parameter_name]["translated_name"] 
     412                        break 
     413            if translated_name: 
     414                parameter_name = translated_name 
    399415            else: 
    400416                raise Exception("synapse type does not have an attribute '%s', or else this attribute is not accessible." % parameter_name) 
     
    468484            #translation = self.parent.synapse_dynamics.reverse_translate({name: value}) 
    469485            #name, value = translation.items()[0] 
    470             name = self.parent.synapse_dynamics.fast.translations[name]["translated_name"] # a hack 
     486            translated_name = None 
     487            if self.parent.synapse_dynamics.fast: 
     488                if name in self.parent.synapse_dynamics.fast.translations: 
     489                    translated_name = self.parent.synapse_dynamics.fast.translations[name]["translated_name"] # a hack 
     490            if translated_name is None: 
     491                if self.parent.synapse_dynamics.slow: 
     492                    for component_name in "timing_dependence", "weight_dependence", "voltage_dependence": 
     493                        component = getattr(self.parent.synapse_dynamics.slow, component_name) 
     494                        if component and name in component.translations: 
     495                            translated_name = component.translations[name]["translated_name"] 
     496                            break 
     497            if translated_name: 
     498                name = translated_name 
    471499         
    472500        i = 0 
  • trunk/src/neuroml.py

    r705 r708  
    77from pyNN import common, connectors, cells 
    88import math 
    9 #import numpy, types, sys, shutil 
     9import numpy 
    1010import sys 
    1111sys.path.append('/usr/lib/python%s/site-packages/oldxml' % sys.version[:3]) # needed for Ubuntu 
     
    2424neuroml_xsd="http://www.neuroml.org/NeuroMLValidator/NeuroMLFiles/Schemata/v"+neuroml_ver+"/Level3/NeuroML_Level3_v"+neuroml_ver+".xsd" 
    2525 
     26strict = False 
     27 
    2628# ============================================================================== 
    2729#   Utility classes 
    2830# ============================================================================== 
    2931 
    30 class ID(common.IDMixin): 
     32class ID(int, common.IDMixin): 
    3133    """ 
    3234    Instead of storing ids as integers, we store them as ID objects, 
     
    3840     
    3941    def __init__(self, n): 
    40         common.IDMixin.__init__(self, n) 
     42        common.IDMixin.__init__(self) 
    4143 
    4244# ============================================================================== 
     
    179181        return cell_node, channel_nodes, synapse_nodes 
    180182 
     183 
     184class NotImplementedModel(object): 
     185     
     186    def __init__(self): 
     187        if strict: 
     188            raise Exception('Cell type %s is not available in NeuroML' % self.__class__.__name__) 
     189     
     190    def build_nodes(self): 
     191        cell_node = build_node(':not_implemented_cell', name=self.label) 
     192        doc_node = build_node('meta:notes', "PyNN %s cell type not implemented" % self.__class__.__name__) 
     193        return cell_node, [], [] 
     194         
     195 
    181196# ============================================================================== 
    182197#   Standard cells 
    183198# ============================================================================== 
    184199 
    185 class IF_curr_exp(cells.IF_curr_exp): 
     200class IF_curr_exp(cells.IF_curr_exp, NotImplementedModel): 
    186201    """Leaky integrate and fire model with fixed threshold and 
    187202    decaying-exponential post-synaptic current. (Separate synaptic currents for 
    188203    excitatory and inhibitory synapses""" 
    189204     
     205    n = 0 
     206    translations = common.build_translations(*[(name, name) 
     207                                               for name in cells.IF_curr_exp.default_parameters]) 
     208     
    190209    def __init__(self, parameters): 
    191         raise Exception('Cell type %s is not available in NeuroML' % self.__class__.__name__) 
    192  
    193 class IF_curr_alpha(cells.IF_curr_alpha): 
     210        NotImplementedModel.__init__(self) 
     211        cells.IF_curr_exp.__init__(self, parameters) 
     212        self.label = '%s%d' % (self.__class__.__name__, self.__class__.n) 
     213        self.synapse_type = "doub_exp_syn" 
     214        self.__class__.n += 1 
     215 
     216class IF_curr_alpha(cells.IF_curr_alpha, NotImplementedModel): 
    194217    """Leaky integrate and fire model with fixed threshold and alpha-function- 
    195218    shaped post-synaptic current.""" 
    196219     
     220    n = 0 
     221    translations = common.build_translations(*[(name, name) 
     222                                               for name in cells.IF_curr_alpha.default_parameters]) 
     223     
    197224    def __init__(self, parameters): 
    198         raise Exception('Cell type %s is not available in NeuroML' % self.__class__.__name__) 
     225        NotImplementedModel.__init__(self) 
     226        cells.IF_curr_exp.__init__(self, parameters) 
     227        self.label = '%s%d' % (self.__class__.__name__, self.__class__.n) 
     228        self.synapse_type = "doub_exp_syn" 
     229        self.__class__.n += 1 
    199230 
    200231class IF_cond_exp(cells.IF_cond_exp, IF_base): 
     
    226257        self.__class__.n += 1 
    227258 
    228 class SpikeSourcePoisson(cells.SpikeSourcePoisson): 
     259class SpikeSourcePoisson(cells.SpikeSourcePoisson, NotImplementedModel): 
    229260    """Spike source, generating spikes according to a Poisson process.""" 
    230261 
     262    n = 0 
     263    translations = common.build_translations(*[(name, name) 
     264                                               for name in cells.SpikeSourcePoisson.default_parameters]) 
     265     
    231266    def __init__(self, parameters): 
    232         raise Exception('Cell type %s not yet implemented' % self.__class__.__name__) 
     267        NotImplementedModel.__init__(self) 
    233268        cells.SpikeSourcePoisson.__init__(self, parameters) 
    234          
    235  
    236 class SpikeSourceArray(cells.SpikeSourceArray): 
     269        self.label = '%s%d' % (self.__class__.__name__, self.__class__.n) 
     270        self.__class__.n += 1 
     271         
     272 
     273class SpikeSourceArray(cells.SpikeSourceArray, NotImplementedModel): 
    237274    """Spike source generating spikes at the times given in the spike_times array.""" 
    238275 
     276    n = 0 
     277    translations = common.build_translations(*[(name, name) 
     278                                               for name in cells.SpikeSourcePoisson.default_parameters]) 
     279 
    239280    def __init__(self, parameters): 
    240         raise Exception('Cell type %s not yet implemented' % self.__class__.__name__) 
    241         cells.SpikeSourceArray.__init__(self, parameters) 
     281        NotImplementedModel.__init__(self) 
     282        cells.SpikeSourceARRAY.__init__(self, parameters) 
     283        self.label = '%s%d' % (self.__class__.__name__, self.__class__.n) 
     284        self.__class__.n += 1 
    242285         
    243286 
     
    253296    simulator but not by others. 
    254297    """ 
    255     global xmldoc, xmlfile, populations_node, projections_node, inputs_node, cells_node, channels_node, neuromlNode 
     298    global xmldoc, xmlfile, populations_node, projections_node, inputs_node, cells_node, channels_node, neuromlNode, strict 
    256299    xmlfile = extra_params['file'] 
    257300    if isinstance(xmlfile, basestring): 
    258301        xmlfile = open(xmlfile, 'w') 
     302    if 'strict' in extra_params: 
     303        strict = extra_params['strict'] 
    259304    dt = timestep 
    260305    xmldoc = xml.dom.minidom.Document() 
     
    296341def num_processes(): 
    297342    return 1 
     343common.num_processes = num_processes 
     344 
     345def rank(): 
     346    return 0 
     347common.rank = rank 
    298348 
    299349 
     
    388438            channels_node.appendChild(synapse_node) 
    389439 
     440        self.first_id = 0 
     441        self.last_id = self.size-1 
     442        self.all_cells = numpy.array([ID(id) for id in range(self.first_id, self.last_id+1)], dtype=ID).reshape(dims) 
     443        self._mask_local = numpy.ones_like(self.all_cells).astype(bool) 
     444        self.local_cells = self.all_cells[self._mask_local] 
     445 
     446    def _record(self, variable, record_from=None, rng=None, to_file=True): 
     447        """ 
     448        Private method called by record() and record_v(). 
     449        """ 
     450        pass 
     451     
     452    def meanSpikeCount(self): 
     453        return -1 
     454     
     455    def printSpikes(self, file, gather=True, compatible_output=True): 
     456        pass 
     457     
     458    def print_v(self, file, gather=True, compatible_output=True): 
     459        pass 
    390460 
    391461class AlltoAllConnector(connectors.AllToAllConnector): 
     
    531601        Projection.n += 1 
    532602 
    533  
    534 # ============================================================================== 
     603    def saveConnections(self, filename, gather=True, compatible_output=True): 
     604        pass 
     605     
     606    def __len__(self): 
     607        return 0 # needs implementing properly 
     608 
     609# ============================================================================== 
  • trunk/src/pcsim/electrodes.py

    r705 r708  
    1919    def inject_into(self, cell_list): 
    2020        """Inject this current source into some cells.""" 
    21         print "injecting current source into cells: %s" % str(cell_list) 
    2221        if simulator.state.num_processes == 1: 
    2322            delay = 0.0 
     
    2524            delay = simulator.state.min_delay # perhaps it would be better to replicate the current source on each node, to avoid this delay 
    2625        for cell in cell_list: 
    27             print cell, cell.local, cell.cellclass.recordable 
    2826            if cell.local and 'v' not in cell.cellclass.recordable: 
    2927                raise TypeError("Can't inject current into a spike source.") 
    3028            c = simulator.net.connect(self.input_node, cell, pypcsim.StaticAnalogSynapse(delay=0.001*delay)) 
    3129            self.connections.append(c) 
    32             print "connected current source to cell %s" % cell 
    3330     
    3431