Changeset 387

Show
Ignore:
Timestamp:
06/23/08 17:32:59 (5 months ago)
Author:
apdavison
Message:

In neuron2, implemented randomizeWeights(), randomizeDelays() and saveConnections(), plus the remaining Connector classes. Projection.connections now contains Connection objects that store the pre and post cell IDs as well as the NetCon.

Files:

Legend:

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

    r379 r387  
    644644        if isinstance(w, float) or isinstance(w, int): 
    645645            logging.info("Projection %s: setWeights(%s)" % (self.label, w)) 
    646             for nc in self.connections: 
    647                 nc.weight[0] = w # should first check weight value is ok, i.e. +ve for conductance-based, -ve for inhibitory current-based, not outside the weight limits for STDP...  
     646            for c in self.connections: 
     647                c.nc.weight[0] = w # should first check weight value is ok, i.e. +ve for conductance-based, -ve for inhibitory current-based, not outside the weight limits for STDP...  
    648648        elif isinstance(w, list) or isinstance(w, numpy.ndarray): 
    649649            assert len(w) == len(self), "List of weights has length %d, Projection %s has length %d" % (len(w), self.label, len(self)) 
    650650            logging.info("Projection %s: setWeights(iterable(min=%s, max=%s))" % (self.label, min(w), max(w))) 
    651             for nc, weight in zip(self.connections, w): 
    652                 nc.weight[0] = w 
     651            for c, weight in zip(self.connections, w): 
     652                c.nc.weight[0] = weight 
    653653        else: 
    654654            raise TypeError("Argument should be a numeric type (int, float...), a list, or a numpy array.") 
     
    664664                raise Exception("Delays must be greater than or equal to the minimum delay, currently %g ms" % get_min_delay()) 
    665665            logging.info("Projection %s: setDelays(%s)" % (self.label, d)) 
    666             for nc in self.connections: 
    667                 nc.delay = d 
     666            for c in self.connections: 
     667                c.nc.delay = d 
    668668            # if we have STDP, need to update pre2wa and post2wa delays as well 
    669669            if self.synapse_dynamics and self.synapse_dynamics.slow: 
     
    678678            assert len(d) == len(self), "List of delays has length %d, Projection %s has length %d" % (len(d), self.label, len(self)) 
    679679            logging.info("Projection %s: setDelays(iterable(min=%s, max=%s))" % (self.label, min(d), max(d))) 
    680             for nc, delay in zip(self.connections, d): 
    681                 nc.delay = delay 
     680            for c, delay in zip(self.connections, d): 
     681                c.nc.delay = delay 
    682682            # if we have STDP, need to update pre2wa and post2wa delays as well 
    683683            if self.synapse_dynamics and self.synapse_dynamics.slow: 
     
    688688        else: 
    689689            raise TypeError("Argument should be a numeric type (int, float...), a list, or a numpy array.") 
    690          
     690     
     691    def randomizeWeights(self, rand_distr): 
     692        """ 
     693        Set weights to random values taken from rand_distr. 
     694        """ 
     695        # If we have a native rng, we do the loops in hoc. Otherwise, we do the loops in 
     696        # Python 
     697        if isinstance(rand_distr.rng, NativeRNG): 
     698            rarr = simulator.nativeRNG_pick(len(self), 
     699                                            rand_distr.rng, 
     700                                            rand_distr.name, 
     701                                            rand_distr.parameters) 
     702        else:        
     703            rarr = rand_distr.next(len(self))   
     704        logging.info("--- Projection[%s].__randomizeWeights__() ---" % self.label) 
     705        self.setWeights(rarr) 
     706     
     707    def randomizeDelays(self, rand_distr): 
     708        """ 
     709        Set delays to random values taken from rand_distr. 
     710        """ 
     711        # If we have a native rng, we do the loops in hoc. Otherwise, we do the loops in 
     712        # Python 
     713        if isinstance(rand_distr.rng, NativeRNG): 
     714            rarr = simulator.nativeRNG_pick(len(self), 
     715                                            rand_distr.rng, 
     716                                            rand_distr.name, 
     717                                            rand_distr.parameters) 
     718        else:        
     719            rarr = rand_distr.next(len(self))   
     720        logging.info("--- Projection[%s].__randomizeDelays__() ---" % self.label) 
     721        self.setDelays(rarr) 
     722     
     723    # --- Methods for writing/reading information to/from file. ---------------- 
     724     
     725    def saveConnections(self, filename, gather=False): 
     726        """Save connections to file in a format suitable for reading in with the 
     727        'fromFile' method.""" 
     728        if gather: 
     729            raise Exception("saveConnections() with gather=True not yet implemented") 
     730        elif num_processes() > 1: 
     731            filename += '.%d' % rank() 
     732        logging.debug("--- Projection[%s].__saveConnections__() ---" % self.label) 
     733        f = open(filename, 'w', 10000) 
     734        for c in self.connections: 
     735            line = "%s%s\t%s%s\t%g\t%g\n" % (self.pre.label, 
     736                                     self.pre.locate(c.pre), 
     737                                     self.post.label, 
     738                                     self.post.locate(c.post), 
     739                                     c.nc.weight[0], 
     740                                     c.nc.delay) 
     741            line = line.replace('(','[').replace(')',']') 
     742            f.write(line) 
     743        f.close() 
  • trunk/src/neuron2/connectors.py

    r379 r387  
    1414 
    1515# ============================================================================== 
    16 #   Connection method classes 
     16#   Utility functions/classes (not part of the API) 
    1717# ============================================================================== 
    1818 
     
    5050    def _process_conn_list(self, conn_list, projection): 
    5151        """Extract fields from list of tuples and construct the hoc commands.""" 
    52         hoc_commands = [] 
    5352        for i in xrange(len(conn_list)): 
    5453            src, tgt, weight, delay = conn_list[i][:] 
    5554            src = projection.pre[tuple(src)] 
    5655            tgt = projection.post[tuple(tgt)] 
    57             hoc_commands += self.singleConnect(projection, src, tgt, weight, delay) 
    58         return hoc_commands 
     56            projection.connections.append(simulator.single_connect(src, tgt, weight, delay, projection.synapse_type)) 
    5957 
    6058def probabilistic_connect(connector, projection, p): 
     
    6260    delays = connector.delays_iterator() 
    6361    if isinstance(projection.rng, NativeRNG): 
    64         rng = simulator.h.Random(0 or projection.rng.seed) 
    65         rarr = [rng.uniform(0,1)] 
    66         rarr.extend([rng.repick() for j in xrange(projection.pre.size*projection.post.size-1)]) 
    67         rarr = numpy.array(rarr) 
     62        rarr = simulator.nativeRNG_pick(projection.pre.size*projection.post.size, 
     63                                        projection.rng, 
     64                                        'uniform', (0,1)) 
    6865    else: 
    6966        # We use concatenate, rather than just creating 
     
    8986    assert j == required_length 
    9087 
     88# ============================================================================== 
     89#   Connection method classes 
     90# ============================================================================== 
     91 
    9192class AllToAllConnector(common.AllToAllConnector, HocConnector):     
    9293     
     
    134135        probabilistic_connect(self, projection, p_array.flatten()) 
    135136 
    136 #class _FixedNumberConnector(common.FixedNumberPreConnector, HocConnector): 
    137 #     
    138 #    def _connect(self, projection, x_list, y_list, type): 
    139 #        weight = self.getWeight(self.weights) 
    140 #        delay = self.getDelay(self.delays) 
    141 #        hoc_commands = [] 
    142 #         
    143 #        if projection.rng: 
    144 #            if isinstance(projection.rng, NativeRNG): 
    145 #                raise Exception("NativeRNG not yet supported for the FixedNumberPreConnector") 
    146 #            rng = projection.rng 
    147 #        else: 
    148 #            rng = numpy.random 
    149 #        for y in y_list:             
    150 #            # pick n neurons at random 
    151 #            if hasattr(self, 'rand_distr'): 
    152 #                n = self.rand_distr.next() 
    153 #            elif hasattr(self, 'n'): 
    154 #                n = self.n 
    155 #            candidates = x_list 
    156 #            xs = [] 
    157 #            while len(xs) < n: # if the number of requested cells is larger than the size of the 
    158 #                                    # presynaptic population, we allow multiple connections for a given cell 
    159 #                xs += [candidates[candidates.index(id)] for id in rng.permutation(candidates)[0:n]] 
    160 #                # have to use index() because rng.permutation returns ints, not ID objects 
    161 #            xs = xs[:n] 
    162 #            for x in xs: 
    163 #                if self.allow_self_connections or (x != y): 
    164 #                    if hasattr(weight, 'next'): 
    165 #                        w = weight.next() 
    166 #                    else: 
    167 #                        w = weight 
    168 #                    if hasattr(delay, 'next'): 
    169 #                        d = delay.next() 
    170 #                    else: 
    171 #                        d = delay 
    172 #                    if type == 'pre': 
    173 #                        hoc_commands += self.singleConnect(projection, x, y, w, d) 
    174 #                    elif type == 'post': 
    175 #                        hoc_commands += self.singleConnect(projection, y, x, w, d) 
    176 #                    else: 
    177 #                        raise Exception('Problem in _FixedNumberConnector') 
    178 #        return hoc_commands 
    179 
    180 
    181 #class FixedNumberPreConnector(_FixedNumberConnector): 
    182 #     
    183 #    def connect(self, projection): 
    184 #        return self._connect(projection, projection.pre.gidlist, projection.post.gidlist, 'pre') 
    185 
    186 
    187 #class FixedNumberPostConnector(_FixedNumberConnector): 
    188 #      
    189 #    def connect(self, projection): 
    190 #        return self._connect(projection, projection.post.gidlist, projection.pre.gidlist, 'post') 
    191 
    192 
    193 #class FromListConnector(common.FromListConnector, HocConnector): 
    194 #     
    195 #    def connect(self, projection): 
    196 #        return self._process_conn_list(self.conn_list, projection) 
    197 
    198 #     
    199 #class FromFileConnector(common.FromFileConnector, HocConnector): 
    200 #     
    201 #    def connect(self, projection): 
    202 #        if self.distributed: 
    203 #            myid = int(h.pc.id()) 
    204 #            self.filename += ".%d" % myid 
    205 #        # open the file... 
    206 #        f = open(self.filename, 'r', 10000) 
    207 #        lines = f.readlines() 
    208 #        f.close() 
    209 #        # gather all the data in a list of tuples (one per line) 
    210 #        input_tuples = [] 
    211 #        for line in lines: 
    212 #            single_line = line.rstrip() 
    213 #            src, tgt, w, d = single_line.split("\t", 4) 
    214 #            src = "[%s" % src.split("[",1)[1] 
    215 #            tgt = "[%s" % tgt.split("[",1)[1] 
    216 #            input_tuples.append((eval(src), eval(tgt), float(w), float(d))) 
    217 #        return self._process_conn_list(input_tuples, projection) 
     137class _FixedNumberConnector(common.FixedNumberPreConnector, HocConnector): 
     138     
     139    def _connect(self, projection, x_list, y_list, type): 
     140        weights = self.weights_iterator() 
     141        delays = self.delays_iterator() 
     142       
     143        if projection.rng: 
     144            if isinstance(projection.rng, NativeRNG): 
     145                raise Exception("NativeRNG not yet supported for the FixedNumberPreConnector") 
     146            rng = projection.rng 
     147        else: 
     148            rng = numpy.random 
     149        for y in y_list:             
     150            # pick n neurons at random 
     151            if hasattr(self, 'rand_distr'): 
     152                n = self.rand_distr.next() 
     153            elif hasattr(self, 'n'): 
     154                n = self.n 
     155            candidates = x_list 
     156            xs = [] 
     157            while len(xs) < n: # if the number of requested cells is larger than the size of the 
     158                                    # presynaptic population, we allow multiple connections for a given cell 
     159                xs += [candidates[candidates.index(id)] for id in rng.permutation(candidates)[0:n]] 
     160                # have to use index() because rng.permutation returns ints, not ID objects 
     161            xs = xs[:n] 
     162            for x in xs: 
     163                if self.allow_self_connections or (x != y): 
     164                    if type == 'pre': 
     165                        src = x; tgt = y   
     166                    elif type == 'post': 
     167                        src = y; tgt = x 
     168                    else: 
     169                        raise Exception('Problem in _FixedNumberConnector') 
     170                    projection.connections.append( 
     171                        simulator.single_connect(src, tgt, weights.next(), delays.next(), projection.synapse_type)) 
     172 
     173 
     174class FixedNumberPreConnector(_FixedNumberConnector): 
     175     
     176    def connect(self, projection): 
     177        self._connect(projection, projection.pre._all_ids.flatten().tolist(), projection.post._local_ids, 'pre') 
     178 
     179 
     180class FixedNumberPostConnector(_FixedNumberConnector): 
     181      
     182    def connect(self, projection): 
     183        self._connect(projection, projection.post._all_ids.flatten().tolist(), projection.pre._all_ids.flatten(), 'post') 
     184 
     185 
     186class FromListConnector(common.FromListConnector, HocConnector): 
     187     
     188    def connect(self, projection): 
     189        self._process_conn_list(self.conn_list, projection) 
     190 
     191     
     192class FromFileConnector(common.FromFileConnector, HocConnector): 
     193     
     194    def connect(self, projection): 
     195        if self.distributed: 
     196            myid = int(h.pc.id()) 
     197            self.filename += ".%d" % myid 
     198        # open the file... 
     199        f = open(self.filename, 'r', 10000) 
     200        lines = f.readlines() 
     201        f.close() 
     202        # gather all the data in a list of tuples (one per line) 
     203        input_tuples = [] 
     204        for line in lines: 
     205            single_line = line.rstrip() 
     206            src, tgt, w, d = single_line.split("\t", 4) 
     207            src = "[%s" % src.split("[",1)[1] 
     208            tgt = "[%s" % tgt.split("[",1)[1] 
     209            input_tuples.append((eval(src), eval(tgt), float(w), float(d))) 
     210        self._process_conn_list(input_tuples, projection) 
  • trunk/src/neuron2/simulator.py

    r379 r387  
    185185    nc = neuron.NetCon(source, None)                          # } associate the cell spike source 
    186186    state.parallel_context.cell(gid, nc.hoc_obj)              # } with the gid (using a temporary NetCon) 
     187 
     188def nativeRNG_pick(n, rng, distribution='uniform', parameters=[0,1]): 
     189    native_rng = h.Random(0 or rng.seed) 
     190    rarr = [getattr(native_rng, distribution)(*parameters)] 
     191    rarr.extend([native_rng.repick() for j in xrange(n-1)]) 
     192    return numpy.array(rarr) 
     193 
     194class Connection(object): 
     195 
     196    def __init__(self, source, target, nc): 
     197        self.pre = source 
     198        self.post = target 
     199        self.nc = nc 
    187200 
    188201def single_connect(source, target, weight, delay, synapse_type): 
     
    212225    nc.weight[0] = weight 
    213226    nc.delay  = delay 
    214     return nc 
     227    return Connection(source, target, nc) 
    215228 
    216229# The following are executed every time the module is imported. 
  • trunk/test/neuron2tests.py

    r379 r387  
    8686        # conn will be an empty list if it does not exist on that node 
    8787        self.assertEqual(len(conn_list), 1) 
    88         assert is_NetCon(conn_list[0]), 'Error creating connection, conn=%s' % conn 
     88        assert is_NetCon(conn_list[0].nc), 'Error creating connection, conn_list=%s' % conn_list 
    8989         
    9090    def testConnectTwoCellsWithWeight(self): 
     
    9393        conn_list = neuron.connect(self.precells[0], self.postcells[0], weight=0.1234) 
    9494        if conn_list: 
    95             weight = conn_list[0].weight[0] 
     95            weight = conn_list[0].nc.weight[0] 
    9696            assert weight == 0.1234, "Weight set (0.1234) does not match weight retrieved (%s)" % weight 
    9797     
     
    100100        conn_list = neuron.connect(self.precells[0], self.postcells[0], delay=4.321) 
    101101        if conn_list: 
    102             delay = conn_list[0].delay 
     102            delay = conn_list[0].nc.delay 
    103103            assert delay == 4.321, "Delay set (4.321) does not match delay retrieved (%s)." % delay 
    104104     
     
    531531                prj.setWeights(1.234) 
    532532                weights = [] 
    533                 for nc in prj.connections: 
    534                     weights.append(nc.weight[0]) 
     533                for c in prj.connections: 
     534                    weights.append(c.nc.weight[0]) 
    535535                assert weights == [1.234]*len(prj) 
    536536         
     
    562562                assert (0 < len(prj) < len(self.source33)*len(self.target33)) 
    563563         
    564 
    565 #    def testFixedNumberPre(self): 
    566 #        c1 = neuron.FixedNumberPreConnector(10) 
    567 #        c2 = neuron.FixedNumberPreConnector(3) 
    568 #        c3 = neuron.FixedNumberPreConnector(random.RandomDistribution('poisson',[5])) 
    569 #        for srcP in [self.source5, self.source22]: 
    570 #            for tgtP in [self.target6, self.target33]: 
    571 #                for c in c1, c2: 
    572 #                    prj1 = neuron.Projection(srcP, tgtP, c) 
    573 #                    self.assertEqual(len(prj1.connections), c.n*len(tgtP)) 
    574 #                prj3 = neuron.Projection(srcP, tgtP, c3) # just a test that no Exceptions are raised 
    575 
    576 #    def testFixedNumberPost(self): 
    577 #        c1 = neuron.FixedNumberPostConnector(10) 
    578 #        c2 = neuron.FixedNumberPostConnector(3) 
    579 #        c3 = neuron.FixedNumberPostConnector(random.RandomDistribution('poisson',[5])) 
    580 #        for srcP in [self.source5, self.source22]: 
    581 #            for tgtP in [self.target6, self.target33]: 
    582 #                for c in c1, c2: 
    583 #                    prj1 = neuron.Projection(srcP, tgtP, c) 
    584 #                    self.assertEqual(len(prj1.connections), c.n*len(srcP)) 
    585 #                prj2 = neuron.Projection(srcP, tgtP, c3) # just a test that no Exceptions are raised 
    586 
    587 #    def testSaveAndLoad(self): 
    588 #        prj1 = neuron.Projection(self.source33, self.target33, 'oneToOne') 
    589 #        prj1.setDelays(1) 
    590 #        prj1.setWeights(1.234) 
    591 #        prj1.saveConnections("connections.tmp", gather=False) 
    592 #        #prj2 = neuron.Projection(self.source33, self.target33, 'fromFile',"connections.tmp") 
    593 #        if neuron.num_processes() > 1: 
    594 #            distributed = True 
    595 #        else: 
    596 #            distributed = False 
    597 #        prj3 = neuron.Projection(self.source33, self.target33, neuron.FromFileConnector("connections.tmp", 
    598 #                                                                                        distributed=distributed)) 
    599 #        w1 = []; w2 = []; w3 = []; d1 = []; d2 = []; d3 = [] 
    600 #        # For a connections scheme saved and reloaded, we test if the connections, their weights and their delays 
    601 #        # are equal. 
    602 #        hoc_list1 = getattr(h, prj1.label) 
    603 #        #hoc_list2 = getattr(h, prj2.label) 
    604 #        hoc_list3 = getattr(h, prj3.label) 
    605 #        for connection_id in prj1.connections: 
    606 #            w1.append(hoc_list1.object(prj1.connections.index(connection_id)).weight[0]) 
    607 #            #w2.append(hoc_list2.object(prj2.connections.index(connection_id)).weight[0]) 
    608 #            w3.append(hoc_list3.object(prj3.connections.index(connection_id)).weight[0]) 
    609 #            d1.append(hoc_list1.object(prj1.connections.index(connection_id)).delay) 
    610 #            #d2.append(hoc_list2.object(prj2.connections.index(connection_id)).delay) 
    611 #            d3.append(hoc_list3.object(prj3.connections.index(connection_id)).delay) 
    612 #        #assert (w1 == w2 == w3) and (d1 == d2 == d3) 
    613 #        assert (w1 == w3) and (d1 == d3) 
    614 #           
    615 #    def testSettingDelays(self): 
    616 #        """Delays should be set correctly when using a Connector object.""" 
    617 #        for srcP in [self.source5, self.source22]: 
    618 #            for tgtP in [self.target6, self.target33]: 
    619 #                prj1 = neuron.Projection(srcP, tgtP, neuron.AllToAllConnector(delays=0.321)) 
    620 #                hoc_list = getattr(neuron.h, prj1.label) 
    621 #                assert hoc_list.object(0).delay == 0.321, "Delay should be 0.321, actually %g" % hoc_list.object(0).delay 
    622 
    623 #class ProjectionSetTest(unittest.TestCase): 
    624 #    """Tests of the setWeights(), setDelays(), randomizeWeights() and 
    625 #    randomizeDelays() methods of the Projection class.""" 
    626 
    627 #    def setUp(self): 
    628 #        self.target   = neuron.Population((3,3), neuron.IF_curr_alpha) 
    629 #        self.source   = neuron.Population((3,3), neuron.SpikeSourcePoisson,{'rate': 200}) 
    630 #        self.distrib_Numpy = RandomDistribution(rng=NumpyRNG(12345), distribution='uniform', parameters=(0,1))  
    631 #        self.distrib_Native= RandomDistribution(rng=NativeRNG(12345), distribution='uniform', parameters=(0,1))  
    632 #         
    633 #    def testSetWeights(self): 
    634 #        prj1 = neuron.Projection(self.source, self.target, 'allToAll') 
    635 #        prj1.setWeights(2.345) 
    636 #        weights = [] 
    637 #        hoc_list = getattr(h, prj1.label) 
    638 #        for connection_id in prj1.connections: 
    639 #            #weights.append(HocToPy.get('%s.object(%d).weight' % (prj1.label, prj1.connections.index(connection_id)))) 
    640 #            weights.append(hoc_list.object(prj1.connections.index(connection_id)).weight[0]) 
    641 #        result = 2.345*numpy.ones(len(prj1.connections)) 
    642 #        assert (weights == result.tolist()) 
    643 #         
    644 #    def testSetDelays(self): 
    645 #        prj1 = neuron.Projection(self.source, self.target, 'allToAll') 
    646 #        prj1.setDelays(2.345) 
    647 #        delays = [] 
    648 #        hoc_list = getattr(h, prj1.label) 
    649 #        for connection_id in prj1.connections: 
    650 #            #delays.append(HocToPy.get('%s.object(%d).delay' % (prj1.label, prj1.connections.index(connection_id)))) 
    651 #            delays.append(hoc_list.object(prj1.connections.index(connection_id)).delay) 
    652 #        result = 2.345*numpy.ones(len(prj1.connections)) 
    653 #        assert (delays == result.tolist()) 
    654 #         
    655 #    def testRandomizeWeights(self): 
    656 #        # The probability of having two consecutive weights vector that are equal should be 0 
    657 #        prj1 = neuron.Projection(self.source, self.target, 'allToAll') 
    658 #        prj2 = neuron.Projection(self.source, self.target, 'allToAll') 
    659 #        prj1.randomizeWeights(self.distrib_Numpy) 
    660 #        prj2.randomizeWeights(self.distrib_Native) 
    661 #        w1 = []; w2 = []; w3 = []; w4 = [] 
    662 #        hoc_list1 = getattr(h, prj1.label) 
    663 #        hoc_list2 = getattr(h, prj2.label) 
    664 #        for connection_id in prj1.connections: 
    665 #            #w1.append(HocToPy.get('%s.object(%d).weight' % (prj1.label, prj1.connections.index(connection_id)))) 
    666 #            #w2.append(HocToPy.get('%s.object(%d).weight' % (prj2.label, prj1.connections.index(connection_id)))) 
    667 #            w1.append(hoc_list1.object(prj1.connections.index(connection_id)).weight[0]) 
    668 #            w2.append(hoc_list2.object(prj2.connections.index(connection_id)).weight[0]) 
    669 #        prj1.randomizeWeights(self.distrib_Numpy) 
    670 #        prj2.randomizeWeights(self.distrib_Native) 
    671 #        for connection_id in prj1.connections: 
    672 #            #w3.append(HocToPy.get('%s.object(%d).weight' % (prj1.label, prj1.connections.index(connection_id)))) 
    673 #            #w4.append(HocToPy.get('%s.object(%d).weight' % (prj2.label, prj1.connections.index(connection_id)))) 
    674 #            w3.append(hoc_list1.object(prj1.connections.index(connection_id)).weight[0]) 
    675 #            w4.append(hoc_list2.object(prj2.connections.index(connection_id)).weight[0]) 
    676 #        self.assertNotEqual(w1, w3) and self.assertNotEqual(w2, w4)  
    677 #         
    678 #    def testRandomizeDelays(self): 
    679 #        # The probability of having two consecutive delays vector that are equal should be 0 
    680 #        prj1 = neuron.Projection(self.source, self.target, 'allToAll') 
    681 #        prj2 = neuron.Projection(self.source, self.target, 'allToAll') 
    682 #        prj1.randomizeDelays(self.distrib_Numpy) 
    683 #        prj2.randomizeDelays(self.distrib_Native) 
    684 #        d1 = []; d2 = []; d3 = []; d4 = [] 
    685 #        hoc_list1 = getattr(h, prj1.label) 
    686 #        hoc_list2 = getattr(h, prj2.label) 
    687 #        for connection_id in prj1.connections: 
    688 #            #d1.append(HocToPy.get('%s.object(%d).delay' % (prj1.label, prj1.connections.index(connection_id)))) 
    689 #            #d2.append(HocToPy.get('%s.object(%d).delay' % (prj2.label, prj1.connections.index(connection_id)))) 
    690 #            d1.append(hoc_list1.object(prj1.connections.index(connection_id)).delay) 
    691 #            d2.append(hoc_list2.object(prj2.connections.index(connection_id)).delay) 
    692 #        prj1.randomizeDelays(self.distrib_Numpy) 
    693 #        prj2.randomizeDelays(self.distrib_Native) 
    694 #        for connection_id in prj1.connections: 
    695 #            #d3.append(HocToPy.get('%s.object(%d).delay' % (prj1.label, prj1.connections.index(connection_id)))) 
    696 #            #d4.append(HocToPy.get('%s.object(%d).delay' % (prj2.label, prj1.connections.index(connection_id)))) 
    697 #            d3.append(hoc_list1.object(prj1.connections.index(connection_id)).delay) 
    698 #            d4.append(hoc_list2.object(prj2.connections.index(connection_id)).delay) 
    699 #        self.assertNotEqual(d1, d3) and self.assertNotEqual(d2, d4)  
    700 #                
    701 #         
     564 
     565    def testFixedNumberPre(self): 
     566        c1 = neuron.FixedNumberPreConnector(10) 
     567        c2 = neuron.FixedNumberPreConnector(3) 
     568        c3 = neuron.FixedNumberPreConnector(random.RandomDistribution('poisson',[5])) 
     569        for srcP in [self.source5, self.source22]: 
     570            for tgtP in [self.target6, self.target33]: 
     571                for c in c1, c2: 
     572                    prj1 = neuron.Projection(srcP, tgtP, c) 
     573                    self.assertEqual(len(prj1.connections), c.n*len(tgtP)) 
     574                prj3 = neuron.Projection(srcP, tgtP, c3) # just a test that no Exceptions are raised 
     575 
     576    def testFixedNumberPost(self): 
     577        c1 = neuron.FixedNumberPostConnector(10) 
     578        c2 = neuron.FixedNumberPostConnector(3) 
     579        c3 = neuron.FixedNumberPostConnector(random.RandomDistribution('poisson',[5])) 
     580        for srcP in [self.source5, self.source22]: 
     581            for tgtP in [self.target6, self.target33]: 
     582                for c in c1, c2: 
     583                    prj1 = neuron.Projection(srcP, tgtP, c) 
     584                    self.assertEqual(len(prj1.connections), c.n*len(srcP)) 
     585                prj2 = neuron.Projection(srcP, tgtP, c3) # just a test that no Exceptions are raised 
     586 
     587    def testSaveAndLoad(self): 
     588        prj1 = neuron.Projection(self.source33, self.target33, neuron.OneToOneConnector()) 
     589        prj1.setDelays(1) 
     590        prj1.setWeights(1.234) 
     591        prj1.saveConnections("connections.tmp", gather=False) 
     592        if neuron.num_processes() > 1: 
     593            distributed = True 
     594        else: 
     595            distributed = False 
     596        prj2 = neuron.Projection(self.source33, self.target33, neuron.FromFileConnector("connections.tmp", 
     597                                                                                        distributed=distributed)) 
     598        w1 = []; w2 = []; d1 = []; d2 = [] 
     599        # For a connections scheme saved and reloaded, we test if the connections, their weights and their delays 
     600        # are equal. 
     601        for c1,c2 in zip(prj1.connections, prj2.connections): 
     602            w1.append(c1.nc.weight[0]) 
     603            w2.append(c2.nc.weight[0]) 
     604            d1.append(c1.nc.delay) 
     605            d2.append(c2.nc.delay) 
     606        assert (w1 == w2), 'w1 = %s\nw2 = %s' % (w1, w2) 
     607        assert (d1 == d2), 'd1 = %s\nd2 = %s' % (d1, d2) 
     608           
     609    def testSettingDelays(self): 
     610        """Delays should be set correctly when using a Connector object.""" 
     611        for srcP in [self.source5, self.source22]: 
     612            for tgtP in [self.target6, self.target33]: 
     613                prj1 = neuron.Projection(srcP, tgtP, neuron.AllToAllConnector(delays=0.321)) 
     614                assert prj1.connections[0].nc.delay == 0.321, "Delay should be 0.321, actually %g" % prj1.connections[0].nc.delay 
     615 
     616class ProjectionSetTest(unittest.TestCase): 
     617    """Tests of the setWeights(), setDelays(), randomizeWeights() and 
     618    randomizeDelays() methods of the Projection class.""" 
     619 
     620    def setUp(self): 
     621        self.target   = neuron.Population((3,3), neuron.IF_curr_alpha) 
     622        self.source   = neuron.Population((3,3), neuron.SpikeSourcePoisson,{'rate': 200}) 
     623        self.distrib_Numpy = random.RandomDistribution(rng=random.NumpyRNG(12345), distribution='uniform', parameters=(0.2,1))  
     624        self.distrib_Native= random.RandomDistribution(rng=random.NativeRNG(12345), distribution='uniform', parameters=(0.2,1))  
     625         
     626    def testSetWeights(self): 
     627        prj1 = neuron.Projection(self.source, self.target, neuron.AllToAllConnector()) 
     628        prj1.setWeights(2.345) 
     629        weights = [] 
     630        for c in prj1.connections: 
     631            weights.append(c.nc.weight[0]) 
     632        result = 2.345*numpy.ones(len(prj1.connections)) 
     633        assert (weights == result.tolist()) 
     634         
     635    def testSetDelays(self): 
     636        prj1 = neuron.Projection(self.source, self.target, neuron.AllToAllConnector()) 
     637        prj1.setDelays(2.345) 
     638        delays = [] 
     639        for c in prj1.connections: 
     640            delays.append(c.nc.delay) 
     641        result = 2.345*numpy.ones(len(prj1.connections)) 
     642        assert (delays == result.tolist()) 
     643         
     644    def testRandomizeWeights(self): 
     645        # The probability of having two consecutive weights vector that are equal should be 0 
     646        prj1 = neuron.Projection(self.source, self.target, neuron.AllToAllConnector()) 
     647        prj2 = neuron.Projection(self.source, self.target, neuron.AllToAllConnector()) 
     648        prj1.randomizeWeights(self.distrib_Numpy) 
     649        prj2.randomizeWeights(self.distrib_Native) 
     650        w1 = []; w2 = []; w3 = []; w4 = [] 
     651        for c in prj1.connections: 
     652            w1.append(c.nc.weight[0]) 
     653            w2.append(c.nc.weight[0]) 
     654        prj1.randomizeWeights(self.distrib_Numpy) 
     655        prj2.randomizeWeights(self.distrib_Native) 
     656        for c in prj1.connections: 
     657            w3.append(c.nc.weight[0]) 
     658            w4.append(c.nc.weight[0]) 
     659        self.assertNotEqual(w1, w3) and self.assertNotEqual(w2, w4)  
     660         
     661    def testRandomizeDelays(self): 
     662        # The probability of having two consecutive delays vector that are equal should be 0 
     663        prj1 = neuron.Projection(self.source, self.target, neuron.AllToAllConnector()) 
     664        prj2 = neuron.Projection(self.source, self.target, neuron.AllToAllConnector()) 
     665        prj1.randomizeDelays(self.distrib_Numpy) 
     666        prj2.randomizeDelays(self.distrib_Native) 
     667        d1 = []; d2 = []; d3 = []; d4 = [] 
     668        for c in prj1.connections: 
     669            d1.append(c.nc.weight[0]) 
     670            d2.append(c.nc.weight[0]) 
     671        prj1.randomizeWeights(self.distrib_Numpy) 
     672        prj2.randomizeWeights(self.distrib_Native) 
     673        for c in prj1.connections: 
     674            d3.append(c.nc.weight[0]) 
     675            d4.append(c.nc.weight[0]) 
     676        self.assertNotEqual(d1, d3) and self.assertNotEqual(d2, d4)  
     677                
     678         
    702679#    # If STDP works, a strong stimulation with only LTP should increase the mean weight 
    703680#    def testSTDP(self): 
     
    795772#                assert (delay == 54.32), delay 
    796773# 
    797 #class IDTest(unittest.TestCase): 
    798 #    """Tests of the ID class.""" 
    799 #     
    800 #    def setUp(self): 
    801 #        neuron.Population.nPop = 0 
    802 #        self.pop1 = neuron.Population((5,), neuron.IF_curr_alpha,{'tau_m':10.0}) 
    803 #        self.pop2 = neuron.Population((5,4), neuron.IF_curr_exp,{'v_reset':-60.0}) 
    804 #     
    805 #    def testIDSetAndGet(self): 
    806 #        if self.pop1[3] in self.pop1.gidlist
    807 #            self.pop1[3].tau_m = 20.0 
    808 #            self.assertEqual(20.0, self.pop1[3].tau_m) 
    809 #        if self.pop1[0] in self.pop1.gidlist
    810 #            self.assertEqual(10.0, self.pop1[0].tau_m) 
    811 #        if self.pop2[3,2] in self.pop2.gidlist
    812 #            self.pop2[3,2].v_reset = -70.0 
    813 #            self.assertEqual(-70.0, self.pop2[3,2].v_reset) 
    814 #        if self.pop2[0,0] in self.pop2.gidlist
    815 #            self.assertEqual(-60.0, self.pop2[0,0].v_reset) 
    816 
    817 #    def testGetCellClass(self): 
    818 #        self.assertEqual(neuron.IF_curr_alpha, self.pop1[0].cellclass) 
    819 #        self.assertEqual(neuron.IF_curr_exp, self.pop2[4,3].cellclass) 
    820 #         
    821 #    def testSetAndGetPosition(self): 
    822 #        self.assert_((self.pop2[0,2].position == (0.0,2.0,0.0)).all()) 
    823 #        new_pos = (0.5,1.5,0.0) 
    824 #        self.pop2[0,2].position = new_pos 
    825 #        self.assert_((self.pop2[0,2].position == (0.5,1.5,0.0)).all()) 
    826 #        new_pos = (-0.6,3.5,-100.0) # check that position is set-by-value from new_pos 
    827 #        self.assert_((self.pop2[0,2].position == (0.5,1.5,0.0)).all()) 
     774class IDTest(unittest.TestCase): 
     775    """Tests of the ID class.""" 
     776     
     777    def setUp(self): 
     778        neuron.Population.nPop = 0 
     779        self.pop1 = neuron.Population((5,), neuron.IF_curr_alpha,{'tau_m':10.0}) 
     780        self.pop2 = neuron.Population((5,4), neuron.IF_curr_exp,{'v_reset':-60.0}) 
     781     
     782    def testIDSetAndGet(self): 
     783        if self.pop1[3] in self.pop1
     784            self.pop1[3].tau_m = 20.0 
     785            self.assertEqual(20.0, self.pop1[3].tau_m) 
     786        if self.pop1[0] in self.pop1
     787            self.assertEqual(10.0, self.pop1[0].tau_m) 
     788        if self.pop2[3,2] in self.pop2
     789            self.pop2[3,2].v_reset = -70.0 
     790            self.assertEqual(-70.0, self.pop2[3,2].v_reset) 
     791        if self.pop2[0,0] in self.pop2
     792            self.assertEqual(-60.0, self.pop2[0,0].v_reset) 
     793 
     794    def testGetCellClass(self): 
     795        self.assertEqual(neuron.IF_curr_alpha, self.pop1[0].cellclass) 
     796        self.assertEqual(neuron.IF_curr_exp, self.pop2[4,3].cellclass) 
     797         
     798    def testSetAndGetPosition(self): 
     799        self.assert_((self.pop2[0,2].position == (0.0,2.0,0.0)).all()) 
     800        new_pos = (0.5,1.5,0.0) 
     801        self.pop2[0,2].position = new_pos 
     802        self.assert_((self.pop2[0,2].position == (0.5,1.5,0.0)).all()) 
     803        new_pos = (-0.6,3.5,-100.0) # check that position is set-by-value from new_pos 
     804        self.assert_((self.pop2[0,2].position == (0.5,1.5,0.0)).all()) 
    828805         
    829806if __name__ == "__main__": 
    830     #sys.argv = ['./nrnpython'] 
    831807    if '-python' in sys.argv: 
    832808        sys.argv.remove('-python') 
     
    834810        if 'bin/nrniv' in arg: 
    835811            sys.argv.remove(arg) 
    836     #print sys.argv 
    837812    neuron.setup() 
    838813    unittest.main()