This file is indexed.

/usr/share/pyshared/pyNN/connectors2.py is in python-pynn 0.7.4-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
import numpy, logging, sys
from pyNN import errors, common, core, random, utility
from pyNN.space import Space
from pyNN.random import RandomDistribution
from numpy import arccos, arcsin, arctan, arctan2, ceil, cos, cosh, e, exp, \
                    fabs, floor, fmod, hypot, ldexp, log, log10, modf, pi, power, \
                    sin, sinh, sqrt, tan, tanh, maximum, minimum

logger = logging.getLogger("PyNN")

class ConnectionAttributeGenerator(object):
    
    def __init__(self, source, local_mask, safe=True):
        self.source     = source
        self.local_mask = local_mask
        self.local_size = local_mask.sum()
        self.safe       = safe
        if self.safe:
            self.get = self.get_safe    
        if isinstance(self.source, numpy.ndarray):
            self.source_iterator = iter(self.source)
    
    def check(self, data):
        return data
        
    def extract(self, N, distance_matrix=None, sub_mask=None):
        #local_mask is supposed to be a mask of booleans, while 
        #sub_mask is a list of cells ids.
        if isinstance(self.source, basestring):
            assert distance_matrix is not None
            d      = distance_matrix.as_array(sub_mask)
            values = eval(self.source)
            return values
        elif hasattr(self.source, 'func_name'):
            assert distance_matrix is not None
            d      = distance_matrix.as_array(sub_mask)
            values = self.source(d)
            return values
        elif numpy.isscalar(self.source):
            if sub_mask is None:
                values = numpy.ones((self.local_size,))*self.source
            else:
                values = numpy.ones((len(sub_mask),))*self.source
            return values
        elif isinstance(self.source, RandomDistribution):
            if sub_mask is None:
                values = self.source.next(N, mask_local=self.local_mask)
            else:
                values = self.source.next(len(sub_mask), mask_local=self.local_mask)
            return values
        elif isinstance(self.source, numpy.ndarray):
            source_row = self.source_iterator.next()
            values     = source_row[self.local_mask]
            if sub_mask is not None:
                values = values[sub_mask]
            return values    

    def get_safe(self, N, distance_matrix=None, sub_mask=None):
        return self.check(self.extract(N, distance_matrix, sub_mask))
    
    def get(self, N, distance_matrix=None, sub_mask=None):
        return self.extract(N, distance_matrix, sub_mask)


class WeightGenerator(ConnectionAttributeGenerator):
    
    def __init__(self, source, local_mask, projection, safe=True):
      ConnectionAttributeGenerator.__init__(self, source, local_mask, safe)
      self.projection     = projection
      self.is_conductance = common.is_conductance(projection.post.all_cells[0])
      
    def check(self, weight):
        if weight is None:
            weight = DEFAULT_WEIGHT
        if core.is_listlike(weight):
            weight     = numpy.array(weight)
            nan_filter = (1-numpy.isnan(weight)).astype(bool) # weight arrays may contain NaN, which should be ignored
            filtered_weight = weight[nan_filter]
            all_negative = (filtered_weight<=0).all()
            all_positive = (filtered_weight>=0).all()
            if not (all_negative or all_positive):
                raise errors.InvalidWeightError("Weights must be either all positive or all negative")
        elif numpy.isscalar(weight):
            all_positive = weight >= 0
            all_negative = weight < 0
        else:
            raise Exception("Weight must be a number or a list/array of numbers.")
        if self.is_conductance or self.projection.synapse_type == 'excitatory':
            if not all_positive:
                raise errors.InvalidWeightError("Weights must be positive for conductance-based and/or excitatory synapses")
        elif self.is_conductance==False and self.projection.synapse_type == 'inhibitory':
            if not all_negative:
                raise errors.InvalidWeightError("Weights must be negative for current-based, inhibitory synapses")
        else: # is_conductance is None. This happens if the cell does not exist on the current node.
            logger.debug("Can't check weight, conductance status unknown.")
        return weight
        
    

class DelayGenerator(ConnectionAttributeGenerator):

    def __init__(self, source, local_mask, safe=True):
        ConnectionAttributeGenerator.__init__(self, source, local_mask, safe)
        self.min_delay = common.get_min_delay()
        self.max_delay = common.get_max_delay()
        
    def check(self, delay):
        all_negative = (delay<=self.max_delay).all()
        all_positive = (delay>=self.min_delay).all()# If the delay is too small , we have to throw an error
        if not (all_negative and all_positive):
            raise errors.ConnectionError("delay (%s) is out of range [%s,%s]" % (delay, common.get_min_delay(), common.get_max_delay()))
        return delay    

class ProbaGenerator(ConnectionAttributeGenerator):
    pass


class DistanceMatrix(object):
    
    def __init__(self, B, space, mask=None):
        assert B.shape[0] == 3
        self.space = space
        if mask is not None:
            self.B = B[:,mask]
        else:
            self.B = B
        
    def as_array(self, sub_mask=None):
        if self._distance_matrix is None and self.A is not None:
            if sub_mask is None:
                self._distance_matrix = self.space.distances(self.A, self.B)[0]
            else:
                self._distance_matrix = self.space.distances(self.A, self.B[:,sub_mask])[0]
        return self._distance_matrix
        
    def set_source(self, A):
        assert A.shape == (3,)
        self.A = A
        self._distance_matrix = None        


class Connector(object):
    
    def __init__(self, weights=0.0, delays=None, space=Space(), safe=True, verbose=False):
        self.weights = weights
        self.space   = space
        self.safe    = safe
        self.verbose = verbose
        min_delay    = common.get_min_delay()
        if delays is None:
            self.delays = min_delay
        else:
            if core.is_listlike(delays):
                assert min(delays) >= min_delay
            elif not (isinstance(delays, basestring) or isinstance(delays, RandomDistribution)):
                assert delays >= min_delay
            self.delays = delays        
        
    def connect(self, projection):
        pass
    
    def progressbar(self, N):
        self.prog = utility.ProgressBar(0, N, 20, mode='fixed')        
    
    def progression(self, count):
        self.prog.update_amount(count)
        if self.verbose and common.rank() == 0:           
            print self.prog, "\r",
            sys.stdout.flush()
            


class ProbabilisticConnector(Connector):
    
    def __init__(self, projection, weights=0.0, delays=None, allow_self_connections=True, space=Space(), safe=True):

        Connector.__init__(self, weights, delays, space, safe)
        if isinstance(projection.rng, random.NativeRNG):
            raise Exception("Use of NativeRNG not implemented.")
        else:
            self.rng = projection.rng
        
        self.local             = numpy.ones(len(projection.pre), bool)
        self.N                 = projection.pre.size
        self.weights_generator = WeightGenerator(weights, self.local, projection, safe)
        self.delays_generator  = DelayGenerator(delays, self.local, safe)
        self.probas_generator  = ProbaGenerator(RandomDistribution('uniform',(0,1), rng=self.rng), self.local)
        self.distance_matrix   = DistanceMatrix(projection.pre.positions, self.space, self.local)
        self.projection        = projection
        self.allow_self_connections = allow_self_connections
        
        
    def _probabilistic_connect(self, tgt, p):
        """
        Connect-up a Projection with connection probability p, where p may be either
        a float 0<=p<=1, or a dict containing a float array for each pre-synaptic
        cell, the array containing the connection probabilities for all the local
        targets of that pre-synaptic cell.
        """
        if numpy.isscalar(p) and p == 1:
            create = numpy.arange(self.local.sum())
        else:
            rarr   = self.probas_generator.get(self.N)
            if not core.is_listlike(rarr) and numpy.isscalar(rarr): # if N=1, rarr will be a single number
                rarr = numpy.array([rarr])
            create = numpy.where(rarr < p)[0]  
        self.distance_matrix.set_source(tgt.position)
        #create  = self.projection.pre.id_to_index(create).astype(int)
        sources = self.projection.pre.all_cells.flatten()[create]
        if not self.allow_self_connections and self.projection.pre == self.projection.post and tgt in sources:
            i       = numpy.where(sources == tgt)[0]
            sources = numpy.delete(sources, i)
            create  = numpy.delete(create, i)

        weights = self.weights_generator.get(self.N, self.distance_matrix, create)
        delays  = self.delays_generator.get(self.N, self.distance_matrix, create)        
        
        if len(sources) > 0:
            self.projection.connection_manager.convergent_connect(sources.tolist(), tgt, weights, delays)
    
    
class AllToAllConnector(Connector):
    """
    Connects all cells in the presynaptic population to all cells in the
    postsynaptic population.
    """
    
    def __init__(self, allow_self_connections=True, weights=0.0, delays=None, space=Space(), safe=True, verbose=False):
        """
        Create a new connector.
        
        `allow_self_connections` -- if the connector is used to connect a
            Population to itself, this flag determines whether a neuron is
            allowed to connect to itself, or only to other neurons in the
            Population.
        `weights` -- may either be a float, a RandomDistribution object, a list/
                     1D array with at least as many items as connections to be
                     created. Units nA.
        `delays`  -- as `weights`. If `None`, all synaptic delays will be set
                     to the global minimum delay.
        `space` -- a `Space` object, needed if you wish to specify distance-
                   dependent weights or delays
        """
        Connector.__init__(self, weights, delays, space, safe, verbose)
        assert isinstance(allow_self_connections, bool)
        self.allow_self_connections = allow_self_connections
        
    def connect(self, projection):
        connector = ProbabilisticConnector(projection, self.weights, self.delays, self.allow_self_connections, self.space, safe=self.safe)        
        self.progressbar(len(projection.post.local_cells))
        for count, tgt in enumerate(projection.post.local_cells.flat):
            connector._probabilistic_connect(tgt, 1)
            self.progression(count)        
    

class FixedProbabilityConnector(Connector):
    """
    For each pair of pre-post cells, the connection probability is constant.
    """
    
    def __init__(self, p_connect, allow_self_connections=True, weights=0.0, delays=None, space=Space(), 
                       safe=True, verbose=False):
        """
        Create a new connector.
        
        `p_connect` -- a float between zero and one. Each potential connection
                       is created with this probability.
        `allow_self_connections` -- if the connector is used to connect a
            Population to itself, this flag determines whether a neuron is
            allowed to connect to itself, or only to other neurons in the
            Population.
        `weights` -- may either be a float, a RandomDistribution object, a list/
                     1D array with at least as many items as connections to be
                     created. Units nA.
        `delays`  -- as `weights`. If `None`, all synaptic delays will be set
                     to the global minimum delay.
        `space` -- a `Space` object, needed if you wish to specify distance-
                   dependent weights or delays
        """
        Connector.__init__(self, weights, delays, space, safe, verbose)
        assert isinstance(allow_self_connections, bool)
        self.allow_self_connections = allow_self_connections
        self.p_connect = float(p_connect)
        assert 0 <= self.p_connect
        
    def connect(self, projection):
        connector = ProbabilisticConnector(projection, self.weights, self.delays, self.allow_self_connections, self.space, safe=self.safe)
        self.progressbar(len(projection.post.local_cells))
        for count, tgt in enumerate(projection.post.local_cells.flat):
            connector._probabilistic_connect(tgt, self.p_connect)
            self.progression(count)
            

class DistanceDependentProbabilityConnector(ProbabilisticConnector):
    """
    For each pair of pre-post cells, the connection probability depends on distance.
    """
    
    def __init__(self, d_expression, allow_self_connections=True,
                 weights=0.0, delays=None, space=Space(), safe=True, verbose=False):
        """
        Create a new connector.
        
        `d_expression` -- the right-hand side of a valid python expression for
            probability, involving 'd', e.g. "exp(-abs(d))", or "d<3"
        `space` -- a Space object.
        `weights` -- may either be a float, a RandomDistribution object, a list/
                     1D array with at least as many items as connections to be
                     created, or a DistanceDependence object. Units nA.
        `delays`  -- as `weights`. If `None`, all synaptic delays will be set
                     to the global minimum delay.
        """
        Connector.__init__(self, weights, delays, space, safe, verbose)
        assert isinstance(d_expression, str)
        try:
            d = 0; assert 0 <= eval(d_expression), eval(d_expression)
            d = 1e12; assert 0 <= eval(d_expression), eval(d_expression)
        except ZeroDivisionError, err:
            raise ZeroDivisionError("Error in the distance expression %s. %s" % (d_expression, err))
        self.d_expression = d_expression
        assert isinstance(allow_self_connections, bool)
        self.allow_self_connections = allow_self_connections
        
    def connect(self, projection):
        """Connect-up a Projection."""
        connector       = ProbabilisticConnector(projection, self.weights, self.delays, self.allow_self_connections, self.space, safe=self.safe)
        proba_generator = ProbaGenerator(self.d_expression, connector.local)
        self.progressbar(len(projection.post.local_cells))
        for count, tgt in enumerate(projection.post.local_cells.flat):
            connector.distance_matrix.set_source(tgt.position)
            proba  = proba_generator.get(connector.N, connector.distance_matrix)
            if proba.dtype == 'bool':
                proba = proba.astype(float)
            connector._probabilistic_connect(tgt, proba)
            self.progression(count)
    

class FromListConnector(Connector):
    """
    Make connections according to a list.
    """
    
    def __init__(self, conn_list, safe=True, verbose=False):
        """
        Create a new connector.
        
        `conn_list` -- a list of tuples, one tuple for each connection. Each
                       tuple should contain:
                          (pre_addr, post_addr, weight, delay)
                       where pre_addr is the address (a tuple) of the presynaptic
                       neuron, and post_addr is the address of the postsynaptic
                       neuron.
        """
        # needs extending for dynamic synapses.
        Connector.__init__(self, 0., common.get_min_delay(), safe=safe, verbose=verbose)
        self.conn_list = conn_list        
        
    def connect(self, projection):
        """Connect-up a Projection."""
        # slow: should maybe sort by pre
        self.progressbar(len(self.conn_list))
        for count, i in enumerate(xrange(len(self.conn_list))):
            src, tgt, weight, delay = self.conn_list[i][:]
            src = projection.pre[tuple(src)]           
            tgt = projection.post[tuple(tgt)]
            projection.connection_manager.connect(src, [tgt], weight, delay)
            self.progression(count)
            

class FromFileConnector(FromListConnector):
    """
    Make connections according to a list read from a file.
    """
    
    def __init__(self, filename, distributed=False, safe=True, verbose=False):
        """
        Create a new connector.
        
        `filename` -- name of a text file containing a list of connections, in
                      the format required by `FromListConnector`.
        `distributed` -- if this is True, then each node will read connections
                         from a file called `filename.x`, where `x` is the MPI
                         rank. This speeds up loading connections for
                         distributed simulations.
        """
        Connector.__init__(self, 0., common.get_min_delay(), safe=safe, verbose=verbose)
        self.filename = filename
        self.distributed = distributed

    def connect(self, projection):
        """Connect-up a Projection."""
        if self.distributed:
            self.filename += ".%d" % common.rank()
        # open the file...
        f = open(self.filename, 'r', 10000)
        lines = f.readlines()
        f.close()
        # gather all the data in a list of tuples (one per line)
        input_tuples = []
        for line in lines:
            single_line = line.rstrip()
            src, tgt, w, d = single_line.split("\t", 4)
            src = "[%s" % src.split("[",1)[1]
            tgt = "[%s" % tgt.split("[",1)[1]
            input_tuples.append((eval(src), eval(tgt), float(w), float(d)))
        self.conn_list = input_tuples
        FromListConnector.connect(self, projection)



class FixedNumberPostConnector(Connector):
    """
    Each pre-synaptic neuron is connected to exactly n post-synaptic neurons
    chosen at random.
    
    If n is less than the size of the post-synaptic population, there are no
    multiple connections, i.e., no instances of the same pair of neurons being
    multiply connected. If n is greater than the size of the post-synaptic
    population, all possible single connections are made before starting to add
    duplicate connections.
    """
    
    def __init__(self, n, allow_self_connections=True, weights=0.0, delays=None, space=Space(), safe=True, verbose=False):
        """
        Create a new connector.
        
        `n` -- either a positive integer, or a `RandomDistribution` that produces
               positive integers. If `n` is a `RandomDistribution`, then the
               number of post-synaptic neurons is drawn from this distribution
               for each pre-synaptic neuron.
        `allow_self_connections` -- if the connector is used to connect a
               Population to itself, this flag determines whether a neuron is
               allowed to connect to itself, or only to other neurons in the
               Population.
        `weights` -- may either be a float, a RandomDistribution object, a list/
                     1D array with at least as many items as connections to be
                     created. Units nA.
        `delays`  -- as `weights`. If `None`, all synaptic delays will be set
                     to the global minimum delay.
        """
        Connector.__init__(self, weights, delays, space, safe, verbose)
        assert isinstance(allow_self_connections, bool)
        self.allow_self_connections = allow_self_connections
        if isinstance(n, int):
            self.n = n
            assert n >= 0
        elif isinstance(n, random.RandomDistribution):
            self.rand_distr = n
            # weak check that the random distribution is ok
            assert numpy.all(numpy.array(n.next(100)) >= 0), "the random distribution produces negative numbers"
        else:
            raise Exception("n must be an integer or a RandomDistribution object")
        
    def connect(self, projection):
        """Connect-up a Projection."""        
        local             = numpy.ones(len(projection.post), bool)
        weights_generator = WeightGenerator(self.weights, local, projection, self.safe)
        delays_generator  = DelayGenerator(self.delays, local, self.safe)
        distance_matrix   = DistanceMatrix(projection.post.positions, self.space)
        self.progressbar(len(projection.pre))
        
        if isinstance(projection.rng, random.NativeRNG):
            raise Exception("Use of NativeRNG not implemented.")        
        
        for count, src in enumerate(projection.pre.all()):
            # pick n neurons at random
            if hasattr(self, 'rand_distr'):
                n = self.rand_distr.next()
            else:
                n = self.n
            
            candidates  = projection.post.all_cells.flatten()
            if not self.allow_self_connections and projection.pre == projection.post:                
                idx        = numpy.where(candidates == src)[0]
                candidates = numpy.delete(candidates, idx)

            targets = numpy.array([])          
            while len(targets) < n: # if the number of requested cells is larger than the size of the
                                    # postsynaptic population, we allow multiple connections for a given cell   
                targets = numpy.concatenate((targets, projection.rng.permutation(candidates)[:n]))                 
            
            distance_matrix.set_source(src.position)
            targets = targets[:n]
            create  = projection.post.id_to_index(targets).astype(int)
            weights = weights_generator.get(n, distance_matrix, create)
            delays  = delays_generator.get(n, distance_matrix, create)      
               
            if len(targets) > 0:
                projection.connection_manager.connect(src, targets.tolist(), weights, delays)
            
            self.progression(count)
            

class FixedNumberPreConnector(Connector):
    """
    Each post-synaptic neuron is connected to exactly n pre-synaptic neurons
    chosen at random.
    
    If n is less than the size of the pre-synaptic population, there are no
    multiple connections, i.e., no instances of the same pair of neurons being
    multiply connected. If n is greater than the size of the pre-synaptic
    population, all possible single connections are made before starting to add
    duplicate connections.
    """
    
    def __init__(self, n, allow_self_connections=True, weights=0.0, delays=None, space=Space(), safe=True, verbose=False):
        """
        Create a new connector.
        
        `n` -- either a positive integer, or a `RandomDistribution` that produces
               positive integers. If `n` is a `RandomDistribution`, then the
               number of pre-synaptic neurons is drawn from this distribution
               for each post-synaptic neuron.
        `allow_self_connections` -- if the connector is used to connect a
            Population to itself, this flag determines whether a neuron is
            allowed to connect to itself, or only to other neurons in the
            Population.
        `weights` -- may either be a float, a RandomDistribution object, a list/
                     1D array with at least as many items as connections to be
                     created. Units nA.
        `delays`  -- as `weights`. If `None`, all synaptic delays will be set
                     to the global minimum delay.
        """
        Connector.__init__(self, weights, delays, space, safe, verbose)
        assert isinstance(allow_self_connections, bool)
        self.allow_self_connections = allow_self_connections
        if isinstance(n, int):
            self.n = n
            assert n >= 0
        elif isinstance(n, random.RandomDistribution):
            self.rand_distr = n
            # weak check that the random distribution is ok
            assert numpy.all(numpy.array(n.next(100)) >= 0), "the random distribution produces negative numbers"
        else:
            raise Exception("n must be an integer or a RandomDistribution object")

    def connect(self, projection):
        """Connect-up a Projection."""
        local             = numpy.ones(len(projection.pre), bool)
        weights_generator = WeightGenerator(self.weights, local, projection, self.safe)
        delays_generator  = DelayGenerator(self.delays, local, self.safe)
        distance_matrix   = DistanceMatrix(projection.pre.positions, self.space)              
        self.progressbar(len(projection.post.local_cells))
        
        if isinstance(projection.rng, random.NativeRNG):
            raise Exception("Warning: use of NativeRNG not implemented.")
            
        for count, tgt in enumerate(projection.post.local_cells.flat):
            # pick n neurons at random
            if hasattr(self, 'rand_distr'):
                n = self.rand_distr.next()
            else:
                n = self.n
            
            candidates = projection.pre.all_cells.flatten()          
            if not self.allow_self_connections and projection.pre == projection.post:
                i          = numpy.where(candidates == tgt)[0]
                candidates = numpy.delete(candidates, i)
            sources = numpy.array([]) 
            while len(sources) < n: # if the number of requested cells is larger than the size of the
                                    # presynaptic population, we allow multiple connections for a given cell
                sources = numpy.concatenate((sources, projection.rng.permutation(candidates)[:n])) 
                            
            distance_matrix.set_source(tgt.position)
            sources = sources[:n]
            create  = projection.pre.id_to_index(sources).astype(int)
            weights = weights_generator.get(n, distance_matrix, create)
            delays  = delays_generator.get(n, distance_matrix, create)                                            
            if len(sources) > 0:
                projection.connection_manager.convergent_connect(sources, tgt, weights, delays)
            self.progression(count)
            

class OneToOneConnector(Connector):
    """
    Where the pre- and postsynaptic populations have the same size, connect
    cell i in the presynaptic population to cell i in the postsynaptic
    population for all i.
    """
    #In fact, despite the name, this should probably be generalised to the
    #case where the pre and post populations have different dimensions, e.g.,
    #cell i in a 1D pre population of size n should connect to all cells
    #in row i of a 2D post population of size (n,m).
    
    
    def __init__(self, weights=0.0, delays=None, space=Space(), safe=True, verbose=False):
        """
        Create a new connector.
        
        `weights` -- may either be a float, a RandomDistribution object, a list/
                     1D array with at least as many items as connections to be
                     created. Units nA.
        `delays`  -- as `weights`. If `None`, all synaptic delays will be set
                     to the global minimum delay.
        """
        Connector.__init__(self, weights, delays, space, verbose)
        self.space = space
        self.safe  = safe
    
    def connect(self, projection):
        """Connect-up a Projection."""        
        if projection.pre.dim == projection.post.dim:
            N                 = projection.post.size
            local             = projection.post._mask_local.flatten()
            if isinstance(self.weights, basestring) or isinstance(self.delays, basestring):
                raise Exception('Expression for weights or delays is not supported for OneToOneConnector !')
            weights_generator = WeightGenerator(self.weights, local, projection, self.safe)
            delays_generator  = DelayGenerator(self.delays, local, self.safe)                
            weights           = weights_generator.get(N)
            delays            = delays_generator.get(N)
            self.progressbar(len(projection.post.local_cells))                        
            count             = 0
            
            for tgt, w, d in zip(projection.post.local_cells, weights, delays):
                src = projection.pre.index(projection.post.id_to_index(tgt))
                
                # the float is in case the values are of type numpy.float64, which NEST chokes on
                projection.connection_manager.connect(src, [tgt], float(w), float(d))
                self.progression(count)
                count += 1
        else:
            raise errors.InvalidDimensionsError("OneToOneConnector does not support presynaptic and postsynaptic Populations of different sizes.")


class SmallWorldConnector(Connector):
    """
    For each pair of pre-post cells, the connection probability depends on distance.
    """
    
    def __init__(self, degree, rewiring, allow_self_connections=True,
                 weights=0.0, delays=None, space=Space(), safe=True, verbose=False):
        """
        Create a new connector.
        
        `degree` -- the region lenght where nodes will be connected locally
        `rewiring` -- the probability of rewiring each eadges 
        `space` -- a Space object.
        `allow_self_connections` -- if the connector is used to connect a
            Population to itself, this flag determines whether a neuron is
            allowed to connect to itself, or only to other neurons in the
            Population.        
        `weights` -- may either be a float, a RandomDistribution object, a list/
                     1D array with at least as many items as connections to be
                     created, or a DistanceDependence object. Units nA.
        `delays`  -- as `weights`. If `None`, all synaptic delays will be set
                     to the global minimum delay.
        """
        Connector.__init__(self, weights, delays, space, safe, verbose)
        assert 0 <= rewiring <= 1
        assert isinstance(allow_self_connections, bool)        
        self.rewiring               = rewiring    
        self.d_expression           = "d < %g" %degree        
        self.allow_self_connections = allow_self_connections
        
    def _smallworld_connect(self, src, p):
        """
        Connect-up a Projection with connection probability p, where p may be either
        a float 0<=p<=1, or a dict containing a float array for each pre-synaptic
        cell, the array containing the connection probabilities for all the local
        targets of that pre-synaptic cell.
        """
        rarr   = self.probas_generator.get(self.N)
        if not core.is_listlike(rarr) and numpy.isscalar(rarr): # if N=1, rarr will be a single number
            rarr = numpy.array([rarr])
        create = numpy.where(rarr < p)[0]  
        self.distance_matrix.set_source(src.position)        
        
        targets    = self.candidates[create]        
        candidates = self.projection.post.all_cells.flatten()          
        if not self.allow_self_connections and projection.pre == projection.post:
            i          = numpy.where(candidates == src)[0]
            candidates = numpy.delete(candidates, i)
        
        rarr            = self.probas_generator.get(len(create))
        rewired         = rarr < self.rewiring
        if sum(rewired) > 0:
            idx              = numpy.random.random_integers(0, len(candidates)-1, sum(rewired))
            targets[rewired] = candidates[idx]
        create          = self.projection.post.id_to_index(targets).astype(int)
        weights         = self.weights_generator.get(self.N, self.distance_matrix, create)
        delays          = self.delays_generator.get(self.N, self.distance_matrix, create)      
                    
        if len(targets) > 0:
            self.projection.connection_manager.connect(src, targets.tolist(), weights, delays)
    
    def connect(self, projection):
        """Connect-up a Projection."""
        local                  = numpy.ones(len(projection.post), bool)
        self.N                 = projection.post.size        
        if isinstance(projection.rng, random.NativeRNG):
            raise Exception("Use of NativeRNG not implemented.")
        else:
            self.rng = projection.rng
        self.weights_generator = WeightGenerator(self.weights, local, projection, self.safe)
        self.delays_generator  = DelayGenerator(self.delays, local, self.safe)
        self.probas_generator  = ProbaGenerator(RandomDistribution('uniform',(0,1), rng=self.rng), local)
        self.distance_matrix   = DistanceMatrix(projection.post.positions, self.space, local)
        self.projection        = projection
        self.candidates        = self.projection.post.all_cells.flatten()
        self.progressbar(len(projection.pre))        
        proba_generator = ProbaGenerator(self.d_expression, local)
        for count, src in enumerate(projection.pre.all()):     
            self.distance_matrix.set_source(src.position)
            proba = proba_generator.get(self.N, self.distance_matrix).astype(float)
            self._smallworld_connect(src, proba)
            self.progression(count)