Changeset 376

Show
Ignore:
Timestamp:
06/19/08 15:54:15 (5 months ago)
Author:
apdavison
Message:

More work on getting unit tests for neuron2 running

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/src/neuron2/__init__.py

    r375 r376  
    9191    """Return the current time in the simulation.""" 
    9292    return h.t 
     93common.get_current_time = get_current_time 
    9394 
    9495def get_time_step(): 
     
    190191    Used by `connect()` and the `Connector` classes. 
    191192    """ 
     193    global gid_counter 
    192194    if not isinstance(source, int) or source > gid_counter or source < 0: 
    193         raise common.ConnectionError("Invalid source ID: %s" % source) 
     195        errmsg = "Invalid source ID: %s (gid_counter=%d)" % (source, gid_counter) 
     196        raise common.ConnectionError(errmsg) 
    194197    if not isinstance(target, ID): 
    195198        raise common.ConnectionError("Invalid target ID: %s" % target) 
     
    389392        values = [getattr(cell, parameter_name) for cell in self] 
    390393        if as_array: 
    391             values = numpy.array(values) 
     394            values = numpy.array(values).reshape(self.dim) 
    392395        return values 
    393396 
     
    432435        ##values = values.take(local_indices) # take just the values for cells on this machine 
    433436        assert local_values.size == self._local_ids.size, "%d != %d" % (local_values.size, self._local_ids.size) 
    434          
    435         logging.info("%s.tset('%s', array(shape=%s, min=%s, max=%s)", 
    436                      self.label, parametername, value_array.shape, 
    437                      value_array.min(), value_array.max()) 
     437        try: 
     438            logging.info("%s.tset('%s', array(shape=%s, min=%s, max=%s))", 
     439                         self.label, parametername, value_array.shape, 
     440                         value_array.min(), value_array.max()) 
     441        except TypeError: # min() and max() won't work for non-numeric values 
     442            logging.info("%s.tset('%s', non_numeric_array(shape=%s))", 
     443                         self.label, parametername, value_array.shape) 
    438444        # Set the values for each cell 
    439445        for cell, val in zip(self, local_values.flat): 
     
    594600        context.update(celltype=self.celltype.__class__.__name__) 
    595601        return template % context 
     602     
     603 
     604class Projection(common.Projection): 
     605    """ 
     606    A container for all the connections of a given type (same synapse type and 
     607    plasticity mechanisms) between two populations, together with methods to set 
     608    parameters of those connections, including of plasticity mechanisms. 
     609    """ 
     610     
     611    nProj = 0 
     612     
     613    def __init__(self, presynaptic_population, postsynaptic_population, method='allToAll', 
     614                 method_parameters=None, source=None, target=None, 
     615                 synapse_dynamics=None, label=None, rng=None): 
     616        """ 
     617        presynaptic_population and postsynaptic_population - Population objects. 
     618         
     619        source - string specifying which attribute of the presynaptic cell 
     620                 signals action potentials 
     621                  
     622        target - string specifying which synapse on the postsynaptic cell to 
     623                 connect to 
     624                  
     625        If source and/or target are not given, default values are used. 
     626         
     627        method - string indicating which algorithm to use in determining 
     628                 connections. 
     629        Allowed methods are 'allToAll', 'oneToOne', 'fixedProbability', 
     630        'distanceDependentProbability', 'fixedNumberPre', 'fixedNumberPost', 
     631        'fromFile', 'fromList'. 
     632         
     633        method_parameters - dict containing parameters needed by the connection 
     634        method, although we should allow this to be a number or string if there 
     635        is only one parameter. 
     636         
     637        synapse_dynamics - a `SynapseDynamics` object specifying which 
     638        synaptic plasticity mechanisms to use. 
     639         
     640        rng - since most of the connection methods need uniform random numbers, 
     641        it is probably more convenient to specify a RNG object here rather 
     642        than within method_parameters, particularly since some methods also use 
     643        random numbers to give variability in the number of connections per cell. 
     644        """ 
     645        common.Projection.__init__(self, presynaptic_population, postsynaptic_population, method, 
     646                                   method_parameters, source, target, synapse_dynamics, label, rng) 
     647        self.connections = [] 
     648        if not label: 
     649            self.label = 'projection%d' % Projection.nProj 
     650        if not rng: 
     651            self.rng = NumpyRNG() 
     652        self.synapse_type = target 
     653         
     654        ## Deal with short-term synaptic plasticity 
     655        if self.short_term_plasticity_mechanism: 
     656            U = self._short_term_plasticity_parameters['U'] 
     657            tau_rec = self._short_term_plasticity_parameters['tau_rec'] 
     658            tau_facil = self._short_term_plasticity_parameters['tau_facil'] 
     659            u0 = self._short_term_plasticity_parameters['u0'] 
     660            for cell in self.post: 
     661                cell._cell.use_Tsodyks_Markram_synapses(self.synapse_type, U, tau_rec, tau_facil, u0) 
     662                 
     663        ## Create connections 
     664        if isinstance(method, str): 
     665            connection_method = getattr(self,'_%s' % method)    
     666            connection_method(method_parameters) 
     667        elif isinstance(method, common.Connector): 
     668            print "gid_counter = ", gid_counter 
     669            method.connect(self) 
     670             
     671        logging.info("--- Projection[%s].__init__() ---" %self.label) 
     672         
     673        # By defaut, we set all the delays to min_delay, except if 
     674        # the Projection data have been loaded from a file or a list. 
     675        # This should already have been done if using a Connector object 
     676        if isinstance(method, str) and (method != 'fromList') and (method != 'fromFile'): 
     677            self.setDelays(get_min_delay()) 
     678                 
     679        ## Deal with long-term synaptic plasticity 
     680        if self.long_term_plasticity_mechanism: 
     681            self._setupSTDP(self.long_term_plasticity_mechanism, self._stdp_parameters) 
     682             
     683        Projection.nProj += 1 
     684 
     685    def __len__(self): 
     686        """Return the total number of connections.""" 
     687        return len(self.connections) 
     688 
     689    # --- Connection methods --------------------------------------------------- 
     690     
  • trunk/src/neuron2/cells.py

    r375 r376  
    1414ResetRefrac = neuron.new_point_process('ResetRefrac') 
    1515VecStim = neuron.new_hoc_class('VecStim') 
    16 NetStim = neuron.new_hoc_class('VecStim') 
     16NetStim = neuron.new_hoc_class('NetStim') 
     17tmgsyn = neuron.new_hoc_class('tmgsyn') 
    1718 
    1819def _new_property(obj_hierarchy, attr_name): 
     
    126127        self.seg.v = self.v_init 
    127128 
     129     
     130    def use_Tsodyks_Markram_synapses(ei, U, tau_rec, tau_facil, u0): 
     131        if self.syn_type == 'current': 
     132            raise Exception("Tsodyks-Markram mechanism only available for conductance-based synapses.") 
     133        elif ei == 'excitatory': 
     134            self.esyn = tmgsyn(self, 0.5) 
     135            self.esyn.tau_1 = self.tau_e 
     136            self.esyn.e = self.e_e 
     137            syn = self.esyn 
     138        elif ei == 'inhibitory': 
     139            self.isyn = tmgsyn(self, 0.5) 
     140            self.isyn.tau_1 = self.tau_i 
     141            self.isyn.e = self.e_i 
     142            syn = self.isyn 
     143        syn.U = U 
     144        syn.tau_rec = tau_rec 
     145        syn.tau_facil = tau_facil 
     146        syn.u0 = u0 
     147 
    128148 
    129149class SpikeSource(object): 
     150     
     151    parameter_names = { 
     152        'NetStim': ['start', 'interval', 'number'], 
     153        'VecStim': ['spiketimes'] 
     154    } 
    130155     
    131156    def __init__(self, source_type, start=0, interval=1e12, number=0, spiketimes=[]): 
    132157        self.source = source_type() 
     158        self.parameter_names = SpikeSource.parameter_names[source_type.__name__] 
    133159        if spiketimes: 
    134160            self.spiketimes = neuron.Vector(spiketimes) 
     
    141167            self.do_not_record = False 
    142168 
     169    start    = _new_property('source', 'start') 
     170    interval = _new_property('source', 'interval') 
     171    number   = _new_property('source', 'number') 
     172 
    143173    def record(self, active): 
    144174        if not self.do_not_record: # for VecStims, etc, recording doesn't make sense as we already have the spike times 
    145175            if active: 
    146                 rec = NetCon(self.source, None) 
    147                 rec.record(self.spiketimes
     176                rec = neuron.NetCon(self.source, None) 
     177                rec.record(self.spiketimes.hoc_obj
    148178             
    149179 
     
    291321    def __init__(self, parameters): 
    292322        common.SpikeSourcePoisson.__init__(self, parameters) 
    293         self.parameters['source_type'] = NetStim            
     323        self.parameters['source_type'] = NetStim 
     324 
    294325 
    295326class SpikeSourceArray(SpikeSource, common.SpikeSourceArray): 
  • trunk/src/neuron2/connectors.py

    r374 r376  
    66from pyNN import common 
    77from pyNN.random import RandomDistribution, NativeRNG 
    8 from pyNN.neuron.__init__ import hoc_execute, h, get_min_delay 
     8from pyNN.neuron2.__init__ import get_min_delay, _single_connect 
    99import numpy 
    1010from math import * 
     
    1616# ============================================================================== 
    1717 
     18class ConstIter(object): 
     19    """An iterator that always returns the same value.""" 
     20    def __init__(self, x): 
     21        self.x = x 
     22    def next(self): 
     23        return self.x 
     24 
    1825class HocConnector(object): 
    1926     
    20     def singleConnect(self, projection, src, tgt, weight, delay): 
    21         """ 
    22         Write hoc commands to connect a single pair of neurons. 
    23         """ 
    24         if "cond" in tgt.cellclass.__name__: 
    25             weight = abs(weight) # Weights must be positive for conductance-based synapses 
    26         cmdlist = ['nc = pc.gid_connect(%d,%s.object(%d).%s)' % (src, 
    27                                                                  projection.post.hoc_label, 
    28                                                                  projection.post.gidlist.index(tgt), 
    29                                                                  projection._syn_objref), 
    30                 'nc.weight = %f' % weight, 
    31                 'nc.delay  = %f' % delay, 
    32                 'tmp = %s.append(nc)' % projection.hoc_label] 
    33         projection.connections.append((src, tgt)) 
    34         return cmdlist 
    35      
    36     def getWeight(self, w): 
     27    def weights_iterator(self): 
     28        w = self.weights 
    3729        if w is not None: 
    3830            if hasattr(w, '__len__'): # d is an array 
    39                 weight = w.__iter__() 
     31                weights = w.__iter__() 
    4032            else: 
    41                 weight = w 
     33                weights = ConstIter(w) 
    4234        else:  
    43             weight = 1. 
    44         return weight 
    45      
    46     def getDelay(self, d): 
     35            weights = ConstIter(1.0) 
     36        return weights 
     37     
     38    def delays_iterator(self): 
     39        d = self.delays 
    4740        if d is not None: 
    4841            if hasattr(d, '__len__'): # d is an array 
    49                 delay = d.__iter__() 
     42                delays = d.__iter__() 
    5043            else: 
    51                 delay = max((d, get_min_delay())) 
     44                delays = ConstIter(max((d, get_min_delay()))) 
    5245        else: 
    53             delay = get_min_delay(
    54         return delay 
     46            delays = ConstIter(get_min_delay()
     47        return delays 
    5548 
    5649    def _process_conn_list(self, conn_list, projection): 
     
    6457        return hoc_commands 
    6558 
     59def probabilistic_connect(connector, projection, p): 
     60    weights = connector.weights_iterator() 
     61    delays = connector.delays_iterator() 
     62    if isinstance(projection.rng, NativeRNG): 
     63        rng = neuron.h.Random(0 or projection.rng.seed), 
     64        rarr = [rng.uniform(0,1)] 
     65        rarr.extend([rng.repick() for j in xrange(projection.pre.size*projection.post.size-1)]) 
     66        rarr = numpy.array(rarr) 
     67    else: 
     68        # We use concatenate, rather than just creating 
     69        # n=projection.pre.size*projection.post.size random numbers, 
     70        # in case of uneven distribution of neurons between MPI nodes 
     71        rarr = numpy.concatenate([projection.rng.next(projection.post.size, 'uniform', (0,1)) \ 
     72                                      for src in projection.pre._all_ids]) 
     73    j = 0 
     74    required_rarr_length = projection.pre.size * len(projection.post._local_ids) 
     75    assert len(rarr) >= required_rarr_length, \ 
     76           "Random array is too short (%d elements, needs %d)" % (len(rarr), required_rarr_length) 
     77         
     78    create = rarr<p 
     79    for src in projection.pre._all_ids: 
     80        for tgt in projection.post:     
     81            if connector.allow_self_connections or projection.pre != projection.post or tgt != src: 
     82                if create[j]: 
     83                    projection.connections.append( 
     84                            _single_connect(src, tgt, 
     85                                            weights.next(), delays.next(), 
     86                                            projection.synapse_type)) 
     87 
    6688 
    6789class AllToAllConnector(common.AllToAllConnector, HocConnector):     
    6890     
    6991    def connect(self, projection): 
    70         weight = self.getWeight(self.weights) 
    71         delay = self.getDelay(self.delays) 
    72         hoc_commands = [] 
    73         for src in projection.pre.fullgidlist: 
    74             for tgt in projection.post.gidlist:     
    75                 if self.allow_self_connections or projection.pre != projection.post or tgt != src: 
    76                     if hasattr(weight, 'next'): 
    77                         w = weight.next() 
    78                     else: 
    79                         w = weight 
    80                     if hasattr(delay, 'next'): 
    81                         d = delay.next() 
    82                     else: 
    83                         d = delay 
    84                     #print "Setting connection delay from %s to %s in %s to %g" % (src, tgt, projection.label, d) 
    85                     hoc_commands += self.singleConnect(projection, src, tgt, w, d) 
    86         return hoc_commands 
    87  
     92        probabilistic_connect(self, projection, 1.0) 
     93         
    8894 
    8995class OneToOneConnector(common.OneToOneConnector, HocConnector): 
    9096     
    9197    def connect(self, projection): 
    92         weight = self.getWeight(self.weights
    93         delay = self.getDelay(self.delays
     98        weights = connector.weights_iterator(
     99        delays = connector.delays_iterator(
    94100        if projection.pre.dim == projection.post.dim: 
    95             hoc_commands = [] 
    96             for tgt in projection.post.gidlist: 
     101            for tgt in projection.post: 
    97102                src = tgt - projection.post.first_id + projection.pre.first_id 
    98                 if hasattr(weight, 'next'): 
    99                     w = weight.next() 
    100                 else: 
    101                     w = weight 
    102                 if hasattr(delay, 'next'): 
    103                     d = delay.next() 
    104                 else: 
    105                     d = delay 
    106                 hoc_commands += self.singleConnect(projection, src, tgt, w, d) 
     103                projection.connections.append( 
     104                    _single_connect(src, tgt, weights.next(), delays.next(), projection.synapse_type)) 
    107105        else: 
    108106            raise Exception("OneToOneConnector does not support presynaptic and postsynaptic Populations of different sizes.") 
     
    110108 
    111109 
    112 class FixedProbabilityConnector(common.FixedProbabilityConnector, HocConnector): 
    113      
    114     def connect(self, projection): 
    115         weight = self.getWeight(self.weights) 
    116         delay = self.getDelay(self.delays) 
    117         if isinstance(projection.rng, NativeRNG): 
    118             hoc_commands = ['rng = new Random(%d)' % 0 or distribution.rng.seed, 
    119                             'tmp = rng.uniform(0,1)'] 
    120             # Here we are forced to execute the commands on line to be able to 
    121             # catch the connections from NEURON 
    122             hoc_execute(hoc_commands) 
    123             #rarr = [HocToPy.get('rng.repick()','float') for j in xrange(projection.pre.size*projection.post.size)] 
    124             rarr = [h.rng.repick() for j in xrange(projection.pre.size*projection.post.size)] 
    125         else: 
    126             # We use concatenate, rather than just creating 
    127             # n=projection.pre.size*projection.post.size random numbers, 
    128             # in case of uneven distribution of neurons between MPI nodes 
    129             rarr = numpy.concatenate([projection.rng.next(projection.post.size, 'uniform', (0,1)) \ 
    130                                       for src in projection.pre.fullgidlist]) 
    131         hoc_commands = [] 
    132         j = 0 
    133         required_rarr_length = len(projection.pre.fullgidlist) * len(projection.post.gidlist) 
    134         assert len(rarr) >= required_rarr_length, \ 
    135                "Random array is too short (%d elements, needs %d)" % (len(rarr), required_rarr_length) 
    136         for src in projection.pre.fullgidlist: 
    137             for tgt in projection.post.gidlist: 
    138                 if self.allow_self_connections or projection.pre != projection.post or tgt != src: 
    139                     if rarr[j] < self.p_connect:   
    140                         if hasattr(weight, 'next'): 
    141                             w = weight.next() 
    142                         else: 
    143                             w = weight 
    144                         if hasattr(delay, 'next'): 
    145                             d = delay.next() 
    146                         else: 
    147                             d = delay 
    148                         hoc_commands += self.singleConnect(projection, src, tgt, w, d)  
    149                 j += 1 
    150         return hoc_commands 
    151  
    152  
    153 class DistanceDependentProbabilityConnector(common.DistanceDependentProbabilityConnector, HocConnector): 
    154      
    155     def connect(self, projection): 
    156         weight = self.getWeight(self.weights) 
    157         delay = self.getDelay(self.delays) 
    158         periodic_boundaries = self.periodic_boundaries 
    159         if periodic_boundaries is not None: 
    160             dimensions = projection.post.dim 
    161             periodic_boundaries = numpy.concatenate((dimensions, numpy.zeros(3-len(dimensions)))) 
    162         if isinstance(projection.rng, NativeRNG): 
    163             hoc_commands = ['rng = new Random(%d)' % 0 or distribution.rng.seed, 
    164                             'tmp = rng.uniform(0,1)'] 
    165             # Here we are forced to execute the commands on line to be able to 
    166             # catch the connections from NEURON 
    167             hoc_execute(hoc_commands) 
    168             #rarr = [HocToPy.get('rng.repick()','float') for j in xrange(projection.pre.size*projection.post.size)] 
    169             rarr = [h.rng.repick() for j in xrange(projection.pre.size*projection.post.size)] 
    170         else: 
    171             rarr = projection.rng.uniform(0,1, projection.pre.size*projection.post.size) 
    172         # We need to use the gid stored as ID, so we should modify the loop to scan the global gidlist (containing ID) 
    173         hoc_commands = [] 
    174         j = 0 
    175         for tgt in projection.post.gidlist: 
    176             idx_pre  = 0 
    177             distances = common.distances(projection.pre, tgt, self.mask, self.scale_factor, self.offset, periodic_boundaries) 
    178             for src in projection.pre.fullgidlist: 
    179                 if self.allow_self_connections or projection.pre != projection.post or tgt != src:  
    180                     # calculate the distance between the two cells : 
    181                     d = distances[idx_pre][0] 
    182                     p = eval(self.d_expression) 
    183                     if p >= 1 or (0 < p < 1 and rarr[j] < p): 
    184                         if hasattr(weight, 'next'): 
    185                             w = weight.next() 
    186                         else: 
    187                             w = weight 
    188                         if hasattr(delay, 'next'): 
    189                             d = delay.next() 
    190                         else: 
    191                             d = delay 
    192                         hoc_commands += self.singleConnect(projection, src, tgt, w, d) 
    193                 j += 1 
    194                 idx_pre += 1 
    195         return hoc_commands 
    196  
    197 class _FixedNumberConnector(common.FixedNumberPreConnector, HocConnector): 
    198      
    199     def _connect(self, projection, x_list, y_list, type): 
    200         weight = self.getWeight(self.weights) 
    201         delay = self.getDelay(self.delays) 
    202         hoc_commands = [] 
    203          
    204         if projection.rng: 
    205             if isinstance(projection.rng, NativeRNG): 
    206                 raise Exception("NativeRNG not yet supported for the FixedNumberPreConnector") 
    207             rng = projection.rng 
    208         else: 
    209             rng = numpy.random 
    210         for y in y_list:             
    211             # pick n neurons at random 
    212             if hasattr(self, 'rand_distr'): 
    213                 n = self.rand_distr.next() 
    214             elif hasattr(self, 'n'): 
    215                 n = self.n 
    216             candidates = x_list 
    217             xs = [] 
    218             while len(xs) < n: # if the number of requested cells is larger than the size of the 
    219                                     # presynaptic population, we allow multiple connections for a given cell 
    220                 xs += [candidates[candidates.index(id)] for id in rng.permutation(candidates)[0:n]] 
    221                 # have to use index() because rng.permutation returns ints, not ID objects 
    222             xs = xs[:n] 
    223             for x in xs: 
    224                 if self.allow_self_connections or (x != y): 
    225                     if hasattr(weight, 'next'): 
    226                         w = weight.next() 
    227                     else: 
    228                         w = weight 
    229                     if hasattr(delay, 'next'): 
    230                         d = delay.next() 
    231                     else: 
    232                         d = delay 
    233                     if type == 'pre': 
    234                         hoc_commands += self.singleConnect(projection, x, y, w, d) 
    235                     elif type == 'post': 
    236                         hoc_commands += self.singleConnect(projection, y, x, w, d) 
    237                     else: 
    238                         raise Exception('Problem in _FixedNumberConnector') 
    239         return hoc_commands 
    240  
    241  
    242 class FixedNumberPreConnector(_FixedNumberConnector): 
    243      
    244     def connect(self, projection): 
    245         return self._connect(projection, projection.pre.gidlist, projection.post.gidlist, 'pre') 
    246  
    247  
    248 class FixedNumberPostConnector(_FixedNumberConnector): 
    249       
    250     def connect(self, projection): 
    251         return self._connect(projection, projection.post.gidlist, projection.pre.gidlist, 'post') 
    252  
    253  
    254 class FromListConnector(common.FromListConnector, HocConnector): 
    255      
    256     def connect(self, projection): 
    257         return self._process_conn_list(self.conn_list, projection) 
    258  
    259      
    260 class FromFileConnector(common.FromFileConnector, HocConnector): 
    261      
    262     def connect(self, projection): 
    263         if self.distributed: 
    264             myid = int(h.pc.id()) 
    265             self.filename += ".%d" % myid 
    266         # open the file... 
    267         f = open(self.filename, 'r', 10000) 
    268         lines = f.readlines() 
    269         f.close() 
    270         # gather all the data in a list of tuples (one per line) 
    271         input_tuples = [] 
    272         for line in lines: 
    273             single_line = line.rstrip() 
    274             src, tgt, w, d = single_line.split("\t", 4) 
    275             src = "[%s" % src.split("[",1)[1] 
    276             tgt = "[%s" % tgt.split("[",1)[1] 
    277             input_tuples.append((eval(src), eval(tgt), float(w), float(d))) 
    278         return self._process_conn_list(input_tuples, projection) 
     110#class FixedProbabilityConnector(common.FixedProbabilityConnector, HocConnector): 
     111#     
     112#    def connect(self, projection): 
     113#        weight = self.getWeight(self.weights) 
     114#        delay = self.getDelay(self.delays) 
     115#        if isinstance(projection.rng, NativeRNG): 
     116#            hoc_commands = ['rng = new Random(%d)' % 0 or distribution.rng.seed, 
     117#                            'tmp = rng.uniform(0,1)'] 
     118#            # Here we are forced to execute the commands on line to be able to 
     119#            # catch the connections from NEURON 
     120#            hoc_execute(hoc_commands) 
     121#            #rarr = [HocToPy.get('rng.repick()','float') for j in xrange(projection.pre.size*projection.post.size)] 
     122#            rarr = [h.rng.repick() for j in xrange(projection.pre.size*projection.post.size)] 
     123#        else: 
     124#            # We use concatenate, rather than just creating 
     125#            # n=projection.pre.size*projection.post.size random numbers, 
     126#            # in case of uneven distribution of neurons between MPI nodes 
     127#            rarr = numpy.concatenate([projection.rng.next(projection.post.size, 'uniform', (0,1)) \ 
     128#                                      for src in projection.pre.fullgidlist]) 
     129#        hoc_commands = [] 
     130#        j = 0 
     131#        required_rarr_length = len(projection.pre.fullgidlist) * len(projection.post.gidlist) 
     132#        assert len(rarr) >= required_rarr_length, \ 
     133#               "Random array is too short (%d elements, needs %d)" % (len(rarr), required_rarr_length) 
     134#        for src in projection.pre.fullgidlist: 
     135#            for tgt in projection.post.gidlist: 
     136#                if self.allow_self_connections or projection.pre != projection.post or tgt != src: 
     137#                    if rarr[j] < self.p_connect:   
     138#                        if hasattr(weight, 'next'): 
     139#                            w = weight.next() 
     140#                        else: 
     141#                            w = weight 
     142#                        if hasattr(delay, 'next'): 
     143#                            d = delay.next() 
     144#                        else: 
     145#                            d = delay 
     146#                        hoc_commands += self.singleConnect(projection, src, tgt, w, d)  
     147#                j += 1 
     148#        return hoc_commands 
     149
     150 
     151#class DistanceDependentProbabilityConnector(common.DistanceDependentProbabilityConnector, HocConnector): 
     152#     
     153#    def connect(self, projection): 
     154#        weight = self.getWeight(self.weights) 
     155#        delay = self.getDelay(self.delays) 
     156#        periodic_boundaries = self.periodic_boundaries 
     157#        if periodic_boundaries is not None: 
     158#            dimensions = projection.post.dim 
     159#            periodic_boundaries = numpy.concatenate((dimensions, numpy.zeros(3-len(dimensions)))) 
     160#        if isinstance(projection.rng, NativeRNG): 
     161#            hoc_commands = ['rng = new Random(%d)' % 0 or distribution.rng.seed, 
     162#                            'tmp = rng.uniform(0,1)'] 
     163#            # Here we are forced to execute the commands on line to be able to 
     164#            # catch the connections from NEURON 
     165#            hoc_execute(hoc_commands) 
     166#            #rarr = [HocToPy.get('rng.repick()','float') for j in xrange(projection.pre.size*projection.post.size)] 
     167#            rarr = [h.rng.repick() for j in xrange(projection.pre.size*projection.post.size)] 
     168#        else: 
     169#            rarr = projection.rng.uniform(0,1, projection.pre.size*projection.post.size) 
     170#        # We need to use the gid stored as ID, so we should modify the loop to scan the global gidlist (containing ID) 
     171#        hoc_commands = [] 
     172#        j = 0 
     173#        for tgt in projection.post.gidlist: 
     174#            idx_pre  = 0 
     175#            distances = common.distances(projection.pre, tgt, self.mask, self.scale_factor, self.offset, periodic_boundaries) 
     176#            for src in projection.pre.fullgidlist: 
     177#                if self.allow_self_connections or projection.pre != projection.post or tgt != src:  
     178#                    # calculate the distance between the two cells : 
     179#                    d = distances[idx_pre][0] 
     180#                    p = eval(self.d_expression) 
     181#                    if p >= 1 or (0 < p < 1 and rarr[j] < p): 
     182#                        if hasattr(weight, 'next'): 
     183#                            w = weight.next() 
     184#                        else: 
     185#                            w = weight 
     186#                        if hasattr(delay, 'next'): 
     187#                            d = delay.next() 
     188#                        else: 
     189#                            d = delay 
     190#                        hoc_commands += self.singleConnect(projection, src, tgt, w, d) 
     191#                j += 1 
     192#                idx_pre += 1 
     193#        return hoc_commands 
     194
     195#class _FixedNumberConnector(common.FixedNumberPreConnector, HocConnector): 
     196#     
     197#    def _connect(self, projection, x_list, y_list, type): 
     198#        weight = self.getWeight(self.weights) 
     199#        delay = self.getDelay(self.delays) 
     200#        hoc_commands = [] 
     201#         
     202#        if projection.rng: 
     203#            if isinstance(projection.rng, NativeRNG): 
     204#                raise Exception("NativeRNG not yet supported for the FixedNumberPreConnector") 
     205#            rng = projection.rng 
     206#        else: 
     207#            rng = numpy.random 
     208#        for y in y_list:             
     209#            # pick n neurons at random 
     210#            if hasattr(self, 'rand_distr'): 
     211#                n = self.rand_distr.next() 
     212#            elif hasattr(self, 'n'): 
     213#                n = self.n 
     214#            candidates = x_list 
     215#            xs = [] 
     216#            while len(xs) < n: # if the number of requested cells is larger than the size of the 
     217#                                    # presynaptic population, we allow multiple connections for a given cell 
     218#                xs += [candidates[candidates.index(id)] for id in rng.permutation(candidates)[0:n]] 
     219#                # have to use index() because rng.permutation returns ints, not ID objects 
     220#            xs = xs[:n] 
     221#            for x in xs: 
     222#                if self.allow_self_connections or (x != y): 
     223#                    if hasattr(weight, 'next'): 
     224#                        w = weight.next() 
     225#                    else: 
     226#                        w = weight 
     227#                    if hasattr(delay, 'next'): 
     228#                        d = delay.next() 
     229#                    else: 
     230#                        d = delay 
     231#                    if type == 'pre': 
     232#                        hoc_commands += self.singleConnect(projection, x, y, w, d) 
     233#                    elif type == 'post': 
     234#                        hoc_commands += self.singleConnect(projection, y, x, w, d) 
     235#                    else: 
     236#                        raise Exception('Problem in _FixedNumberConnector') 
     237#        return hoc_commands 
     238
     239
     240#class FixedNumberPreConnector(_FixedNumberConnector): 
     241#     
     242#    def connect(self, projection): 
     243#        return self._connect(projection, projection.pre.gidlist, projection.post.gidlist, 'pre') 
     244
     245
     246#class FixedNumberPostConnector(_FixedNumberConnector): 
     247#      
     248#    def connect(self, projection): 
     249#        return self._connect(projection, projection.post.gidlist, projection.pre.gidlist, 'post') 
     250
     251
     252#class FromListConnector(common.FromListConnector, HocConnector): 
     253#     
     254#    def connect(self, projection): 
     255#        return self._process_conn_list(self.conn_list, projection) 
     256
     257#     
     258#class FromFileConnector(common.FromFileConnector, HocConnector): 
     259#     
     260#    def connect(self, projection): 
     261#        if self.distributed: 
     262#            myid = int(h.pc.id()) 
     263#            self.filename += ".%d" % myid 
     264#        # open the file... 
     265#        f = open(self.filename, 'r', 10000) 
     266#        lines = f.readlines() 
     267#        f.close() 
     268#        # gather all the data in a list of tuples (one per line) 
     269#        input_tuples = [] 
     270#        for line in lines: 
     271#            single_line = line.rstrip() 
     272#            src, tgt, w, d = single_line.split("\t", 4) 
     273#            src = "[%s" % src.split("[",1)[1] 
     274#            tgt = "[%s" % tgt.split("[",1)[1] 
     275#            input_tuples.append((eval(src), eval(tgt), float(w), float(d))) 
     276#        return self._process_conn_list(input_tuples, projection) 
  • trunk/src/neuron2/utility.py

    r372 r376  
    6969            for id in self.recorded: 
    7070                spikes = id._cell.spiketimes.toarray() 
     71                print "t = ", common.get_current_time() 
     72                spikes = spikes[spikes<=common.get_current_time()+1e-9] 
    7173                if len(spikes) > 0: 
    7274                    new_data = numpy.array([spikes, numpy.ones(spikes.shape)*id]).T 
     
    101103        for item in items: 
    102104            if isinstance(item, common.Population): 
    103                 if "Source" not in item.__class__.__name__: 
     105                if "Source" not in item.celltype.__class__.__name__: # don't do memb_init() on spike sources 
    104106                    self.population_list.append(item) 
    105107            else: 
     
    116118                cell._cell.memb_init() 
    117119 
     120 
    118121load_mechanisms() 
  • trunk/test/neuron2tests.py

    r375 r376  
    242242        self.assertRaises(common.InvalidModelError, neuron.Population, (3,3), 'qwerty', {}) 
    243243         
    244 #    def testInitWithNonStandardModel(self): 
    245 #        """Population.__init__(): the cell list in hoc should have the same length as the population size.""" 
    246 #        net = neuron.Population((3,3), 'StandardIF', {'syn_type':'current', 'syn_shape':'exp'}) 
    247 #        n_cells = getattr(h, net.label).count() 
    248 #        n_cells_lower = int(getattr(h, net.label).count()) 
    249 #        # round-robin distribution 
    250 #        assert 9/neuron.nhost <= n_cells_lower <= 9/neuron.nhost+1, "%d not between %d and %d" % (n_cells_lower, 9/neuron.nhost, 9/neuron.nhost+1) 
    251 #     
    252 
    253 ## ============================================================================== 
    254 #class PopulationIndexTest(unittest.TestCase): 
    255 #    """Tests of the Population class indexing.""" 
    256 #     
    257 #    def setUp(self): 
    258 #        neuron.Population.nPop = 0 
    259 #        self.net1 = neuron.Population((10,), neuron.IF_curr_alpha) 
    260 #        self.net2 = neuron.Population((2,4,3), neuron.IF_curr_exp) 
    261 #        self.net3 = neuron.Population((2,2,1), neuron.SpikeSourceArray) 
    262 #        self.net4 = neuron.Population((1,2,1), neuron.SpikeSourceArray) 
    263 #        self.net5 = neuron.Population((3,3), neuron.IF_cond_alpha) 
    264 #     
    265 #    def testValidIndices(self): 
    266 #        for i in range(10): 
    267 #            self.assertEqual((i,), self.net1.locate(self.net1[i])) 
    268 
    269 #    def testValidAddresses(self): 
    270 #        for addr in ( (0,0,0), (0,0,1), (0,0,2), (0,1,0), (0,1,1), (0,1,2), (0,2,0), (0,2,1), (0,2,2), (0,3,0), (0,3,1), (0,3,2), 
    271 #                      (1,0,0), (1,0,1), (1,0,2), (1,1,0), (1,1,1), (1,1,2), (1,2,0), (1,2,1), (1,2,2), (1,3,0), (1,3,1), (1,3,2) ): 
    272 #            id = self.net2[addr] 
    273 #            self.assertEqual(addr, self.net2.locate(id)) 
    274 #        for addr in ( (0,0,0), (0,1,0), (1,0,0), (1,1,0) ): 
    275 #            id = self.net3[addr] 
    276 #            self.assertEqual(addr, self.net3.locate(id)) 
    277 #        for addr in ( (0,0,0), (0,1,0) ): 
    278 #            id = self.net4[addr] 
    279 #            self.assertEqual(addr, self.net4.locate(id)) 
    280 #        for addr in ( (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2) ): 
    281 #            id = self.net5[addr] 
    282 #            self.assertEqual(addr, self.net5.locate(id)) 
    283 
    284 #    def testInvalidIndices(self): 
    285 #        self.assertRaises(IndexError, self.net1.__getitem__, (11,)) 
    286 #         
    287 #    def testInvalidIndexDimension(self): 
    288 #        self.assertRaises(common.InvalidDimensionsError, self.net1.__getitem__, (10,2)) 
    289 #      
    290 ## ============================================================================== 
    291 #class PopulationIteratorTest(unittest.TestCase): 
    292 #    """Tests of the Population class iterators.""" 
    293 #     
    294 #    def setUp(self): 
    295 #        neuron.Population.nPop = 0 
    296 #        self.net1 = neuron.Population((10,), neuron.IF_curr_alpha) 
    297 #        self.net2 = neuron.Population((2,4,3), neuron.IF_curr_exp) 
    298 #        self.net3 = neuron.Population((2,2,1), neuron.SpikeSourceArray) 
    299 #        self.net4 = neuron.Population((1,2,1), neuron.SpikeSourceArray) 
    300 #        self.net5 = neuron.Population((3,3), neuron.IF_cond_alpha) 
    301 #         
    302 #    def testIter(self): 
    303 #        """This needs more thought for the distributed case.""" 
    304 #        for net in self.net1, self.net2: 
    305 #            ids = [i for i in net] 
    306 #            self.assertEqual(ids, net.gidlist) 
    307 #            self.assert_(isinstance(ids[0], neuron.ID)) 
    308 #             
    309 #    def testAddressIter(self): 
    310 #        for net in self.net1, self.net2: 
    311 #            for id, addr in zip(net.ids(), net.addresses()): 
    312 #                self.assertEqual(id, net[addr]) 
    313 #                self.assertEqual(addr, net.locate(id)) 
    314 #             
    315 #     
    316 ## ============================================================================== 
    317 #class PopulationSetTest(unittest.TestCase): 
    318 #         
    319 #    def setUp(self): 
    320 #        neuron.Population.nPop = 0 
    321 #        self.net = neuron.Population((3,3), neuron.IF_curr_alpha) 
    322 #        self.net2 = neuron.Population((5,),'StandardIF',{'syn_type':'current','syn_shape':'exp'}) 
    323 #     
    324 #    def testSetFromDict(self): 
    325 #        """Population.set(): Parameters set in a dict should all be retrievable using the top-level HocObject""" 
    326 #        self.net.set({'tau_m':43.21}) 
    327 #        cell_list = getattr(h, self.net.label) 
    328 #        for i in range(int(cell_list.count())): 
    329 #            assert cell_list.object(i).tau_m == 43.21 
    330 #     
    331 #    def testSetFromPair(self): 
    332 #        """Population.set(): A parameter set as a string, value pair should be retrievable using the top-level HocObject""" 
    333 #        self.net.set('tau_m',12.34) 
    334 #        cell_list = getattr(h, self.net.label) 
    335 #        for i in range(int(cell_list.count())): 
    336 #            assert cell_list.object(i).tau_m == 12.34 
    337 #     
    338 #    def testSetInvalidFromPair(self): 
    339 #        """Population.set(): Trying to set an invalid value for a parameter should raise an exception.""" 
    340 #        self.assertRaises(common.InvalidParameterValueError, self.net.set, 'tau_m', []) 
    341 #     
    342 #    def testSetInvalidFromDict(self): 
    343 #        """Population.set(): When any of the parameters in a dict have invalid values, then an exception should be raised. 
    344 #           There is no guarantee that the valid parameters will be set.""" 
    345 #        self.assertRaises(common.InvalidParameterValueError, self.net.set, {'v_thresh':'hello','tau_m':56.78}) 
    346 #     
    347 #    def testSetNonexistentFromPair(self): 
    348 #        """Population.set(): Trying to set a nonexistent parameter should raise an exception.""" 
    349 #        self.assertRaises(common.NonExistentParameterError, self.net.set, 'tau_foo', 10.0) 
    350 #     
    351 #    def testSetNonexistentFromDict(self): 
    352 #        """Population.set(): When some of the parameters in a dict are inexistent, an exception should be raised. 
    353 #           There is no guarantee that the existing parameters will be set.""" 
    354 #        self.assertRaises(common.NonExistentParameterError, self.net.set, {'tau_foo': 10.0, 'tau_m': 21.0}) 
    355 #     
    356 #    def testSetWithNonStandardModel(self): 
    357 #        """Population.set(): Parameters set in a dict should all be retrievable using the top-level HocObject""" 
    358 #        self.net2.set({'tau_m':43.21}) 
    359 #        cell_list = getattr(h, self.net2.label) 
    360 #        for i in range(int(cell_list.count())): 
    361 #            assert cell_list.object(i).tau_m == 43.21 
    362 #         
    363 #    def testTSet(self): 
    364 #        """Population.tset(): The valueArray passed should be retrievable using the top-level HocObject on all nodes.""" 
    365 #        array_in = numpy.array([[0.1,0.2,0.3],[0.4,0.5,0.6],[0.7,0.8,0.9]]) 
    366 #        self.net.tset('i_offset', array_in) 
    367 #        array_out = numpy.zeros((3,3), float) 
    368 #        hoc_net = getattr(h, self.net.label) 
    369 #        for i in 0,1,2: 
    370 #            for j in 0,1,2: 
    371 #                id = 3*i+j 
    372 #                if id in self.net.gidlist: 
    373 #                    list_index = self.net.gidlist.index(id) 
    374 #                    cell = hoc_net.object(list_index) 
    375 #                    array_out[i, j] = cell.stim.amp 
    376 #                else: 
    377 #                    array_out[i, j] = array_in[i, j] 
    378 #        assert numpy.equal(array_in, array_out).all(), array_out 
    379 #     
    380 #    def testTSetInvalidDimensions(self): 
    381 #        """Population.tset(): If the size of the valueArray does not match that of the Population, should raise an InvalidDimensionsError.""" 
    382 #        array_in = numpy.array([[0.1,0.2,0.3],[0.4,0.5,0.6]]) 
    383 #        self.assertRaises(common.InvalidDimensionsError, self.net.tset, 'i_offset', array_in) 
    384 #     
    385 #